lib/CGI/OptimalQuery/Base.pm

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