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

filter: Statementstmt 0.0% 0 / 394 Branchbran 0.0% 0 / 222 Conditioncond 0.0% 0 / 125 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 15 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 765 CC 112 SCAR 64.7
CC
112
Cov
0%
execute_saved_search_alerts
1122.0
custom_output_handler
756.0
on_init
552.0
CRAP 647.8
1 package CGI::OptimalQuery::SaveSearchTool;
2  
3 use strict;
4 use POSIX qw/strftime/;
5 use Data::Dumper;
6 use Mail::Sendmail();
7 use CGI qw( escapeHTML );
8 use JSON::XS;
9  
10 # save a reference to the current saved save that is running via crontab right now
11 our $current_saved_search;
12  
13 # this is called from Base constructor
14 sub on_init {
15 my ($o) = @_;
16  
17 # adjust config if a saved search alert is running via cron right now
18 # unable to set these earlier because we dont have a constructed OQ yet
19 $$o{schema}{savedSearchAlertMaxRecs} ||= 1000;
20 $$o{schema}{savedSearchAlertEmailCharLimit} ||= 500000;
21  
22 # one more to detect overflow
23 $$o{q}->param('rows_page', $$o{schema}{savedSearchAlertMaxRecs} + 1) if $current_saved_search;
24  
25 # request to save a search?
26 if ($$o{q}->param('OQsaveSearchTitle') ne '') {
27  
28 eval {
29 # serialize params
30 my $params;
31 { my %data;
32 foreach my $p (qw( show filter sort rows_page queryDescr hiddenFilter )) {
33 $data{$p} = $$o{q}->param($p);
34 }
35 delete $data{rows_page} unless $data{rows_page} eq 'All' || $data{rows_page} > 25;
36 if (ref($$o{schema}{state_params}) eq 'ARRAY') {
37 foreach my $p (@{ $$o{schema}{state_params} }) {
38 my @v = $$o{q}->param($p);
39 $data{$p} = \@v;
40 }
41 }
42
43 local $Data::Dumper::Indent = 0;
44 local $Data::Dumper::Quotekeys = 0;
45 local $Data::Dumper::Pair = '=>';
46 local $Data::Dumper::Sortkeys = 1;
47 $params = Dumper(\%data);
48 $params =~ s/^[^\{]+\{//;
49 $params =~ s/\}\;\s*$//;
50 }
51
52 $$o{q}->param('queryDescr', $$o{q}->param('OQsaveSearchTitle'));
53
54 my %rec = (
55 user_id => $$o{schema}{savedSearchUserID},
56 uri => $$o{schema}{URI},
57 oq_title => $$o{schema}{title},
58 user_title => $$o{q}->param('OQsaveSearchTitle'),
59 params => $params
60 );
61
62 # does the user want to set this as the default search, and if so do they have permission
63 if($$o{schema}{canSaveDefaultSearches} && defined $$o{q}->param('save_search_default')) {
64 $rec{is_default} = $$o{q}->param('save_search_default') || 0;
65 }
66  
67 # is saved search alerts enabled
68 if ($$o{schema}{savedSearchAlerts}) {
69 $rec{alert_mask} = $$o{q}->param('alert_mask') || 0;
70 }
71  
72 # if user enabled search search alerts
73 if ($rec{alert_mask}) {
74 $rec{alert_interval_min} = $$o{q}->param('alert_interval_min');
75 $rec{alert_dow} = $$o{q}->param('alert_dow');
76 $rec{alert_start_hour} = $$o{q}->param('alert_start_hour');
77 $rec{alert_end_hour} = $$o{q}->param('alert_end_hour');
78 $rec{alert_last_dt} = [get_sysdate_sql($$o{dbh})];
79
80 # get starting alert_uids
81 my @uids;
82 my $sth = $$o{oq}->prepare(
83 show => ['UID'],
84 filter => scalar($$o{q}->param('filter')),
85 forceFilter => $$o{schema}{forceFilter},
86 hiddenFilter => scalar($$o{q}->param('hiddenFilter'))
87 );
88  
89 $sth->execute(limit => [1, $$o{schema}{savedSearchAlertMaxRecs} + 1]);
90 while (my $h = $sth->fetchrow_hashref()) {
91 push @uids, $$h{U_ID};
92 }
93 die "MAX_ROWS_EXCEEDED - your report contains too many rows to send alerts via email. Reduce the total row count of your report by adding additional filters." if scalar(@uids) > $$o{schema}{savedSearchAlertMaxRecs};
94 $rec{alert_uids} = join('~', @uids);
95 }
96
97 # save saved search to db
98 my $is_update=0;
99 if ($$o{q}->param('OQss') ne '') {
100 my $id = scalar($$o{q}->param('OQss'));
101 ($is_update) = $$o{dbh}->selectrow_array("SELECT 1 FROM oq_saved_search WHERE id=? AND user_id=?", undef, $id, $rec{user_id});
102 if ($is_update) {
103 my (@cols,@binds);
104 while (my ($col,$val) = each %rec) {
105 if (ref($val) eq 'ARRAY') {
106 my ($sql,@rest) = @$val;
107 push @cols, "$col=$sql";
108 push @binds, map { $_ eq '' ? undef : $_ } @rest;
109 } else {
110 push @cols, "$col=?";
111 push @binds, ($val eq '') ? undef : $val;
112 }
113 }
114 push @binds, $id;
115 $$o{dbh}->do("UPDATE oq_saved_search SET ".join(',', @cols)." WHERE id=?", undef, @binds);
116 $rec{id} = $id;
117 }
118 }
119 if (! $is_update) {
120 ($rec{id}) = $$o{dbh}->selectrow_array("SELECT s_oq_saved_search.nextval FROM dual") if $$o{dbh}{Driver}{Name} eq 'Oracle';
121 my (@cols,@vals,@binds);
122 while (my ($col,$val) = each %rec) {
123 push @cols, $col;
124 if (ref($val) eq 'ARRAY') {
125 my ($sql,@rest) = @$val;
126 push @vals, $sql;
127 push @binds, map { $_ eq '' ? undef : $_ } @rest;
128 } else {
129 push @vals, '?';
130 push @binds, ($val eq '') ? undef : $val;
131 }
132 }
133 $$o{dbh}->do("INSERT INTO oq_saved_search (".join(',',@cols).") VALUES (".join(',',@vals).")", undef, @binds);
134 $rec{id} ||= $$o{dbh}->last_insert_id("","","","");
135 }
136
137 # ensure only one possible default saved search
138 eval {
139 if($$o{schema}{canSaveDefaultSearches} && $rec{is_default}) {
140 my $stmt = $$o{dbh}->prepare('UPDATE oq_saved_search SET is_default = 0 WHERE id <> ? AND uri = ?');
141 $stmt->execute($rec{id}, $rec{uri});
142 }
143 }; if($@) {}
144
145 $$o{output_handler}->(CGI::header('application/json').encode_json({ status => "ok", msg => "search saved successfully", id => $rec{id} }));
146 }; if ($@) {
147 my $err = $@;
148 $err =~ s/\ at\ .*//;
149  
150 if ($err =~ /unique\ constraint/i ||
151 $err =~ /duplicate\ entry/i ||
152 $err =~ /unique\_violation/i ||
153 $err =~ /unique\ key/i ||
154 $err =~ /duplicate\ key/i ||
155 $err =~ /constraint\_unique/i) {
156 $err = 'Another record with this name already exists.';
157 }
158  
159 $$o{output_handler}->(CGI::header('application/json').encode_json({ status => "error", msg => $err }));
160 }
161 return undef;
162 }
163 }
164  
165  
166 sub on_open {
167 my ($o) = @_;
168 my $buf;
169  
170 # if saved search alerts are enabled
171 if ($$o{schema}{savedSearchAlerts}) {
172 my $rec;
173 if ($$o{q}->param('OQss') ne '') {
174 $rec = $$o{dbh}->selectrow_hashref("SELECT USER_TITLE,ALERT_MASK,ALERT_INTERVAL_MIN,ALERT_DOW,ALERT_START_HOUR,ALERT_END_HOUR FROM oq_saved_search WHERE id=? AND user_id=?", undef, scalar($$o{q}->param('OQss')), $$o{schema}{savedSearchUserID});
175 }
176 $rec ||= {};
177 my $alerts_enabled = ($$rec{ALERT_MASK} > 0) ? 1 : 0;
178 $$rec{ALERT_MASK} ||= 1;
179 $$rec{ALERT_INTERVAL_MIN} ||= 1440;
180 $$rec{ALERT_DOW} ||= '12345';
181 $$rec{ALERT_START_HOUR} ||= 8;
182 $$rec{ALERT_END_HOUR} ||= 17;
183  
184 if ($$rec{ALERT_START_HOUR} > 12) {
185 $$rec{ALERT_START_HOUR} = ($$rec{ALERT_START_HOUR} - 12).'PM';
186 } else {
187 $$rec{ALERT_START_HOUR} .= 'AM';
188 }
189 if ($$rec{ALERT_END_HOUR} > 12) {
190 $$rec{ALERT_END_HOUR} = ($$rec{ALERT_END_HOUR} - 12).'PM';
191 } else {
192 $$rec{ALERT_END_HOUR} .= 'AM';
193 }
194  
195 $buf .= "
196 <label>name <input type=text id=OQsaveSearchTitle value='".$o->escape_html($$rec{USER_TITLE})."'></label>
197 <fieldset id=OQSaveReportEmailAlertOpts".($alerts_enabled?' class=opened':'').">
198 <legend><label class=ckbox style='width:12em;text-align:left;'><input type=checkbox id=OQalertenabled".($alerts_enabled?' checked':'')."> send email alert</label></legend>
199  
200 <p>
201 <label>when records are:</label>
202 <label><input type=checkbox name=OQalert_mask value=1".(($$rec{ALERT_MASK} & 1)?' checked':'')."> added</label>
203 <label><input type=checkbox name=OQalert_mask value=2".(($$rec{ALERT_MASK} & 2)?' checked':'')."> removed</label>
204 <label><input type=checkbox name=OQalert_mask value=4".(($$rec{ALERT_MASK} & 4)?' checked':'')."> present</label>
205
206 <p>
207 <label>check every: <input type=text id=OQalert_interval_min size=4 maxlength=6 value='".$o->escape_html($$rec{ALERT_INTERVAL_MIN})."'> minutes</label>
208 <small>(1440 min per day)</small>
209  
210 <p>
211 <label title='Specify which days to send the alert.'>on days:</label>
212 <label class=ckbox title=Sunday><input type=checkbox class=OQalert_dow value=0". ($$rec{ALERT_DOW}=~/0/?' checked':'').">S</label>
213 <label class=ckbox title=Monday><input type=checkbox class=OQalert_dow value=1". ($$rec{ALERT_DOW}=~/1/?' checked':'').">M</label>
214 <label class=ckbox title=Tuesday><input type=checkbox class=OQalert_dow value=2". ($$rec{ALERT_DOW}=~/2/?' checked':'').">T</label>
215 <label class=ckbox title=Wednesday><input type=checkbox class=OQalert_dow value=3".($$rec{ALERT_DOW}=~/3/?' checked':'').">W</label>
216 <label class=ckbox title=Thursday><input type=checkbox class=OQalert_dow value=4". ($$rec{ALERT_DOW}=~/4/?' checked':'').">T</label>
217 <label class=ckbox title=Friday><input type=checkbox class=OQalert_dow value=5". ($$rec{ALERT_DOW}=~/5/?' checked':'').">F</label>
218 <label class=ckbox title=Saturday><input type=checkbox class=OQalert_dow value=6". ($$rec{ALERT_DOW}=~/6/?' checked':'').">S</label>
219  
220 <p>
221 <label title='Specify start hour to sent an alert.'>from: <input type=text value='".$o->escape_html($$rec{ALERT_START_HOUR})."' size=4 maxlength=4 id=OQalert_start_hour placeholder=8AM></label> <label>to: <input type=text value='".$o->escape_html($$rec{ALERT_END_HOUR})."' size=4 maxlength=4 id=OQalert_end_hour placeholder=5PM></label>
222 <p><strong>Notice:</strong> This tool sends automatic alerts over insecure email. By creating an alert you acknowledge that the fields in the report will never contain sensitive data. Alerts are automatically disabled when the count exceeds $$o{schema}{savedSearchAlertMaxRecs}.</strong>
223 </fieldset>";
224 }
225 else {
226 my $rec;
227 if ($$o{q}->param('OQss') ne '') {
228 $rec = $$o{dbh}->selectrow_hashref("SELECT USER_TITLE FROM oq_saved_search WHERE id=? AND user_id=?", undef, scalar($$o{q}->param('OQss')), $$o{schema}{savedSearchUserID});
229 }
230 $rec ||= {};
231 $buf .= "
232 <label>name <input type=text id=OQsaveSearchTitle value='".$o->escape_html($$rec{USER_TITLE})."'></label>";
233 }
234  
235 # include checkbox to allow user to set saved search as the default settings
236 if($$o{schema}{canSaveDefaultSearches}) {
237 my ($is_default_ss) = $$o{dbh}->selectrow_array("SELECT is_default FROM oq_saved_search WHERE id=? AND user_id=?", undef, scalar($$o{q}->param('OQss')), $$o{schema}{savedSearchUserID});
238 $buf .= "<label class=ckbox style='margin-left:17px;width:12em;text-align:left;'><input title='Set the filter, sort, and shown columns in this reports as the system default for all users' type=checkbox value=1 id=OQsave_search_default".($is_default_ss ? ' checked' : '').">set as system default</label>";
239 }
240  
241 $buf .= "<p>";
242 $buf .= "<button type=button class=OQSaveNewReportBut>save as new</button>" if $$o{q}->param('OQss') ne '';
243 $buf .= "<button type=button class=OQSaveReportBut>save</button>";
244
245 return $buf;
246 }
247  
248 sub activate {
249 my ($o) = @_;
250 $$o{schema}{tools}{savereport} ||= {
251 title => "Save Report",
252 on_init => \&on_init,
253 on_open => \&on_open
254 };
255 }
256  
257  
258 # this function is called from a cron to help execute saved searches that have alerts that need to be checked
259 # Note: this custom output handler does not print anything as normal output handlers do.
260 # This output handler insteads updates the $current_saved_search
261 # it discovers which uids have been added, deleted, or are still present for a saved search.
262 # this information is then used by the [arent caller (execute_saved_search_alerts) to send out alert emails
263 sub custom_output_handler {
264 my ($o) = @_;
265 # verify that a proper email_to was defined
266 die "missing email_to" if $$current_saved_search{email_to} eq '';
267  
268 my %opts;
269 if (exists $$o{schema}{options}{__PACKAGE__}) {
270 %opts = %{$$o{schema}{options}{__PACKAGE__}};
271 } elsif (exists $$o{schema}{options}{'CGI::OptimalQuery::InteractiveQuery'}) {
272 %opts = %{$$o{schema}{options}{'CGI::OptimalQuery::InteractiveQuery'}};
273 }
274 my %noEsc = map { $_ => 1 } @{ $opts{noEscapeCol} };
275  
276  
277 # fetch all records in the report
278 # update the uids hash
279 # $$current_saved_search{uids}{<U_ID>} => 1-deleted, 2-seen before, 3-first time seen
280 # Before this block all values for previously seen uids are 1
281 # if the uid was previously seen and then seen again, we'll mark it with a 2
282 # if it was not previously seen, and we see it now, we'll mark it with a 3
283 # at the end of processing all previously found uids that weren't seen will still be marked 1
284 # which indicates the record is no longer within the report
285 my $cnt = 0;
286 my $dataTruc = 0;
287 my $row_cnt = 0;
288 my $buf;
289 { my $filter = $o->get_filter();
290 $buf .= "<p><strong>Query: </strong>"
291 .escapeHTML($$o{queryDescr}) if $$o{queryDescr};
292 $buf .= "<p><strong>Filter: </strong>"
293 .escapeHTML($filter) if $filter;
294 $buf .= "<p><table class=OQdata><thead><tr><td></td>";
295 foreach my $colAlias (@{ $o->get_usersel_cols }) {
296 my $colOpts = $$o{schema}{select}{$colAlias}[3];
297 $buf .= "<td>".escapeHTML($o->get_nice_name($colAlias))."</td>";
298 }
299 $buf .= "</tr></thead><tbody>";
300 }
301  
302 # remember state param vals that were used so we can provide a link to view the live data
303 if ($$o{schema}{state_params}) {
304 my $args;
305 foreach my $p (@{ $$o{schema}{state_params} }) {
306 my $v = $$o{q}->param($p);
307 $args .= '&'.$p.'='.$o->escape_uri($v) if $v;
308 }
309 $$current_saved_search{state_param_args} = $args;
310 }
311  
312 while (my $rec = $o->sth->fetchrow_hashref()) {
313 die "MAX_ROWS_EXCEEDED - your report contains too many rows to send alerts via email. Reduce the total row count of your report by adding additional filters." if ++$cnt > $$o{schema}{savedSearchAlertMaxRecs};
314 $opts{mutateRecord}->($rec) if ref($opts{mutateRecord}) eq 'CODE';
315  
316 # if this record has been seen before, mark it with a '2'
317 if (exists $$current_saved_search{uids}{$$rec{U_ID}}) {
318 $$current_saved_search{uids}{$$rec{U_ID}}=2;
319 }
320  
321 # if this record hasn't been seen before, mark it with a '3'
322 else {
323 $$current_saved_search{uids}{$$rec{U_ID}}=3;
324 }
325  
326 # if we need to output report
327 if (! $dataTruc && (
328 # output if when rows are present is checked
329 ($$current_saved_search{ALERT_MASK} & 4)
330 # output if when rows are added is checked AND this is a new row not seen before
331 || ($$current_saved_search{ALERT_MASK} & 1 && $$current_saved_search{uids}{$$rec{U_ID}}==3))) {
332  
333 $row_cnt++;
334  
335 # get open record link
336 my $link;
337 if (ref($opts{OQdataLCol}) eq 'CODE') {
338 $link = $opts{OQdataLCol}->($rec);
339 if ($link =~ /href\s*\=\s*\"?\'?([^\s\'\"\>]+)/i) {
340 $link = $1;
341 }
342 } elsif (ref($opts{buildEditLink}) eq 'CODE') {
343 $link = $opts{buildEditLink}->($o, $rec, \%opts);
344 } elsif ($opts{editLink} ne '' && $$rec{U_ID} ne '') {
345 $link = $opts{editLink}.(($opts{editLink} =~ /\?/)?'&':'?')."act=load&id=$$rec{U_ID}";
346 }
347 $buf .= "<tr";
348  
349 # if this record is first time visible
350 $buf .= " class=ftv" if $$current_saved_search{uids}{$$rec{U_ID}}==3;
351 $buf .= "><td>";
352 if ($link) {
353 if ($link !~ /^https?\:\/\//i) {
354 $link .= '/'.$link unless $link =~ /^\//;
355 $link = $$current_saved_search{opts}{base_url}.$link;
356 }
357 $buf .= "<a href='".escapeHTML($link)."'>open</a>";
358 }
359 $buf .= "</td>";
360 foreach my $col (@{ $o->get_usersel_cols }) {
361 my $val;
362 if (exists $noEsc{$col}) {
363 if (ref($$rec{$col}) eq 'ARRAY') {
364 $val = join(' ', @{ $$rec{$col} });
365 } else {
366 $val = $$rec{$col};
367 }
368 } elsif (ref($$rec{$col}) eq 'ARRAY') {
369 $val = join(', ', map { escapeHTML($_) } @{ $$rec{$col} });
370 } else {
371 $val = escapeHTML($$rec{$col});
372 }
373 $buf .= "<td>$val</td>";
374 }
375 $buf .= "</tr>\n";
376  
377 $dataTruc = 1 if length($buf) > $$o{schema}{savedSearchAlertEmailCharLimit};
378 }
379 }
380 $o->sth->finish();
381  
382 # if we found rows, encase it in a table with thead
383 if ($row_cnt > 0) {
384 $buf .= "</tbody></table>";
385 $buf .= "<p><strong>This report does not show all data found because the report exceeds the maximum limit. Reduce report size by hiding columns, adding additional filters, or only showing new records.</strong>" if $dataTruc;
386 $$current_saved_search{buf} = $buf;
387 }
388  
389  
390 return undef;
391 }
392  
393  
394 sub sendmail_handler {
395 my %email = @_;
396 $email{from} ||= ($ENV{USER}||'root').'@'.($ENV{HOSTNAME}||'localhost');
397 return Mail::Sendmail::sendmail(%email);
398 }
399  
400 sub get_sysdate_sql {
401 my ($dbh) = @_;
402 my $now;
403 if ($$dbh{Driver}{Name} eq 'Oracle') {
404 $now = 'SYSDATE';
405 } elsif ($$dbh{Driver}{Name} eq 'SQLite') {
406 $now = 'DATETIME()';
407 } elsif ($$dbh{Driver}{Name} eq 'mysql') {
408 $now = 'NOW()';
409 } elsif ($$dbh{Driver}{Name} eq 'Pg' || $$dbh{Driver}{Name} eq 'Microsoft SQL Server') {
410 $now = 'CURRENT_TIMESTAMP';
411 } else {
412 die "Driver: $$dbh{Driver}{Name} not yet supported. Please add support for this database";
413 }
414 return $now;
415 }
416  
417  
418 sub execute_saved_search_alerts {
419 my %opts = @_;
420 my $sendmail_handler = $opts{sendmail_handler} ||= \&sendmail_handler;
421  
422 if ($opts{base_url} =~ /^(https?\:\/\/[^\/]+)(.*)/i) {
423 $opts{server_url} = $1;
424 $opts{path_prefix} = $2;
425 } else {
426 die "invalid option base_url";
427 }
428 die "missing option handler" unless ref($opts{handler}) eq 'CODE';
429 my $dbh = $opts{dbh} or die "missing dbh";
430
431 $opts{error_handler} ||= sub {
432 my ($type, @msg) = @_;
433 my $dt = strftime "%F %T", localtime $^T;
434 my $msg = join(' ', $dt, lc($type), @msg)."\n";
435 if ($type =~ /^(err|debug)$/i) {
436 print STDERR $msg;
437 } else {
438 print $msg;
439 }
440 };
441  
442 $opts{error_handler}->("info", "execute_saved_search_alerts started");
443  
444 local $CGI::OptimalQuery::CustomOutput::custom_output_handler = \&custom_output_handler;
445  
446 my @dt = localtime;
447 my $dow = $dt[6];
448 my $hour = $dt[2];
449  
450 if ($$dbh{Driver}{Name} eq 'Oracle') {
451 $$dbh{LongReadLen} = 900000;
452 my ($readLen) = $dbh->selectrow_array("
453 SELECT GREATEST(
454 dbms_lob.getlength(params),
455 dbms_lob.getlength(alert_uids)
456 )
457 FROM oq_saved_search");
458 $$dbh{LongReadLen} = $readLen if $readLen > $$dbh{LongReadLen};
459 }
460  
461 # find all saved searches that need to be checked
462 my @recs;
463 { local $$dbh{FetchHashKeyName} = 'NAME_uc';
464 my @binds = ('%'.$dow.'%', $hour);
465 my $sql = "
466 SELECT *
467 FROM oq_saved_search
468 WHERE alert_dow LIKE ?
469 AND alert_mask > 0
470 AND ? BETWEEN alert_start_hour AND alert_end_hour";
471  
472 # only select if interval has been exceeded
473 if ($$dbh{Driver}{Name} eq 'Oracle') {
474 $sql .= "\nAND ((SYSDATE - alert_last_dt) * 24 * 60) > alert_interval_min";
475 }
476 elsif ($$dbh{Driver}{Name} eq 'SQLite') {
477 $sql .= "\nAND (strftime('%s','now') - strftime('%s',COALESCE(alert_last_dt,'2000-01-01'))) > alert_interval_min";
478 }
479 elsif ($$dbh{Driver}{Name} eq 'mysql') {
480 $sql .= "\nAND alert_last_dt <= DATE_SUB(NOW(), INTERVAL alert_interval_min MINUTE)";
481 }
482 elsif ($$dbh{Driver}{Name} eq 'Pg') {
483 $sql .= "\nAND ((CURRENT_TIMESTAMP - alert_last_dt) * 24 * 60) > alert_interval_min";
484 }
485 elsif ($$dbh{Driver}{Name} eq 'Microsoft SQL Server') {
486 $sql .= "\nAND DATEADD(minute, alert_interval_min, alert_last_dt) < CURRENT_TIMESTAMP";
487 }
488 else {
489 die "Driver: $$dbh{Driver}{Name} not yet supported. Please add support for this database";
490 }
491 $sql .= "\nORDER BY id";
492 my $sth = $dbh->prepare($sql);
493
494 $opts{error_handler}->("debug", "search for saved searches that need checked. BINDS: ".join(',', @binds)) if $opts{debug};
495 $sth->execute(@binds);
496 while (my $h = $sth->fetchrow_hashref()) { push @recs, $h; }
497 }
498  
499 $opts{error_handler}->("debug", "found ".scalar(@recs)." saved searches to execute") if $opts{debug};
500  
501 # for each saved search that has alerts which need to be checked
502 local $current_saved_search = undef;
503 while ($#recs > -1) {
504 my $rec = pop @recs;
505  
506 $current_saved_search = $rec;
507 my %uids = map { $_ => 1 } split /\~/, $$rec{ALERT_UIDS};
508 $$rec{opts} = \%opts;
509 $$rec{uids} = \%uids; # contains all the previously seen uids
510 $$rec{buf} = ''; # will be populated with a table containing report rows for a simple HTML email
511 $$rec{err_msg} = '';
512 $opts{error_handler}->("info", "executing saved search: $$rec{ID}");
513  
514 # configure CGI environment
515 # construct a query string
516 local $ENV{QUERY_STRING};
517 { my $p = eval '{'.$$rec{PARAMS}.'}';
518 $p = {} unless ref($p) eq 'HASH';
519 $$p{module} = 'CustomOutput'; # this will call our custom_output_handler function
520 $$p{page} = 1;
521 my @args;
522 while (my ($k,$v) = each %$p) {
523 if (ref($v) eq 'ARRAY') {
524 foreach my $v2 (@$v) {
525 push @args, "$k=".CGI::escape($v2);
526 }
527 } else {
528 push @args, "$k=".CGI::escape($v);
529 }
530 }
531 $ENV{QUERY_STRING} = join('&', @args);
532 }
533 local $ENV{REQUEST_METHOD} ||= 'GET';
534 local $ENV{REMOTE_ADDR} ||= '127.0.0.1';
535 local $ENV{SCRIPT_URL} = $$rec{URI};
536  
537 local $ENV{REQUEST_URI} = $$rec{URI};
538 $ENV{REQUEST_URI} .= '?'.$ENV{QUERY_STRING} if $ENV{QUERY_STRING};
539  
540 local $ENV{HTTP_HOST} ||= ($opts{base_url} =~ /https?\:\/\/([^\/]+)/) ? $1 : 'localhost';
541 local $ENV{SERVER_NAME} ||= $ENV{HTTP_HOST};
542 local $ENV{SCRIPT_URI} = $opts{base_url}.$ENV{REQUEST_URI};
543  
544 # The CGI library has some globals that need to be reset otherwise the previous params stick around
545 CGI::initialize_globals();
546  
547 # call app specific request bootstrap handler
548 # which will execute a CGI::OptimalQuery object somehow
549 # and populate $$rec{buf}, $$rec{uids}, $$rec{err_msg}
550 eval {
551 $opts{handler}->($rec);
552 die "email_to not defined" if $$rec{email_to} eq '';
553 $opts{error_handler}->("debug", "after OQ execution uids: ".Dumper(\%uids)) if $opts{debug};
554 };
555 if ($@) {
556 $$rec{err_msg} = $@;
557 $$rec{err_msg} =~ s/\ at\ .*//;
558 }
559  
560 my @update_uids;
561 # if there was an error processing saved search, send user an email
562 if ($$rec{err_msg}) {
563 $opts{error_handler}->("err", "Error: $@\n\nsaved search:\n".Dumper($rec)."\n\nENV:\n".Dumper(\%ENV)."\n\n");
564 if ($$rec{email_to}) {
565 my %email = (
566 to => $$rec{email_to},
567 from => $$rec{email_from} || $opts{email_from},
568 'Reply-To' => $$rec{'email_Reply-To'} || $opts{'email_Reply-To'},
569 subject => "Problem with email alert: $$rec{OQ_TITLE} - $$rec{USER_TITLE}",
570 body => "Your saved search alert encountered the following error:
571  
572 $$rec{err_msg}
573  
574 load report:
575 ".$opts{base_url}.$$rec{URI}.'?OQLoadSavedSearch='.$$rec{ID}.$$rec{state_param_args}."
576  
577 Please contact your administrator if you are unable to fix the problem."
578 );
579  
580 if ($opts{debug}) {
581 $opts{error_handler}->("debug", "debug sendmail (not sent): ".Dumper(\%email));
582 } else {
583 $opts{error_handler}->("info", "sending email to: $email{to}; subject: $email{subject}");
584 $sendmail_handler->(%email) or die "could not send email to: $$rec{email_to}";
585 }
586 }
587 }
588  
589 else {
590 my $total_new = 0;
591 my $total_deleted = 0;
592 my $total_count = 0;
593 while (my ($uid, $status) = each %uids) {
594 if ($status == 1) {
595 $total_deleted++;
596 }
597 else {
598 push @update_uids, $uid;
599 $total_count++;
600 if ($status == 3) {
601 $total_new++;
602 }
603 }
604 }
605 $opts{error_handler}->("info", "total_new: $total_new; total_deleted: $total_deleted; total_count: $total_count");
606  
607 my $should_send_email = 1 if
608 ( # alert when records are added
609 ($$rec{ALERT_MASK} & 1 && $total_new > 0) ||
610 # alert when records are deleted
611 ($$rec{ALERT_MASK} & 2 && $total_deleted > 0) ||
612 # alert when records are present
613 ($$rec{ALERT_MASK} & 4 && $total_count > 0)
614 );
615  
616 if ($should_send_email) {
617 my %email = (
618 to => $$rec{email_to},
619 from => $$rec{email_from} || $opts{email_from},
620 'Reply-To' => $$rec{'email_Reply-To'} || $opts{'email_Reply-To'},
621 subject => "$$rec{OQ_TITLE} - $$rec{USER_TITLE}",
622 'content-type' => 'text/html; charset="iso-8859-1"'
623 );
624 $email{subject} .= " ($total_new added)" if $total_new > 0;
625  
626 $email{body} =
627 "<html>
628 <head>
629 <title>".escapeHTML("$$rec{OQ_TITLE} - $$rec{USER_TITLE}")."</title>
630 <style>
631 .OQSSAlert * {
632 font-family: sans-serif;
633 }
634 .OQSSAlert h2 {
635 margin: 0;
636 font-size: 14px;
637 }
638 .OQSSAlert table {
639 border-collapse: collapse;
640 }
641 .OQSSAlert thead td {
642 font-weight: bold;
643 color: white;
644 background-color: #999;
645 }
646 .OQSSAlert td {
647 padding: 4px;
648 border: 1px solid #aaa;
649 font-size: 11px;
650 }
651 .OQSSAlert .ftv {
652 background-color: #E2FFE2;
653 }
654 .OQSSAlert p {
655 margin: .5em 0;
656 }
657 .OQSSAlert .ib {
658 display: inline-block;
659 margin-left: 6px;
660 padding: 6px;
661 }
662 </style>
663 </head>
664 <body>
665 <div class=OQSSAlert>
666 <h2>".escapeHTML("$$rec{OQ_TITLE} - $$rec{USER_TITLE}")."</h2>
667 <p>
668 $$rec{buf}
669 <p>
670 <span class=ib>total: $total_count</span>
671 <span class='ftv ib'>added: $total_new</span>
672 <span class=ib>removed: $total_deleted</span>
673 <p>
674 <a href='".escapeHTML($opts{base_url}.$$rec{URI}.'?OQLoadSavedSearch='.$$rec{ID}.$$rec{state_param_args})."'>load report</a>
675 </div>
676 </body>
677 </html>";
678  
679 if ($opts{debug}) {
680 $opts{error_handler}->("debug", "debug sendmail (not sent): ".Dumper(\%email));
681 } else {
682 $opts{error_handler}->("info", "sending email to: $email{to}; subject: $email{subject}");
683 $sendmail_handler->(%email) or die "could not send email to: $$rec{email_to}";
684 }
685 }
686 }
687  
688 # update database
689 my $update_uids = join('~', sort @update_uids);
690 $update_uids = undef if $update_uids eq '';
691 $$rec{err_msg} = undef if $$rec{err_msg} eq '';
692 my @binds = ($$rec{err_msg});
693 my $now = get_sysdate_sql($dbh);
694  
695 my $sql = "UPDATE oq_saved_search SET alert_last_dt=$now, alert_err=?";
696 if ($update_uids ne $$rec{ALERT_UIDS}) {
697 $sql .= ", alert_uids=?";
698 push @binds, $update_uids;
699 }
700 $sql .= " WHERE id=?";
701 push @binds, $$rec{ID};
702 $opts{error_handler}->("debug", "SQL: $sql\nBINDS: ".join(',', @binds)) if $opts{debug};
703 my $sth = $dbh->prepare_cached($sql);
704 $sth->execute(@binds);
705  
706 $current_saved_search = undef;
707 }
708  
709 $opts{error_handler}->("info", "execute_saved_search_alerts done");
710 }
711  
712  
713 # helper function to execute a script. called from with execute_saved_search_alerts from perl script
714 my %COMPILED_FUNCS;
715 sub execute_script {
716 my ($fn) = @_;
717 if (! exists $COMPILED_FUNCS{$fn}) {
718 open my $fh, "<", $fn or die "can't read file $fn; $!";
719 local $/=undef;
720 my $code = 'sub { '.scalar(<$fh>). ' }';
721 $COMPILED_FUNCS{$fn} = eval $code;
722 die "could not compile $fn; $@" if $@;
723 }
724 $COMPILED_FUNCS{$fn}->();
725 return undef;
726 }
727  
728 sub execute_handler {
729 my ($pack, $func) = @_;
730 $func ||= 'handler';
731 my $rv = eval "require $pack";
732 die "NOT_FOUND - $@" if $@ =~ /Can\'t locate/;
733 die "COMPILE_ERROR - $@" if $@;
734 die "COMPILE_ERROR - module must end with true value" unless $rv == 1;
735 my $codeRef = $pack->can($func);
736 die "MISSING_HANDLER - could not find ".$pack.'::'.$func unless $codeRef;
737 return $codeRef->();
738 }
739 1;