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

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