3
# ==========================================================================
5
# ZoneMinder Event Filter Script, $Date: 2009-06-08 10:11:56 +0100 (Mon, 08 Jun 2009) $, $Revision: 2908 $
6
# Copyright (C) 2001-2008 Philip Coombes
8
# This program is free software; you can redistribute it and/or
9
# modify it under the terms of the GNU General Public License
10
# as published by the Free Software Foundation; either version 2
11
# of the License, or (at your option) any later version.
13
# This program is distributed in the hope that it will be useful,
14
# but WITHOUT ANY WARRANTY; without even the implied warranty of
15
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
# GNU General Public License for more details.
18
# You should have received a copy of the GNU General Public License
19
# along with this program; if not, write to the Free Software
20
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22
# ==========================================================================
24
# This script continuously monitors the recorded events for the given
25
# monitor and applies any filters which would delete and/or upload
31
# ==========================================================================
33
# These are the elements you can edit to suit your installation
35
# ==========================================================================
37
use constant DBG_ID => "zmfilter"; # Tag that appears in debug to identify source
38
use constant DBG_LEVEL => 0; # 0 is errors, warnings and info only, > 0 for debug
40
use constant START_DELAY => 5; # How long to wait before starting
42
# ==========================================================================
44
# You shouldn't need to change anything from here downwards
46
# ==========================================================================
52
use Time::HiRes qw/gettimeofday/;
55
use PHP::Serialization qw(serialize unserialize);
58
use constant EVENT_PATH => ZM_PATH_WEB.'/'.ZM_DIR_EVENTS;
60
zmDbgInit( DBG_ID, level=>DBG_LEVEL );
65
# Comment these out if you don't have them and don't want to upload
66
# or don't want to use that format
67
if ( ZM_UPLOAD_ARCH_FORMAT eq "zip" )
70
import Archive::Zip qw( :ERROR_CODES :CONSTANTS );
81
if ( ZM_NEW_MAIL_MODULES )
94
if ( ZM_NEW_MAIL_MODULES )
101
require MIME::Entity;
108
$ENV{PATH} = '/bin:/usr/bin';
109
$ENV{SHELL} = '/bin/sh' if exists $ENV{SHELL};
110
delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
112
my $delay = ZM_FILTER_EXECUTE_INTERVAL;
114
my $filter_parm = "";
119
Usage: zmfilter.pl [-f <filter name>,--filter=<filter name>]
121
-f<filter name>, --filter=<filter name> - The name of a specific filter to run
127
# More or less replicates the equivalent PHP function
132
return( UnixDate( $dt_str, '%s' ) );
136
# More or less replicates the equivalent PHP function
142
return( ${string}x${count} );
145
# Formats a date into MySQL format
149
my $dt_val = strtotime( $dt_str );
152
Error( "Unable to parse date string '$dt_str'\n" );
155
return( strftime( "%Y-%m-%d %H:%M:%S", localtime( $dt_val ) ) );
158
if ( !GetOptions( 'filter=s'=>\$filter_parm ) )
165
my $dbh = zmDbConnect();
169
Info( "Scanning for events using filter '$filter_parm'\n" );
173
Info( "Scanning for events\n" );
178
sleep( START_DELAY );
186
if ( (time() - $last_action) > ZM_FILTER_RELOAD_DELAY )
188
Debug( "Reloading filters\n" );
189
$last_action = time();
190
$filters = getFilters( $filter_parm );
193
foreach my $filter ( @$filters )
195
checkFilter( $filter );
198
last if ( $filter_parm );
200
Debug( "Sleeping for $delay seconds\n" );
206
my $command = "df .";
207
my $df = qx( $command );
209
if ( $df =~ /\s(\d+)%/ms )
218
my $command = "df .";
219
my $df = qx( $command );
221
if ( $df =~ /\s(\d+)\s+\d+\s+\d+%/ms )
230
my $command = "uptime .";
231
my $uptime = qx( $command );
233
if ( $uptime =~ /load average:\s+([\d.]+)/ms )
236
Info( "Load: $load" );
243
my $filter_name = shift;
246
my $sql = "select * from Filters where";
249
$sql .= " Name = ? and";
253
$sql .= " Background = 1 and";
255
$sql .= " (AutoArchive = 1 or AutoVideo = 1 or AutoUpload = 1 or AutoEmail = 1 or AutoMessage = 1 or AutoExecute = 1 or AutoDelete = 1) order by Name";
256
my $sth = $dbh->prepare_cached( $sql ) or Fatal( "Can't prepare '$sql': ".$dbh->errstr() );
260
$res = $sth->execute( $filter_name ) or Fatal( "Can't execute '$sql': ".$sth->errstr() );
264
$res = $sth->execute() or Fatal( "Can't execute '$sql': ".$sth->errstr() );
266
FILTER: while( my $db_filter = $sth->fetchrow_hashref() )
268
Debug( "Found filter '$db_filter->{Name}'\n" );
269
my $filter_expr = unserialize( $db_filter->{Query} );
270
my $sql = "select E.Id,E.MonitorId,M.Name as MonitorName,M.DefaultRate,M.DefaultScale,E.Name,E.Cause,E.Notes,E.StartTime,unix_timestamp(E.StartTime) as Time,E.Length,E.Frames,E.AlarmFrames,E.TotScore,E.AvgScore,E.MaxScore,E.Archived,E.Videoed,E.Uploaded,E.Emailed,E.Messaged,E.Executed from Events as E inner join Monitors as M on M.Id = E.MonitorId where not isnull(E.EndTime)";
271
$db_filter->{Sql} = '';
273
if ( @{$filter_expr->{terms}} )
275
for ( my $i = 0; $i < @{$filter_expr->{terms}}; $i++ )
277
if ( exists($filter_expr->{terms}[$i]->{cnj}) )
279
$db_filter->{Sql} .= " ".$filter_expr->{terms}[$i]->{cnj}." ";
281
if ( exists($filter_expr->{terms}[$i]->{obr}) )
283
$db_filter->{Sql} .= " ".str_repeat( "(", $filter_expr->{terms}[$i]->{obr} )." ";
285
my $value = $filter_expr->{terms}[$i]->{val};
287
if ( $filter_expr->{terms}[$i]->{attr} )
289
if ( $filter_expr->{terms}[$i]->{attr} =~ /^Monitor/ )
291
my ( $temp_attr_name ) = $filter_expr->{terms}[$i]->{attr} =~ /^Monitor(.+)$/;
292
$db_filter->{Sql} .= "M.".$temp_attr_name;
294
elsif ( $filter_expr->{terms}[$i]->{attr} eq 'DateTime' )
296
$db_filter->{Sql} .= "E.StartTime";
298
elsif ( $filter_expr->{terms}[$i]->{attr} eq 'Date' )
300
$db_filter->{Sql} .= "to_days( E.StartTime )";
302
elsif ( $filter_expr->{terms}[$i]->{attr} eq 'Time' )
304
$db_filter->{Sql} .= "extract( hour_second from E.StartTime )";
306
elsif ( $filter_expr->{terms}[$i]->{attr} eq 'Weekday' )
308
$db_filter->{Sql} .= "weekday( E.StartTime )";
310
elsif ( $filter_expr->{terms}[$i]->{attr} eq 'DiskPercent' )
312
$db_filter->{Sql} .= "zmDiskPercent";
313
$db_filter->{HasDiskPercent} = !undef;
315
elsif ( $filter_expr->{terms}[$i]->{attr} eq 'DiskBlocks' )
317
$db_filter->{Sql} .= "zmDiskBlocks";
318
$db_filter->{HasDiskBlocks} = !undef;
320
elsif ( $filter_expr->{terms}[$i]->{attr} eq 'SystemLoad' )
322
$db_filter->{Sql} .= "zmSystemLoad";
323
$db_filter->{HasSystemLoad} = !undef;
327
$db_filter->{Sql} .= "E.".$filter_expr->{terms}[$i]->{attr};
330
( my $stripped_value = $value ) =~ s/^["\']+?(.+)["\']+?$/$1/;
331
foreach my $temp_value ( split( '/["\'\s]*?,["\'\s]*?/', $stripped_value ) )
333
if ( $filter_expr->{terms}[$i]->{attr} =~ /^Monitor/ )
335
$value = "'$temp_value'";
337
elsif ( $filter_expr->{terms}[$i]->{attr} eq 'Name' || $filter_expr->{terms}[$i]->{attr} eq 'Cause' || $filter_expr->{terms}[$i]->{attr} eq 'Notes' )
339
$value = "'$temp_value'";
341
elsif ( $filter_expr->{terms}[$i]->{attr} eq 'DateTime' )
343
$value = DateTimeToSQL( $temp_value );
346
Error( "Error parsing date/time '$temp_value', skipping filter '$db_filter->{Name}'\n" );
351
elsif ( $filter_expr->{terms}[$i]->{attr} eq 'Date' )
353
$value = DateTimeToSQL( $temp_value );
356
Error( "Error parsing date/time '$temp_value', skipping filter '$db_filter->{Name}'\n" );
359
$value = "to_days( '$value' )";
361
elsif ( $filter_expr->{terms}[$i]->{attr} eq 'Time' )
363
$value = DateTimeToSQL( $temp_value );
366
Error( "Error parsing date/time '$temp_value', skipping filter '$db_filter->{Name}'\n" );
369
$value = "extract( hour_second from '$value' )";
373
$value = $temp_value;
375
push( @value_list, $value );
378
if ( $filter_expr->{terms}[$i]->{op} )
380
if ( $filter_expr->{terms}[$i]->{op} eq '=~' )
382
$db_filter->{Sql} .= " regexp $value";
384
elsif ( $filter_expr->{terms}[$i]->{op} eq '!~' )
386
$db_filter->{Sql} .= " not regexp $value";
388
elsif ( $filter_expr->{terms}[$i]->{op} eq '=[]' )
390
$db_filter->{Sql} .= " in (".join( ",", @value_list ).")";
392
elsif ( $filter_expr->{terms}[$i]->{op} eq '!~' )
394
$db_filter->{Sql} .= " not in (".join( ",", @value_list ).")";
398
$db_filter->{Sql} .= " ".$filter_expr->{terms}[$i]->{op}." $value";
401
if ( exists($filter_expr->{terms}[$i]->{cbr}) )
403
$db_filter->{Sql} .= " ".str_repeat( ")", $filter_expr->{terms}[$i]->{cbr} )." ";
407
if ( $db_filter->{Sql} )
409
$sql .= " and ( ".$db_filter->{Sql}." )";
412
if ( $db_filter->{AutoArchive} )
414
push( @auto_terms, "E.Archived = 0" )
416
if ( $db_filter->{AutoVideo} )
418
push( @auto_terms, "E.Videoed = 0" )
420
if ( $db_filter->{AutoUpload} )
422
push( @auto_terms, "E.Uploaded = 0" )
424
if ( $db_filter->{AutoEmail} )
426
push( @auto_terms, "E.Emailed = 0" )
428
if ( $db_filter->{AutoMessage} )
430
push( @auto_terms, "E.Messaged = 0" )
432
if ( $db_filter->{AutoExecute} )
434
push( @auto_terms, "E.Executed = 0" )
438
$sql .= " and ( ".join( " or ", @auto_terms )." )";
440
if ( !$filter_expr->{sort_field} )
442
$filter_expr->{sort_field} = 'StartTime';
443
$filter_expr->{sort_asc} = 0;
445
my $sort_column = '';
446
if ( $filter_expr->{sort_field} eq 'Id' )
448
$sort_column = "E.Id";
450
elsif ( $filter_expr->{sort_field} eq 'MonitorName' )
452
$sort_column = "M.Name";
454
elsif ( $filter_expr->{sort_field} eq 'Name' )
456
$sort_column = "E.Name";
458
elsif ( $filter_expr->{sort_field} eq 'StartTime' )
460
$sort_column = "E.StartTime";
462
elsif ( $filter_expr->{sort_field} eq 'Secs' )
464
$sort_column = "E.Length";
466
elsif ( $filter_expr->{sort_field} eq 'Frames' )
468
$sort_column = "E.Frames";
470
elsif ( $filter_expr->{sort_field} eq 'AlarmFrames' )
472
$sort_column = "E.AlarmFrames";
474
elsif ( $filter_expr->{sort_field} eq 'TotScore' )
476
$sort_column = "E.TotScore";
478
elsif ( $filter_expr->{sort_field} eq 'AvgScore' )
480
$sort_column = "E.AvgScore";
482
elsif ( $filter_expr->{sort_field} eq 'MaxScore' )
484
$sort_column = "E.MaxScore";
488
$sort_column = "E.StartTime";
490
my $sort_order = $filter_expr->{sort_asc}?"asc":"desc";
491
$sql .= " order by ".$sort_column." ".$sort_order;
492
if ( $filter_expr->{limit} )
494
$sql .= " limit 0,".$filter_expr->{limit};
496
Debug( "SQL:$sql\n" );
497
$db_filter->{Sql} = $sql;
498
if ( $db_filter->{AutoExecute} )
500
my $script = $db_filter->{AutoExecuteCmd};
501
$script =~ s/\s.*$//;
504
Error( "Auto execute script '$script' not found, skipping filter '$db_filter->{Name}'\n" );
508
elsif ( !-x $script )
510
Error( "Auto execute script '$script' not executable, skipping filter '$db_filter->{Name}'\n" );
514
push( @filters, $db_filter );
525
Debug( "Checking filter '$filter->{Name}'".
526
($filter->{AutoDelete}?", delete":"").
527
($filter->{AutoArchive}?", archive":"").
528
($filter->{AutoVideo}?", video":"").
529
($filter->{AutoUpload}?", upload":"").
530
($filter->{AutoEmail}?", email":"").
531
($filter->{AutoMessage}?", message":"").
532
($filter->{AutoExecute}?", execute":"").
535
my $sql = $filter->{Sql};
537
if ( $filter->{HasDiskPercent} )
539
my $disk_percent = getDiskPercent();
540
$sql =~ s/zmDiskPercent/$disk_percent/g;
542
if ( $filter->{HasDiskBlocks} )
544
my $disk_blocks = getDiskBlocks();
545
$sql =~ s/zmDiskBlocks/$disk_blocks/g;
547
if ( $filter->{HasSystemLoad} )
549
my $load = getLoad();
550
$sql =~ s/zmSystemLoad/$load/g;
553
my $sth = $dbh->prepare_cached( $sql ) or Fatal( "Can't prepare '$sql': ".$dbh->errstr() );
554
my $res = $sth->execute();
557
Error( "Can't execute filter '$sql', ignoring: ".$sth->errstr() );
561
while( my $event = $sth->fetchrow_hashref() )
563
Debug( "Checking event $event->{Id}\n" );
564
my $delete_ok = !undef;
565
if ( $filter->{AutoArchive} )
567
Info( "Archiving event $event->{Id}\n" );
568
# Do it individually to avoid locking up the table for new events
569
my $sql = "update Events set Archived = 1 where Id = ?";
570
my $sth = $dbh->prepare_cached( $sql ) or Fatal( "Can't prepare '$sql': ".$dbh->errstr() );
571
my $res = $sth->execute( $event->{Id} ) or Fatal( "Can't execute '$sql': ".$sth->errstr() );
573
if ( ZM_OPT_FFMPEG && $filter->{AutoVideo} )
575
if ( !$event->{Videoed} )
577
$delete_ok = undef if ( !generateVideo( $filter, $event ) );
580
if ( ZM_OPT_EMAIL && $filter->{AutoEmail} )
582
if ( !$event->{Emailed} )
584
$delete_ok = undef if ( !sendEmail( $filter, $event ) );
587
if ( ZM_OPT_MESSAGE && $filter->{AutoMessage} )
589
if ( !$event->{Messaged} )
591
$delete_ok = undef if ( !sendMessage( $filter, $event ) );
594
if ( ZM_OPT_UPLOAD && $filter->{AutoUpload} )
596
if ( !$event->{Uploaded} )
598
$delete_ok = undef if ( !uploadArchFile( $filter, $event ) );
601
if ( $filter->{AutoExecute} )
603
if ( !$event->{Execute} )
605
$delete_ok = undef if ( !executeCommand( $filter, $event ) );
608
if ( $filter->{AutoDelete} )
612
Info( "Deleting event $event->{Id}\n" );
613
# Do it individually to avoid locking up the table for new events
614
my $sql = "delete from Events where Id = ?";
615
my $sth = $dbh->prepare_cached( $sql ) or Fatal( "Can't prepare '$sql': ".$dbh->errstr() );
616
my $res = $sth->execute( $event->{Id} ) or Fatal( "Can't execute '$sql': ".$sth->errstr() );
618
if ( !ZM_OPT_FAST_DELETE )
620
my $sql = "delete from Frames where EventId = ?";
621
my $sth = $dbh->prepare_cached( $sql ) or Fatal( "Can't prepare '$sql': ".$dbh->errstr() );
622
my $res = $sth->execute( $event->{Id} ) or Fatal( "Can't execute '$sql': ".$sth->errstr() );
624
$sql = "delete from Stats where EventId = ?";
625
$sth = $dbh->prepare_cached( $sql ) or Fatal( "Can't prepare '$sql': ".$dbh->errstr() );
626
$res = $sth->execute( $event->{Id} ) or Fatal( "Can't execute '$sql': ".$sth->errstr() );
628
deleteEventFiles( $event->{Id}, $event->{MonitorId} );
633
Error( "Unable to delete event $event->{Id} as previous operations failed\n" );
646
my $rate = $event->{DefaultRate}/100;
647
my $scale = $event->{DefaultScale}/100;
650
my @ffmpeg_formats = split( /\s+/, ZM_FFMPEG_FORMATS );
651
my $default_video_format;
652
my $default_phone_format;
653
foreach my $ffmpeg_format( @ffmpeg_formats )
655
if ( $ffmpeg_format =~ /^(.+)\*\*$/ )
657
$default_phone_format = $1;
659
elsif ( $ffmpeg_format =~ /^(.+)\*$/ )
661
$default_video_format = $1;
665
if ( $phone && $default_phone_format )
667
$format = $default_phone_format;
669
elsif ( $default_video_format )
671
$format = $default_video_format;
675
$format = $ffmpeg_formats[0];
678
my $command = ZM_PATH_BIN."/zmvideo.pl -e ".$event->{Id}." -r ".$rate." -s ".$scale." -f ".$format;
679
my $output = qx($command);
681
my $status = $? >> 8;
682
if ( $status || DBG_LEVEL > 0 )
684
Debug( "Output: $output\n" );
688
Error( "Video generation '$command' failed with status: $status\n" );
691
return( undef, undef );
697
my $sql = "update Events set Videoed = 1 where Id = ?";
698
my $sth = $dbh->prepare_cached( $sql ) or Fatal( "Can't prepare '$sql': ".$dbh->errstr() );
699
my $res = $sth->execute( $event->{Id} ) or Fatal( "Can't execute '$sql': ".$sth->errstr() );
702
return( $format, sprintf( "%s/%s", getEventPath( $event ), $output ) );
713
if ( !ZM_UPLOAD_FTP_HOST )
715
Error( "Cannot upload archive as no FTP host defined" );
719
my $arch_file = ZM_UPLOAD_FTP_LOC_DIR.'/'.$event->{MonitorName}.'-'.$event->{Id};
720
my $arch_image_path = getEventPath( $event )."/".((ZM_UPLOAD_ARCH_ANALYSE)?'{*analyse,*capture}':'*capture').".jpg";
721
my @arch_image_files = glob($arch_image_path);
724
if ( ZM_UPLOAD_ARCH_FORMAT eq "zip" )
726
$arch_file .= '.zip';
727
my $zip = Archive::Zip->new();
728
Info( "Creating upload file '$arch_file', ".int(@arch_image_files)." files\n" );
731
foreach my $image_file ( @arch_image_files )
733
Info( "Adding $image_file\n" );
734
my $member = $zip->addFile( $image_file );
735
last unless ( $member );
736
$member->desiredCompressionMethod( (ZM_UPLOAD_ARCH_COMPRESS)?&COMPRESSION_DEFLATED:&COMPRESSION_STORED );
738
$status = $zip->writeToFileNamed( $arch_file );
740
if ( $arch_error = ($status != &AZ_OK) )
742
Error( "Zip error: $status\n " );
745
elsif ( ZM_UPLOAD_ARCH_FORMAT eq "tar" )
747
if ( ZM_UPLOAD_ARCH_COMPRESS )
749
$arch_file .= '.tar.gz';
753
$arch_file .= '.tar';
755
Info( "Creating upload file '$arch_file', ".int(@arch_image_files)." files\n" );
757
if ( $arch_error = !Archive::Tar->create_archive( $arch_file, ZM_UPLOAD_ARCH_COMPRESS, @arch_image_files ) )
759
Error( "Tar error: ".Archive::Tar->error()."\n " );
769
Info( "Uploading to ".ZM_UPLOAD_FTP_HOST."\n" );
770
my $ftp = Net::FTP->new( ZM_UPLOAD_FTP_HOST, Timeout=>ZM_UPLOAD_FTP_TIMEOUT, Passive=>ZM_UPLOAD_FTP_PASSIVE, Debug=>ZM_UPLOAD_FTP_DEBUG );
773
warn( "Can't create ftp connection: $@" );
777
$ftp->login( ZM_UPLOAD_FTP_USER, ZM_UPLOAD_FTP_PASS ) or warn( "FTP - Can't login" );
778
$ftp->binary() or warn( "FTP - Can't go binary" );
779
$ftp->cwd( ZM_UPLOAD_FTP_REM_DIR ) or warn( "FTP - Can't cwd" );
780
$ftp->put( $arch_file ) or warn( "FTP - Can't upload '$arch_file'" );
781
$ftp->quit() or warn( "FTP - Can't quit" );
782
unlink( $arch_file );
783
my $sql = "update Events set Uploaded = 1 where Id = ?";
784
my $sth = $dbh->prepare_cached( $sql ) or Fatal( "Can't prepare '$sql': ".$dbh->errstr() );
785
my $res = $sth->execute( $event->{Id} ) or Fatal( "Can't execute '$sql': ".$sth->errstr() );
795
my $attachments_ref = shift;
797
# First we'd better check what we need to get
798
# We have a filter and an event, do we need any more
799
# monitor information?
800
my $need_monitor = $text =~ /%(?:MET|MEH|MED|MEW|MEN|MEA)%/;
805
my $db_now = strftime( "%Y-%m-%d %H:%M:%S", localtime() );
806
my $sql = "select M.Id, count(E.Id) as EventCount, count(if(E.Archived,1,NULL)) as ArchEventCount, count(if(E.StartTime>'$db_now' - INTERVAL 1 HOUR && E.Archived = 0,1,NULL)) as HourEventCount, count(if(E.StartTime>'$db_now' - INTERVAL 1 DAY && E.Archived = 0,1,NULL)) as DayEventCount, count(if(E.StartTime>'$db_now' - INTERVAL 7 DAY && E.Archived = 0,1,NULL)) as WeekEventCount, count(if(E.StartTime>'$db_now' - INTERVAL 1 MONTH && E.Archived = 0,1,NULL)) as MonthEventCount from Monitors as M left join Events as E on E.MonitorId = M.Id where MonitorId = ? group by E.MonitorId order by Id";
807
my $sth = $dbh->prepare_cached( $sql ) or Fatal( "Can't prepare '$sql': ".$dbh->errstr() );
808
my $res = $sth->execute( $event->{MonitorId} ) or Fatal( "Can't execute '$sql': ".$sth->errstr() );
809
$monitor = $sth->fetchrow_hashref();
811
return() if ( !$monitor );
814
# Do we need the image information too?
815
my $need_images = $text =~ /%(?:EPI1|EPIM|EI1|EIM)%/;
816
my $first_alarm_frame;
818
my $max_alarm_score = 0;
821
my $sql = "select * from Frames where EventId = ? and Type = 'Alarm' order by FrameId";
822
my $sth = $dbh->prepare_cached( $sql ) or Fatal( "Can't prepare '$sql': ".$dbh->errstr() );
823
my $res = $sth->execute( $event->{Id} ) or Fatal( "Can't execute '$sql': ".$sth->errstr() );
824
while( my $frame = $sth->fetchrow_hashref() )
826
if ( !$first_alarm_frame )
828
$first_alarm_frame = $frame;
830
if ( $frame->{Score} > $max_alarm_score )
832
$max_alarm_frame = $frame;
833
$max_alarm_score = $frame->{Score};
840
$text =~ s/%ZP%/$url/g;
841
$text =~ s/%MN%/$event->{MonitorName}/g;
842
$text =~ s/%MET%/$monitor->{EventCount}/g;
843
$text =~ s/%MEH%/$monitor->{HourEventCount}/g;
844
$text =~ s/%MED%/$monitor->{DayEventCount}/g;
845
$text =~ s/%MEW%/$monitor->{WeekEventCount}/g;
846
$text =~ s/%MEM%/$monitor->{MonthEventCount}/g;
847
$text =~ s/%MEA%/$monitor->{ArchEventCount}/g;
848
$text =~ s/%MP%/$url?view=watch&mid=$event->{MonitorId}/g;
849
$text =~ s/%MPS%/$url?view=watchfeed&mid=$event->{MonitorId}&mode=stream/g;
850
$text =~ s/%MPI%/$url?view=watchfeed&mid=$event->{MonitorId}&mode=still/g;
851
$text =~ s/%EP%/$url?view=event&mid=$event->{MonitorId}&eid=$event->{Id}/g;
852
$text =~ s/%EPS%/$url?view=event&mode=stream&mid=$event->{MonitorId}&eid=$event->{Id}/g;
853
$text =~ s/%EPI%/$url?view=event&mode=still&mid=$event->{MonitorId}&eid=$event->{Id}/g;
854
$text =~ s/%EI%/$event->{Id}/g;
855
$text =~ s/%EN%/$event->{Name}/g;
856
$text =~ s/%EC%/$event->{Cause}/g;
857
$text =~ s/%ED%/$event->{Notes}/g;
858
$text =~ s/%ET%/$event->{StartTime}/g;
859
$text =~ s/%EL%/$event->{Length}/g;
860
$text =~ s/%EF%/$event->{Frames}/g;
861
$text =~ s/%EFA%/$event->{AlarmFrames}/g;
862
$text =~ s/%EST%/$event->{TotScore}/g;
863
$text =~ s/%ESA%/$event->{AvgScore}/g;
864
$text =~ s/%ESM%/$event->{MaxScore}/g;
865
if ( $first_alarm_frame )
867
$text =~ s/%EPI1%/$url?view=frame&mid=$event->{MonitorId}&eid=$event->{Id}&fid=$first_alarm_frame->{FrameId}/g;
868
$text =~ s/%EPIM%/$url?view=frame&mid=$event->{MonitorId}&eid=$event->{Id}&fid=$max_alarm_frame->{FrameId}/g;
869
if ( $attachments_ref && $text =~ s/%EI1%//g )
871
push( @$attachments_ref, { type=>"image/jpeg", path=>sprintf( "%s/%0".ZM_EVENT_IMAGE_DIGITS."d-capture.jpg", getEventPath( $event ), $first_alarm_frame->{FrameId} ) } );
873
if ( $attachments_ref && $text =~ s/%EIM%//g )
875
# Don't attach the same image twice
876
if ( !@$attachments_ref || ($first_alarm_frame->{FrameId} != $max_alarm_frame->{FrameId} ) )
878
push( @$attachments_ref, { type=>"image/jpeg", path=>sprintf( "%s/%0".ZM_EVENT_IMAGE_DIGITS."d-capture.jpg", getEventPath( $event ), $max_alarm_frame->{FrameId} ) } );
882
if ( $attachments_ref && ZM_OPT_FFMPEG )
884
if ( $text =~ s/%EV%//g )
886
my ( $format, $path ) = generateVideo( $filter, $event );
891
push( @$attachments_ref, { type=>"video/$format", path=>$path } );
893
if ( $text =~ s/%EVM%//g )
895
my ( $format, $path ) = generateVideo( $filter, $event, 1 );
900
push( @$attachments_ref, { type=>"video/$format", path=>$path } );
903
$text =~ s/%FN%/$filter->{Name}/g;
904
( my $filter_name = $filter->{Name} ) =~ s/ /+/g;
905
$text =~ s/%FP%/$url?view=filter&mid=$event->{MonitorId}&filter_name=$filter_name/g;
915
if ( !ZM_FROM_EMAIL )
917
warn( "No 'from' email address defined, not sending email" );
920
if ( !ZM_EMAIL_ADDRESS )
922
warn( "No email address defined, not sending email" );
926
Info( "Creating notification email\n" );
928
my $subject = substituteTags( ZM_EMAIL_SUBJECT, $filter, $event );
929
return( 0 ) if ( !$subject );
931
my $body = substituteTags( ZM_EMAIL_BODY, $filter, $event, \@attachments );
932
return( 0 ) if ( !$body );
934
Info( "Sending notification email '$subject'\n" );
938
if ( ZM_NEW_MAIL_MODULES )
940
### Create the multipart container
941
my $mail = MIME::Lite->new (
942
From => ZM_FROM_EMAIL,
943
To => ZM_EMAIL_ADDRESS,
945
Type => "multipart/mixed"
947
### Add the text message part
952
### Add the attachments
953
foreach my $attachment ( @attachments )
955
Info( "Attaching '$attachment->{path}\n" );
957
Path => $attachment->{path},
958
Type => $attachment->{type},
959
Disposition => "attachment"
963
MIME::Lite->send( "smtp", ZM_EMAIL_HOST, Timeout=>60 );
968
my $mail = MIME::Entity->build(
969
From => ZM_FROM_EMAIL,
970
To => ZM_EMAIL_ADDRESS,
972
Type => (($body=~/<html>/)?'text/html':'text/plain'),
976
foreach my $attachment ( @attachments )
978
Info( "Attaching '$attachment->{path}\n" );
980
Path => $attachment->{path},
981
Type => $attachment->{type},
985
$mail->smtpsend( Host => ZM_EMAIL_HOST, MailFrom => ZM_FROM_EMAIL );
990
warn( "Can't send email: $@" );
995
Info( "Notification email sent\n" );
997
my $sql = "update Events set Emailed = 1 where Id = ?";
998
my $sth = $dbh->prepare_cached( $sql ) or Fatal( "Can't prepare '$sql': ".$dbh->errstr() );
999
my $res = $sth->execute( $event->{Id} ) or Fatal( "Can't execute '$sql': ".$sth->errstr() );
1009
if ( !ZM_FROM_EMAIL )
1011
warn( "No 'from' email address defined, not sending message" );
1014
if ( !ZM_MESSAGE_ADDRESS )
1016
warn( "No message address defined, not sending message" );
1020
Info( "Creating notification message\n" );
1022
my $subject = substituteTags( ZM_MESSAGE_SUBJECT, $filter, $event );
1023
return( 0 ) if ( !$subject );
1025
my $body = substituteTags( ZM_MESSAGE_BODY, $filter, $event, \@attachments );
1026
return( 0 ) if ( !$body );
1028
Info( "Sending notification message '$subject'\n" );
1032
if ( ZM_NEW_MAIL_MODULES )
1034
### Create the multipart container
1035
my $mail = MIME::Lite->new (
1036
From => ZM_FROM_EMAIL,
1037
To => ZM_MESSAGE_ADDRESS,
1038
Subject => $subject,
1039
Type => "multipart/mixed"
1041
### Add the text message part
1046
### Add the attachments
1047
foreach my $attachment ( @attachments )
1049
Info( "Attaching '$attachment->{path}\n" );
1051
Path => $attachment->{path},
1052
Type => $attachment->{type},
1053
Disposition => "attachment"
1056
### Send the Message
1057
MIME::Lite->send( "smtp", ZM_EMAIL_HOST, Timeout=>60 );
1062
my $mail = MIME::Entity->build(
1063
From => ZM_FROM_EMAIL,
1064
To => ZM_MESSAGE_ADDRESS,
1065
Subject => $subject,
1066
Type => (($body=~/<html>/)?'text/html':'text/plain'),
1070
foreach my $attachment ( @attachments )
1072
Info( "Attaching '$attachment->{path}\n" );
1074
Path => $attachment->{path},
1075
Type => $attachment->{type},
1076
Encoding => "base64"
1079
$mail->smtpsend( Host => ZM_EMAIL_HOST, MailFrom => ZM_FROM_EMAIL );
1084
warn( "Can't send email: $@" );
1089
Info( "Notification message sent\n" );
1091
my $sql = "update Events set Messaged = 1 where Id = ?";
1092
my $sth = $dbh->prepare_cached( $sql ) or Fatal( "Can't prepare '$sql': ".$dbh->errstr() );
1093
my $res = $sth->execute( $event->{Id} ) or Fatal( "Can't execute '$sql': ".$sth->errstr() );
1103
my $event_path = getEventPath( $event );
1105
my $command = $filter->{AutoExecuteCmd};
1106
$command .= " $event_path";
1108
Info( "Executing '$command'\n" );
1109
my $output = qx($command);
1110
my $status = $? >> 8;
1111
if ( $status || DBG_LEVEL > 0 )
1114
Debug( "Output: $output\n" );
1118
Error( "Command '$command' exited with status: $status\n" );
1123
my $sql = "update Events set Executed = 1 where Id = ?";
1124
my $sth = $dbh->prepare_cached( $sql ) or Fatal( "Can't prepare '$sql': ".$dbh->errstr() );
1125
my $res = $sth->execute( $event->{Id} ) or Fatal( "Can't execute '$sql': ".$sth->errstr() );