/[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 157 by dpavlin, Sat Nov 26 16:21:51 2005 UTC revision 404 by dpavlin, Sun Feb 19 20:16:11 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;  use Time::HiRes qw/time/;
13    use Encode qw/encode decode from_to/;
14    use Template;
15    
16  =head1 NAME  =head1 NAME
17    
# Line 34  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    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 45  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 62  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            $self->{est_node} = Search::Estraier::Node->new(
81                    url => $url,
82                    user => $est_cfg->{user},
83                    passwd => $est_cfg->{passwd},
84            );
85    
86          my $db_path = $c->config->{webpac}->{db_path};          $log->fatal("can't create Search::Estraier::Node $url") unless ($self->{est_node});
87          my $template_path = $c->config->{webpac}->{template_path};  
88          $self->{template_path} = $template_path;          # 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          # save config parametars in object          $self->{databases} = $c->config->{databases} || $log->fatal("can't find databases in config");
117          foreach my $f (qw/hits_on_page/) {  
118                  $self->{$f} = $c->config->{hyperestraier}->{$f};          # create Template toolkit instance
119                  $log->debug("self->{$f} = " . $self->{$f});          $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};
                 $self->config->{webpac}->{out_encoding},  
                 $self->config->{webpac}->{webpac_encoding},  
         );  
156    
157          $self->{iconv_save}->convert( @_ );          $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 137  sub iconv_on_save { Line 169  sub iconv_on_save {
169          get_attr => [ '@uri' ],          get_attr => [ '@uri' ],
170          max => 42,          max => 42,
171          template => 'result_template.tt',          template => 'result_template.tt',
172            depth => 1,
173    );    );
174    
175  All fields are standard C<WebPAC::Search::Estraier> parametars except  All fields are standard C<WebPAC::Search::Estraier> parametars except
# Line 148  selected template. Line 181  selected template.
181  sub search {  sub search {
182          my $self = shift;          my $self = shift;
183    
184            my $search_start_t = time();
185    
186          my $args = {@_};          my $args = {@_};
187    
188          my $log = $self->{log};          my $log = $self->{log};
189    
190          $log->debug("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_on_page'};          $args->{max} ||= $self->{'hits_for_pager'};
197          if (! $args->{max}) {          if (! $args->{max}) {
198                  $args->{max} = 10;                  $args->{max} = 100;
199                  $log->warn("max not set when calling model. Using default of 10");                  $log->warn("max not set when calling model. Using default of $args->{max}");
200          }          }
201    
202          my $times;      # store some times for benchmarking          my $times;      # store some times for benchmarking
203    
204          my $t = time();          my $t = time();
205    
206          my @results = $self->{est}->search( %{ $args } );          # transfer depth of search
207            if (! $args->{depth}) {
208                    my $default = $self->{defaultdepth} || $log->logdie("can't find defaultdepth in estraier configuration");
209                    $args->{depth} = $default;
210                    $log->warn("using default search depth $default");
211            }
212            $args->{depth} ||= 0;
213    
214            $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          my $hits = $#results + 1;          $cond->set_max( $page * $max );
240    
241          $log->debug( sprintf("search took %.2fs and returned $hits hits.", $times->{est}) );          my $result = $self->{est_node}->search($cond, $args->{depth});
242            my $hits = $result->doc_num;
243    
244          # just return results?          $times->{est} += time() - $t;
245          return @results unless ($args->{'template'});  
246            $log->debug( sprintf("search took %.6fs and returned $hits hits.", $times->{est}) );
247    
248            $log->dumper($result->{hints}, 'result->hints' );
249    
250          #          #
251          # construct HTML results          # fetch results
252          #          #
253    
254          my @html_results;          my @results;
255    
256          for my $i ( 0 .. $#results ) {          for my $i ( (($page - 1) * $max) .. ( $hits - 1 ) ) {
257    
258                  my $mfn = $1 if ( $results[$i]->{'@uri'} =~ m#/(\d+)$#);                  $t = time();
259    
260                  #$log->debug("load_ds( $mfn )");                  #$log->debug("get_doc($i)");
261                    my $doc = $result->get_doc( $i );
262                    if (! $doc) {
263                            $log->warn("can't find result $i");
264                            next;
265                    }
266    
267                  $t = time();                  my $hash;
268    
269                  my $ds = $self->{db}->load_ds( $mfn ) || $log->error("can't load_ds( $mfn )") && next;                  foreach my $attr (@{ $args->{get_attr} }) {
270                            my $val = $doc->attr( $attr );
271                            #$log->debug("attr $attr = ", $val || 'undef');
272                            $hash->{$attr} = $val if (defined($val));
273                    }
274    
275                  $times->{db} += time() - $t;                  $times->{hash} += time() - $t;
276    
277                  #$log->debug( "ds = " . Dumper( \@html_results ) );                  next unless ($hash);
278    
279                  $t = time();                  if (! $args->{'template'}) {
280                            push @results, $hash;
281                    } else {
282                            my ($database, $prefix, $id);
283    
284                  my $html = $self->{out}->apply(                          if ( $hash->{'@uri'} =~ m!/([^/]+)/([^/]+)/(\d+)$!) {
285                          template => $template_filename,                                  ($database, $prefix,$id) = ($1,$2,$3);
286                          data => $ds,                          } else {
287                  );                                  $log->warn("can't decode database/prefix/id from " .  $hash->{'@uri'});
288                                    next;
289                            }
290    
291                  $times->{out} += time() - $t;                          #$log->debug("load_ds( id => $id, prefix => '$prefix' )");
292    
293                  $t = time();                          $t = time();
294    
295                  $html = $self->{iconv}->convert( $html ) || $log->error("can't convert: $html");                          my $ds = $self->{db}->load_ds( database => $database, prefix => $prefix, id => $id );
296                            if (! $ds) {
297                                    $log->error("can't load_ds( ${database}/${prefix}/${id} )");
298                                    next;
299                            }
300    
301                  $times->{iconv} += time() - $t;                          $times->{db} += time() - $t;
302    
303                  push @html_results, $html;                          $t = time();
304    
305          }                          my $html = $self->apply(
306                                    template => $template_filename,
307                                    data => $ds,
308                                    record_uri => "${database}/${prefix}/${id}",
309                                    config => $self->{databases}->{$database},
310                            );
311    
312                            $times->{apply} += time() - $t;
313    
314                            $t = time();
315    
316          #$log->debug( '@html_results = ' . Dumper( \@html_results ) );                          $html = decode($self->{webpac_encoding}, $html);
317    
318                            $times->{decode} += time() - $t;
319    
320                            push @results, $html;
321                    }
322    
323            }
324    
325          $log->debug( sprintf(          $log->debug( sprintf(
326                  "time spent: db = %.2f, out = %.2f, iconv = %.2f",                  "duration breakdown: estraier %.6fs, hash %.6fs, store %.6fs, apply %.6fs, decode %.06f, total: %.6fs",
327                  $times->{db}, $times->{out}, $times->{iconv},                  $times->{est}, $times->{hash}, $times->{db}, $times->{apply}, $times->{decode}, time() - $search_start_t,
328          ) );          ) );
329    
330          return \@html_results;          return \@results;
331  }  }
332    
333    =head2 record
334    
335      my $html = $m->record(
336            mfn => 42,
337            template => 'foo.tt',
338      );
339    
340    This will load one record, convert it to html using C<template> and return
341    it.
342    
343    =cut
344    
345    sub record {
346            my $self = shift;
347    
348            my $args = {@_};
349            my $log = $self->{log};
350            $log->dumper( $args, 'args' );
351    
352            foreach my $f (qw/record_uri template/) {
353                    $log->fatal("need $f") unless ($args->{$f});
354            }
355    
356            my ($database, $prefix, $id);
357    
358            if ($args->{record_uri} =~ m#^([^/]+)/([^/]+)/([^/]+)$#) {
359                    ($database, $prefix, $id) = ($1,$2,$3);
360            } else {
361                    $log->error("can't parse $args->{record_uri} into prefix, database and uri");
362                    return;
363            }
364    
365            my $ds = $self->{db}->load_ds( id => $id, prefix => $prefix, database => $database );
366            if (! $ds) {
367                    $log->error("can't load_ds( $database/$prefix/$id )");
368                    return;
369            }
370    
371            my $html = $self->apply(
372                    template => $args->{template},
373                    data => $ds,
374                    record_uri => $args->{record_uri},
375                    config => $self->{databases}->{$database},
376            );
377    
378            $html = decode($self->{webpac_encoding}, $html);
379    
380            return $html;
381    }
382    
383    
384    =head2 list_nodes
385    
386      my @nodes = $m->list_nodes( 'site' );
387    
388    Return all databases which have records for selected site. Returned array of
389    hashes has elements C<name> and C<label>.
390    
391    =cut
392    
393    sub list_nodes {
394            my $self = shift;
395    
396            my $site = shift;
397    
398            $self->{log}->debug("list_nodes use site $site");
399    
400            $self->setup_site( $site );
401    
402            my @nodes;
403    
404            if ($self->{est_node}->doc_num > 0) {
405                    push @nodes, {
406                            name => $self->{est_node}->name,
407                            label => $self->{est_node}->label,
408                            doc_num => $self->{est_node}->doc_num,
409                    }
410            }
411    
412            # refresh set info
413            $self->{est_node}->_set_info;
414    
415            my $links = $self->{est_node}->links || return @nodes;
416    
417            $self->{log}->dumper( $links, 'links' );
418    
419            foreach my $link (@{ $links }) {
420                    my ($url, $label, $credit) = split(/\t/, $link, 3);
421                    if ($url =~ m#/node/(.+)$#) {
422                            my $node = $1;
423                            $self->setup_site( $node );
424                            $self->{est_node}->_set_info;
425                            push @nodes, {
426                                    name => $node,
427                                    label => $label,
428                                    doc_num => $self->{est_node}->doc_num,
429                            }
430                    } else {
431                            $self->{log}->warn("can't find node name in link $link");
432                    }
433            }
434    
435            $self->setup_site( $site );
436            $self->{est_node}->_set_info;
437    
438            $self->{log}->dumper( \@nodes, 'nodes' );
439    
440            return @nodes;
441    }
442    
443    =cut
444    
445    
446  =head2 save_html  =head2 save_html
447    
448    $m->save_html( '/full/path/to/file', $content );    $m->save_html( '/full/path/to/file', $content );
449    
450  It will use C<iconv_on_save> to convert content encoding back to  It will use C<Encode> to convert content encoding back to
451  Webpac codepage, recode JavaScript Unicode entities (%u1234),  Webpac codepage, recode JavaScript Unicode entities (%u1234),
452  strip extra newlines at beginning and end, and save to  strip extra newlines at beginning and end, and save to
453  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 250  it over original file which should be at Line 458  it over original file which should be at
458  sub save_html {  sub save_html {
459          my ($self, $path, $content) = @_;          my ($self, $path, $content) = @_;
460    
461          $content = $self->iconv_on_save( $content ) || die "no content?";          # FIXME Should this be UTF-8 or someting?
462            my $js_encoding = $self->{webpac_encoding};
463            $js_encoding = 'UTF-16';
464    
465          sub _conv_js {          sub _conv_js {
466                  my $t = shift || return;                  return '0x' . $_[1];
467                  return $self->{iconv}->convert(chr(hex($t)));                  return encode($_[0], chr(hex($_[1])));
468          }          }
469          $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;
470          $content =~ s/^[\n\r]+//s;          $content =~ s/^[\n\r]+//s;
471          $content =~ s/[\n\r]+$/\n/s;          $content =~ s/[\n\r]+$/\n/s;
472            $content =~ s/\n\r/\n/gs;
473    
474            my $disk_encoding = $self->{webpac_encoding} || 'utf-8';
475            $self->{log}->debug("convert encoding to $disk_encoding");
476            from_to($content, 'utf-8', $disk_encoding) || $self->{log}->warn("encoding from utf-8 to $disk_encoding failed for: $content");
477    
478          write_file($path . '.new', $content) || die "can't save ${path}.new $!";          write_file($path . '.new', {binmode => ':raw' }, $content) || die "can't save ${path}.new $!";
479          rename $path . '.new', $path || die "can't rename to $path: $!";          rename $path . '.new', $path || die "can't rename to $path: $!";
480  }  }
481    
# Line 279  sub load_html { Line 494  sub load_html {
494    
495          die "no path?" unless ($path);          die "no path?" unless ($path);
496    
497          my $content = read_file($path) || die "can't read $path: $!";          my $content = read_file($path, {binmode => ':raw' }) || die "can't read $path: $!";
498          #$content = $q->escapeHTML($iconv_utf8->convert($content));  
499          $content = $self->{iconv}->convert($content);          return decode($self->{webpac_encoding}, $content);
500    }
501    
502    
503    =head2 apply
504    
505    Create output from in-memory data structure using Template Toolkit template.
506    
507     my $text = $tt->apply(
508            template => 'text.tt',
509            data => $ds,
510            record_uri => 'database/prefix/mfn',
511     );
512    
513    It also has follwing template toolikit filter routies defined:
514    
515    =cut
516    
517    sub apply {
518            my $self = shift;
519    
520            my $args = {@_};
521    
522            my $log = $self->{log} || die "no log?";
523    
524            foreach my $a (qw/template data/) {
525                    $log->fatal("need $a") unless ($args->{$a});
526            }
527    
528    =head3 tt_filter_type
529    
530    filter to return values of specified from $ds, usage from TT template is in form
531    C<d('FieldName','delimiter')>, where C<delimiter> is optional, like this:
532    
533      [% d('Title') %]
534      [% d('Author',', ' %]
535    
536    =cut
537    
538            sub tt_filter_type {
539                    my ($data,$type) = @_;
540                    
541                    die "no data?" unless ($data);
542                    $type ||= 'display';
543    
544                    my $default_delimiter = {
545                            'display' => '&#182;<br/>',
546                            'index' => '\n',
547                    };
548    
549                    return sub {
550    
551                            my ($name,$join) = @_;
552    
553                            die "no data hash" unless ($data->{'data'} && ref($data->{'data'}) eq 'HASH');
554                            # Hm? Should we die here?
555                            return unless ($name);
556    
557                            my $item = $data->{'data'}->{$name} || return;
558    
559                            my $v = $item->{$type} || return;
560    
561                            if (ref($v) eq 'ARRAY') {
562                                    if ($#{$v} == 0) {
563                                            $v = $v->[0];
564                                    } else {
565                                            $join = $default_delimiter->{$type} unless defined($join);
566                                            $v = join($join, @{$v});
567                                    }
568                            } else {
569                                    warn("TT filter $type(): field $name values aren't ARRAY, ignoring");
570                            }
571    
572                            return $v;
573                    }
574            }
575    
576            $args->{'d'} = tt_filter_type($args, 'display');
577            $args->{'display'} = tt_filter_type($args, 'display');
578    
579    =head3 tt_filter_search
580    
581    filter to return links to search, usage in TT:
582    
583      [% search('FieldToDisplay','FieldToSearch','optional delimiter', 'optional_template.tt') %]
584    
585    =cut
586    
587            sub tt_filter_search {
588    
589                    my ($data) = @_;
590    
591                    die "no data?" unless ($data);
592                    
593                    return sub {
594    
595                            my ($display,$search,$delimiter,$template) = @_;
596                            
597                            # default delimiter
598                            $delimiter ||= '&#182;<br/>',
599    
600                            die "no data hash" unless ($data->{'data'} && ref($data->{'data'}) eq 'HASH');
601                            # Hm? Should we die here?
602                            return unless ($display);
603    
604                            my $item = $data->{'data'}->{$display} || return;
605    
606                            return unless($item->{'display'});
607                            if (! $item->{'search'}) {
608                                    warn "error in TT template: field $display didn't insert anything into search, use d('$display') and not search('$display'...)";
609                                    return;
610                            }
611    
612                            my @warn;
613                            foreach my $type (qw/display search/) {
614                                    push @warn, "field $display type $type values aren't ARRAY" unless (ref($item->{$type}) eq 'ARRAY');
615                            }
616    
617                            if (@warn) {
618                                    warn("TT filter search(): " . join(",", @warn) . ", skipping");
619                                    return;
620                            }
621                            my @html;
622    
623                            my $d_el = $#{ $item->{'display'} };
624                            my $s_el = $#{ $item->{'search'} };
625    
626                            # easy, both fields have same number of elements or there is just
627                            # one search and multiple display
628                            if ( $d_el == $s_el || $s_el == 0 ) {
629    
630                                    foreach my $i ( 0 .. $d_el ) {
631    
632                                            my $s;
633                                            if ($s_el > 0) {
634                                                    $s = $item->{'search'}->[$i] or warn "can't find value $i for type search in field $search";
635                                            } else {
636                                                    $s = $item->{'search'}->[0];
637                                            }
638                                            #$s =~ s/([^\w.-])/sprintf("%%%02X",ord($1))/eg;
639                                            $s = __quotemeta( $s );
640    
641                                            my $d = $item->{'display'}->[$i] or warn "can't find value $i for type display in field $display";
642    
643                                            my $template_arg = '';
644                                            $template_arg = qq{,'$template'} if ($template);
645    
646                                            push @html, qq{<a href="#" onclick="return search_via_link('$search','$s'${template_arg})">$d</a>};
647                                    }
648    
649                                    return join($delimiter, @html);
650                            } else {
651                                    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>};
652                                    my $v = $item->{'display'};
653    
654                                    if ($#{$v} == 0) {
655                                            $html .= $v->[0];
656                                    } else {
657                                            $html .= join($delimiter, @{$v});
658                                    }
659                                    return $html;
660                            }
661                    }
662            }
663    
664            $args->{'search'} = tt_filter_search($args);
665    
666    =head3 load_rec
667    
668    Used mostly for onClick events like this:
669    
670      <a href="#" onClick="[% load_rec( record_uri, 'template_name.tt') %]>foo</a>
671    
672    It will automatically do sanity checking and create correct JavaScript code.
673    
674    =cut
675    
676            $args->{'load_rec'} = sub {
677                    my @errors;
678    
679                    my $record_uri = shift or push @errors, "record_uri missing";
680                    my $template = shift or push @errors, "template missing";
681    
682                    if ($record_uri !~ m#^[^/]+/[^/]+/[^/]+$#) {
683                            push @errors, "invalid format of record_uri: $record_uri";
684                    }
685    
686          return $content;                  if (@errors) {
687                            return "Logger.error('errors in load_rec: " . join(", ", @errors) . "'); return false;";
688                    } else {
689                            return "load_rec('$record_uri','$template'); return false;";
690                    }
691            };
692    
693    =head3 load_template
694    
695    Used to re-submit search request and load results in different template
696    
697      <a href="#" onClick="[% load_template( 'template_name.tt' ) %]">bar</a>
698    
699    =cut
700    
701            $args->{'load_template'} = sub {
702                    my $template = shift or return "Logger.error('load_template missing template name!'); return false;";
703                    return "load_template($template); return false;";
704            };
705    
706            my $out;
707    
708            $self->{'tt'}->process(
709                    $args->{'template'},
710                    $args,
711                    \$out
712            ) || $log->error( "apply can't process template: ", $self->{'tt'}->error() );
713    
714            return $out;
715  }  }
716    
717    
718    =head2 __quotemeta
719    
720    Helper to quote JavaScript-friendly characters
721    
722    =cut
723    
724    sub __quotemeta {
725            local $_ = shift;
726            $_ = decode('iso-8859-2', $_);
727    
728            s<([\x{0080}-\x{fffd}]+)>{sprintf '\u%0*v4X', '\u', $1}ge if ( Encode::is_utf8($_) );
729            {
730                    use bytes;  
731                    s<((?:[^ \x21-\x7E]|(?:\\(?!u)))+)>{sprintf '\x%0*v2X', '\x', $1}ge;
732            }
733    
734            s/\\x09/\\t/g;
735            s/\\x0A/\\n/g;
736            s/\\x0D/\\r/g;
737            s/"/\\"/g;
738            s/\\x5C/\\\\/g;
739    
740            return $_;
741    }
742    
743    
744    
745  =head1 AUTHOR  =head1 AUTHOR
746    
747  Dobrica Pavlinusic  Dobrica Pavlinusic C<< <dpavlin@rot13.org> >>
748    
749  =head1 LICENSE  =head1 LICENSE
750    

Legend:
Removed from v.157  
changed lines
  Added in v.404

  ViewVC Help
Powered by ViewVC 1.1.26