blib/lib/CGI/OptimalQuery/Base.pm untested

filter: Statementstmt 0.0% 0 / 287 Branchbran 0.0% 0 / 120 Conditioncond 0.0% 0 / 60 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 45 Podpod 0.0% 0 / 34 totaltotal 0.0% 0 / 546 SCAR 82.4
CC
61
Cov
0%
new
930.0
sth
72.0
default_html_formatter
30.0
CRAP 3782.0
1 package CGI::OptimalQuery::Base;
2  
3 use strict;
4 use warnings;
5 no warnings qw( uninitialized redefine );
6  
7 use CGI();
8 use Carp('confess');
9 use POSIX();
10 use DBIx::OptimalQuery;
11 use JSON::XS;
12  
13 # some tools that OQ auto activates
14 use CGI::OptimalQuery::ExportDataTool();
15 use CGI::OptimalQuery::SaveSearchTool();
16 use CGI::OptimalQuery::LoadSearchTool();
17  
18 sub escapeHTML {
19 local ($_) = @_;
20 s{&}{&}gso;
21 s{<}{&lt;}gso;
22 s{>}{&gt;}gso;
23 s{"}{&quot;}gso;
24 s{'}{&#39;}gso;
25 s{\x8b}{&#8249;}gso;
26 s{\x9b}{&#8250;}gso;
27 return $_;
28 }
29  
30 sub can_embed { 0 }
31  
32 # alias for output
33 sub print {
34 my $o = shift;
35 $o->output(@_);
36 }
37  
38 sub new {
39 my $pack = shift;
40 my $schema = shift;
41 die "could not find schema!" unless ref($schema) eq 'HASH';
42  
43 my $o = bless {}, $pack;
44  
45 $$o{schema} = clone($schema);
46  
47 $$o{dbh} = $$o{schema}{dbh}
48 or confess "couldn't find dbh in schema!";
49 $$o{q} = $$o{schema}{q}
50 or confess "couldn't find q in schema!";
51 $$o{output_handler} = $$o{schema}{output_handler};
52 $$o{error_handler} = $$o{schema}{error_handler};
53  
54 # check for required attributes
55 confess "specified select is not a hash ref!"
56 unless ref $$o{schema}{select} eq "HASH";
57 confess "specified joins is not a hash ref!"
58 unless ref $$o{schema}{joins} eq "HASH";
59
60 # set defaults
61 $$o{schema}{debug} ||= 0;
62 $$o{schema}{check} = $ENV{'CGI-OPTIMALQUERY_CHECK'}
63 if ! defined $$o{schema}{check};
64 $$o{schema}{check} = 0 if ! defined $$o{schema}{check};
65 $$o{schema}{title} ||= "";
66 $$o{schema}{options} ||= {};
67 $$o{schema}{resourceURI} ||= $ENV{OPTIMALQUERY_RESOURCES} || '/OptimalQuery';
68  
69 if (! $$o{schema}{URI}) {
70 $_ = ($$o{q}->can('uri')) ? $$o{q}->uri() : $ENV{REQUEST_URI}; s/\?.*$//;
71 $$o{schema}{URI} = $_;
72 # disabled so we can run from command line for testing where REQUEST_URI probably isn't defined
73 # or die "could not find 'URI' in schema";
74 }
75  
76 $$o{schema}{URI_standalone} ||= $$o{schema}{URI};
77  
78 # make sure developer is not using illegal state_params
79 if (ref($$o{schema}{state_params}) eq 'ARRAY') {
80 foreach my $p (@{ $$o{schema}{state_params} }) {
81 die "cannot use reserved state param name: act" if $p eq 'act';
82 die "cannot use reserved state param name: module" if $p eq 'module';
83 die "cannot use reserved state param name: view" if $p eq 'view';
84 }
85 }
86  
87 # construct optimal query object
88 $$o{oq} = DBIx::OptimalQuery->new(
89 'dbh' => $$o{schema}{dbh},
90 'select' => $$o{schema}{select},
91 'joins' => $$o{schema}{joins},
92 'named_filters' => $$o{schema}{named_filters},
93 'named_sorts' => $$o{schema}{named_sorts},
94 'debug' => $$o{schema}{debug},
95 'error_handler' => $$o{schema}{error_handler}
96 );
97  
98 # the following code is responsible for setting the disable_sort flag for all
99 # multi valued selects (since it never makes since to sort a m-valued column)
100 my %cached_dep_multival_status;
101 my $find_dep_multival_status_i;
102 my $find_dep_multival_status;
103 $find_dep_multival_status = sub {
104 my $joinAlias = shift;
105 $find_dep_multival_status_i++;
106 die "could not resolve join alias: $joinAlias deps" if $find_dep_multival_status_i > 100;
107 if (! exists $cached_dep_multival_status{$joinAlias}) {
108 my $v;
109 if (exists $$o{oq}{joins}{$joinAlias}[3]{new_cursor}) { $v = 0; }
110 elsif (! @{ $$o{oq}{joins}{$joinAlias}[0] }) { $v = 1; }
111 else { $v = $find_dep_multival_status->($$o{oq}{joins}{$joinAlias}[0][0]); }
112 $cached_dep_multival_status{$joinAlias} = $v;
113 }
114 return $cached_dep_multival_status{$joinAlias};
115 };
116  
117 # loop though all selects
118 foreach my $selectAlias (keys %{ $$o{oq}{select} }) {
119 $find_dep_multival_status_i = 0;
120  
121 # set the disable sort flag is select is a multi value
122 $$o{oq}{select}{$selectAlias}[3]{disable_sort} = 1
123 if ! $find_dep_multival_status->($$o{oq}{select}{$selectAlias}[0][0]);
124  
125 # set is_hidden flag if select does not have a nice name assigned
126 $$o{oq}{select}{$selectAlias}[3]{is_hidden} = 1
127 if ! $$o{oq}{select}{$selectAlias}[2];
128  
129 # if no SQL (could be a recview) then disable sort, filter
130 if (! $$o{oq}{select}{$selectAlias}[1]) {
131 $$o{oq}{select}{$selectAlias}[3]{disable_sort} = 1;
132 $$o{oq}{select}{$selectAlias}[3]{disable_filter} = 1;
133 }
134  
135 # if a select column has additional select fields specified in options, make sure that the options array is an array
136 if ($$o{oq}{select}{$selectAlias}[3]{select} && ref($$o{oq}{select}{$selectAlias}[3]{select}) ne 'ARRAY') {
137 my @x = split /\ *\,\ */, $$o{oq}{select}{$selectAlias}[3]{select};
138 $$o{oq}{select}{$selectAlias}[3]{select} = \@x;
139 }
140 }
141  
142 # if any fields are passed into on_select, ensure they are always selected
143 my $on_select = $$o{q}->param('on_select');
144 if ($on_select =~ /[^\,]+\,(.+)/) {
145 my @fields = split /\,/, $1;
146 for (@fields) {
147 $$o{oq}{'select'}{$_}[3]{always_select}=1
148 if exists $$o{oq}{'select'}{$_};
149 }
150 }
151  
152 # check schema validity
153 $$o{oq}->check_join_counts() if $$o{schema}{check} && ! defined $$o{q}->param('module');
154  
155 # install the export tool
156 CGI::OptimalQuery::ExportDataTool::activate($o);
157  
158 # if savedSearchUserID enable savereport and loadreport tools
159 $$o{schema}{savedSearchUserID} ||= undef;
160 if ($$o{schema}{savedSearchUserID} =~ /^\d+$/) {
161 CGI::OptimalQuery::LoadSearchTool::activate($o);
162 CGI::OptimalQuery::SaveSearchTool::activate($o);
163 }
164  
165 # run on_init function for each enabled tool
166 foreach my $v (values %{ $$o{schema}{tools} }) {
167 $$v{on_init}->($o) if ref($$v{on_init}) eq 'CODE';
168 }
169  
170 my $schemaparams = $$o{schema}{params} || {};
171 foreach my $k (qw( page rows_page show filter hiddenFilter queryDescr sort mode )) {
172 if (exists $$schemaparams{$k}) {
173 $$o{$k} = $$schemaparams{$k};
174 } elsif (defined $$o{q}->param($k)) {
175 $$o{$k} = $$o{q}->param($k);
176 } else {
177 $$o{$k} = $$o{schema}{$k};
178 }
179 }
180  
181 $$o{mode} ||= 'default';
182 $$o{mode} =~ s/\W//g;
183  
184 $$o{schema}{results_per_page_picker_nums} ||= [25,50,100,500,1000,'All'];
185 $$o{rows_page} ||= $$o{schema}{rows_page} || $$o{schema}{results_per_page_picker_nums}[0] || 10;
186 $$o{page} ||= 1;
187  
188 # convert show into array
189 if (! ref($$o{show})) {
190 my @ar = split /\,/, $$o{show};
191 $$o{show} = \@ar;
192 }
193  
194 # if we still don't have something to show then show all cols
195 # that aren't hidden
196 if (! scalar( @{ $$o{show} } )) {
197 for (keys %{ $$o{schema}{select} }) {
198 push @{$$o{show}}, $_ unless $$o{oq}->{'select'}->{$_}->[3]->{is_hidden};
199 }
200 }
201  
202 return $o;
203 }
204  
205 sub oq { $_[0]{oq} }
206  
207 # ----------- UTILITY METHODS ------------------------------------------------
208  
209 sub escape_html { escapeHTML($_[1]) }
210 sub escape_uri { CGI::escape($_[1]) }
211 sub escape_js {
212 my $o = shift;
213 $_ = shift;
214 s/\\/\\x5C/g; #escape \
215 s/\n/\\x0A/g; #escape new lines
216 s/\'/\\x27/g; #escape '
217 s/\"/\\x22/g; #escape "
218 s/\&/\\x26/g; #escape &
219 s/\r//g; #remove carriage returns
220 s/script/scr\\x69pt/ig; # make nice script tags
221 return $_;
222 }
223 sub commify {
224 my $o = shift;
225 my $text = reverse $_[0];
226 $text =~ s/(\d\d\d)(?=\d)(?!\d*\.)/$1,/g;
227 return scalar reverse $text;
228 } # Commify
229  
230  
231 my %no_clone = ('dbh' => 1, 'q' => 1);
232 sub clone {
233 my $thing = shift;
234 if (ref($thing) eq 'HASH') {
235 my %tmp;
236 while (my ($k,$v) = each %$thing) {
237 if (exists $no_clone{$k}) { $tmp{$k} = $v; }
238 else { $tmp{$k} = clone($v); }
239 }
240 $thing = \%tmp;
241 } elsif (ref($thing) eq 'ARRAY') {
242 my @tmp;
243 foreach my $v (@$thing) { push @tmp, clone($v); }
244 $thing = \@tmp;
245 }
246 return $thing;
247 }
248  
249  
250  
251 #-------------- ACCESSORS --------------------------------------------------
252 sub sth {
253 my ($o) = @_;
254 return $$o{sth} if $$o{sth};
255  
256 # show is made up of all the fields that should be selected
257 my @show; {
258 my %show;
259 foreach my $colalias (@{$$o{show}}) {
260 if (ref($$o{schema}{select}{$colalias}[3]{select}) eq 'ARRAY') {
261 $show{$_}=1 for @{ $$o{schema}{select}{$colalias}[3]{select} };
262 }
263 if ($$o{schema}{select}{$colalias}[1]) {
264 $show{$colalias}=1;
265 }
266 }
267 @show = sort keys %show;
268 }
269  
270 # create & execute SQL statement
271 $$o{sth} = $$o{oq}->prepare(
272 show => \@show,
273 filter => $$o{filter},
274 hiddenFilter => $$o{hiddenFilter},
275 forceFilter => $$o{schema}{forceFilter},
276 sort => $$o{sort} );
277  
278 # current fetched row
279 $$o{rec} = undef;
280  
281 # calculate what the limit is
282 # and make sure page, num_pages, rows_page make sense
283 if ($$o{sth}->count() == 0) {
284 $$o{page} = 0;
285 $$o{rows_page} = 0;
286 $$o{num_pages} = 0;
287 $$o{limit} = [0,0];
288 } elsif ($$o{rows_page} eq 'All' || ($$o{sth}->count() < $$o{rows_page})) {
289 $$o{rows_page} = "All";
290 $$o{page} = 1;
291 $$o{num_pages} = 1;
292 $$o{limit} = [1, $$o{sth}->count()];
293 } else {
294 $$o{num_pages} = POSIX::ceil($$o{sth}->count() / $$o{rows_page});
295 $$o{page} = $$o{num_pages} if $$o{page} > $$o{num_pages};
296 my $lo = ($$o{rows_page} * $$o{page}) - $$o{rows_page} + 1;
297 my $hi = $lo + $$o{rows_page} - 1;
298 $hi = $$o{sth}->count() if $hi > $$o{sth}->count();
299 $$o{limit} = [$lo, $hi];
300 }
301  
302 $$o{sth}->set_limit($$o{limit});
303  
304 return $$o{sth};
305 }
306 sub get_count { $_[0]->sth->count() }
307 sub get_rows_page { $_[0]{rows_page} }
308 sub get_current_page { $_[0]{page} }
309 sub get_lo_rec { $_[0]->sth->get_lo_rec() }
310 sub get_hi_rec { $_[0]->sth->get_hi_rec() }
311 sub get_num_pages { $_[0]{num_pages} }
312 sub get_title { $_[0]{schema}{title} }
313 sub get_filter { $_[0]->sth->filter_descr() }
314 sub get_sort { $_[0]->sth->sort_descr() }
315 sub get_query { $_[0]{query} }
316 sub get_nice_name { $_[0]{schema}{select}{$_[1]}[2] }
317 sub get_num_usersel_cols { scalar @{$_[0]{show}} }
318 sub get_usersel_cols { $_[0]{show} }
319  
320 sub finish {
321 my ($o) = @_;
322 $$o{sth}->finish() if $$o{sth};
323 undef $$o{sth};
324 }
325  
326 # get the options
327 sub get_opts {
328 my ($o) = @_;
329  
330 if (! $$o{_opts}) {
331 my $class = ref $o;
332  
333 if (exists $$o{schema}{options}{$class}) {
334 $$o{_opts} = $$o{schema}{options}{$class};
335 }
336  
337 # remove numerics and try again, this allows for module developers to create upgraded modules that use
338 # backwards compatible options example: InteractiveQuery & InteractiveQuery2
339 elsif ($class =~ s/\d+$// && exists $$o{schema}{options}{$class}) {
340 $$o{_opts} = $$o{schema}{options}{$class};
341 }
342  
343 else {
344 $$o{_opts} = {};
345 }
346 }
347  
348 return $$o{_opts};
349 }
350  
351 sub fetch {
352 my ($o) = @_;
353 if ($$o{rec} = $o->sth->fetchrow_hashref()) {
354 my $mutator = $o->get_opts()->{'mutateRecord'};
355 $mutator->($$o{rec}) if ref($mutator) eq 'CODE';
356 $$o{schema}{mutateRecord}->($$o{rec}) if ref($$o{schema}{mutateRecord}) eq 'CODE';
357 return $$o{rec};
358 }
359 return undef;
360 }
361  
362 sub get_val {
363 my ($o, $colAlias) = @_;
364 $o->fetch() unless $$o{rec};
365 my $formatter = $$o{schema}{select}{$colAlias}[3]{formatter} || \&default_formatter;
366 return $formatter->($$o{rec}{$colAlias}, $$o{rec}, $o, $colAlias);
367 }
368  
369 sub get_html_val {
370 my ($o, $colAlias) = @_;
371 $o->fetch() unless $$o{rec};
372 my $formatter = $$o{schema}{select}{$colAlias}[3]{html_formatter} || \&default_html_formatter;
373 return $formatter->($$o{rec}{$colAlias}, $$o{rec}, $o, $colAlias);
374 }
375  
376 sub default_formatter {
377 my ($val) = @_;
378 return (ref($val) eq 'ARRAY') ? join(', ', @$val) : $val;
379 }
380  
381 sub default_html_formatter {
382 my ($val, $rec, $o, $colAlias) = @_;
383 if (! exists $$o{_noEscapeColMap}) {
384 my %noEsc = map { $_ => 1 } @{ $o->get_opts()->{'noEscapeCol'} || [] };
385 $$o{_noEscapeColMap} = \%noEsc;
386 }
387 if ($$o{_noEscapeColMap}{$colAlias}) {
388 $val = join(' ', @$val) if ref($val) eq 'ARRAY';
389 } elsif (ref($val) eq 'ARRAY') {
390 $val = join(', ', map { escapeHTML($_) } @$val);
391 } else {
392 $val = escapeHTML($val);
393 }
394 return $val;
395 }
396  
397 sub recview_formatter {
398 my ($val, $rec, $o, $colAlias) = @_;
399  
400 my @val;
401 foreach my $colAlias2 (@{ $$o{schema}{select}{$colAlias}[3]{select} }) {
402 my $val2 = default_formatter($$rec{$colAlias2});
403 if ($val2 ne '') {
404 my $label = $$o{schema}{select}{$colAlias2}[2] || $colAlias2;
405 push @val, "$label: $val2";
406 }
407 }
408 return join("\n", @val);
409 }
410  
411 sub recview_html_formatter {
412 my ($val, $rec, $o, $colAlias) = @_;
413  
414 my @val;
415 foreach my $colAlias2 (@{ $$o{schema}{select}{$colAlias}[3]{select} }) {
416 my $val2 = $o->get_html_val($colAlias2);
417 if ($val2 ne '') {
418 my $label = $$o{schema}{select}{$colAlias2}[2] || $colAlias2;
419 push @val, "<tr><td>".escapeHTML($label)."</td><td>$val2</td></tr>";
420 }
421 }
422 return $#val > -1 ? "<table class=OQrecview>".join('', @val)."</table>" : '';
423 }
424  
425 sub get_link {
426 my ($o) = @_;
427 my @args;
428 foreach my $k (qw( show filter hiddenFilter queryDescr sort)) {
429 my $v1 = $$o{$k};
430 $v1 = join(',', @$v1) if ref($v1) eq 'ARRAY';
431 my $v2 = $$o{schema}{$k};
432 $v2 = join(',', @$v2) if ref($v2) eq 'ARRAY';
433 push @args, "$k=".CGI::escape($v1) if $v1 ne $v2;
434 }
435 my $rv = $$o{schema}{URI};
436 my $args = join('&', @args);
437 $rv .= '?'.$args if $args;
438 return $rv;
439 }
440  
441 1;