From 2773737e54cf270926cf42aac2c9dacea975f1ad Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Wed, 19 Aug 2020 16:57:20 -0400 Subject: [PATCH 001/199] Use gcc builtin functions for cpuid --- src/zm_utils.cpp | 54 ++++++++++-------------------------------------- 1 file changed, 11 insertions(+), 43 deletions(-) diff --git a/src/zm_utils.cpp b/src/zm_utils.cpp index c96851e79..ecb220021 100644 --- a/src/zm_utils.cpp +++ b/src/zm_utils.cpp @@ -229,63 +229,31 @@ void hwcaps_detect() { neonversion = 0; sse_version = 0; #if (defined(__i386__) || defined(__x86_64__)) - /* x86 or x86-64 processor */ - uint32_t r_edx, r_ecx, r_ebx; + __builtin_cpu_init(); -#ifdef __x86_64__ - __asm__ __volatile__( - "push %%rbx\n\t" - "mov $0x0,%%ecx\n\t" - "mov $0x7,%%eax\n\t" - "cpuid\n\t" - "push %%rbx\n\t" - "mov $0x1,%%eax\n\t" - "cpuid\n\t" - "pop %%rax\n\t" - "pop %%rbx\n\t" - : "=d" (r_edx), "=c" (r_ecx), "=a" (r_ebx) - : - : - ); -#else - __asm__ __volatile__( - "push %%ebx\n\t" - "mov $0x0,%%ecx\n\t" - "mov $0x7,%%eax\n\t" - "cpuid\n\t" - "push %%ebx\n\t" - "mov $0x1,%%eax\n\t" - "cpuid\n\t" - "pop %%eax\n\t" - "pop %%ebx\n\t" - : "=d" (r_edx), "=c" (r_ecx), "=a" (r_ebx) - : - : - ); -#endif - if ( r_ebx & 0x00000020 ) { + if ( __builtin_cpu_supports("avx2") ) { sse_version = 52; /* AVX2 */ Debug(1, "Detected a x86\\x86-64 processor with AVX2"); - } else if ( r_ecx & 0x10000000 ) { + } else if ( __builtin_cpu_supports("avx") ) { sse_version = 51; /* AVX */ Debug(1, "Detected a x86\\x86-64 processor with AVX"); - } else if ( r_ecx & 0x00100000 ) { + } else if ( __builtin_cpu_supports("sse4.2") ) { sse_version = 42; /* SSE4.2 */ Debug(1, "Detected a x86\\x86-64 processor with SSE4.2"); - } else if ( r_ecx & 0x00080000 ) { + } else if ( __builtin_cpu_supports("sse4.1") ) { sse_version = 41; /* SSE4.1 */ Debug(1, "Detected a x86\\x86-64 processor with SSE4.1"); - } else if ( r_ecx & 0x00000200 ) { + } else if ( __builtin_cpu_supports("ssse3") ) { sse_version = 35; /* SSSE3 */ Debug(1,"Detected a x86\\x86-64 processor with SSSE3"); - } else if ( r_ecx & 0x00000001 ) { + } else if ( __builtin_cpu_supports("sse3") ) { sse_version = 30; /* SSE3 */ Debug(1, "Detected a x86\\x86-64 processor with SSE3"); - } else if ( r_edx & 0x04000000 ) { + } else if ( __builtin_cpu_supports("sse2") ) { sse_version = 20; /* SSE2 */ Debug(1, "Detected a x86\\x86-64 processor with SSE2"); - } else if ( r_edx & 0x02000000 ) { + } else if ( __builtin_cpu_supports("sse") ) { sse_version = 10; /* SSE */ Debug(1, "Detected a x86\\x86-64 processor with SSE"); } else { @@ -320,7 +288,7 @@ __attribute__((noinline,__target__("sse2"))) #endif void* sse2_aligned_memcpy(void* dest, const void* src, size_t bytes) { #if ((defined(__i386__) || defined(__x86_64__) || defined(ZM_KEEP_SSE)) && !defined(ZM_STRIP_SSE)) - if ( bytes > 128 ) { + if(bytes > 128) { unsigned int remainder = bytes % 128; const uint8_t* lastsrc = (uint8_t*)src + (bytes - remainder); @@ -362,7 +330,7 @@ void* sse2_aligned_memcpy(void* dest, const void* src, size_t bytes) { } #else /* Non x86\x86-64 platform, use memcpy */ - memcpy(dest, src, bytes); + memcpy(dest,src,bytes); #endif return dest; } From 1361f0936c1417722ef8c0f4804623b5de763933 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Mon, 28 Sep 2020 15:38:56 -0500 Subject: [PATCH 002/199] clean up download view --- web/skins/classic/views/download.php | 117 ++++++++++++++------------- 1 file changed, 60 insertions(+), 57 deletions(-) diff --git a/web/skins/classic/views/download.php b/web/skins/classic/views/download.php index 91ac635fe..1869c4bcf 100644 --- a/web/skins/classic/views/download.php +++ b/web/skins/classic/views/download.php @@ -18,23 +18,77 @@ // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // +function getDLEventHTML($eid, $eids) { + $result = ''; + + if ( !empty($eid) ) { + $result .= ''.PHP_EOL; + + $Event = new ZM\Event($eid); + if ( !$Event->Id() ) { + ZM\Error('Invalid event id'); + $result .= '
Invalid event id
'.PHP_EOL; + } else { + $result .= 'Downloading event ' . $Event->Id . '. Resulting file should be approximately ' . human_filesize( $Event->DiskSpace() ).PHP_EOL; + } + } else if ( !empty($eids) ) { + $total_size = 0; + foreach ( $eids as $eid ) { + if ( !validInt($eid) ) { + ZM\Warning("Invalid event id in eids[] $eid"); + continue; + } + $Event = new ZM\Event($eid); + $total_size += $Event->DiskSpace(); + $result .= ''.PHP_EOL; + } + unset($eid); + $result .= 'Downloading ' . count($eids) . ' events. Resulting file should be approximately ' . human_filesize($total_size).PHP_EOL; + } else { + $result .= '
There are no events found. Resulting download will be empty.
'; + } + + return $result; +} + +function getGeneratedHTML($generated) { + $result = ''; + + if ( $generated = '' ) { + $result .= ''.PHP_EOL; + } else { + $result .= '

'.PHP_EOL; + $result .= '' .($generated ? translate('ExportSucceeded'):translate('ExportFailed')). ''.PHP_EOL; + $result .= ''.PHP_EOL; + $result .= '

'.PHP_EOL; + } + if ( $generated ) { + $result .= ''.PHP_EOL; + } +} + if ( !canView('Events') ) { $view = 'error'; return; } +$eid = isset($_REQUEST['eid']) ? $_REQUEST['eid'] : ''; +$eids = isset($_REQUEST['eids']) ? $_REQUEST['eids'] : array(); +$generated = isset($_REQUEST['generated']) ? $_REQUEST['generated'] : ''; + $total_size = 0; -if ( isset($_SESSION['montageReviewFilter']) and !isset($_REQUEST['eids']) ) { +if ( isset($_SESSION['montageReviewFilter']) and !$eids ) { # Handles montageReview filter $eventsSql = 'SELECT E.Id, E.DiskSpace FROM Events AS E WHERE 1'; $eventsSql .= $_SESSION['montageReviewFilter']['sql']; $results = dbQuery($eventsSql); - $eids = []; while ( $event_row = dbFetchNext( $results ) ) { array_push($eids, $event_row['Id']); $total_size += $event_row['DiskSpace']; } - $_REQUEST['eids'] = $eids; if ( ! count($eids) ) { ZM\Error("No events found for download using $eventsSql"); } @@ -70,37 +124,7 @@ xhtmlHeaders(__FILE__, translate('Download'));
- - - Id() ) { - ZM\Error('Invalid event id'); - echo '
Invalid event id
'; - } else { - echo 'Downloading event ' . $Event->Id . '. Resulting file should be approximately ' . human_filesize( $Event->DiskSpace() ); - } -} else if ( !empty($_REQUEST['eids']) ) { - $total_size = 0; - foreach ( $_REQUEST['eids'] as $eid ) { - if ( ! validInt($eid) ) { - ZM\Warning("Invalid event id in eids[] $eid"); - continue; - } - $Event = new ZM\Event($eid); - $total_size += $Event->DiskSpace(); -?> - -There are no events found. Resulting download will be empty.
'; -} -?> + @@ -118,32 +142,11 @@ if ( !empty($_REQUEST['eid']) ) {
- -

- - -

- - - - - + From fc366aa5032a77e71bb155f494414a7a974bf26d Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Mon, 28 Sep 2020 15:41:07 -0500 Subject: [PATCH 003/199] add missing echo --- web/skins/classic/views/download.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/skins/classic/views/download.php b/web/skins/classic/views/download.php index 1869c4bcf..7a7c51acc 100644 --- a/web/skins/classic/views/download.php +++ b/web/skins/classic/views/download.php @@ -147,6 +147,6 @@ xhtmlHeaders(__FILE__, translate('Download')); - + From 1af20cea6a3726735cc0aca130a51a28c3ac60a3 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Tue, 29 Sep 2020 09:42:31 -0400 Subject: [PATCH 004/199] Fix unarchive. The reload was killing the getJSON. Should only do that on success --- web/skins/classic/views/js/events.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/skins/classic/views/js/events.js b/web/skins/classic/views/js/events.js index 477adb96f..68870060b 100644 --- a/web/skins/classic/views/js/events.js +++ b/web/skins/classic/views/js/events.js @@ -197,7 +197,7 @@ function initPage() { }) .fail(logAjaxFail); - window.location.reload(true); + //window.location.reload(true); }); // Manage the EDIT button From 5200af820680b3e14b46f5d1b643c7b208f7931f Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Tue, 29 Sep 2020 09:50:15 -0500 Subject: [PATCH 005/199] add missing return to download view --- web/skins/classic/views/download.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/web/skins/classic/views/download.php b/web/skins/classic/views/download.php index 7a7c51acc..b52c7a4ab 100644 --- a/web/skins/classic/views/download.php +++ b/web/skins/classic/views/download.php @@ -68,6 +68,8 @@ function getGeneratedHTML($generated) { if ( $generated ) { $result .= ''.PHP_EOL; } + + return $result; } if ( !canView('Events') ) { From 953a6e0785fb7b77c5ff14ad079a0a7b18c39cf5 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Tue, 29 Sep 2020 10:15:58 -0500 Subject: [PATCH 006/199] more fixes to download view --- web/skins/classic/views/download.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/web/skins/classic/views/download.php b/web/skins/classic/views/download.php index b52c7a4ab..a4044fbe6 100644 --- a/web/skins/classic/views/download.php +++ b/web/skins/classic/views/download.php @@ -51,24 +51,24 @@ function getDLEventHTML($eid, $eids) { return $result; } -function getGeneratedHTML($generated) { +function getGeneratedHTML($generated, $exportFormat) { $result = ''; - if ( $generated = '' ) { + if ( $generated == '' ) { $result .= ''.PHP_EOL; } else { $result .= '

'.PHP_EOL; - $result .= '' .($generated ? translate('ExportSucceeded'):translate('ExportFailed')). ''.PHP_EOL; + $result .= '' .($generated ? translate('ExportSucceeded') : translate('ExportFailed')). ''.PHP_EOL; $result .= ''.PHP_EOL; $result .= '

'.PHP_EOL; } if ( $generated ) { $result .= ''.PHP_EOL; } - + return $result; } @@ -149,6 +149,6 @@ xhtmlHeaders(__FILE__, translate('Download')); - + From a12a870e2c1acf6f636c0cbfb81119ef1b3aa8ac Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Tue, 29 Sep 2020 12:51:01 -0500 Subject: [PATCH 007/199] download.js - replace mootools with jquery --- web/skins/classic/views/js/download.js | 34 ++++++++++++++++---------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/web/skins/classic/views/js/download.js b/web/skins/classic/views/js/download.js index 16b47c8b4..797ea2464 100644 --- a/web/skins/classic/views/js/download.js +++ b/web/skins/classic/views/js/download.js @@ -18,16 +18,24 @@ function startDownload( exportFile ) { var exportTimer = null; function exportProgress() { - var tickerText = $('exportProgressTicker').get('text'); + var tickerText = $j('#exportProgressTicker').text(); if ( tickerText.length < 1 || tickerText.length > 4 ) { - $('exportProgressTicker').set( 'text', '.' ); + $j('#exportProgressTicker').text( '.' ); } else { - $('exportProgressTicker').appendText( '.' ); + $j('#exportProgressTicker').append( '.' ); } } function exportResponse(respObj, respText) { console.log(respObj); + + var fullUrl = thisUrl+'?view='+currentView+'&'+eidParm+ + '&exportFormat='+respObj.exportFormat+ + '&exportFile='+respObj.exportFile+ + '&generated='+((respObj.result=='Ok')?1:0)+ + '&connkey='+connkey; + + console.log('the full url is: '+fullUrl); window.location.replace( thisUrl+'?view='+currentView+'&'+eidParm+ '&exportFormat='+respObj.exportFormat+ @@ -38,15 +46,13 @@ function exportResponse(respObj, respText) { } function exportEvent( element ) { - var form = element.form; - var parms = 'view=request&request=event&action=download'; - parms += '&'+$(form).toQueryString(); - console.log(parms); - var query = new Request.JSON( {url: thisUrl, method: 'post', data: parms, onSuccess: exportResponse} ); - query.send(); - $('exportProgress').removeClass( 'hidden' ); - $('exportProgress').setProperty( 'class', 'warnText' ); - $('exportProgressText').set( 'text', exportProgressString ); + var form = $j('#contentForm').serialize(); + $j.getJSON(thisUrl + '?view=request&request=event&action=download', form) + .done(exportResponse) + .fail(logAjaxFail); + $j('#exportProgress').removeClass( 'hidden' ); + $j('#exportProgress').addClass( 'warnText' ); + $j('#exportProgressText').text( exportProgressString ); exportProgress(); exportTimer = exportProgress.periodical( 500 ); } @@ -60,4 +66,6 @@ function initPage() { }); } -window.addEventListener( 'DOMContentLoaded', initPage ); +$j(document).ready(function() { + initPage(); +}); From 4694ce59bbb58503a3e6b6d34ffcd93a7f80ca62 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Tue, 29 Sep 2020 12:55:57 -0500 Subject: [PATCH 008/199] export event function does not need element --- web/skins/classic/views/js/download.js | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/web/skins/classic/views/js/download.js b/web/skins/classic/views/js/download.js index 797ea2464..6241b3170 100644 --- a/web/skins/classic/views/js/download.js +++ b/web/skins/classic/views/js/download.js @@ -35,17 +35,11 @@ function exportResponse(respObj, respText) { '&generated='+((respObj.result=='Ok')?1:0)+ '&connkey='+connkey; - console.log('the full url is: '+fullUrl); - window.location.replace( - thisUrl+'?view='+currentView+'&'+eidParm+ - '&exportFormat='+respObj.exportFormat+ - '&exportFile='+respObj.exportFile+ - '&generated='+((respObj.result=='Ok')?1:0)+ - '&connkey='+connkey - ); + console.log('The full url is: ' + fullUrl); + window.location.replace(fullUrl); } -function exportEvent( element ) { +function exportEvent() { var form = $j('#contentForm').serialize(); $j.getJSON(thisUrl + '?view=request&request=event&action=download', form) .done(exportResponse) @@ -61,9 +55,7 @@ function initPage() { if ( exportReady ) { startDownload.pass( exportFile ).delay( 1500 ); } - document.getElementById('exportButton').addEventListener("click", function onClick(evt) { - exportEvent(this); - }); + document.getElementById('exportButton').addEventListener("click", exportEvent ); } $j(document).ready(function() { From 6eaa8aa2115015e3a5ceff067fe7640fcbf85c3b Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Tue, 29 Sep 2020 13:05:00 -0500 Subject: [PATCH 009/199] whitespace --- web/skins/classic/views/js/download.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/web/skins/classic/views/js/download.js b/web/skins/classic/views/js/download.js index 6241b3170..5ad145083 100644 --- a/web/skins/classic/views/js/download.js +++ b/web/skins/classic/views/js/download.js @@ -28,7 +28,7 @@ function exportProgress() { function exportResponse(respObj, respText) { console.log(respObj); - + var fullUrl = thisUrl+'?view='+currentView+'&'+eidParm+ '&exportFormat='+respObj.exportFormat+ '&exportFile='+respObj.exportFile+ @@ -43,7 +43,7 @@ function exportEvent() { var form = $j('#contentForm').serialize(); $j.getJSON(thisUrl + '?view=request&request=event&action=download', form) .done(exportResponse) - .fail(logAjaxFail); + .fail(logAjaxFail); $j('#exportProgress').removeClass( 'hidden' ); $j('#exportProgress').addClass( 'warnText' ); $j('#exportProgressText').text( exportProgressString ); From f2e4d1dd5c53ba919fefc21c05a64132ef18fc14 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Tue, 29 Sep 2020 15:02:46 -0400 Subject: [PATCH 010/199] Handle PostSQL Conditions when generating SQL --- scripts/ZoneMinder/lib/ZoneMinder/Filter.pm | 187 ++++++++++---------- 1 file changed, 97 insertions(+), 90 deletions(-) diff --git a/scripts/ZoneMinder/lib/ZoneMinder/Filter.pm b/scripts/ZoneMinder/lib/ZoneMinder/Filter.pm index b48946d1f..9903e38ec 100644 --- a/scripts/ZoneMinder/lib/ZoneMinder/Filter.pm +++ b/scripts/ZoneMinder/lib/ZoneMinder/Filter.pm @@ -205,6 +205,8 @@ sub Sql { # } elsif ( $term->{attr} eq 'ExistsInFileSystem' ) { push @{$self->{PostSQLConditions}}, $term; + $self->{Sql} .= 'TRUE /* ExistsInFileSystem */'; + } elsif ( $term->{attr} eq 'DiskSpace' ) { $self->{Sql} .= 'E.DiskSpace'; } elsif ( $term->{attr} eq 'DiskPercent' ) { @@ -223,109 +225,114 @@ sub Sql { $self->{Sql} .= 'E.'.$term->{attr}; } - ( my $stripped_value = $value ) =~ s/^["\']+?(.+)["\']+?$/$1/; - foreach my $temp_value ( split( /["'\s]*?,["'\s]*?/, $stripped_value ) ) { - - if ( $term->{attr} eq 'AlarmedZoneId' ) { - $value = '(SELECT * FROM Stats WHERE EventId=E.Id AND ZoneId='.$value.')'; - } elsif ( $term->{attr} =~ /^MonitorName/ ) { - $value = "'$temp_value'"; - } elsif ( $term->{attr} =~ /ServerId/) { - Debug("ServerId, temp_value is ($temp_value) ($ZoneMinder::Config::Config{ZM_SERVER_ID})"); - if ( $temp_value eq 'ZM_SERVER_ID' ) { - $value = "'$ZoneMinder::Config::Config{ZM_SERVER_ID}'"; - # This gets used later, I forget for what - $$self{Server} = new ZoneMinder::Server($ZoneMinder::Config::Config{ZM_SERVER_ID}); - } elsif ( $temp_value eq 'NULL' ) { - $value = $temp_value; - } else { + if ( $term->{attr} eq 'ExistsInFileSystem' ) { + # PostCondition, so no further SQL + } else { + ( my $stripped_value = $value ) =~ s/^["\']+?(.+)["\']+?$/$1/; + foreach my $temp_value ( split( /["'\s]*?,["'\s]*?/, $stripped_value ) ) { + + if ( $term->{attr} eq 'AlarmedZoneId' ) { + $value = '(SELECT * FROM Stats WHERE EventId=E.Id AND ZoneId='.$value.')'; + } elsif ( $term->{attr} =~ /^MonitorName/ ) { $value = "'$temp_value'"; - # This gets used later, I forget for what - $$self{Server} = new ZoneMinder::Server($temp_value); - } - } elsif ( $term->{attr} eq 'StorageId' ) { - $value = "'$temp_value'"; - $$self{Storage} = new ZoneMinder::Storage($temp_value); - } elsif ( $term->{attr} eq 'Name' + } elsif ( $term->{attr} =~ /ServerId/) { + Debug("ServerId, temp_value is ($temp_value) ($ZoneMinder::Config::Config{ZM_SERVER_ID})"); + if ( $temp_value eq 'ZM_SERVER_ID' ) { + $value = "'$ZoneMinder::Config::Config{ZM_SERVER_ID}'"; + # This gets used later, I forget for what + $$self{Server} = new ZoneMinder::Server($ZoneMinder::Config::Config{ZM_SERVER_ID}); + } elsif ( $temp_value eq 'NULL' ) { + $value = $temp_value; + } else { + $value = "'$temp_value'"; + # This gets used later, I forget for what + $$self{Server} = new ZoneMinder::Server($temp_value); + } + } elsif ( $term->{attr} eq 'StorageId' ) { + $value = "'$temp_value'"; + $$self{Storage} = new ZoneMinder::Storage($temp_value); + } elsif ( $term->{attr} eq 'Name' || $term->{attr} eq 'Cause' || $term->{attr} eq 'Notes' - ) { + ) { if ( $term->{op} eq 'LIKE' - || $term->{op} eq 'NOT LIKE' + || $term->{op} eq 'NOT LIKE' ) { - $temp_value = '%'.$temp_value.'%' if $temp_value !~ /%/; + $temp_value = '%'.$temp_value.'%' if $temp_value !~ /%/; + } + $value = "'$temp_value'"; + } elsif ( $term->{attr} eq 'DateTime' or $term->{attr} eq 'StartDateTime' or $term->{attr} eq 'EndDateTime' ) { + if ( $temp_value eq 'NULL' ) { + $value = $temp_value; + } else { + $value = DateTimeToSQL($temp_value); + if ( !$value ) { + Error("Error parsing date/time '$temp_value', skipping filter '$self->{Name}'"); + return; + } + $value = "'$value'"; + } + } elsif ( $term->{attr} eq 'Date' or $term->{attr} eq 'StartDate' or $term->{attr} eq 'EndDate' ) { + if ( $temp_value eq 'NULL' ) { + $value = $temp_value; + } elsif ( $temp_value eq 'CURDATE()' or $temp_value eq 'NOW()' ) { + $value = 'to_days('.$temp_value.')'; + } else { + $value = DateTimeToSQL($temp_value); + if ( !$value ) { + Error("Error parsing date/time '$temp_value', skipping filter '$self->{Name}'"); + return; + } + $value = "to_days( '$value' )"; + } + } elsif ( $term->{attr} eq 'Time' or $term->{attr} eq 'StartTime' or $term->{attr} eq 'EndTime' ) { + if ( $temp_value eq 'NULL' ) { + $value = $temp_value; + } else { + $value = DateTimeToSQL($temp_value); + if ( !$value ) { + Error("Error parsing date/time '$temp_value', skipping filter '$self->{Name}'"); + return; + } + $value = "extract( hour_second from '$value' )"; } - $value = "'$temp_value'"; - } elsif ( $term->{attr} eq 'DateTime' or $term->{attr} eq 'StartDateTime' or $term->{attr} eq 'EndDateTime' ) { - if ( $temp_value eq 'NULL' ) { - $value = $temp_value; } else { - $value = DateTimeToSQL($temp_value); - if ( !$value ) { - Error("Error parsing date/time '$temp_value', skipping filter '$self->{Name}'"); - return; - } - $value = "'$value'"; - } - } elsif ( $term->{attr} eq 'Date' or $term->{attr} eq 'StartDate' or $term->{attr} eq 'EndDate' ) { - if ( $temp_value eq 'NULL' ) { $value = $temp_value; - } elsif ( $temp_value eq 'CURDATE()' or $temp_value eq 'NOW()' ) { - $value = 'to_days('.$temp_value.')'; - } else { - $value = DateTimeToSQL($temp_value); - if ( !$value ) { - Error("Error parsing date/time '$temp_value', skipping filter '$self->{Name}'"); - return; - } - $value = "to_days( '$value' )"; } - } elsif ( $term->{attr} eq 'Time' or $term->{attr} eq 'StartTime' or $term->{attr} eq 'EndTime' ) { - if ( $temp_value eq 'NULL' ) { - $value = $temp_value; + push @value_list, $value; + } # end foreach temp_value + } # end if has an attr + + if ( $term->{op} ) { + if ( $term->{op} eq '=~' ) { + $self->{Sql} .= ' REGEXP '.$value; + } elsif ( $term->{op} eq '!~' ) { + $self->{Sql} .= ' NOT REGEXP '.$value; + } elsif ( $term->{op} eq 'IS' ) { + if ( $value eq 'Odd' ) { + $self->{Sql} .= ' % 2 = 1'; + } elsif ( $value eq 'Even' ) { + $self->{Sql} .= ' % 2 = 0'; } else { - $value = DateTimeToSQL($temp_value); - if ( !$value ) { - Error("Error parsing date/time '$temp_value', skipping filter '$self->{Name}'"); - return; - } - $value = "extract( hour_second from '$value' )"; + $self->{Sql} .= " IS $value"; } + } elsif ( $term->{op} eq 'EXISTS' ) { + $self->{Sql} .= ' EXISTS '.$value; + } elsif ( $term->{op} eq 'IS NOT' ) { + $self->{Sql} .= ' IS NOT '.$value; + } elsif ( $term->{op} eq '=[]' ) { + $self->{Sql} .= ' IN ('.join(',', @value_list).')'; + } elsif ( $term->{op} eq '!~' ) { + $self->{Sql} .= ' NOT IN ('.join(',', @value_list).')'; + } elsif ( $term->{op} eq 'LIKE' ) { + $self->{Sql} .= ' LIKE '.$value; + } elsif ( $term->{op} eq 'NOT LIKE' ) { + $self->{Sql} .= ' NOT LIKE '.$value; } else { - $value = $temp_value; + $self->{Sql} .= ' '.$term->{op}.' '.$value; } - push @value_list, $value; - } # end foreach temp_value - } # end if has an attr - if ( $term->{op} ) { - if ( $term->{op} eq '=~' ) { - $self->{Sql} .= " regexp $value"; - } elsif ( $term->{op} eq '!~' ) { - $self->{Sql} .= " not regexp $value"; - } elsif ( $term->{op} eq 'IS' ) { - if ( $value eq 'Odd' ) { - $self->{Sql} .= ' % 2 = 1'; - } elsif ( $value eq 'Even' ) { - $self->{Sql} .= ' % 2 = 0'; - } else { - $self->{Sql} .= " IS $value"; - } - } elsif ( $term->{op} eq 'EXISTS' ) { - $self->{Sql} .= " EXISTS $value"; - } elsif ( $term->{op} eq 'IS NOT' ) { - $self->{Sql} .= " IS NOT $value"; - } elsif ( $term->{op} eq '=[]' ) { - $self->{Sql} .= ' IN ('.join(',', @value_list).')'; - } elsif ( $term->{op} eq '!~' ) { - $self->{Sql} .= ' NOT IN ('.join(',', @value_list).')'; - } elsif ( $term->{op} eq 'LIKE' ) { - $self->{Sql} .= " LIKE $value"; - } elsif ( $term->{op} eq 'NOT LIKE' ) { - $self->{Sql} .= " NOT LIKE $value"; - } else { - $self->{Sql} .= ' '.$term->{op}.' '.$value; - } - } # end if has an operator + } # end if has an operator + } # end if Pre/Post or SQL if ( exists($term->{cbr}) ) { $self->{Sql} .= ' '.str_repeat(')', $term->{cbr}).' '; } From 24d8b99eea88e0e5c12ed091e9fcb2a4b4c86f8f Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Tue, 29 Sep 2020 16:47:49 -0400 Subject: [PATCH 011/199] test for property_exists to quiet errors --- web/includes/Monitor.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/web/includes/Monitor.php b/web/includes/Monitor.php index d1bd51509..fec452551 100644 --- a/web/includes/Monitor.php +++ b/web/includes/Monitor.php @@ -293,7 +293,7 @@ class Monitor extends ZM_Object { } function zmcControl( $mode=false ) { - if ( ! $this->{'Id'} ) { + if ( !(property_exists($this,'Id') and $this->{'Id'}) ) { Warning('Attempt to control a monitor with no Id'); return; } @@ -346,7 +346,7 @@ class Monitor extends ZM_Object { } // end function zmcControl function zmaControl($mode=false) { - if ( !$this->{'Id'} ) { + if ( ! (property_exists($this, 'Id') and $this->{'Id'}) ) { Warning('Attempt to control a monitor with no Id'); return; } From aa7ba44ed902d0f922ecd67d81870fb578c775cc Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Tue, 29 Sep 2020 16:48:22 -0400 Subject: [PATCH 012/199] Use ->zmaControl instead of invalid zmaControl(). the old zmaControl takes a mid, not a monitor object --- web/includes/actions/function.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/web/includes/actions/function.php b/web/includes/actions/function.php index 9667b8c24..0a1569a01 100644 --- a/web/includes/actions/function.php +++ b/web/includes/actions/function.php @@ -32,7 +32,7 @@ if ( !canEdit('Monitors', $mid) ) { if ( $action == 'function' ) { $monitor = new ZM\Monitor($mid); - if ( !$monitor ) { + if ( !$monitor->Id() ) { ZM\Error("Monitor not found with Id=$mid"); return; } @@ -46,10 +46,10 @@ if ( $action == 'function' ) { $monitor->save(array('Function'=>$newFunction, 'Enabled'=>$newEnabled)); if ( daemonCheck() && ($monitor->Type() != 'WebSite') ) { - zmaControl($monitor, 'stop'); - zmcControl($monitor, ($newFunction != 'None') ? 'restart' : 'stop'); + $monitor->zmaControl('stop'); + $monitor->zmcControl(($newFunction != 'None') ? 'restart' : 'stop'); if ( $newFunction != 'None' && $newFunction != 'NoDect' ) - zmaControl($monitor, 'start'); + $monitor->zmaControl('start'); } } else { ZM\Logger::Debug('No change to function, not doing anything.'); From 02d4785e7103cabff7bbdd2cf2771fbe17fdca33 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Tue, 29 Sep 2020 17:26:55 -0400 Subject: [PATCH 013/199] Split out user creation/updating into it's own function --- distros/ubuntu2004/zoneminder.postinst | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/distros/ubuntu2004/zoneminder.postinst b/distros/ubuntu2004/zoneminder.postinst index 39a2fa1b0..a8b8eaf51 100644 --- a/distros/ubuntu2004/zoneminder.postinst +++ b/distros/ubuntu2004/zoneminder.postinst @@ -16,17 +16,20 @@ create_db () { else echo "Db exists." fi +} + +create_update_user () { USER_EXISTS="$(mysql --defaults-file=/etc/mysql/debian.cnf -sse "SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = '$ZM_DB_USER')")" if [ $USER_EXISTS -ne 1 ]; then echo "Creating zm user $ZM_DB_USER" # This creates the user. echo "CREATE USER '${ZM_DB_USER}'@${ZM_DB_HOST} IDENTIFIED BY '${ZM_DB_PASS}';" | mysql --defaults-file=/etc/mysql/debian.cnf mysql fi + echo "Updating permissions" + echo "GRANT LOCK tables,alter,drop,select,insert,update,delete,create,index,alter routine,create routine,trigger,execute ON ${ZM_DB_NAME}.* TO '${ZM_DB_USER}'@${ZM_DB_HOST};" | mysql --defaults-file=/etc/mysql/debian.cnf mysql } update_db () { - echo "Updating permissions" - echo "GRANT LOCK tables,alter,drop,select,insert,update,delete,create,index,alter routine,create routine,trigger,execute ON ${ZM_DB_NAME}.* TO '${ZM_DB_USER}'@${ZM_DB_HOST};" | mysql --defaults-file=/etc/mysql/debian.cnf mysql zmupdate.pl --nointeractive zmupdate.pl --nointeractive -f @@ -94,6 +97,7 @@ if [ "$1" = "configure" ]; then # Make sure systemctl status exit code is 0; i.e. the DB is running if systemctl is-active --quiet "$DBSERVICE"; then create_db + create_update_user update_db else echo 'NOTE: MySQL/MariaDB not running; please start mysql and run dpkg-reconfigure zoneminder when it is running.' @@ -108,6 +112,7 @@ if [ "$1" = "configure" ]; then fi if $(/etc/init.d/mysql status >/dev/null 2>&1); then create_db + create_update_user update_db else echo 'NOTE: MySQL/MariaDB not running; please start mysql and run dpkg-reconfigure zoneminder when it is running.' From 3eae356ed79a4372b8b8bc992b35dc8ea8524b2f Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Wed, 30 Sep 2020 09:39:31 -0400 Subject: [PATCH 014/199] Bump to 1.35.8. Change table engine to InnoDb for Monitor_Status. --- db/zm_create.sql.in | 2 +- db/zm_update-1.35.8.sql | 12 ++++++++++++ distros/redhat/zoneminder.spec | 2 +- version | 2 +- 4 files changed, 15 insertions(+), 3 deletions(-) create mode 100644 db/zm_update-1.35.8.sql diff --git a/db/zm_create.sql.in b/db/zm_create.sql.in index cd4622df1..a0ab83c80 100644 --- a/db/zm_create.sql.in +++ b/db/zm_create.sql.in @@ -551,7 +551,7 @@ CREATE TABLE `Monitor_Status` ( `AnalysisFPS` DECIMAL(5,2) NOT NULL default 0, `CaptureBandwidth` INT NOT NULL default 0, PRIMARY KEY (`MonitorId`) -) ENGINE=MEMORY; +) ENGINE=@ZM_MYSQL_ENGINE@; -- -- Table structure for table `States` -- PP - Added IsActive to track custom run states diff --git a/db/zm_update-1.35.8.sql b/db/zm_update-1.35.8.sql new file mode 100644 index 000000000..1549903ab --- /dev/null +++ b/db/zm_update-1.35.8.sql @@ -0,0 +1,12 @@ +/* The MEMORY TABLE TYPE IS BAD! Switch to regular InnoDB */ + +DROP TABLE IF EXISTS `Monitor_Status`; +CREATE TABLE `Monitor_Status` ( + `MonitorId` int(10) unsigned NOT NULL, + `Status` enum('Unknown','NotRunning','Running','Connected','Signal') NOT NULL default 'Unknown', + `CaptureFPS` DECIMAL(10,2) NOT NULL default 0, + `AnalysisFPS` DECIMAL(5,2) NOT NULL default 0, + `CaptureBandwidth` INT NOT NULL default 0, + PRIMARY KEY (`MonitorId`) +) ENGINE=InnoDB; + diff --git a/distros/redhat/zoneminder.spec b/distros/redhat/zoneminder.spec index b594c2de2..594da469d 100644 --- a/distros/redhat/zoneminder.spec +++ b/distros/redhat/zoneminder.spec @@ -28,7 +28,7 @@ %global _hardened_build 1 Name: zoneminder -Version: 1.35.7 +Version: 1.35.8 Release: 1%{?dist} Summary: A camera monitoring and analysis tool Group: System Environment/Daemons diff --git a/version b/version index 96eced874..39db50cf2 100644 --- a/version +++ b/version @@ -1 +1 @@ -1.35.7 +1.35.8 From 2d30d7aafaca6c28501a1d4f7b46408258fea654 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Wed, 30 Sep 2020 09:12:54 -0500 Subject: [PATCH 015/199] convert download view to modal --- web/ajax/modals/download.php | 119 ++++++++++++++++ web/skins/classic/js/skin.js | 30 ++++ web/skins/classic/js/skin.js.php | 6 +- web/skins/classic/views/download.php | 154 --------------------- web/skins/classic/views/js/download.js | 63 --------- web/skins/classic/views/js/download.js.php | 23 --- web/skins/classic/views/js/events.js | 13 +- 7 files changed, 165 insertions(+), 243 deletions(-) create mode 100644 web/ajax/modals/download.php delete mode 100644 web/skins/classic/views/download.php delete mode 100644 web/skins/classic/views/js/download.js delete mode 100644 web/skins/classic/views/js/download.js.php diff --git a/web/ajax/modals/download.php b/web/ajax/modals/download.php new file mode 100644 index 000000000..4f19abc0f --- /dev/null +++ b/web/ajax/modals/download.php @@ -0,0 +1,119 @@ +'.PHP_EOL; + + $Event = new ZM\Event($eid); + if ( !$Event->Id() ) { + ZM\Error('Invalid event id'); + $result .= '
Invalid event id
'.PHP_EOL; + } else { + $result .= 'Downloading event ' . $Event->Id . '. Resulting file should be approximately ' . human_filesize( $Event->DiskSpace() ).PHP_EOL; + } + } else if ( !empty($eids) ) { + $total_size = 0; + foreach ( $eids as $eid ) { + if ( !validInt($eid) ) { + ZM\Warning("Invalid event id in eids[] $eid"); + continue; + } + $Event = new ZM\Event($eid); + $total_size += $Event->DiskSpace(); + $result .= ''.PHP_EOL; + } + unset($eid); + $result .= 'Downloading ' . count($eids) . ' events. Resulting file should be approximately ' . human_filesize($total_size).PHP_EOL; + } else { + $result .= '
There are no events found. Resulting download will be empty.
'; + } + + return $result; +} + +if ( !canView('Events') ) { + $view = 'error'; + return; +} + +$eid = isset($_REQUEST['eid']) ? $_REQUEST['eid'] : ''; +$eids = isset($_REQUEST['eids']) ? $_REQUEST['eids'] : array(); +$generated = isset($_REQUEST['generated']) ? $_REQUEST['generated'] : ''; + +$total_size = 0; +if ( isset($_SESSION['montageReviewFilter']) and !$eids ) { + # Handles montageReview filter + $eventsSql = 'SELECT E.Id, E.DiskSpace FROM Events AS E WHERE 1'; + $eventsSql .= $_SESSION['montageReviewFilter']['sql']; + $results = dbQuery($eventsSql); + while ( $event_row = dbFetchNext( $results ) ) { + array_push($eids, $event_row['Id']); + $total_size += $event_row['DiskSpace']; + } + if ( ! count($eids) ) { + ZM\Error("No events found for download using $eventsSql"); + } + #session_start(); + #unset($_SESSION['montageReviewFilter']); + #session_write_close(); +#} else { +#Logger::Debug("NO montageReviewFilter"); +} + +$exportFormat = ''; +if ( isset($_REQUEST['exportFormat']) ) { + if ( !in_array($_REQUEST['exportFormat'], array('zip', 'tar')) ) { + ZM\Error('Invalid exportFormat: '.$_REQUEST['exportFormat']); + } else { + $exportFormat = $_REQUEST['exportFormat']; + } +} + +$focusWindow = true; +$connkey = isset($_REQUEST['connkey']) ? validInt($_REQUEST['connkey']) : generateConnKey(); + +?> + diff --git a/web/skins/classic/js/skin.js b/web/skins/classic/js/skin.js index dc45f32fe..cb95becf3 100644 --- a/web/skins/classic/js/skin.js +++ b/web/skins/classic/js/skin.js @@ -924,4 +924,34 @@ function human_filesize(size, precision = 2) { return (Math.round(size*(10^precision))/(10^precision))+units[i]; } +function startDownload( exportFile ) { + console.log("Starting download from " + exportFile); + window.location.replace( exportFile ); +} +function exportResponse(data, responseText) { + console.log(data); + + var generated = (data.result=='Ok') ? 1 : 0; + var exportFile = '?view=archive&type='+data.exportFormat+'&connkey='+data.connkey; + + $j('#exportProgress').removeClass( 'text-warning' ); + if ( generated ) { + $j('#downloadLink').text('Download'); + $j('#downloadLink').attr("href", thisUrl + exportFile); + $j('#exportProgress').addClass( 'text-success' ); + $j('#exportProgress').text(exportSucceededString); + startDownload.pass( exportFile ).delay( 1500 ); + } else { + $j('#exportProgress').addClass( 'text-danger' ); + $j('#exportProgress').text(exportFailedString); + } +} + +function exportEvent() { + var form = $j('#downloadForm').serialize(); + $j.getJSON(thisUrl + '?view=request&request=event&action=download', form) + .done(exportResponse) + .fail(logAjaxFail); + $j('#exportProgress').removeClass( 'invisible' ); +} diff --git a/web/skins/classic/js/skin.js.php b/web/skins/classic/js/skin.js.php index 08ed2d57d..9bf0cda6f 100644 --- a/web/skins/classic/js/skin.js.php +++ b/web/skins/classic/js/skin.js.php @@ -25,10 +25,12 @@ ?> var AJAX_TIMEOUT = ; - var navBarRefresh = ; - var currentView = ''; + +var exportProgressString = ''; +var exportFailedString = ''; +var exportSucceededString = ''; '.PHP_EOL; - - $Event = new ZM\Event($eid); - if ( !$Event->Id() ) { - ZM\Error('Invalid event id'); - $result .= '
Invalid event id
'.PHP_EOL; - } else { - $result .= 'Downloading event ' . $Event->Id . '. Resulting file should be approximately ' . human_filesize( $Event->DiskSpace() ).PHP_EOL; - } - } else if ( !empty($eids) ) { - $total_size = 0; - foreach ( $eids as $eid ) { - if ( !validInt($eid) ) { - ZM\Warning("Invalid event id in eids[] $eid"); - continue; - } - $Event = new ZM\Event($eid); - $total_size += $Event->DiskSpace(); - $result .= ''.PHP_EOL; - } - unset($eid); - $result .= 'Downloading ' . count($eids) . ' events. Resulting file should be approximately ' . human_filesize($total_size).PHP_EOL; - } else { - $result .= '
There are no events found. Resulting download will be empty.
'; - } - - return $result; -} - -function getGeneratedHTML($generated, $exportFormat) { - $result = ''; - - if ( $generated == '' ) { - $result .= ''.PHP_EOL; - } else { - $result .= '

'.PHP_EOL; - $result .= '' .($generated ? translate('ExportSucceeded') : translate('ExportFailed')). ''.PHP_EOL; - $result .= ''.PHP_EOL; - $result .= '

'.PHP_EOL; - } - if ( $generated ) { - $result .= ''.PHP_EOL; - } - - return $result; -} - -if ( !canView('Events') ) { - $view = 'error'; - return; -} - -$eid = isset($_REQUEST['eid']) ? $_REQUEST['eid'] : ''; -$eids = isset($_REQUEST['eids']) ? $_REQUEST['eids'] : array(); -$generated = isset($_REQUEST['generated']) ? $_REQUEST['generated'] : ''; - -$total_size = 0; -if ( isset($_SESSION['montageReviewFilter']) and !$eids ) { - # Handles montageReview filter - $eventsSql = 'SELECT E.Id, E.DiskSpace FROM Events AS E WHERE 1'; - $eventsSql .= $_SESSION['montageReviewFilter']['sql']; - $results = dbQuery($eventsSql); - while ( $event_row = dbFetchNext( $results ) ) { - array_push($eids, $event_row['Id']); - $total_size += $event_row['DiskSpace']; - } - if ( ! count($eids) ) { - ZM\Error("No events found for download using $eventsSql"); - } - #session_start(); - #unset($_SESSION['montageReviewFilter']); - #session_write_close(); -#} else { -#Logger::Debug("NO montageReviewFilter"); -} - -$exportFormat = ''; -if ( isset($_REQUEST['exportFormat']) ) { - if ( !in_array($_REQUEST['exportFormat'], array('zip', 'tar')) ) { - ZM\Error('Invalid exportFormat: '.$_REQUEST['exportFormat']); - } else { - $exportFormat = $_REQUEST['exportFormat']; - } -} - -$focusWindow = true; -$connkey = isset($_REQUEST['connkey']) ? validInt($_REQUEST['connkey']) : generateConnKey(); - -xhtmlHeaders(__FILE__, translate('Download')); -?> - -
- -
-
- - - - - - - - - - - - -
- - - - -
- -
-
- -
- diff --git a/web/skins/classic/views/js/download.js b/web/skins/classic/views/js/download.js deleted file mode 100644 index 5ad145083..000000000 --- a/web/skins/classic/views/js/download.js +++ /dev/null @@ -1,63 +0,0 @@ -function configureExportButton( element ) { - var form = element.form; - - var radioCount = 0; - for ( var i = 0, len=form.elements.length; i < len; i++ ) { - if ( form.elements[i].type == "radio" && form.elements[i].checked ) { - radioCount++; - } - } - form.elements['exportButton'].disabled = (radioCount == 0); -} - -function startDownload( exportFile ) { - console.log("Starting download from " + exportFile); - window.location.replace( exportFile ); -} - -var exportTimer = null; - -function exportProgress() { - var tickerText = $j('#exportProgressTicker').text(); - if ( tickerText.length < 1 || tickerText.length > 4 ) { - $j('#exportProgressTicker').text( '.' ); - } else { - $j('#exportProgressTicker').append( '.' ); - } -} - -function exportResponse(respObj, respText) { - console.log(respObj); - - var fullUrl = thisUrl+'?view='+currentView+'&'+eidParm+ - '&exportFormat='+respObj.exportFormat+ - '&exportFile='+respObj.exportFile+ - '&generated='+((respObj.result=='Ok')?1:0)+ - '&connkey='+connkey; - - console.log('The full url is: ' + fullUrl); - window.location.replace(fullUrl); -} - -function exportEvent() { - var form = $j('#contentForm').serialize(); - $j.getJSON(thisUrl + '?view=request&request=event&action=download', form) - .done(exportResponse) - .fail(logAjaxFail); - $j('#exportProgress').removeClass( 'hidden' ); - $j('#exportProgress').addClass( 'warnText' ); - $j('#exportProgressText').text( exportProgressString ); - exportProgress(); - exportTimer = exportProgress.periodical( 500 ); -} - -function initPage() { - if ( exportReady ) { - startDownload.pass( exportFile ).delay( 1500 ); - } - document.getElementById('exportButton').addEventListener("click", exportEvent ); -} - -$j(document).ready(function() { - initPage(); -}); diff --git a/web/skins/classic/views/js/download.js.php b/web/skins/classic/views/js/download.js.php deleted file mode 100644 index 390c9d17f..000000000 --- a/web/skins/classic/views/js/download.js.php +++ /dev/null @@ -1,23 +0,0 @@ - -var eidParm = ''; - -var eidParm = 'eid='; - - -var exportReady = ; -var exportFile = '?view=archive&type=&connkey='; -var connkey = ''; - -var exportProgressString = ''; diff --git a/web/skins/classic/views/js/events.js b/web/skins/classic/views/js/events.js index 68870060b..c826ad5f0 100644 --- a/web/skins/classic/views/js/events.js +++ b/web/skins/classic/views/js/events.js @@ -240,7 +240,18 @@ function initPage() { var selections = getIdSelections(); evt.preventDefault(); - createPopup('?view=download&eids[]='+selections.join('&eids[]='), 'zmDownload', 'download'); + $j.getJSON(thisUrl + '?request=modal&modal=download&eids[]='+selections.join('&eids[]=')) + .done(function(data) { + if ( $j('#downloadModal').length ) { + $j('#downloadModal').replaceWith(data.html); + } else { + $j("body").append(data.html); + } + $j('#downloadModal').modal('show'); + // Manage the GENERATE DOWNLOAD button + $j('#exportButton').click(exportEvent); + }) + .fail(logAjaxFail); }); // Manage the DELETE button From 9bb82f6e9a1edee624287293c25c388b6e49e334 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Wed, 30 Sep 2020 09:25:52 -0500 Subject: [PATCH 016/199] whitespace --- web/skins/classic/js/skin.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/web/skins/classic/js/skin.js b/web/skins/classic/js/skin.js index cb95becf3..5cc4b9534 100644 --- a/web/skins/classic/js/skin.js +++ b/web/skins/classic/js/skin.js @@ -931,7 +931,7 @@ function startDownload( exportFile ) { function exportResponse(data, responseText) { console.log(data); - + var generated = (data.result=='Ok') ? 1 : 0; var exportFile = '?view=archive&type='+data.exportFormat+'&connkey='+data.connkey; @@ -952,6 +952,6 @@ function exportEvent() { var form = $j('#downloadForm').serialize(); $j.getJSON(thisUrl + '?view=request&request=event&action=download', form) .done(exportResponse) - .fail(logAjaxFail); + .fail(logAjaxFail); $j('#exportProgress').removeClass( 'invisible' ); } From d77b55d1d6a044e1a18526731db76455aec66813 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Wed, 30 Sep 2020 10:40:13 -0500 Subject: [PATCH 017/199] replace popup code in add_monitor --- web/skins/classic/views/js/add_monitors.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/web/skins/classic/views/js/add_monitors.js b/web/skins/classic/views/js/add_monitors.js index be46dc3c2..8738cda38 100644 --- a/web/skins/classic/views/js/add_monitors.js +++ b/web/skins/classic/views/js/add_monitors.js @@ -66,7 +66,7 @@ function addMonitor(url) { var Monitor = Stream.Monitor; var mid = Monitor.Id ? Monitor.Id : ''; - popup_url = '?view=monitor&mid='+mid+'&newMonitor[Path]='+url; + urlString = '?view=monitor&mid='+mid+'&newMonitor[Path]='+url; keys = Object.keys( Monitor ); for ( i in Monitor ) { if ( ! Monitor[i] ) { @@ -75,9 +75,9 @@ function addMonitor(url) { if ( Monitor[i] == 'null' ) { Monitor[i]=''; } - popup_url += '&newMonitor['+i+']='+Monitor[i]; + urlString += '&newMonitor['+i+']='+Monitor[i]; } - createPopup( popup_url, 'zmMonitor'+mid, 'monitor' ); + window.location.assign( urlString ); } function import_csv( form ) { From 9b9138f113a0541388376c94147a4424ab6670bb Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Wed, 30 Sep 2020 12:20:24 -0500 Subject: [PATCH 018/199] replace popup calls in montagereview --- web/skins/classic/views/js/montagereview.js | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/web/skins/classic/views/js/montagereview.js b/web/skins/classic/views/js/montagereview.js index 5207f24d5..aa6bfa8a5 100644 --- a/web/skins/classic/views/js/montagereview.js +++ b/web/skins/classic/views/js/montagereview.js @@ -735,8 +735,21 @@ function click_panright() { maxTimeSecs = minTimeSecs + rangeTimeSecs - 1; clicknav(minTimeSecs, maxTimeSecs, 0); } +// Manage the DOWNLOAD VIDEO button function click_download() { - createPopup('?view=download', 'zmDownload', 'download'); + $j.getJSON(thisUrl + '?request=modal&modal=download) + .done(function(data) { + if ( $j('#downloadModal').length ) { + $j('#downloadModal').replaceWith(data.html); + } else { + $j("body").append(data.html); + } + $j('#downloadModal').modal('show'); + // Manage the GENERATE DOWNLOAD button + $j('#exportButton').click(exportEvent); + }) + .fail(logAjaxFail); + }); } function click_all_events() { clicknav(0, 0, 0); @@ -869,15 +882,15 @@ function showOneMonitor(monId) { var url; if ( liveMode != 0 ) { url = '?view=watch&mid=' + monId.toString(); - createPopup(url, 'zmWatch', 'watch', monitorWidth[monId], monitorHeight[monId]); + window.location.assign(url); } else { var Frame = getFrame(monId, currentTimeSecs); if ( Frame ) { url = '?view=event&eid=' + Frame.EventId + '&fid=' + Frame.FrameId; - createPopup(url, 'zmEvent', 'event', monitorWidth[monId], monitorHeight[monId]); + window.location.assign(url); } else { url = '?view=watch&mid=' + monId.toString(); - createPopup(url, 'zmWatch', 'watch', monitorWidth[monId], monitorHeight[monId]); + window.location.assign(url); } } // end if live/events } From 4bc373105d6f870368a81caa8d65e47a11acbcf0 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Wed, 30 Sep 2020 13:12:58 -0500 Subject: [PATCH 019/199] fix typo --- web/skins/classic/views/js/montagereview.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/skins/classic/views/js/montagereview.js b/web/skins/classic/views/js/montagereview.js index aa6bfa8a5..b992400d6 100644 --- a/web/skins/classic/views/js/montagereview.js +++ b/web/skins/classic/views/js/montagereview.js @@ -737,7 +737,7 @@ function click_panright() { } // Manage the DOWNLOAD VIDEO button function click_download() { - $j.getJSON(thisUrl + '?request=modal&modal=download) + $j.getJSON(thisUrl + '?request=modal&modal=download') .done(function(data) { if ( $j('#downloadModal').length ) { $j('#downloadModal').replaceWith(data.html); From 591a30f1fe5564a23f8752a1b03b944104aeab38 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Wed, 30 Sep 2020 13:33:11 -0500 Subject: [PATCH 020/199] fix typo --- web/skins/classic/views/js/montagereview.js | 1 - 1 file changed, 1 deletion(-) diff --git a/web/skins/classic/views/js/montagereview.js b/web/skins/classic/views/js/montagereview.js index b992400d6..a26174cfe 100644 --- a/web/skins/classic/views/js/montagereview.js +++ b/web/skins/classic/views/js/montagereview.js @@ -749,7 +749,6 @@ function click_download() { $j('#exportButton').click(exportEvent); }) .fail(logAjaxFail); - }); } function click_all_events() { clicknav(0, 0, 0); From c4cf52c2bc7f64e683315166e4e75059b51a9832 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Thu, 1 Oct 2020 08:15:20 -0500 Subject: [PATCH 021/199] new version notice is now part of the navbar --- web/skins/classic/views/js/console.js | 5 +- web/skins/classic/views/js/console.js.php | 25 ++----- web/skins/classic/views/js/version.js | 13 ---- web/skins/classic/views/js/version.js.php | 1 - web/skins/classic/views/version.php | 88 ----------------------- 5 files changed, 8 insertions(+), 124 deletions(-) delete mode 100644 web/skins/classic/views/js/version.js delete mode 100644 web/skins/classic/views/js/version.js.php delete mode 100644 web/skins/classic/views/version.php diff --git a/web/skins/classic/views/js/console.js b/web/skins/classic/views/js/console.js index 47201689d..9bc05ed9f 100644 --- a/web/skins/classic/views/js/console.js +++ b/web/skins/classic/views/js/console.js @@ -170,9 +170,6 @@ function manageFunctionModal() { function initPage() { reloadWindow.periodical(consoleRefreshTimeout); - if ( showVersionPopup ) { - window.location.assign('?view=version'); - } if ( showDonatePopup ) { $j.getJSON(thisUrl + '?request=modal&modal=donate') .done(function(data) { @@ -228,4 +225,4 @@ function applySort(event, ui) { ajax.send(); } // end function applySort(event,ui) -window.addEventListener( 'DOMContentLoaded', initPage ); +$j(document).ready(initPage ); diff --git a/web/skins/classic/views/js/console.js.php b/web/skins/classic/views/js/console.js.php index 6ef6c199c..9f5355dc6 100644 --- a/web/skins/classic/views/js/console.js.php +++ b/web/skins/classic/views/js/console.js.php @@ -1,26 +1,15 @@ var consoleRefreshTimeout = ; 0 ) { - if ( ZM_DYN_DONATE_REMINDER_TIME < time() ) { - $showDonatePopup = true; - } - } else { - $nextReminder = time() + 30*24*60*60; - dbQuery("UPDATE Config SET Value = '".$nextReminder."' WHERE Name = 'ZM_DYN_DONATE_REMINDER_TIME'"); - } +if ( canEdit('System') && ZM_DYN_SHOW_DONATE_REMINDER ) { + if ( ZM_DYN_DONATE_REMINDER_TIME > 0 ) { + if ( ZM_DYN_DONATE_REMINDER_TIME < time() ) $showDonatePopup = true; + } else { + $nextReminder = time() + 30*24*60*60; + dbQuery("UPDATE Config SET Value = '".$nextReminder."' WHERE Name = 'ZM_DYN_DONATE_REMINDER_TIME'"); } -} // end if canEdit('System') +} ?> -var showVersionPopup = ; var showDonatePopup = ; var monitors = new Array(); ; diff --git a/web/skins/classic/views/version.php b/web/skins/classic/views/version.php deleted file mode 100644 index 6552c4cd5..000000000 --- a/web/skins/classic/views/version.php +++ /dev/null @@ -1,88 +0,0 @@ - translate('GoToZoneMinder') -); - -if ( verNum(ZM_DYN_CURR_VERSION) != verNum(ZM_DYN_LAST_VERSION) and canEdit('System') ) { - $options = array_merge( $options, array( - 'ignore' => translate('VersionIgnore'), - 'hour' => translate('VersionRemindHour'), - 'day' => translate('VersionRemindDay'), - 'week' => translate('VersionRemindWeek'), - 'month' => translate('VersionRemindMonth'), - 'never' => translate('VersionRemindNever') - ) ); -} - -$focusWindow = true; - -xhtmlHeaders(__FILE__, translate('Version')); -?> - -
- -
- -

-

-
- -

-

-
- - -
- - -

-

-

-
- - - - -
-
-
-
- - From e26e36606f792301a69654ce1b658c6755212319 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Thu, 1 Oct 2020 08:46:58 -0500 Subject: [PATCH 022/199] update version check logic in navbar --- web/skins/classic/includes/functions.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/skins/classic/includes/functions.php b/web/skins/classic/includes/functions.php index bd20dc534..dc97e295a 100644 --- a/web/skins/classic/includes/functions.php +++ b/web/skins/classic/includes/functions.php @@ -524,7 +524,7 @@ function getZMVersionHTML() { $class = 'text-danger'; $tt_text = translate('RunLocalUpdate'); $content = 'v'.ZM_VERSION.PHP_EOL; - } else if ( verNum( ZM_DYN_LAST_VERSION ) <= verNum( ZM_VERSION ) ) { // No update needed + } else if ( verNum( ZM_DYN_LAST_VERSION ) <= verNum( ZM_VERSION ) || !ZM_CHECK_FOR_UPDATES || ZM_DYN_NEXT_REMINDER > time() ) { // No update needed $class = ''; // Don't change the text color under normal conditions $tt_text = translate('UpdateNotNecessary'); $content = 'v'.ZM_VERSION.PHP_EOL; From b8d95dfa053e6e457eded2a8fb6393df6fe786ec Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Thu, 1 Oct 2020 09:13:50 -0500 Subject: [PATCH 023/199] fix array to string php warning --- web/includes/functions.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/includes/functions.php b/web/includes/functions.php index b10e74eac..ea2542070 100644 --- a/web/includes/functions.php +++ b/web/includes/functions.php @@ -544,7 +544,7 @@ function htmlOptions($options, $values) { '; } # end foreach options if ( $values and ! $has_selected ) { - ZM\Warning('Specified value '.$values.' not in contents: '.print_r($options, true)); + ZM\Warning('Specified value '.print_r($values, true).' not in contents: '.print_r($options, true)); } return $options_html; } # end function htmlOptions From 928fa67fced846e9286fa2b285463c426478e59b Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Thu, 1 Oct 2020 10:45:44 -0500 Subject: [PATCH 024/199] redirect to previous view after user perm changes --- web/includes/actions/user.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/includes/actions/user.php b/web/includes/actions/user.php index acbcdab7e..9879b9c85 100644 --- a/web/includes/actions/user.php +++ b/web/includes/actions/user.php @@ -102,7 +102,7 @@ if ( $action == 'Save' ) { session_write_close(); $refreshParent = true; } - $view = 'none'; + $redirect = $_SERVER['HTTP_REFERER']; } } // end if $action == user ?> From ef958b1649b32550e3bb1169840e912b1986312b Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Thu, 1 Oct 2020 10:51:59 -0500 Subject: [PATCH 025/199] enable mgmt of x10 device permissions --- web/skins/classic/views/options.php | 2 ++ web/skins/classic/views/user.php | 4 ++++ 2 files changed, 6 insertions(+) diff --git a/web/skins/classic/views/options.php b/web/skins/classic/views/options.php index 01bda7165..a66c2cf0f 100644 --- a/web/skins/classic/views/options.php +++ b/web/skins/classic/views/options.php @@ -130,6 +130,7 @@ foreach ( array_map('basename', glob('skins/'.$skin.'/css/*', GLOB_ONLYDIR)) as + @@ -167,6 +168,7 @@ foreach ( array_map('basename', glob('skins/'.$skin.'/css/*', GLOB_ONLYDIR)) as + diff --git a/web/skins/classic/views/user.php b/web/skins/classic/views/user.php index d7fc3311b..a8d4cbec7 100644 --- a/web/skins/classic/views/user.php +++ b/web/skins/classic/views/user.php @@ -127,6 +127,10 @@ if ( canEdit('System') and ( $newUser->Username() != 'admin' ) ) { System()) ?> + + + Devices()) ?> + MaxBandwidth()) ?> From 63e42ca651342ff02b6a72aeeda4ca5bfd141a27 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Thu, 1 Oct 2020 12:57:46 -0400 Subject: [PATCH 026/199] Still need libjpeg --- distros/ubuntu2004/control | 1 + 1 file changed, 1 insertion(+) diff --git a/distros/ubuntu2004/control b/distros/ubuntu2004/control index 0a1f9e0de..a2b9ed85d 100644 --- a/distros/ubuntu2004/control +++ b/distros/ubuntu2004/control @@ -17,6 +17,7 @@ Build-Depends: debhelper, dh-systemd, sphinx-doc, python3-sphinx, dh-linktree, d ,libbz2-dev ,libgcrypt20-dev ,libcurl4-gnutls-dev + ,libjpeg9-dev | libjpeg8-dev | libjpeg62-turbo-dev ,libturbojpeg0-dev ,default-libmysqlclient-dev | libmysqlclient-dev | libmariadbclient-dev-compat ,libpcre3-dev From 5f93941755fdea808e2aeffbe17f8daf7d9d57f5 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Thu, 1 Oct 2020 13:34:52 -0400 Subject: [PATCH 027/199] Create codeql-analysis.yml Let's try out github code scanning --- .github/workflows/codeql-analysis.yml | 71 +++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 .github/workflows/codeql-analysis.yml diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml new file mode 100644 index 000000000..ce467330a --- /dev/null +++ b/.github/workflows/codeql-analysis.yml @@ -0,0 +1,71 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +name: "CodeQL" + +on: + push: + branches: [master] + pull_request: + # The branches below must be a subset of the branches above + branches: [master] + schedule: + - cron: '0 3 * * 5' + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + # Override automatic language detection by changing the below list + # Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python'] + language: ['cpp', 'javascript'] + # Learn more... + # https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection + + steps: + - name: Checkout repository + uses: actions/checkout@v2 + with: + # We must fetch at least the immediate parents so that if this is + # a pull request then we can checkout the head. + fetch-depth: 2 + + # If this run was triggered by a pull request event, then checkout + # the head of the pull request instead of the merge commit. + - run: git checkout HEAD^2 + if: ${{ github.event_name == 'pull_request' }} + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v1 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + # queries: ./path/to/local/query, your-org/your-repo/queries@main + + # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v1 + + # ℹ️ Command-line programs to run using the OS shell. + # 📚 https://git.io/JvXDl + + # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines + # and modify them (or add more) to build your code if your project + # uses a compiled language + + #- run: | + # make bootstrap + # make release + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v1 From d139dc010bb070a30dc20eae880d69ba9900c9fc Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Thu, 1 Oct 2020 13:47:39 -0400 Subject: [PATCH 028/199] prefer libjpegturbo to libjpeg8 or 9 --- distros/ubuntu2004/control | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/distros/ubuntu2004/control b/distros/ubuntu2004/control index a2b9ed85d..87c0b76d2 100644 --- a/distros/ubuntu2004/control +++ b/distros/ubuntu2004/control @@ -17,7 +17,7 @@ Build-Depends: debhelper, dh-systemd, sphinx-doc, python3-sphinx, dh-linktree, d ,libbz2-dev ,libgcrypt20-dev ,libcurl4-gnutls-dev - ,libjpeg9-dev | libjpeg8-dev | libjpeg62-turbo-dev + ,libjpeg62-turbo-dev | libjpeg8-dev | libjpeg9-dev ,libturbojpeg0-dev ,default-libmysqlclient-dev | libmysqlclient-dev | libmariadbclient-dev-compat ,libpcre3-dev From c61c111d9ebabbfcb3758dee6cafc356f61f0426 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Thu, 1 Oct 2020 12:52:20 -0500 Subject: [PATCH 029/199] modernize devices view --- web/skins/classic/views/devices.php | 19 ++++++++++++------- web/skins/classic/views/js/devices.js | 25 ++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 8 deletions(-) diff --git a/web/skins/classic/views/devices.php b/web/skins/classic/views/devices.php index 783d7775a..27a53c86d 100644 --- a/web/skins/classic/views/devices.php +++ b/web/skins/classic/views/devices.php @@ -35,9 +35,16 @@ foreach( dbFetchAll( $sql ) as $row ) xhtmlHeaders(__FILE__, translate('Devices') ); ?> +
- - - + diff --git a/web/skins/classic/views/js/devices.js b/web/skins/classic/views/js/devices.js index 703384ad2..a8d08c9d1 100644 --- a/web/skins/classic/views/js/devices.js +++ b/web/skins/classic/views/js/devices.js @@ -37,4 +37,27 @@ function configureButtons( element, name ) { form.deleteBtn.disabled = !checked; } -window.focus(); +// Manage the New button +function New(el) { + url = el.getAttribute('data-url'); + window.location.assign(url); +} + +function initPage() { + // Manage the BACK button + document.getElementById("backBtn").addEventListener("click", function onBackClick(evt) { + evt.preventDefault(); + window.history.back(); + }); + + // Disable the back button if there is nothing to go back to + $j('#backBtn').prop('disabled', !document.referrer.length); + + // Manage the REFRESH Button + document.getElementById("refreshBtn").addEventListener("click", function onRefreshClick(evt) { + evt.preventDefault(); + window.location.reload(true); + }); +} + +$j(document).ready(initPage); From fbded3eb200493e03e58818071f634ac72b0e95e Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Thu, 1 Oct 2020 14:07:11 -0400 Subject: [PATCH 030/199] Update codeql-analysis.yml Add some build dependencies --- .github/workflows/codeql-analysis.yml | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index ce467330a..bfc042066 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -57,7 +57,15 @@ jobs: uses: github/codeql-action/autobuild@v1 # ℹ️ Command-line programs to run using the OS shell. - # 📚 https://git.io/JvXDl + # 📚 https://git.io/JvXDl- + - name: Clean install dependencies and build + run: | + apt-get install libx264-dev libmp4v2-dev libavdevice-dev libavcodec-dev libavformat-dev libavutil-dev libswresample-dev libswscale-dev + apt-get install libbz2-dev libgcrypt20-dev libcurl4-gnutls-dev libjpeg62-turbo-dev libturbojpeg0-dev + apt-get install default-libmysqlclient-dev libpcre3-dev libpolkit-gobject-1-dev libv4l-dev libvlc-dev + apt-get install libdate-manip-perl libdbd-mysql-perl libphp-serialization-perl libsys-mmap-perl + apt-get install libwww-perl libdata-uuid-perl libssl-dev libcrypt-eksblowfish-perl libdata-entropy-perl + # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines # and modify them (or add more) to build your code if your project From bf66903e2e46a79b95477c5b5d93fb8d205158af Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Thu, 1 Oct 2020 14:10:55 -0400 Subject: [PATCH 031/199] Update codeql-analysis.yml Add submodule init --- .github/workflows/codeql-analysis.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index bfc042066..3a80949dd 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -65,6 +65,8 @@ jobs: apt-get install default-libmysqlclient-dev libpcre3-dev libpolkit-gobject-1-dev libv4l-dev libvlc-dev apt-get install libdate-manip-perl libdbd-mysql-perl libphp-serialization-perl libsys-mmap-perl apt-get install libwww-perl libdata-uuid-perl libssl-dev libcrypt-eksblowfish-perl libdata-entropy-perl + git submodule init + git submodule update --init --recursive # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines From 160520b3bf1b94ba5918d496891b16623f7fa6f1 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Thu, 1 Oct 2020 15:50:35 -0400 Subject: [PATCH 032/199] Update codeql-analysis.yml install dependencies before auto build --- .github/workflows/codeql-analysis.yml | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 3a80949dd..192262034 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -51,13 +51,6 @@ jobs: # Prefix the list here with "+" to use these queries and those in the config file. # queries: ./path/to/local/query, your-org/your-repo/queries@main - # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). - # If this step fails, then you should remove it and run the build manually (see below) - - name: Autobuild - uses: github/codeql-action/autobuild@v1 - - # ℹ️ Command-line programs to run using the OS shell. - # 📚 https://git.io/JvXDl- - name: Clean install dependencies and build run: | apt-get install libx264-dev libmp4v2-dev libavdevice-dev libavcodec-dev libavformat-dev libavutil-dev libswresample-dev libswscale-dev @@ -68,6 +61,14 @@ jobs: git submodule init git submodule update --init --recursive + # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v1 + + # ℹ️ Command-line programs to run using the OS shell. + # 📚 https://git.io/JvXDl- + # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines # and modify them (or add more) to build your code if your project From 3091759162c202705f62490b87d7017d550a2f48 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Thu, 1 Oct 2020 16:50:39 -0400 Subject: [PATCH 033/199] Add missing fields and impleent a control function --- scripts/ZoneMinder/lib/ZoneMinder/Monitor.pm | 59 ++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/scripts/ZoneMinder/lib/ZoneMinder/Monitor.pm b/scripts/ZoneMinder/lib/ZoneMinder/Monitor.pm index 963f75638..de53b0d3a 100644 --- a/scripts/ZoneMinder/lib/ZoneMinder/Monitor.pm +++ b/scripts/ZoneMinder/lib/ZoneMinder/Monitor.pm @@ -121,6 +121,24 @@ $serial = $primary_key = 'Id'; WebColour Exif Sequence + TotalEvents + TotalEventDiskSpace + HourEvents + HourEventDiskSpace + DayEvents + DayEventDiskSpace + WeekEvents + WeekEventDiskSpace + MonthEvents + MonthEventDiskSpace + ArchivedEvents + ArchivedEventDiskSpace + ZoneCount + Refresh + DefaultCodec + GroupIds + Latitude + Longitude ); %defaults = ( @@ -201,6 +219,23 @@ $serial = $primary_key = 'Id'; WebColour => '#ff0000', Exif => 0, Sequence => undef, + TotalEvents => undef, + TotalEventDiskSpace => undef, + HourEvents => undef, + HourEventDiskSpace => undef, + DayEvents => undef, + DayEventDiskSpace => undef, + WeekEvents => undef, + WeekEventDiskSpace => undef, + MonthEvents => undef, + MonthEventDiskSpace => undef, + ArchivedEvents => undef, + ArchivedEventDiskSpace => undef, + ZoneCount => 0, + Refresh => null, + DefaultCodec => 'auto', + Latitude => null, + Longitude => null, ); sub Server { @@ -211,6 +246,30 @@ sub Storage { return new ZoneMinder::Storage( $_[0]{StorageId} ); } # end sub Storage +sub control { + my $monitor = shift; + my $command = shift; + my $process = shift; + + if ( $command eq 'stop' or $command eq 'restart' ) { + if ( $process ) { + `/usr/bin/zmdc.pl stop $process -m $$monitor{Id}`; + } else { + `/usr/bin/zmdc.pl stop zma -m $$monitor{Id}`; + `/usr/bin/zmdc.pl stop zmc -m $$monitor{Id}`; + } + } + if ( $command eq 'start' or $command eq 'restart' ) { + if ( $process ) { + `/usr/bin/zmdc.pl start $process -m $$monitor{Id}`; + } else { + `/usr/bin/zmdc.pl start zmc -m $$monitor{Id}`; + `/usr/bin/zmdc.pl start zma -m $$monitor{Id}`; + } # end if + } +} # end sub control + + 1; __END__ From 42debf5392ae16dd37c7e3d8852ef8440d39d6cd Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Thu, 1 Oct 2020 16:50:50 -0400 Subject: [PATCH 034/199] Rough in a Zone class --- scripts/ZoneMinder/lib/ZoneMinder/Zone.pm | 105 ++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 scripts/ZoneMinder/lib/ZoneMinder/Zone.pm diff --git a/scripts/ZoneMinder/lib/ZoneMinder/Zone.pm b/scripts/ZoneMinder/lib/ZoneMinder/Zone.pm new file mode 100644 index 000000000..986c5a4dc --- /dev/null +++ b/scripts/ZoneMinder/lib/ZoneMinder/Zone.pm @@ -0,0 +1,105 @@ +# ========================================================================== +# +# ZoneMinder Zone Module +# Copyright (C) 2020 ZoneMinder LLC +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +# +# ========================================================================== + +package ZoneMinder::Zone; + +use 5.006; +use strict; +use warnings; + +require ZoneMinder::Base; +require ZoneMinder::Object; + +#our @ISA = qw(Exporter ZoneMinder::Base); +use parent qw(ZoneMinder::Object); + +use vars qw/ $table $primary_key %fields $serial %defaults $debug/; +$table = 'Zones'; +$serial = $primary_key = 'Id'; +%fields = map { $_ => $_ } qw( + Id + Name + MonitorId + Type + Units + CheckMethod + MinPixelThreshold + MaxPixelThreshold + MinAlarmPixels + MaxAlarmPixels + FilterX + FilterY + MinFilterPixels + MaxFilterPixels + MinBlobPixels + MaxBlobPixels + MinBlobs + MaxBlobs + OverloadFrames + ExtendAlarmFrames + ); + +%defaults = ( + Name => '', + Type => 'Active', + Units => 'Pixels', + CheckMethod => 'Blobs', + MinPixelThreshold => undef, + MaxPixelThreshold => undef, + MinAlarmPixels => undef, + MaxAlarmPixels => undef, + FilterX => undef, + FilterY => undef, + MinFilterPixels => undef, + MaxFilterPixels => undef, + MinBlobPixels => undef, + MaxBlobPixels => undef, + MinBlobs => undef, + MaxBlobs => undef, + OverloadFrames => 0, + ExtendAlarmFrames => 0, +); + +1; +__END__ + +=head1 NAME + +ZoneMinder::Zone - Perl Class for Zones + +=head1 SYNOPSIS + +use ZoneMinder::Zone; + +=head1 AUTHOR + +Isaac Connor, Eisaac@zoneminder.comE + +=head1 COPYRIGHT AND LICENSE + +Copyright (C) 2001-2017 ZoneMinder LLC + +This library is free software; you can redistribute it and/or modify +it under the same terms as Perl itself, either Perl version 5.8.3 or, +at your option, any later version of Perl 5 you may have available. + + +=cut From 186b8ac947935306890aace5fa8cef849a4f8821 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Thu, 1 Oct 2020 15:52:33 -0500 Subject: [PATCH 035/199] convert x10 device view to a modal --- web/ajax/modals/device.php | 54 ++++++++++++++++++ web/includes/actions/device.php | 8 ++- web/skins/classic/views/device.php | 67 ----------------------- web/skins/classic/views/devices.php | 10 ++-- web/skins/classic/views/js/devices.js | 39 +++++++++++-- web/skins/classic/views/js/devices.js.php | 1 + 6 files changed, 100 insertions(+), 79 deletions(-) create mode 100644 web/ajax/modals/device.php delete mode 100644 web/skins/classic/views/device.php create mode 100644 web/skins/classic/views/js/devices.js.php diff --git a/web/ajax/modals/device.php b/web/ajax/modals/device.php new file mode 100644 index 000000000..5a29785ef --- /dev/null +++ b/web/ajax/modals/device.php @@ -0,0 +1,54 @@ + "", + "Name" => "New Device", + "KeyString" => "" + ); +} + +?> + diff --git a/web/includes/actions/device.php b/web/includes/actions/device.php index c1a882d89..29011dd73 100644 --- a/web/includes/actions/device.php +++ b/web/includes/actions/device.php @@ -28,15 +28,17 @@ if ( $action == 'device' ) { if ( !empty($_REQUEST['command']) ) { setDeviceStatusX10($_REQUEST['key'], $_REQUEST['command']); } else if ( isset($_REQUEST['newDevice']) ) { - if ( isset($_REQUEST['did']) ) { + if ( isset($_REQUEST['did']) && $_REQUEST['did'] ) { + ZM\Warning('did value is: '.$_REQUEST['did']); + ZM\Warning('newDevice array value is: '.print_r($_REQUEST['newDevice'],true)); dbQuery('UPDATE Devices SET Name=?, KeyString=? WHERE Id=?', array($_REQUEST['newDevice']['Name'], $_REQUEST['newDevice']['KeyString'], $_REQUEST['did']) ); } else { + dbQuery('INSERT INTO Devices SET Name=?, KeyString=?', array($_REQUEST['newDevice']['Name'], $_REQUEST['newDevice']['KeyString']) ); } - $refreshParent = true; - $view = 'none'; + $redirect = '?view=devices'; } } else { ZM\Error('Unknown action in device'); diff --git a/web/skins/classic/views/device.php b/web/skins/classic/views/device.php deleted file mode 100644 index fa1a6a9d4..000000000 --- a/web/skins/classic/views/device.php +++ /dev/null @@ -1,67 +0,0 @@ - "", - "Name" => "New Device", - "KeyString" => "" - ); -} - -xhtmlHeaders( __FILE__, translate('Device')." - ".$newDevice['Name'] ); -?> - -
- -
-
- - - - - - - - - - - - - - -
-
- disabled="disabled"/> -
-
-
-
- - diff --git a/web/skins/classic/views/devices.php b/web/skins/classic/views/devices.php index 27a53c86d..7bfdb52c0 100644 --- a/web/skins/classic/views/devices.php +++ b/web/skins/classic/views/devices.php @@ -59,15 +59,15 @@ foreach( $devices as $device ) { if ( $device['Status'] == 'ON' ) { - $fclass = "infoText"; + $fclass = "deviceCol infoText"; } elseif ( $device['Status'] == 'OFF' ) { - $fclass = "warnText"; + $fclass = "deviceCol warnText"; } else { - $fclass = "errorText"; + $fclass = "deviceCol errorText"; } ?> @@ -82,8 +82,8 @@ foreach( $devices as $device )
- - + +
diff --git a/web/skins/classic/views/js/devices.js b/web/skins/classic/views/js/devices.js index a8d08c9d1..eb7810b0f 100644 --- a/web/skins/classic/views/js/devices.js +++ b/web/skins/classic/views/js/devices.js @@ -1,3 +1,5 @@ +var newDeviceBtn = $j('#newDeviceBtn'); + function switchDeviceOn( element, key ) { var form = element.form; form.view.value = currentView; @@ -37,13 +39,42 @@ function configureButtons( element, name ) { form.deleteBtn.disabled = !checked; } -// Manage the New button -function New(el) { - url = el.getAttribute('data-url'); - window.location.assign(url); +// Load the Device Modal HTML via Ajax call +function getDeviceModal(did) { + $j.getJSON(thisUrl + '?request=modal&modal=device&did=' + did) + .done(function(data) { + if ( $j('#deviceModal').length ) { + $j('#deviceModal').replaceWith(data.html); + } else { + $j("body").append(data.html); + } + $j('#deviceModal').modal('show'); + // Manage the Save button + $j('#deviceSaveBtn').click(function(evt) { + evt.preventDefault(); + $j('#deviceModalForm').submit(); + }); + }) + .fail(logAjaxFail); +} + +function enableDeviceModal() { + $j(".deviceCol").click(function(evt) { + evt.preventDefault(); + var did = $j(this).data('did'); + getDeviceModal(did); + }); + newDeviceBtn.click(function(evt) { + evt.preventDefault(); + getDeviceModal(0); + }); } function initPage() { + if ( canEditDevice ) enableDeviceModal(); + + newDeviceBtn.prop('disabled', !canEditDevice); + // Manage the BACK button document.getElementById("backBtn").addEventListener("click", function onBackClick(evt) { evt.preventDefault(); diff --git a/web/skins/classic/views/js/devices.js.php b/web/skins/classic/views/js/devices.js.php new file mode 100644 index 000000000..f80541494 --- /dev/null +++ b/web/skins/classic/views/js/devices.js.php @@ -0,0 +1 @@ +var canEditDevice = ; From a80b4b91fb170b7905537cf329c55bc89d500608 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Thu, 1 Oct 2020 16:03:58 -0500 Subject: [PATCH 036/199] fix x10 device edit --- web/skins/classic/views/devices.php | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/web/skins/classic/views/devices.php b/web/skins/classic/views/devices.php index 7bfdb52c0..4a0688d70 100644 --- a/web/skins/classic/views/devices.php +++ b/web/skins/classic/views/devices.php @@ -55,23 +55,20 @@ xhtmlHeaders(__FILE__, translate('Devices') ); - + From 9fec7c8e5aff5072b33c577b50c905bc9302c7fa Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Thu, 1 Oct 2020 17:11:20 -0400 Subject: [PATCH 037/199] Update codeql-analysis.yml remove dependencies, need to figure out how to make it install them. Just do submodule init for now. --- .github/workflows/codeql-analysis.yml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 192262034..e72fb09bb 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -53,11 +53,6 @@ jobs: - name: Clean install dependencies and build run: | - apt-get install libx264-dev libmp4v2-dev libavdevice-dev libavcodec-dev libavformat-dev libavutil-dev libswresample-dev libswscale-dev - apt-get install libbz2-dev libgcrypt20-dev libcurl4-gnutls-dev libjpeg62-turbo-dev libturbojpeg0-dev - apt-get install default-libmysqlclient-dev libpcre3-dev libpolkit-gobject-1-dev libv4l-dev libvlc-dev - apt-get install libdate-manip-perl libdbd-mysql-perl libphp-serialization-perl libsys-mmap-perl - apt-get install libwww-perl libdata-uuid-perl libssl-dev libcrypt-eksblowfish-perl libdata-entropy-perl git submodule init git submodule update --init --recursive From 06519895d4424993c25b9f7ea737f1018b6d8938 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Fri, 2 Oct 2020 09:04:03 -0400 Subject: [PATCH 038/199] FATAL_ERROR to WARNING. The purpose is to allow codeQL to build cpp even though the perl deps havn't been installed. --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 98457b7c3..f2fee93b2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -806,7 +806,7 @@ find_package( Getopt::Long Time::HiRes Date::Manip LWP::UserAgent ExtUtils::MakeMaker ${ZM_MMAP_PERLPACKAGE}) if(NOT PERLMODULES_FOUND) - message(FATAL_ERROR + message(WARNING "Not all required perl modules were found on your system") endif(NOT PERLMODULES_FOUND) From 7f06920f4a1c0946ff3dbba803a450f136b55467 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Fri, 2 Oct 2020 10:33:42 -0400 Subject: [PATCH 039/199] convert polkit FATAL_ERROR to a WARNING so that codeQL will build --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index f2fee93b2..310d194d2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -842,7 +842,7 @@ if(WITH_SYSTEMD) # Check for polkit find_package(Polkit) if(NOT POLKIT_FOUND) - message(FATAL_ERROR + message(WARNING "Running ZoneMinder requires polkit. Building ZoneMinder requires the polkit development package.") endif(NOT POLKIT_FOUND) endif(WITH_SYSTEMD) From 1691e4321bafd25e4e6cb9f6737dfb7c1e376c91 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Fri, 2 Oct 2020 10:28:50 -0500 Subject: [PATCH 040/199] don't log ajax response text if it is empty --- web/skins/classic/js/skin.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/web/skins/classic/js/skin.js b/web/skins/classic/js/skin.js index 5cc4b9534..600b68502 100644 --- a/web/skins/classic/js/skin.js +++ b/web/skins/classic/js/skin.js @@ -864,8 +864,9 @@ function stateStuff(action, runState, newState) { } function logAjaxFail(jqxhr, textStatus, error) { + var responseText = jqxhr.responseText.replace(/(<([^>]+)>)/gi, '').trim(); // strip any html or whitespace from the response console.log("Request Failed: " + textStatus + ", " + error); - console.log("Response Text: " + jqxhr.responseText.replace(/(<([^>]+)>)/gi, '')); // strip any html from the response + if ( responseText ) console.log("Response Text: " + responseText); } // Load the Modal HTML via Ajax call From db7cfede4a9abbfde82a6aaed8ad47af9f3262d8 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Fri, 2 Oct 2020 12:45:49 -0400 Subject: [PATCH 041/199] Put back dependency install only using sudo now --- .github/workflows/codeql-analysis.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index e72fb09bb..87e01950d 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -55,6 +55,11 @@ jobs: run: | git submodule init git submodule update --init --recursive + sudo apt-get install libx264-dev libmp4v2-dev libavdevice-dev libavcodec-dev libavformat-dev libavutil-dev libswresample-dev libswscale-dev + sudo apt-get install libbz2-dev libgcrypt20-dev libcurl4-gnutls-dev libjpeg62-turbo-dev libturbojpeg0-dev + sudo apt-get install default-libmysqlclient-dev libpcre3-dev libpolkit-gobject-1-dev libv4l-dev libvlc-dev + sudo apt-get install libdate-manip-perl libdbd-mysql-perl libphp-serialization-perl libsys-mmap-perl + sudo apt-get install libwww-perl libdata-uuid-perl libssl-dev libcrypt-eksblowfish-perl libdata-entropy-perl # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) From 5d0c812dfb19f3226dd837884421fce48cfe6c98 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Fri, 2 Oct 2020 12:46:53 -0400 Subject: [PATCH 042/199] fix resource leak on error --- src/zm_eventstream.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/zm_eventstream.cpp b/src/zm_eventstream.cpp index b9abf5e76..00612ebfd 100644 --- a/src/zm_eventstream.cpp +++ b/src/zm_eventstream.cpp @@ -1048,12 +1048,14 @@ bool EventStream::send_file(const char * filepath) { return false; } } - if ( fwrite(img_buffer, img_buffer_size, 1, stdout) != 1 ) { + int rc = fwrite(img_buffer, img_buffer_size, 1, stdout); + fclose(fdj); /* Close the file handle */ + + if ( rc != 1 ) { Error("Unable to send raw frame %u: %s", curr_frame_id, strerror(errno)); return false; } - fclose(fdj); /* Close the file handle */ return true; } // end bool EventStream::send_file(const char * filepath) From 387f5dd39778515ec61d37e947177e8dfef2353c Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Fri, 2 Oct 2020 12:47:05 -0400 Subject: [PATCH 043/199] Fix double free of image --- src/zm_zone.cpp | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/zm_zone.cpp b/src/zm_zone.cpp index 974409ff3..8fc7f88c9 100644 --- a/src/zm_zone.cpp +++ b/src/zm_zone.cpp @@ -126,7 +126,8 @@ void Zone::Setup( Zone::~Zone() { delete[] label; - delete image; + if ( image ) + delete image; delete pg_image; delete[] ranges; } @@ -158,7 +159,8 @@ void Zone::SetScore(unsigned int nScore) { } // end void Zone::SetScore(unsigned int nScore) void Zone::SetAlarmImage(const Image* srcImage) { - delete image; + if ( image ) + delete image; image = new Image(*srcImage); } // end void Zone::SetAlarmImage( const Image* srcImage ) @@ -205,7 +207,8 @@ bool Zone::CheckAlarms(const Image *delta_image) { return false; } - delete image; + if ( image ) + delete image; // Get the difference image Image *diff_image = image = new Image(*delta_image); int diff_width = diff_image->Width(); @@ -734,14 +737,12 @@ bool Zone::CheckAlarms(const Image *delta_image) { // Only need to delete this when 'image' becomes detached and points somewhere else delete diff_image; - } else { - delete image; - image = 0; - } + diff_image = nullptr; + } // end if ( (type < PRECLUSIVE) && (check_method >= BLOBS) && (monitor->GetOptSaveJPEGs() > 1) Debug(1, "%s: Pixel Diff: %d, Alarm Pixels: %d, Filter Pixels: %d, Blob Pixels: %d, Blobs: %d, Score: %d", Label(), pixel_diff, alarm_pixels, alarm_filter_pixels, alarm_blob_pixels, alarm_blobs, score); - } + } // end if score return true; } From 4b10d22ea8ddfa2e1944c872d1e2628fa80b88f3 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Fri, 2 Oct 2020 12:55:44 -0400 Subject: [PATCH 044/199] correct the version on libjpeg-turbo --- distros/ubuntu2004/control | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/distros/ubuntu2004/control b/distros/ubuntu2004/control index 87c0b76d2..25345e96d 100644 --- a/distros/ubuntu2004/control +++ b/distros/ubuntu2004/control @@ -17,7 +17,7 @@ Build-Depends: debhelper, dh-systemd, sphinx-doc, python3-sphinx, dh-linktree, d ,libbz2-dev ,libgcrypt20-dev ,libcurl4-gnutls-dev - ,libjpeg62-turbo-dev | libjpeg8-dev | libjpeg9-dev + ,libjpeg-turbo8-dev | libjpeg8-dev | libjpeg9-dev ,libturbojpeg0-dev ,default-libmysqlclient-dev | libmysqlclient-dev | libmariadbclient-dev-compat ,libpcre3-dev From edf3d989b51aa41c3792491b972cf3be57ef6aa8 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Fri, 2 Oct 2020 12:56:09 -0400 Subject: [PATCH 045/199] correct the version on libjpeg-turbo --- .github/workflows/codeql-analysis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 87e01950d..82320c4cf 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -56,7 +56,7 @@ jobs: git submodule init git submodule update --init --recursive sudo apt-get install libx264-dev libmp4v2-dev libavdevice-dev libavcodec-dev libavformat-dev libavutil-dev libswresample-dev libswscale-dev - sudo apt-get install libbz2-dev libgcrypt20-dev libcurl4-gnutls-dev libjpeg62-turbo-dev libturbojpeg0-dev + sudo apt-get install libbz2-dev libgcrypt20-dev libcurl4-gnutls-dev libjpeg-turbo8-dev libturbojpeg0-dev sudo apt-get install default-libmysqlclient-dev libpcre3-dev libpolkit-gobject-1-dev libv4l-dev libvlc-dev sudo apt-get install libdate-manip-perl libdbd-mysql-perl libphp-serialization-perl libsys-mmap-perl sudo apt-get install libwww-perl libdata-uuid-perl libssl-dev libcrypt-eksblowfish-perl libdata-entropy-perl From 1c54efa88d5c56bc682dab3f838ca1810e84380a Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Fri, 2 Oct 2020 12:59:56 -0400 Subject: [PATCH 046/199] Add apt-get update so that we don't get 404 errors --- .github/workflows/codeql-analysis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 82320c4cf..4a55614da 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -55,6 +55,7 @@ jobs: run: | git submodule init git submodule update --init --recursive + sudo apt-get update sudo apt-get install libx264-dev libmp4v2-dev libavdevice-dev libavcodec-dev libavformat-dev libavutil-dev libswresample-dev libswscale-dev sudo apt-get install libbz2-dev libgcrypt20-dev libcurl4-gnutls-dev libjpeg-turbo8-dev libturbojpeg0-dev sudo apt-get install default-libmysqlclient-dev libpcre3-dev libpolkit-gobject-1-dev libv4l-dev libvlc-dev From 6c0f61ebbd7a564541b7ce97f68caa51b1eb7352 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Fri, 2 Oct 2020 12:39:05 -0500 Subject: [PATCH 047/199] rework devices view, remove inline onclick --- web/ajax/device.php | 47 +++++++++ web/ajax/devices.php | 38 ++++++++ web/lang/en_gb.php | 1 + web/skins/classic/views/devices.php | 69 +++++++++----- web/skins/classic/views/js/devices.js | 132 ++++++++++++++++++-------- 5 files changed, 223 insertions(+), 64 deletions(-) create mode 100644 web/ajax/device.php create mode 100644 web/ajax/devices.php diff --git a/web/ajax/device.php b/web/ajax/device.php new file mode 100644 index 000000000..71e76d8f7 --- /dev/null +++ b/web/ajax/device.php @@ -0,0 +1,47 @@ + diff --git a/web/ajax/devices.php b/web/ajax/devices.php new file mode 100644 index 000000000..25d17af49 --- /dev/null +++ b/web/ajax/devices.php @@ -0,0 +1,38 @@ + diff --git a/web/lang/en_gb.php b/web/lang/en_gb.php index 561ad2cb5..56e6d56b6 100644 --- a/web/lang/en_gb.php +++ b/web/lang/en_gb.php @@ -262,6 +262,7 @@ $SLANG = array( 'ConfiguredFor' => 'Configured for', 'ConfigURL' => 'Config Base URL', 'ConfirmDeleteControl' => 'Warning, deleting a control will reset all monitors that use it to be uncontrollable.

Are you sure you wish to delete?', + 'ConfirmDeleteDevices' => 'Are you sure you wish to delete the selected devices?', 'ConfirmDeleteEvents' => 'Are you sure you wish to delete the selected events?', 'ConfirmDeleteTitle' => 'Delete Confirmation', 'ConfirmPassword' => 'Confirm Password', diff --git a/web/skins/classic/views/devices.php b/web/skins/classic/views/devices.php index 4a0688d70..2b77459cc 100644 --- a/web/skins/classic/views/devices.php +++ b/web/skins/classic/views/devices.php @@ -36,23 +36,45 @@ xhtmlHeaders(__FILE__, translate('Devices') ); ?> -
-
-
- - -
-
-

-
+
+

X10

+ +
+ + + +
-
-
- - - - -
'.validHtmlStr($device['Name']).' ('.validHtmlStr($device['KeyString']).')', canEdit( 'Devices' ) ) ?>'.validHtmlStr($device['Name']).' ('.validHtmlStr($device['KeyString']).')', canEdit( 'Devices' ), $str_opt ) ?> onclick="switchDeviceOn( this, '' )"/> onclick="switchDeviceOff( this, '' )"/> disabled="disabled"/>
+ +
+
+ + + + + + + + + + + + - - - - + + + + + +
'.validHtmlStr($device['Name']).' ('.validHtmlStr($device['KeyString']).')', canEdit( 'Devices' ), $str_opt ) ?> onclick="switchDeviceOn( this, '' )"/> onclick="switchDeviceOff( this, '' )"/> disabled="disabled"/>'.validHtmlStr($device['Name']).'', canEdit( 'Devices' ), $str_opt ) ?>'.validHtmlStr($device['KeyString']).'', canEdit( 'Devices' ), $str_opt ) ?>
-
- - -
-
diff --git a/web/skins/classic/views/js/devices.js b/web/skins/classic/views/js/devices.js index eb7810b0f..cf1a5fa4e 100644 --- a/web/skins/classic/views/js/devices.js +++ b/web/skins/classic/views/js/devices.js @@ -1,43 +1,6 @@ var newDeviceBtn = $j('#newDeviceBtn'); - -function switchDeviceOn( element, key ) { - var form = element.form; - form.view.value = currentView; - form.action.value = 'device'; - form.command.value = 'on'; - form.key.value = key; - form.submit(); -} - -function switchDeviceOff( element, key ) { - var form = element.form; - form.view.value = currentView; - form.action.value = 'device'; - form.command.value = 'off'; - form.key.value = key; - form.submit(); -} - -function deleteDevice( element ) { - var form = element.form; - form.view.value = currentView; - form.action.value = 'delete'; - form.submit(); -} - -function configureButtons( element, name ) { - var form = element.form; - var checked = false; - for (var i = 0; i < form.elements.length; i++) { - if ( form.elements[i].name.indexOf(name) == 0) { - if ( form.elements[i].checked ) { - checked = true; - break; - } - } - } - form.deleteBtn.disabled = !checked; -} +var table = $j('#devicesTable'); +var deleteBtn = $j('#deleteBtn'); // Load the Device Modal HTML via Ajax call function getDeviceModal(did) { @@ -70,7 +33,72 @@ function enableDeviceModal() { }); } +// Load the Delete Confirmation Modal HTML via Ajax call +function getDelConfirmModal(key) { + $j.getJSON(thisUrl + '?request=modal&modal=delconfirm&key=' + key) + .done(function(data) { + if ( $j('#deleteConfirm').length ) { + $j('#deleteConfirm').replaceWith(data.html); + } else { + $j("body").append(data.html); + } + manageDelConfirmModalBtns(); + }) + .fail(logAjaxFail); +} + +// Manage the DELETE CONFIRMATION modal button +function manageDelConfirmModalBtns() { + document.getElementById("delConfirmBtn").addEventListener("click", function onDelConfirmClick(evt) { + if ( ! canEditDevice ) { + enoperm(); + return; + } + + var selections = getIdSelections(); + + evt.preventDefault(); + $j.getJSON(thisUrl + '?request=devices&action=delete&markDids[]='+selections.join('&markDids[]=')) + .done( function(data) { + $j('#devicesTable').bootstrapTable('refresh'); + window.location.reload(true); + }) + .fail(logAjaxFail); + }); + + // Manage the CANCEL modal button + document.getElementById("delCancelBtn").addEventListener("click", function onDelCancelClick(evt) { + $j('#deleteConfirm').modal('hide'); + }); +} + +// Returns the event id's of the selected rows +function getIdSelections() { + return $j.map(table.bootstrapTable('getSelections'), function(row) { + return row.Id.replace(/(<([^>]+)>)/gi, ''); // strip the html from the element before sending + }); +} + +// Take the appropriate action when the user clicks on cells in the table +function processClicks(event, field, value, row, $element) { + if ( field == 'On' || field == 'Off' ) { + var key = row.KeyString.replace(/(<([^>]+)>)/gi, ''); + var url = '?request=device&action=device&command=' + field + '&key=' + key; + console.log('Url sent to device: ' + url); + $j.getJSON(thisUrl + url) + .done(function(data) { + // TODO - verify if either of these are needed + $j('#devicesTable').bootstrapTable('refresh'); + window.location.reload(true); + }) + .fail(logAjaxFail); + } +} + function initPage() { + // Init the bootstrap-table + table.bootstrapTable({icons: icons}); + if ( canEditDevice ) enableDeviceModal(); newDeviceBtn.prop('disabled', !canEditDevice); @@ -89,6 +117,32 @@ function initPage() { evt.preventDefault(); window.location.reload(true); }); + + // Manage the DELETE button + document.getElementById("deleteBtn").addEventListener("click", function onDeleteClick(evt) { + if ( ! canEditDevice ) { + enoperm(); + return; + } + + evt.preventDefault(); + $j('#deleteConfirm').modal('show'); + }); + + // Load the delete confirmation modal into the DOM + getDelConfirmModal('ConfirmDeleteDevices'); + + // enable or disable buttons based on current selection and user rights + table.on('check.bs.table uncheck.bs.table ' + + 'check-all.bs.table uncheck-all.bs.table', + function() { + selections = table.bootstrapTable('getSelections'); + + deleteBtn.prop('disabled', !(selections.length && canEditDevice)); + }); + + // Process mouse clicks on the table cells + table.on('click-cell.bs.table', processClicks); } $j(document).ready(initPage); From 950b04c659dc049f6eed332e9d66de754a630ea7 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Fri, 2 Oct 2020 12:51:17 -0500 Subject: [PATCH 048/199] convert popuplink --- web/skins/classic/views/montage.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/skins/classic/views/montage.php b/web/skins/classic/views/montage.php index 1c62fddf4..ee6b1dc24 100644 --- a/web/skins/classic/views/montage.php +++ b/web/skins/classic/views/montage.php @@ -152,7 +152,7 @@ xhtmlHeaders(__FILE__, translate('Montage'));
From c5f69b94415976426b1844e8ea3ccacd1db7d3ea Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Fri, 2 Oct 2020 13:24:30 -0500 Subject: [PATCH 049/199] eslint --- web/skins/classic/views/js/devices.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/web/skins/classic/views/js/devices.js b/web/skins/classic/views/js/devices.js index cf1a5fa4e..e8b3e25c1 100644 --- a/web/skins/classic/views/js/devices.js +++ b/web/skins/classic/views/js/devices.js @@ -86,12 +86,12 @@ function processClicks(event, field, value, row, $element) { var url = '?request=device&action=device&command=' + field + '&key=' + key; console.log('Url sent to device: ' + url); $j.getJSON(thisUrl + url) - .done(function(data) { - // TODO - verify if either of these are needed - $j('#devicesTable').bootstrapTable('refresh'); - window.location.reload(true); - }) - .fail(logAjaxFail); + .done(function(data) { + // TODO - verify if either of these are needed + $j('#devicesTable').bootstrapTable('refresh'); + window.location.reload(true); + }) + .fail(logAjaxFail); } } From 7b5090ceab7ab52fbf7d9ee2ff7fa1fb99063c5f Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Fri, 2 Oct 2020 13:26:35 -0500 Subject: [PATCH 050/199] move newlog view to log view --- web/skins/classic/css/base/views/log.css | 33 -- web/skins/classic/css/base/views/newlog.css | 18 - web/skins/classic/views/js/log.js | 435 +++++--------------- web/skins/classic/views/js/newlog.js | 105 ----- web/skins/classic/views/log.php | 128 +++--- web/skins/classic/views/newlog.php | 91 ---- 6 files changed, 152 insertions(+), 658 deletions(-) delete mode 100644 web/skins/classic/css/base/views/newlog.css delete mode 100644 web/skins/classic/views/js/newlog.js delete mode 100644 web/skins/classic/views/newlog.php diff --git a/web/skins/classic/css/base/views/log.css b/web/skins/classic/css/base/views/log.css index de6e5eecd..918c1097c 100644 --- a/web/skins/classic/css/base/views/log.css +++ b/web/skins/classic/css/base/views/log.css @@ -1,19 +1,3 @@ -#logSummary { - font-size:10px; -} - -#logSummary tr { - margin: 0; - padding: 0; -} - -#logSummary td { - border: 1px solid #7f7fb2; - padding: 0 6px; - font-size: 10px; - line-height: 15px; -} - tr.log-fat td { background-color:#ffcccc; font-weight: bold; @@ -32,20 +16,3 @@ tr.log-dbg td { font-style: italic; } -#exportLog label { - vertical-align: middle; -} - -#exportLog input[type=radio] { - margin-right: 4px; - vertical-align: middle; -} - -#exportError { - display: none; - color: #dc143c; - margin-bottom: 8px; -} - -#exportErrorText { -} diff --git a/web/skins/classic/css/base/views/newlog.css b/web/skins/classic/css/base/views/newlog.css deleted file mode 100644 index 918c1097c..000000000 --- a/web/skins/classic/css/base/views/newlog.css +++ /dev/null @@ -1,18 +0,0 @@ -tr.log-fat td { - background-color:#ffcccc; - font-weight: bold; -} - -tr.log-err td { - background-color:#ffcccc; -} - -tr.log-war td { - background-color: #ffe4b5; -} - -tr.log-dbg td { - color: #666666; - font-style: italic; -} - diff --git a/web/skins/classic/views/js/log.js b/web/skins/classic/views/js/log.js index 53f197eab..ddaabcfc8 100644 --- a/web/skins/classic/views/js/log.js +++ b/web/skins/classic/views/js/log.js @@ -1,356 +1,105 @@ -var logParms = 'view=request&request=log&task=query'; -var logReq = new Request.JSON( {url: thisUrl, method: 'post', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: logResponse} ); -var logTimer = undefined; -var logTable = undefined; +var table = $j('#logTable'); -var logCodes = { - '0': 'INF', - '-1': 'WAR', - '-2': 'ERR', - '-3': 'FAT', - '-4': 'PNC', +/* +This is the format of the json object sent by bootstrap-table + +var params = +{ +"type":"get", +"data": + { + "search":"some search text", + "sort":"DateTime", + "order":"asc", + "offset":0, + "limit":25 + "filter": + { + "message":"some advanced search text" + "level":"some more advanced search text" + } + }, +"cache":true, +"contentType":"application/json", +"dataType":"json" }; +*/ -var minSampleTime = 2000; -var maxSampleTime = 16000; -var minLogTime = 0; -var maxLogTime = 0; -var logCount = 0; -var maxLogFetch = 100; -var filter = {}; -var logTimeout = maxSampleTime; -var firstLoad = true; -var initialDisplayLimit = 200; -var sortReversed = false; -var filterFields = ['Component', 'ServerId', 'Pid', 'Level', 'File', 'Line']; -var options = {}; - -function escapeHtml(unsafe) { - return unsafe - .replace(/&/g, "&") - .replace(//g, ">") - .replace(/"/g, """) - .replace(/'/g, "'"); +// Called by bootstrap-table to retrieve zm log data +function ajaxRequest(params) { + $j.getJSON(thisUrl + '?view=request&request=newlog&task=query', params.data) + .done(function(data) { + //console.log('Ajax parameters: ' + JSON.stringify(params)); + // rearrange the result into what bootstrap-table expects + params.success({total: data.total, totalNotFiltered: data.totalNotFiltered, rows: data.rows}); + updateHeaderStats(data); + }) + .fail(logAjaxFail); } -function buildFetchParms( parms ) { - var fetchParms = logParms+'&limit='+maxLogFetch; - if ( parms ) { - fetchParms += '&'+parms; - } - Object.each(filter, - function( value, key ) { - fetchParms += '&filter['+key+']='+value; - } - ); - return fetchParms; -} +function updateHeaderStats(data) { + var pageNum = table.bootstrapTable('getOptions').pageNumber; + var pageSize = table.bootstrapTable('getOptions').pageSize; + var startRow = ( (pageNum - 1 ) * pageSize ) + 1; + var stopRow = pageNum * pageSize; + var newClass = (data.logstate == 'ok') ? 'text-success' : (data.logstate == 'alert' ? 'text-warning' : ((data.logstate == 'alarm' ? 'text-danger' : ''))); -function fetchNextLogs() { - logReq.send( buildFetchParms( 'minTime='+maxLogTime ) ); -} + $j('#logState').text(data.logstate); + $j('#logState').removeClass('text-success'); + $j('#logState').removeClass('text-warning'); + $j('#logState').removeClass('text-danger'); + $j('#logState').addClass(newClass); -function fetchPrevLogs() { - logReq.send( buildFetchParms( 'maxTime='+minLogTime ) ); -} - -function logResponse( respObj ) { - if ( logTimer ) { - logTimer = clearTimeout( logTimer ); - } - - if ( respObj.result == 'Ok' ) { - if ( respObj.logs.length > 0 ) { - logTimeout = minSampleTime; - logCount += respObj.logs.length; - try { - respObj.logs.each( - function( log ) { - if ( ( !maxLogTime ) || ( log.TimeKey > maxLogTime ) ) { - maxLogTime = log.TimeKey; - } - if ( ( !minLogTime ) || ( log.TimeKey < minLogTime ) ) { - minLogTime = log.TimeKey; - } - - var row = logTable.push([ - {content: log.DateTime, properties: {style: 'white-space: nowrap'}}, - log.Component, log.Server, log.Pid, log.Code, - escapeHtml(log.Message), - escapeHtml(log.File), - log.Line - ]); - - delete log.Message; - row.tr.store( 'log', log ); - if ( log.Level <= -3 ) { - row.tr.addClass( 'log-fat' ); - } else if ( log.Level <= -2 ) { - row.tr.addClass( 'log-err' ); - } else if ( log.Level <= -1 ) { - row.tr.addClass( 'log-war' ); - } else if ( log.Level > 0 ) { - row.tr.addClass( 'log-dbg' ); - } - if ( !firstLoad ) { - var color = document.defaultView.getComputedStyle(row.tr, null).getPropertyValue('color'); - var colorParts = color.match(/^rgb.*\((\d+),\s*(\d+),\s*(\d+)/); - rowOrigColor = '#' + parseInt(colorParts[1]).toString(16) + parseInt(colorParts[2]).toString(16) + parseInt(colorParts[3]).toString(16); - //new Fx.Tween( row.tr, { duration: 10000, transition: Fx.Transitions.Sine } ).start( 'color', '#6495ED', rowOrigColor ); - } - } - ); - if ( typeof(respObj.options) == 'object' ) { - $j.each( respObj.options, - function( field ) { - if ( options[field] ) { - options[field] = Object.assign(options[field], respObj.options[field]); - } else { - options[field] = respObj.options[field]; - } - } - ); - } - updateFilterSelectors(); - $('lastUpdate').set('text', respObj.updated); - $('logState').set('text', respObj.state); - $('logState').removeClass('ok'); - $('logState').removeClass('alert'); - $('logState').removeClass('alarm'); - $('logState').addClass(respObj.state); - $('totalLogs').set('text', respObj.total); - $('availLogs').set('text', respObj.available); - $('displayLogs').set('text', logCount); - if ( firstLoad ) { - if ( logCount < displayLimit ) { - fetchPrevLogs(); - } - } - logTable.reSort(); - } catch ( e ) { - console.error( e ); - } - logTimeout /= 2; - if ( logTimeout < minSampleTime ) { - logTimeout = minSampleTime; - } - } else { - firstLoad = false; - logTimeout *= 2; - if ( logTimeout > maxSampleTime ) { - logTimeout = maxSampleTime; - } - } // end logs.length > 0 - } // end if result == Ok - logTimer = fetchNextLogs.delay( logTimeout ); -} - -function refreshLog() { - options = {}; - $j('#logTable tbody').empty(); - firstLoad = true; - maxLogTime = 0; - minLogTime = 0; - logCount = 0; - logTimeout = maxSampleTime; - displayLimit = initialDisplayLimit; - fetchNextLogs(); -} - -function expandLog() { - displayLimit += maxLogFetch; - fetchPrevLogs(); -} - -function clearResponse() { - refreshLog(); -} -function clearError() { -} -function clearLog() { - logReq.cancel(); - - var clearParms = 'view=request&request=log&task=delete'; - var clearReq = new Request.JSON({url: thisUrl, method: 'post', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: clearResponse}); - var tbody = $(logTable).getElement('tbody'); - var rows = tbody.getElements('tr'); - if ( rows && rows.length ) { - var minTime = rows[0].getElement('td').get('text'); - clearParms += "&minTime="+encodeURIComponent(minTime); - var maxTime = rows[rows.length-1].getElement('td').get('text'); - clearParms += "&maxTime="+encodeURIComponent(maxTime); - } - var form = $('logForm'); - clearReq.send(clearParms+"&"+form.toQueryString()); -} - -function filterLog() { - filter = {}; - filterFields.each( - function( field ) { - var selector = $('filter['+field+']'); - if ( !selector ) { - if ( window.console && window.console.log ) { - window.console.log('No selector found for ' + field); - } - return; - } - var value = selector.get('value'); - if ( value ) { - filter[field] = value; - } - } - ); - refreshLog(); -} - -function resetLog() { - filter = {}; - refreshLog(); -} - -var exportFormValidator = null; - -function exportLog() { - getModal('log_export'); - - if ( !exportFormValidator ) { - exportFormValidator = new Form.Validator.Inline($('exportForm'), { - useTitles: true, - warningPrefix: '', - errorPrefix: '' - }); - } else { - exportFormValidator.reset(); - } -} - -function exportResponse( response ) { - $('log_exportModal').unspin(); - if ( response.result == 'Ok' ) { - window.location.replace( thisUrl+'?view=request&request=log&task=download&key='+response.key+'&format='+response.format ); - } -} - -function exportFail( request ) { - $('log_exportModal').unspin(); - $('exportErrorText').set('text', request.status+' / '+request.statusText); - $('exportError').show(); - Error('Export request failed: '+request.status+' / '+request.statusText); -} - -function exportRequest() { - var form = $('exportForm'); - console.log(form); - $('exportErrorText').set('text', ''); - $('exportError').hide(); - if ( form.validate() ) { - var exportParms = "view=request&request=log&task=export"; - var exportReq = new Request.JSON({url: thisUrl, method: 'post', link: 'cancel', onSuccess: exportResponse, onFailure: exportFail}); - var selector = form.querySelectorAll('input[name=selector]:checked'); - if ( !selector.length ) { - alert("Please select how to filter logs"); - return; - } - var selection = selector[0].get('value'); - if ( selection == 'filter' || selection == 'current' ) { - $$('#filters select').each( - function( select ) { - exportParms += "&"+select.get('id')+"="+select.get('value'); - } - ); - } - if ( selection == 'current' ) { - var tbody = $(logTable).getElement( 'tbody' ); - var rows = tbody.getElements( 'tr' ); - if ( rows ) { - var minTime = rows[0].getElement('td').get('text'); - exportParms += "&minTime="+encodeURIComponent(minTime); - var maxTime = rows[rows.length-1].getElement('td').get('text'); - exportParms += "&maxTime="+encodeURIComponent(maxTime); - } - } - exportReq.send(exportParms+"&"+form.toQueryString()); - $('log_exportModal').spin(); - } -} - -function updateFilterSelectors() { - Object.each(options, - function( values, key ) { - var selector = $('filter['+key+']'); - if ( !selector ) { - if ( window.console && window.console.log ) { - window.console.log('No selector found for ' + key); - } - return; - } - selector.options.length = 1; - if ( key == 'Level' ) { - Object.each(values, - function( value, label ) { - selector.options[selector.options.length] = new Option(value, label); - } - ); - } else if ( key == 'ServerId' ) { - Object.each(values, - function( value, label ) { - selector.options[selector.options.length] = new Option(value, label); - } - ); - } else { - Object.each(values, - function( value, label ) { - selector.options[selector.options.length] = new Option(value, label); - } - ); - } - if ( filter[key] ) { - selector.set('value', filter[key]); - } - $j(selector).chosen('destroy'); - $j(selector).chosen(); - } - ); + $j('#totalLogs').text(data.total); + $j('#availLogs').text(data.totalNotFiltered); + $j('#lastUpdate').text(data.updated); + $j('#displayLogs').text(startRow + ' to ' + stopRow); } function initPage() { - displayLimit = initialDisplayLimit; - for ( var i = 1; i <= 9; i++ ) { - logCodes[''+i] = 'DB'+i; - } - logTable = new HtmlTable( $('logTable'), - { - zebra: true, - sortable: true, - sortReverse: true + var backBtn = $j('#backBtn'); + + // Init the bootstrap-table with custom icons + table.bootstrapTable({icons: icons}); + + // Assign inf, err, fat, dbg color classes to the rows in the table + table.on('post-body.bs.table', function(data) { + var lvl_ndx = $j('#logTable tr th').filter(function() { + return $j(this).text().trim() == 'Level'; + }).index(); + + $j('#logTable tr').each(function(ndx, row) { + var row = $j(row); + var level = row.find('td').eq(lvl_ndx).text().trim(); + + if (( level == 'FAT' ) || ( level == 'PNC' )) { + row.addClass('log-fat'); + } else if ( level == 'ERR' ) { + row.addClass('log-err'); + } else if ( level == 'WAR' ) { + row.addClass('log-war'); + } else if ( level == 'DBG' ) { + row.addClass('log-dbg'); } - ); - logTable.addEvent( 'sort', function( tbody, index ) { - var header = tbody.getParent('table').getElement('thead'); - var columns = header.getElement('tr').getElements('th'); - var column = columns[index]; - sortReversed = column.hasClass('table-th-sort-rev'); - if ( logCount > displayLimit ) { - var rows = tbody.getElements('tr'); - var startIndex; - if ( sortReversed ) { - startIndex = displayLimit; - } else { - startIndex = 0; - } - for ( var i = startIndex; logCount > displayLimit; i++ ) { - rows[i].destroy(); - logCount--; - } - $('displayLogs').set('text', logCount); - } // end if loCount > displayLimit - } - ); - new Asset.css('css/spinner.css'); - fetchNextLogs(); + }); + }); + + // Don't enable the back button if there is no previous zm page to go back to + backBtn.prop('disabled', !document.referrer.length); + + // Manage the BACK button + document.getElementById("backBtn").addEventListener("click", function onBackClick(evt) { + evt.preventDefault(); + window.history.back(); + }); + + // Manage the REFRESH Button + document.getElementById("refreshBtn").addEventListener("click", function onRefreshClick(evt) { + evt.preventDefault(); + window.location.reload(true); + }); } -// Kick everything off -window.addEventListener('DOMContentLoaded', initPage); +$j(document).ready(function() { + initPage(); +}); diff --git a/web/skins/classic/views/js/newlog.js b/web/skins/classic/views/js/newlog.js deleted file mode 100644 index ddaabcfc8..000000000 --- a/web/skins/classic/views/js/newlog.js +++ /dev/null @@ -1,105 +0,0 @@ -var table = $j('#logTable'); - -/* -This is the format of the json object sent by bootstrap-table - -var params = -{ -"type":"get", -"data": - { - "search":"some search text", - "sort":"DateTime", - "order":"asc", - "offset":0, - "limit":25 - "filter": - { - "message":"some advanced search text" - "level":"some more advanced search text" - } - }, -"cache":true, -"contentType":"application/json", -"dataType":"json" -}; -*/ - -// Called by bootstrap-table to retrieve zm log data -function ajaxRequest(params) { - $j.getJSON(thisUrl + '?view=request&request=newlog&task=query', params.data) - .done(function(data) { - //console.log('Ajax parameters: ' + JSON.stringify(params)); - // rearrange the result into what bootstrap-table expects - params.success({total: data.total, totalNotFiltered: data.totalNotFiltered, rows: data.rows}); - updateHeaderStats(data); - }) - .fail(logAjaxFail); -} - -function updateHeaderStats(data) { - var pageNum = table.bootstrapTable('getOptions').pageNumber; - var pageSize = table.bootstrapTable('getOptions').pageSize; - var startRow = ( (pageNum - 1 ) * pageSize ) + 1; - var stopRow = pageNum * pageSize; - var newClass = (data.logstate == 'ok') ? 'text-success' : (data.logstate == 'alert' ? 'text-warning' : ((data.logstate == 'alarm' ? 'text-danger' : ''))); - - $j('#logState').text(data.logstate); - $j('#logState').removeClass('text-success'); - $j('#logState').removeClass('text-warning'); - $j('#logState').removeClass('text-danger'); - $j('#logState').addClass(newClass); - - $j('#totalLogs').text(data.total); - $j('#availLogs').text(data.totalNotFiltered); - $j('#lastUpdate').text(data.updated); - $j('#displayLogs').text(startRow + ' to ' + stopRow); -} - -function initPage() { - var backBtn = $j('#backBtn'); - - // Init the bootstrap-table with custom icons - table.bootstrapTable({icons: icons}); - - // Assign inf, err, fat, dbg color classes to the rows in the table - table.on('post-body.bs.table', function(data) { - var lvl_ndx = $j('#logTable tr th').filter(function() { - return $j(this).text().trim() == 'Level'; - }).index(); - - $j('#logTable tr').each(function(ndx, row) { - var row = $j(row); - var level = row.find('td').eq(lvl_ndx).text().trim(); - - if (( level == 'FAT' ) || ( level == 'PNC' )) { - row.addClass('log-fat'); - } else if ( level == 'ERR' ) { - row.addClass('log-err'); - } else if ( level == 'WAR' ) { - row.addClass('log-war'); - } else if ( level == 'DBG' ) { - row.addClass('log-dbg'); - } - }); - }); - - // Don't enable the back button if there is no previous zm page to go back to - backBtn.prop('disabled', !document.referrer.length); - - // Manage the BACK button - document.getElementById("backBtn").addEventListener("click", function onBackClick(evt) { - evt.preventDefault(); - window.history.back(); - }); - - // Manage the REFRESH Button - document.getElementById("refreshBtn").addEventListener("click", function onRefreshClick(evt) { - evt.preventDefault(); - window.location.reload(true); - }); -} - -$j(document).ready(function() { - initPage(); -}); diff --git a/web/skins/classic/views/log.php b/web/skins/classic/views/log.php index 8d2e9f293..d706365c3 100644 --- a/web/skins/classic/views/log.php +++ b/web/skins/classic/views/log.php @@ -23,77 +23,69 @@ if ( !canView('System') ) { return; } -$focusWindow = true; - xhtmlHeaders(__FILE__, translate('SystemLog')); ?> -
- -
-
- -
-
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
-
- - - - - - - - - - - - - - - -
-
-
+
+ +
+  -  +  -  +  -  +  -  + +
+ +
+ + +
+ + + + + + + + + + + + + + + + + + + +
diff --git a/web/skins/classic/views/newlog.php b/web/skins/classic/views/newlog.php deleted file mode 100644 index d706365c3..000000000 --- a/web/skins/classic/views/newlog.php +++ /dev/null @@ -1,91 +0,0 @@ - - - -
- -
-  -  -  -  -  -  -  -  - -
- -
- - -
- - - - - - - - - - - - - - - - - - - -
-
- From 2e14d18a13a9910a4f2f622879f99a9120f59530 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Fri, 2 Oct 2020 14:49:44 -0400 Subject: [PATCH 051/199] add Sessions table --- db/zm_create.sql.in | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/db/zm_create.sql.in b/db/zm_create.sql.in index a0ab83c80..40e5840db 100644 --- a/db/zm_create.sql.in +++ b/db/zm_create.sql.in @@ -1024,6 +1024,13 @@ INSERT INTO MontageLayouts (`Name`,`Positions`) VALUES ('3 Wide', '{ "default":{ INSERT INTO MontageLayouts (`Name`,`Positions`) VALUES ('4 Wide', '{ "default":{"float":"left", "width":"24.5%","left":"0px","right":"0px","top":"0px","bottom":"0px"} }' ); INSERT INTO MontageLayouts (`Name`,`Positions`) VALUES ('5 Wide', '{ "default":{"float":"left", "width":"19%","left":"0px","right":"0px","top":"0px","bottom":"0px"} }' ); +CREATE TABLE Sessions ( + id char(32) not null, + access INT(10) UNSIGNED DEFAULT NULL, + data text, + PRIMARY KEY(id) +) ENGINE=InnoDB; + -- We generally don't alter triggers, we drop and re-create them, so let's keep them in a separate file that we can just source in update scripts. source @PKGDATADIR@/db/triggers.sql -- From 3e668b43cf13c7b1f3d9d6e71a0532fbd9bc031e Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Fri, 2 Oct 2020 14:49:59 -0400 Subject: [PATCH 052/199] add Sessions table --- db/zm_update-1.35.9.sql | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 db/zm_update-1.35.9.sql diff --git a/db/zm_update-1.35.9.sql b/db/zm_update-1.35.9.sql new file mode 100644 index 000000000..b5f807225 --- /dev/null +++ b/db/zm_update-1.35.9.sql @@ -0,0 +1,21 @@ +-- +-- This adds Sessions Table +-- + +SET @s = (SELECT IF( + (SELECT COUNT(*) + FROM INFORMATION_SCHEMA.TABLES + WHERE table_name = 'Sessions' + AND table_schema = DATABASE() + ) > 0, + "SELECT 'Sessions table exists'", + "CREATE TABLE Sessions ( + id char(32) not null, + access INT(10) UNSIGNED DEFAULT NULL, + data text, + PRIMARY KEY(id) +) ENGINE=InnoDB;" + )); + +PREPARE stmt FROM @s; +EXECUTE stmt; From 5d20dde85c37e02a5eb363b8dbf55ed3f0ceba51 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Fri, 2 Oct 2020 14:50:22 -0400 Subject: [PATCH 053/199] Implement a Session class that takes over session functions and stores in the database --- web/includes/session.php | 67 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/web/includes/session.php b/web/includes/session.php index 47f85d877..5c4b9afce 100644 --- a/web/includes/session.php +++ b/web/includes/session.php @@ -87,4 +87,71 @@ function zm_session_clear() { session_write_close(); session_start(); } // function zm_session_clear() + + +class Session { + private $db; + public function __construct() { + global $dbConn; + $this->db = $dbConn; + + // Set handler to overide SESSION + session_set_save_handler( + array($this, '_open'), + array($this, '_close'), + array($this, '_read'), + array($this, '_write'), + array($this, '_destroy'), + array($this, '_gc') + ); + + // Start the session + //zm_session_start(); + } + public function _open() { + return $this->db ? true : false; + } + public function _close(){ + // The example code closed the db connection.. I don't think we care to. + return true; + } + public function _read($id){ + ZM\Logger::Debug("read session" . ($this->db ? true : false)); + $sth = $this->db->prepare('SELECT data FROM Sessions WHERE id = :id'); + $sth->bindParam(':id', $id, PDO::PARAM_STR, 32); + + if ( $sth->execute() and ( $row = $sth->fetch(PDO::FETCH_ASSOC) ) ) { + ZM\Logger::Debug("row: " . print_r($row,true)); + return $row['data']; + } + // Return an empty string + return ''; + } + public function _write($id, $data){ + // Create time stamp + $access = time(); + + $sth = $this->db->prepare('REPLACE INTO Sessions VALUES (:id, :access, :data)'); + + $sth->bindParam(':id', $id, PDO::PARAM_STR, 32); + $sth->bindParam(':access', $access, PDO::PARAM_INT); + $sth->bindParam(':data', $data); + + return $sth->execute() ? true : false; + } + public function _destroy($id) { + $sth = $this->db->prepare('DELETE FROM Sessions WHERE Id = :id'); + $sth->bindParam(':id', $id, PDO::PARAM_STR, 32); + return $sth->execute() ? true : false; + } + public function _gc($max) { + // Calculate what is to be deemed old + $old = time() - $max; + $sth = $this->db->prepare('DELETE * FROM Sessions WHERE access < :old'); + $sth->bindParam(':old', $old, PDO::PARAM_INT); + return $sth->execute() ? true : false; + } +} # end class Session + +$session = new Session; ?> From 23f2c1468fadad7f7f7ecfbae478e948a37ebbe9 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Fri, 2 Oct 2020 15:21:58 -0400 Subject: [PATCH 054/199] rough in a table of the logged in users --- web/ajax/modals/logout.php | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/web/ajax/modals/logout.php b/web/ajax/modals/logout.php index 565e80cc2..418a5fa31 100644 --- a/web/ajax/modals/logout.php +++ b/web/ajax/modals/logout.php @@ -30,6 +30,28 @@ global $CLANG;
From 802e439cb588bd601783ea731d75e6965de46885 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Fri, 2 Oct 2020 15:46:28 -0500 Subject: [PATCH 061/199] convert controlpreset view to a modal --- web/ajax/modals/controlpreset.php | 55 +++++++++++++++++++ web/includes/actions/zone.php | 3 +- .../classic/includes/control_functions.php | 2 +- web/skins/classic/views/js/watch.js | 30 +++++++++- web/skins/classic/views/js/watch.js.php | 15 +++++ 5 files changed, 101 insertions(+), 4 deletions(-) create mode 100644 web/ajax/modals/controlpreset.php diff --git a/web/ajax/modals/controlpreset.php b/web/ajax/modals/controlpreset.php new file mode 100644 index 000000000..22e8c73f7 --- /dev/null +++ b/web/ajax/modals/controlpreset.php @@ -0,0 +1,55 @@ + + diff --git a/web/includes/actions/zone.php b/web/includes/actions/zone.php index c0e4eabbb..0b2809fcb 100644 --- a/web/includes/actions/zone.php +++ b/web/includes/actions/zone.php @@ -70,9 +70,8 @@ if ( !empty($_REQUEST['mid']) && canEdit('Monitors', $_REQUEST['mid']) ) { if ( ($_REQUEST['newZone']['Type'] == 'Privacy') && $monitor->Controllable() ) { $monitor->sendControlCommand('quit'); } - $refreshParent = true; } // end if changes - $view = 'none'; + $redirect = $_SERVER['HTTP_REFERER']; } // end if action } // end if $mid and canEdit($mid) ?> diff --git a/web/skins/classic/includes/control_functions.php b/web/skins/classic/includes/control_functions.php index 61138612f..60c70d1dc 100644 --- a/web/skins/classic/includes/control_functions.php +++ b/web/skins/classic/includes/control_functions.php @@ -176,7 +176,7 @@ function controlPresets($monitor, $cmds) { } if ( canEdit('Monitors') && $control->CanSetPresets() ) { ?> - + diff --git a/web/skins/classic/views/js/watch.js b/web/skins/classic/views/js/watch.js index 7fb92fed5..b0011d90b 100644 --- a/web/skins/classic/views/js/watch.js +++ b/web/skins/classic/views/js/watch.js @@ -815,7 +815,35 @@ function reloadWebSite() { document.getElementById('imageFeed').innerHTML = document.getElementById('imageFeed').innerHTML; } +function updatePresetLabels() { + var form = $('contentForm'); + var preset_ddm = form.elements['preset']; + + var presetIndex = preset_ddm[preset_ddm.selectedIndex].value; + if ( labels[presetIndex] ) { + form.newLabel.value = labels[presetIndex]; + } else { + form.newLabel.value = ''; + } +} + +function getCtrlPresetModal() { + $j.getJSON(thisUrl + '?request=modal&modal=controlpreset&mid=' + monitorId) + .done(function(data) { + if ( $j('#ctrlPresetModal').length ) { + $j('#ctrlPresetModal').replaceWith(data.html); + } else { + $j("body").append(data.html); + } + updatePresetLabels(); + }) + .fail(logAjaxFail); +} + function initPage() { + // Load the PTZ Preset modal into the DOM + getCtrlPresetModal(); + if ( monitorType != 'WebSite' ) { if ( streamMode == 'single' ) { statusCmdTimer = statusCmdQuery.delay( (Math.random()+0.1)*statusRefreshTimeout ); @@ -863,4 +891,4 @@ function initPage() { } // Kick everything off -window.addEventListener('DOMContentLoaded', initPage); +$j(document).ready(initPage); diff --git a/web/skins/classic/views/js/watch.js.php b/web/skins/classic/views/js/watch.js.php index 365d62aed..268d9d0e3 100644 --- a/web/skins/classic/views/js/watch.js.php +++ b/web/skins/classic/views/js/watch.js.php @@ -4,6 +4,7 @@ global $connkey; global $monitor; global $scale; + global $labels; ?> // // Import constants @@ -84,3 +85,17 @@ var imageControlMode = null; var refreshApplet = ; var appletRefreshTime = ; + +var labels = new Array(); +Id() ) ) as $row ) { + $labels[$row['Preset']] = $row['Label']; +} + +foreach ( $labels as $index=>$label ) { +?> +labels[] = ''; + From a97e526298d2aaa2173476d9bda7796f87413dfc Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Fri, 2 Oct 2020 16:10:32 -0500 Subject: [PATCH 062/199] fix save button in controlpreset modal --- web/ajax/modals/controlpreset.php | 4 ++-- web/includes/actions/control.php | 2 +- web/skins/classic/views/js/watch.js | 7 ++++++- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/web/ajax/modals/controlpreset.php b/web/ajax/modals/controlpreset.php index 22e8c73f7..775eeda33 100644 --- a/web/ajax/modals/controlpreset.php +++ b/web/ajax/modals/controlpreset.php @@ -38,7 +38,7 @@ for ( $i = 1; $i <= $monitor['NumPresets']; $i++ ) { -

+

@@ -46,7 +46,7 @@ for ( $i = 1; $i <= $monitor['NumPresets']; $i++ ) {

diff --git a/web/includes/actions/control.php b/web/includes/actions/control.php index 5c996e636..bf6db7967 100644 --- a/web/includes/actions/control.php +++ b/web/includes/actions/control.php @@ -36,6 +36,6 @@ if ( $action == 'control' ) { $ctrlCommand = buildControlCommand($monitor); $monitor->sendControlCommand($ctrlCommand); - $view = 'none'; + $redirect = $_SERVER['HTTP_REFERER']; } ?> diff --git a/web/skins/classic/views/js/watch.js b/web/skins/classic/views/js/watch.js index b0011d90b..3c4c03c59 100644 --- a/web/skins/classic/views/js/watch.js +++ b/web/skins/classic/views/js/watch.js @@ -816,7 +816,7 @@ function reloadWebSite() { } function updatePresetLabels() { - var form = $('contentForm'); + var form = $('ctrlPresetForm'); var preset_ddm = form.elements['preset']; var presetIndex = preset_ddm[preset_ddm.selectedIndex].value; @@ -836,6 +836,11 @@ function getCtrlPresetModal() { $j("body").append(data.html); } updatePresetLabels(); + // Manage the Save button + $j('#cPresetSubmitModal').click(function(evt) { + evt.preventDefault(); + $j('#ctrlPresetForm').submit(); + }); }) .fail(logAjaxFail); } From 391ce88f05f6555f3b3ddf6ab6f6a2ca9cf48e6b Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Fri, 2 Oct 2020 21:11:54 -0500 Subject: [PATCH 063/199] eslint --- web/skins/classic/views/js/watch.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/skins/classic/views/js/watch.js b/web/skins/classic/views/js/watch.js index 3c4c03c59..ebb8b4d04 100644 --- a/web/skins/classic/views/js/watch.js +++ b/web/skins/classic/views/js/watch.js @@ -840,7 +840,7 @@ function getCtrlPresetModal() { $j('#cPresetSubmitModal').click(function(evt) { evt.preventDefault(); $j('#ctrlPresetForm').submit(); - }); + }); }) .fail(logAjaxFail); } From 1ef1b48c714ebb302fc8e9143cd981eab8d115f3 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Sat, 3 Oct 2020 07:08:04 -0500 Subject: [PATCH 064/199] remove warnings used for testing --- web/includes/actions/device.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/web/includes/actions/device.php b/web/includes/actions/device.php index 29011dd73..43d970400 100644 --- a/web/includes/actions/device.php +++ b/web/includes/actions/device.php @@ -29,8 +29,6 @@ if ( $action == 'device' ) { setDeviceStatusX10($_REQUEST['key'], $_REQUEST['command']); } else if ( isset($_REQUEST['newDevice']) ) { if ( isset($_REQUEST['did']) && $_REQUEST['did'] ) { - ZM\Warning('did value is: '.$_REQUEST['did']); - ZM\Warning('newDevice array value is: '.print_r($_REQUEST['newDevice'],true)); dbQuery('UPDATE Devices SET Name=?, KeyString=? WHERE Id=?', array($_REQUEST['newDevice']['Name'], $_REQUEST['newDevice']['KeyString'], $_REQUEST['did']) ); } else { From 07d0353373c870c2264b77704ba8c23c29a96545 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Sat, 3 Oct 2020 11:57:22 -0400 Subject: [PATCH 065/199] Fix zms only sending 1 frame due to != instead of == --- src/zm_eventstream.cpp | 44 +++++++++++++++++++++++++----------------- 1 file changed, 26 insertions(+), 18 deletions(-) diff --git a/src/zm_eventstream.cpp b/src/zm_eventstream.cpp index 00612ebfd..7b67c738a 100644 --- a/src/zm_eventstream.cpp +++ b/src/zm_eventstream.cpp @@ -683,9 +683,6 @@ bool EventStream::sendFrame(int delta_us) { #endif // HAVE_LIBAVCODEC { - static unsigned char temp_img_buffer[ZM_MAX_IMAGE_SIZE]; - int img_buffer_size = 0; - uint8_t *img_buffer = temp_img_buffer; bool send_raw = (type == STREAM_JPEG) && ((scale>=ZM_SCALE_BASE)&&(zoom==ZM_SCALE_BASE)) && filepath[0]; @@ -748,6 +745,9 @@ bool EventStream::sendFrame(int delta_us) { } Image *send_image = prepareImage(image); + static unsigned char temp_img_buffer[ZM_MAX_IMAGE_SIZE]; + int img_buffer_size = 0; + uint8_t *img_buffer = temp_img_buffer; switch ( type ) { case STREAM_JPEG : @@ -1010,6 +1010,7 @@ void EventStream::runStream() { bool EventStream::send_file(const char * filepath) { static unsigned char temp_img_buffer[ZM_MAX_IMAGE_SIZE]; + int rc; int img_buffer_size = 0; uint8_t *img_buffer = temp_img_buffer; @@ -1020,39 +1021,46 @@ bool EventStream::send_file(const char * filepath) { Error("Can't open %s: %s", filepath, strerror(errno)); return false; } - bool size_sent = false; - #if HAVE_SENDFILE static struct stat filestat; if ( fstat(fileno(fdj), &filestat) < 0 ) { + fclose(fdj); /* Close the file handle */ Error("Failed getting information about file %s: %s", filepath, strerror(errno)); return false; } + if ( !filestat.st_size ) { + fclose(fdj); /* Close the file handle */ + Info("File size is zero. Unable to send raw frame %u: %s", curr_frame_id); + return false; + } if ( 0 > fprintf(stdout, "Content-Length: %d\r\n\r\n", (int)filestat.st_size) ) { fclose(fdj); /* Close the file handle */ Info("Unable to send raw frame %u: %s", curr_frame_id, strerror(errno)); return false; } - size_sent = true; - - if ( zm_sendfile(fileno(stdout), fileno(fdj), 0, (int)filestat.st_size) != (int)filestat.st_size ) { + rc = zm_sendfile(fileno(stdout), fileno(fdj), 0, (int)filestat.st_size); + if ( rc == (int)filestat.st_size ) { + // Success fclose(fdj); /* Close the file handle */ return true; } + Warning("Unable to send raw frame %u: %s rc %d", curr_frame_id, strerror(errno), rc); #endif img_buffer_size = fread(img_buffer, 1, sizeof(temp_img_buffer), fdj); - if ( !size_sent ) { - if ( 0 > fprintf(stdout, "Content-Length: %d\r\n\r\n", img_buffer_size) ) { - fclose(fdj); /* Close the file handle */ - Info("Unable to send raw frame %u: %s", curr_frame_id, strerror(errno)); - return false; - } - } - int rc = fwrite(img_buffer, img_buffer_size, 1, stdout); fclose(fdj); /* Close the file handle */ + if ( !img_buffer_size ) { + Info("Unable to read raw frame %u: %s", curr_frame_id, strerror(errno)); + return false; + } - if ( rc != 1 ) { - Error("Unable to send raw frame %u: %s", curr_frame_id, strerror(errno)); + if ( 0 > fprintf(stdout, "Content-Length: %d\r\n\r\n", img_buffer_size) ) { + Info("Unable to send raw frame %u: %s", curr_frame_id, strerror(errno)); + return false; + } + rc = fwrite(img_buffer, img_buffer_size, 1, stdout); + + if ( 1 != rc ) { + Error("Unable to send raw frame %u: %s %d", curr_frame_id, strerror(errno), rc); return false; } From 1643fb686b3b00160a80c5718270906fea1b8f4e Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Sat, 3 Oct 2020 16:51:25 -0500 Subject: [PATCH 066/199] convert settings popup to modal --- .../views => ajax/modals}/settings.php | 61 +++++++------------ web/skins/classic/views/js/watch.js | 27 +++++++- web/skins/classic/views/js/watch.js.php | 1 + web/skins/classic/views/watch.php | 4 +- 4 files changed, 52 insertions(+), 41 deletions(-) rename web/{skins/classic/views => ajax/modals}/settings.php (53%) diff --git a/web/skins/classic/views/settings.php b/web/ajax/modals/settings.php similarity index 53% rename from web/skins/classic/views/settings.php rename to web/ajax/modals/settings.php index 0c51add26..59d19ddbb 100644 --- a/web/skins/classic/views/settings.php +++ b/web/ajax/modals/settings.php @@ -1,27 +1,6 @@ $_REQUEST['mid'])); $zmuCommand = getZmuCommand(' -m '.escapeshellarg($_REQUEST['mid']).' -B -C -H -O'); @@ -35,17 +14,22 @@ if ( $zmuOutput ) { $monitor->Colour($colour); } -$focusWindow = true; - -xhtmlHeaders(__FILE__, validHtmlStr($monitor->Name()).' - '.translate('Settings')); ?> - -
- -
-
+
diff --git a/web/skins/classic/views/js/watch.js b/web/skins/classic/views/js/watch.js index ebb8b4d04..48d27dd82 100644 --- a/web/skins/classic/views/js/watch.js +++ b/web/skins/classic/views/js/watch.js @@ -845,9 +845,32 @@ function getCtrlPresetModal() { .fail(logAjaxFail); } +function getSettingsModal() { + $j.getJSON(thisUrl + '?request=modal&modal=settings&mid=' + monitorId) + .done(function(data) { + if ( $j('#settingsModal').length ) { + $j('#settingsModal').replaceWith(data.html); + } else { + $j("body").append(data.html); + } + updatePresetLabels(); + // Manage the Save button + $j('#settingsSubmitModal').click(function(evt) { + evt.preventDefault(); + $j('#settingsForm').submit(); + }); + }) + .fail(logAjaxFail); +} + function initPage() { - // Load the PTZ Preset modal into the DOM - getCtrlPresetModal(); + + if ( canViewControl ) { + // Load the PTZ Preset modal into the DOM + getCtrlPresetModal(); + // Load the settings modal into the DOM + getSettingsModal(); + } if ( monitorType != 'WebSite' ) { if ( streamMode == 'single' ) { diff --git a/web/skins/classic/views/js/watch.js.php b/web/skins/classic/views/js/watch.js.php index 268d9d0e3..d20347476 100644 --- a/web/skins/classic/views/js/watch.js.php +++ b/web/skins/classic/views/js/watch.js.php @@ -68,6 +68,7 @@ var imageRefreshTimeout = ; var canEditMonitors = ; var canStreamNative = ; +var canViewControl = ; var canPlayPauseAudio = Browser.ie; diff --git a/web/skins/classic/views/watch.php b/web/skins/classic/views/watch.php index 1b9ca2994..b0063f4a2 100644 --- a/web/skins/classic/views/watch.php +++ b/web/skins/classic/views/watch.php @@ -67,7 +67,9 @@ xhtmlHeaders(__FILE__, $monitor->Name().' - '.translate('Feed')); Type() == 'Local' ) { ?> -
UrlToIndex().'?view=settings&mid='.$monitor->Id().'&'.get_auth_relay(), 'zmSettings'.$monitor->Id(), 'settings', translate('Settings'), true, 'id="settingsLink"') ?>
+
+ +
From aee5430bc85bd24363d119e836f39b80d1678848 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Sat, 3 Oct 2020 17:00:20 -0500 Subject: [PATCH 067/199] only load preset and settings modals when needed --- web/skins/classic/views/js/watch.js | 4 ++-- web/skins/classic/views/js/watch.js.php | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/web/skins/classic/views/js/watch.js b/web/skins/classic/views/js/watch.js index 48d27dd82..1d3e2dc6e 100644 --- a/web/skins/classic/views/js/watch.js +++ b/web/skins/classic/views/js/watch.js @@ -867,9 +867,9 @@ function initPage() { if ( canViewControl ) { // Load the PTZ Preset modal into the DOM - getCtrlPresetModal(); + if ( monitorControllable ) getCtrlPresetModal(); // Load the settings modal into the DOM - getSettingsModal(); + if ( monitorType == "Local" ) getSettingsModal(); } if ( monitorType != 'WebSite' ) { diff --git a/web/skins/classic/views/js/watch.js.php b/web/skins/classic/views/js/watch.js.php index d20347476..d0904b22a 100644 --- a/web/skins/classic/views/js/watch.js.php +++ b/web/skins/classic/views/js/watch.js.php @@ -59,6 +59,7 @@ var monitorUrl = 'UrlToIndex() ?>'; var monitorType = 'Type() ?>'; var monitorRefresh = 'Refresh() ?>'; var monitorStreamReplayBuffer = StreamReplayBuffer() ?>; +var monitorControllable = Controllable()?'true':'false' ?>; var scale = ''; From 8d19cee8119841223c8d16868fdac4746257c244 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Sat, 3 Oct 2020 17:12:44 -0500 Subject: [PATCH 068/199] unpopup the addnewuser button --- web/skins/classic/views/js/options.js | 6 ++++++ web/skins/classic/views/options.php | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/web/skins/classic/views/js/options.js b/web/skins/classic/views/js/options.js index 843225a67..06d026026 100644 --- a/web/skins/classic/views/js/options.js +++ b/web/skins/classic/views/js/options.js @@ -60,6 +60,12 @@ function enableStorageModal() { }); } +// Manage the Add New User button +function AddNewUser(el) { + url = el.getAttribute('data-url'); + window.location.assign(url); +} + function initPage() { var NewStorageBtn = $j('#NewStorageBtn'); var NewServerBtn = $j('#NewServerBtn'); diff --git a/web/skins/classic/views/options.php b/web/skins/classic/views/options.php index a66c2cf0f..147d250e1 100644 --- a/web/skins/classic/views/options.php +++ b/web/skins/classic/views/options.php @@ -180,7 +180,7 @@ foreach ( array_map('basename', glob('skins/'.$skin.'/css/*', GLOB_ONLYDIR)) as
- +
From 65b6dad48cf40bae5bb4410cbd74d074429b1456 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Sat, 3 Oct 2020 17:38:56 -0500 Subject: [PATCH 069/199] eslint --- web/skins/classic/views/js/watch.js | 1 - 1 file changed, 1 deletion(-) diff --git a/web/skins/classic/views/js/watch.js b/web/skins/classic/views/js/watch.js index 1d3e2dc6e..41778d25a 100644 --- a/web/skins/classic/views/js/watch.js +++ b/web/skins/classic/views/js/watch.js @@ -864,7 +864,6 @@ function getSettingsModal() { } function initPage() { - if ( canViewControl ) { // Load the PTZ Preset modal into the DOM if ( monitorControllable ) getCtrlPresetModal(); From b4d2fa5e7519865dbfe66b8b4fcb069c372c0304 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Sat, 3 Oct 2020 21:14:24 -0500 Subject: [PATCH 070/199] replace inline onchange event --- web/ajax/modals/controlpreset.php | 2 +- web/skins/classic/views/js/watch.js | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/web/ajax/modals/controlpreset.php b/web/ajax/modals/controlpreset.php index 775eeda33..124859507 100644 --- a/web/ajax/modals/controlpreset.php +++ b/web/ajax/modals/controlpreset.php @@ -38,7 +38,7 @@ for ( $i = 1; $i <= $monitor['NumPresets']; $i++ ) { -

+

diff --git a/web/skins/classic/views/js/watch.js b/web/skins/classic/views/js/watch.js index 41778d25a..b026743cb 100644 --- a/web/skins/classic/views/js/watch.js +++ b/web/skins/classic/views/js/watch.js @@ -836,6 +836,8 @@ function getCtrlPresetModal() { $j("body").append(data.html); } updatePresetLabels(); + // Manage the Preset Select box + $j('#preset').change(updatePresetLabels); // Manage the Save button $j('#cPresetSubmitModal').click(function(evt) { evt.preventDefault(); @@ -853,7 +855,6 @@ function getSettingsModal() { } else { $j("body").append(data.html); } - updatePresetLabels(); // Manage the Save button $j('#settingsSubmitModal').click(function(evt) { evt.preventDefault(); From a0ad52bac968ae97909743e14b3b98cae819f0aa Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Sat, 3 Oct 2020 21:30:48 -0500 Subject: [PATCH 071/199] replace another inline onchange event --- web/skins/classic/views/js/monitorpreset.js | 12 +++++++++--- web/skins/classic/views/monitorpreset.php | 4 ++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/web/skins/classic/views/js/monitorpreset.js b/web/skins/classic/views/js/monitorpreset.js index 57b9e343b..71df339f5 100644 --- a/web/skins/classic/views/js/monitorpreset.js +++ b/web/skins/classic/views/js/monitorpreset.js @@ -1,12 +1,18 @@ +var form = $j('#monitorePresetForm'); + function submitPreset( element ) { - var form = element.form; form.target = opener.name; form.view.value = 'monitor'; form.submit(); closeWindow.delay( 250 ); } -function configureButtons( element ) { - var form = element.form; +function configureButtons() { form.saveBtn.disabled = (form.preset.selectedIndex==0); } + +function initPage() { + $j('#preset').change(configureButtons); +} + +$j(document).ready(initPage); diff --git a/web/skins/classic/views/monitorpreset.php b/web/skins/classic/views/monitorpreset.php index 22c960587..ecf8961a7 100644 --- a/web/skins/classic/views/monitorpreset.php +++ b/web/skins/classic/views/monitorpreset.php @@ -40,14 +40,14 @@ xhtmlHeaders(__FILE__, translate('MonitorPreset') );

-
+

- +

From adb715c42c92c7093a9b1d043d57a3f372da4059 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Sat, 3 Oct 2020 21:32:07 -0500 Subject: [PATCH 072/199] fix typo --- web/skins/classic/views/js/monitorpreset.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/skins/classic/views/js/monitorpreset.js b/web/skins/classic/views/js/monitorpreset.js index 71df339f5..f8e11e1cc 100644 --- a/web/skins/classic/views/js/monitorpreset.js +++ b/web/skins/classic/views/js/monitorpreset.js @@ -1,4 +1,4 @@ -var form = $j('#monitorePresetForm'); +var form = $j('#monitorPresetForm'); function submitPreset( element ) { form.target = opener.name; From d9b8a7ceb22d7228a55f5a6ef910d8ae4ee32e74 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Sat, 3 Oct 2020 21:35:38 -0500 Subject: [PATCH 073/199] remove unused view --- web/skins/classic/views/controlpreset.php | 69 ----------------------- 1 file changed, 69 deletions(-) delete mode 100644 web/skins/classic/views/controlpreset.php diff --git a/web/skins/classic/views/controlpreset.php b/web/skins/classic/views/controlpreset.php deleted file mode 100644 index 6d67c5424..000000000 --- a/web/skins/classic/views/controlpreset.php +++ /dev/null @@ -1,69 +0,0 @@ - - -
- -
- - - - - - -

-

- - -

-
- - -
- -
-
- From 2e6efbb34947d82ef71c420b8fa20779805733ef Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Sat, 3 Oct 2020 21:44:24 -0500 Subject: [PATCH 074/199] replace inlince onchange event in control view --- web/skins/classic/views/control.php | 4 ++-- web/skins/classic/views/js/control.js | 9 +++++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/web/skins/classic/views/control.php b/web/skins/classic/views/control.php index 9fad31c41..4cf02cf25 100644 --- a/web/skins/classic/views/control.php +++ b/web/skins/classic/views/control.php @@ -60,9 +60,9 @@ xhtmlHeaders(__FILE__, translate('Control'));

-
+ - +
diff --git a/web/skins/classic/views/js/control.js b/web/skins/classic/views/js/control.js index 35082bc43..d30db28c1 100644 --- a/web/skins/classic/views/js/control.js +++ b/web/skins/classic/views/js/control.js @@ -1,5 +1,6 @@ var controlParms = "view=request&request=control"; var controlReq = new Request.JSON( {url: thisUrl, method: 'post', timeout: AJAX_TIMEOUT, onSuccess: getControlResponse} ); +var form = $j('#controlForm'); function getControlResponse( respObj, respText ) { if ( !respObj ) { @@ -41,3 +42,11 @@ function controlCmd( control, event, xtell, ytell ) { } controlReq.send( controlParms+"&control="+control+locParms ); } + +function initPage() { + $j('#mid').change(function() { + form.submit(); + }); +} + +$j(document).ready(initPage); From 2852d14ca6c8d1be672f48bc3ae11e275318729f Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Sun, 4 Oct 2020 08:04:11 -0500 Subject: [PATCH 075/199] use data-on-change-this instead of inline js --- web/includes/functions.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/includes/functions.php b/web/includes/functions.php index ea2542070..f44cd0899 100644 --- a/web/includes/functions.php +++ b/web/includes/functions.php @@ -582,7 +582,7 @@ function buildSelect($name, $contents, $behaviours=false) { $behaviourText .= ' '.$event.'="'.$action.'"'; } } else { - $behaviourText = ' onchange="'.$behaviours.'"'; + $behaviourText = ' data-on-change-this="'.$behaviours.'"'; } } ?> From 3570c6e8285db6af01655cc7c0bfdfdcc7e4aa1d Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Mon, 5 Oct 2020 09:11:16 -0400 Subject: [PATCH 076/199] Better debug logging of event and frame inserts --- src/zm_event.cpp | 60 ++++++++++++++++++++++++++++-------------------- 1 file changed, 35 insertions(+), 25 deletions(-) diff --git a/src/zm_event.cpp b/src/zm_event.cpp index 6ab53cf54..025f8b43a 100644 --- a/src/zm_event.cpp +++ b/src/zm_event.cpp @@ -39,6 +39,7 @@ //#define USE_PREPARED_SQL 1 const char * Event::frame_type_names[3] = { "Normal", "Bulk", "Alarm" }; +char frame_insert_sql[ZM_SQL_LGE_BUFSIZ] = "INSERT INTO `Frames` (`EventId`, `FrameId`, `Type`, `TimeStamp`, `Delta`, `Score`) VALUES "; int Event::pre_alarm_count = 0; @@ -104,9 +105,11 @@ Event::Event( ); db_mutex.lock(); if ( mysql_query(&dbconn, sql) ) { - Error("Can't insert event: %s. sql was (%s)", mysql_error(&dbconn), sql); db_mutex.unlock(); + Error("Can't insert event: %s. sql was (%s)", mysql_error(&dbconn), sql); return; + } else { + Debug(2, "Created new event with %s", sql); } id = mysql_insert_id(&dbconn); @@ -202,8 +205,8 @@ Event::Event( video_name = stringtf("%" PRIu64 "-%s", id, "video.mp4"); snprintf(sql, sizeof(sql), "UPDATE Events SET DefaultVideo = '%s' WHERE Id=%" PRIu64, video_name.c_str(), id); if ( mysql_query(&dbconn, sql) ) { - Error("Can't update event: %s. sql was (%s)", mysql_error(&dbconn), sql); db_mutex.unlock(); + Error("Can't update event: %s. sql was (%s)", mysql_error(&dbconn), sql); return; } video_file = path + "/" + video_name; @@ -501,8 +504,9 @@ void Event::AddFrames(int n_frames, Image **images, struct timeval **timestamps) } void Event::AddFramesInternal(int n_frames, int start_frame, Image **images, struct timeval **timestamps) { - static char sql[ZM_SQL_LGE_BUFSIZ]; - strncpy(sql, "INSERT INTO `Frames` (`EventId`, `FrameId`, `TimeStamp`, `Delta`) VALUES ", sizeof(sql)); + char *frame_insert_values = (char *)&frame_insert_sql + 90; // 90 == strlen(frame_insert_sql); + //static char sql[ZM_SQL_LGE_BUFSIZ]; + //strncpy(sql, "INSERT INTO `Frames` (`EventId`, `FrameId`, `TimeStamp`, `Delta`) VALUES ", sizeof(sql)); int frameCount = 0; for ( int i = start_frame; i < n_frames && i - start_frame < ZM_SQL_BATCH_SIZE; i++ ) { if ( timestamps[i]->tv_sec <= 0 ) { @@ -541,21 +545,24 @@ void Event::AddFramesInternal(int n_frames, int start_frame, Image **images, str delta_time.sec = 0; } - int sql_len = strlen(sql); - snprintf(sql+sql_len, sizeof(sql)-sql_len, "( %" PRIu64 ", %d, from_unixtime(%ld), %s%ld.%02ld ), ", + frame_insert_values += snprintf(frame_insert_values, + sizeof(frame_insert_sql)-(frame_insert_values-(char *)&frame_insert_sql), + "\n( %" PRIu64 ", %d, 'Normal', from_unixtime(%ld), %s%ld.%02ld, 0 ),", id, frames, timestamps[i]->tv_sec, delta_time.positive?"":"-", delta_time.sec, delta_time.fsec); frameCount++; } // end foreach frame if ( frameCount ) { - Debug(1, "Adding %d/%d frames to DB", frameCount, n_frames); - *(sql+strlen(sql)-2) = '\0'; + *(frame_insert_values-1) = '\0'; db_mutex.lock(); - if ( mysql_query(&dbconn, sql) ) { - Error("Can't insert frames: %s, sql was (%s)", mysql_error(&dbconn), sql); - } + int rc = mysql_query(&dbconn, frame_insert_sql); db_mutex.unlock(); + if ( rc ) { + Error("Can't insert frames: %s, sql was (%s)", mysql_error(&dbconn), frame_insert_sql); + } else { + Debug(1, "INSERT %d/%d frames sql %s", frameCount, n_frames, frame_insert_sql); + } last_db_frame = frames; } else { Debug(1, "No valid pre-capture frames to add"); @@ -563,16 +570,15 @@ void Event::AddFramesInternal(int n_frames, int start_frame, Image **images, str } // void Event::AddFramesInternal(int n_frames, int start_frame, Image **images, struct timeval **timestamps) void Event::WriteDbFrames() { - static char sql[ZM_SQL_LGE_BUFSIZ]; - char * sql_ptr = (char *)&sql; - sql_ptr += snprintf(sql, sizeof(sql), - "INSERT INTO Frames ( EventId, FrameId, Type, TimeStamp, Delta, Score ) VALUES " - ); + char *frame_insert_values_ptr = (char *)&frame_insert_sql + 90; // 90 == strlen(frame_insert_sql); while ( frame_data.size() ) { Frame *frame = frame_data.front(); frame_data.pop(); - sql_ptr += snprintf(sql_ptr, sizeof(sql)-(sql_ptr-(char *)&sql), "( %" PRIu64 ", %d, '%s', from_unixtime( %ld ), %s%ld.%02ld, %d ), ", - id, frame->frame_id, frame_type_names[frame->type], + frame_insert_values_ptr += snprintf(frame_insert_values_ptr, + sizeof(frame_insert_sql)-(frame_insert_values_ptr-(char *)&frame_insert_sql), + "\n( %" PRIu64 ", %d, '%s', from_unixtime( %ld ), %s%ld.%02ld, %d ),", + id, frame->frame_id, + frame_type_names[frame->type], frame->timestamp.tv_sec, frame->delta.positive?"":"-", frame->delta.sec, @@ -580,14 +586,17 @@ void Event::WriteDbFrames() { frame->score); delete frame; } - *(sql_ptr-2) = '\0'; + *(frame_insert_values_ptr-1) = '\0'; // The -2 is for the extra , added for values above db_mutex.lock(); - if ( mysql_query(&dbconn, sql) ) { - db_mutex.unlock(); - Error("Can't insert frames: %s, sql was %s", mysql_error(&dbconn), sql); - return; - } + int rc = mysql_query(&dbconn, frame_insert_sql); db_mutex.unlock(); + + if ( rc ) { + Error("Can't insert frames: %s, sql was %s", mysql_error(&dbconn), frame_insert_sql); + return; + } else { + Debug(1, "INSERT FRAMES: sql was %s", frame_insert_sql); + } } // end void Event::WriteDbFrames() // Subtract an offset time from frames deltas to match with video start time @@ -668,6 +677,8 @@ void Event::AddFrame(Image *image, struct timeval timestamp, int score, Image *a struct DeltaTimeval delta_time; DELTA_TIMEVAL(delta_time, timestamp, start_time, DT_PREC_2); + Debug(1, "Frame delta is %d.%d - %d.%d = %d.%d", + start_time.tv_sec, start_time.tv_usec, timestamp.tv_sec, timestamp.tv_usec, delta_time.sec, delta_time.fsec); bool db_frame = ( frame_type != BULK ) || (frames==1) || ((frames%config.bulk_frame_interval)==0) ; if ( db_frame ) { @@ -680,7 +691,6 @@ void Event::AddFrame(Image *image, struct timeval timestamp, int score, Image *a frame_data.size(), write_to_db, monitor->get_fps()); WriteDbFrames(); last_db_frame = frames; - Debug(1, "Adding %d frames to DB, done", frame_data.size()); } // We are writing a Bulk frame From 283f224a954e17f9371d06c10c3585ae40201e7f Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Mon, 5 Oct 2020 09:19:48 -0400 Subject: [PATCH 077/199] Add pre-alarm frames when alarm_frame_count > 1 and prealarmcount=0 --- src/zm_monitor.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/zm_monitor.cpp b/src/zm_monitor.cpp index de245f854..8674e5498 100644 --- a/src/zm_monitor.cpp +++ b/src/zm_monitor.cpp @@ -1631,6 +1631,13 @@ bool Monitor::Analyse() { } } event->AddFrames(pre_event_images, images, timestamps); + } else if ( alarm_frame_count > 1 ) { + int temp_alarm_frame_count = alarm_frame_count; + while ( --temp_alarm_frame_count ) { + Debug(1, "Adding previous frame due to alarm_frame_count %d", pre_index); + event->AddFrame(image_buffer[pre_index].image, *image_buffer[pre_index].timestamp, 0, nullptr); + pre_index = (pre_index + 1)%image_buffer_count; + } } // end if pre_event_images if ( ( alarm_frame_count > 1 ) && Event::PreAlarmCount() ) { From 93021f5806aaf501fe04dc1b3b48d0838cf1a6d1 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Mon, 5 Oct 2020 09:30:33 -0400 Subject: [PATCH 078/199] Update getNearEvents to handle when event doesn't exist --- web/ajax/status.php | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/web/ajax/status.php b/web/ajax/status.php index a80559998..5c0f866f7 100644 --- a/web/ajax/status.php +++ b/web/ajax/status.php @@ -411,7 +411,10 @@ function getNearEvents() { global $user, $sortColumn, $sortOrder; $eventId = $_REQUEST['id']; + $NearEvents = array( 'EventId'=>$eventId ); + $event = dbFetchOne('SELECT * FROM Events WHERE Id=?', NULL, array($eventId)); + if ( !$event ) return $NearEvents; parseFilter($_REQUEST['filter']); parseSort(); @@ -423,10 +426,10 @@ function getNearEvents() { # When listing, it may make sense to list them in descending order. But when viewing Prev should timewise earlier and Next should be after. if ( $sortColumn == 'E.Id' or $sortColumn == 'E.StartTime' ) { - $sortOrder = 'asc'; + $sortOrder = 'ASC'; } - $sql = "SELECT E.Id AS Id, E.StartTime AS StartTime FROM Events AS E INNER JOIN Monitors AS M ON E.MonitorId = M.Id WHERE $sortColumn ".($sortOrder=='asc'?'<=':'>=')." '".$event[$_REQUEST['sort_field']]."'".$_REQUEST['filter']['sql'].$midSql.' AND E.Id<'.$event['Id'] . " ORDER BY $sortColumn ".($sortOrder=='asc'?'desc':'asc'); + $sql = 'SELECT E.Id AS Id, E.StartTime AS StartTime FROM Events AS E INNER JOIN Monitors AS M ON E.MonitorId = M.Id WHERE '.$sortColumn.' '.($sortOrder=='ASC'?'<=':'>=').' \''.$event[$_REQUEST['sort_field']].'\''.$_REQUEST['filter']['sql'].$midSql.' AND E.Id<'.$event['Id'] . ' ORDER BY '.$sortColumn.' '.($sortOrder=='ASC'?'DESC':'ASC'); if ( $sortColumn != 'E.Id' ) { # When sorting by starttime, if we have two events with the same starttime (diffreent monitors) then we should sort secondly by Id $sql .= ', E.Id DESC'; @@ -435,31 +438,30 @@ function getNearEvents() { $result = dbQuery($sql); $prevEvent = dbFetchNext($result); - $sql = "SELECT E.Id AS Id, E.StartTime AS StartTime FROM Events AS E INNER JOIN Monitors AS M ON E.MonitorId = M.Id WHERE $sortColumn ".($sortOrder=='asc'?'>=':'<=')." '".$event[$_REQUEST['sort_field']]."'".$_REQUEST['filter']['sql'].$midSql.' AND E.Id>'.$event['Id'] . " ORDER BY $sortColumn $sortOrder"; + $sql = 'SELECT E.Id AS Id, E.StartTime AS StartTime FROM Events AS E INNER JOIN Monitors AS M ON E.MonitorId = M.Id WHERE '.$sortColumn .' '.($sortOrder=='asc'?'>=':'<=').' \''.$event[$_REQUEST['sort_field']]."'".$_REQUEST['filter']['sql'].$midSql.' AND E.Id>'.$event['Id'] . ' ORDER BY '.$sortColumn.' '.($sortOrder=='ASC'?'ASC':'DESC'); if ( $sortColumn != 'E.Id' ) { # When sorting by starttime, if we have two events with the same starttime (diffreent monitors) then we should sort secondly by Id $sql .= ', E.Id ASC'; } $sql .= ' LIMIT 1'; - $result = dbQuery( $sql ); - $nextEvent = dbFetchNext( $result ); + $result = dbQuery($sql); + $nextEvent = dbFetchNext($result); - $result = array( 'EventId'=>$eventId ); if ( $prevEvent ) { - $result['PrevEventId'] = $prevEvent['Id']; - $result['PrevEventStartTime'] = $prevEvent['StartTime']; - $result['PrevEventDefVideoPath'] = getEventDefaultVideoPath($prevEvent['Id']); + $NearEvents['PrevEventId'] = $prevEvent['Id']; + $NearEvents['PrevEventStartTime'] = $prevEvent['StartTime']; + $NearEvents['PrevEventDefVideoPath'] = getEventDefaultVideoPath($prevEvent['Id']); } else { - $result['PrevEventId'] = $result['PrevEventStartTime'] = $result['PrevEventDefVideoPath'] = 0; + $NearEvents['PrevEventId'] = $result['PrevEventStartTime'] = $result['PrevEventDefVideoPath'] = 0; } if ( $nextEvent ) { - $result['NextEventId'] = $nextEvent['Id']; - $result['NextEventStartTime'] = $nextEvent['StartTime']; - $result['NextEventDefVideoPath'] = getEventDefaultVideoPath($nextEvent['Id']); + $NearEvents['NextEventId'] = $nextEvent['Id']; + $NearEvents['NextEventStartTime'] = $nextEvent['StartTime']; + $NearEvents['NextEventDefVideoPath'] = getEventDefaultVideoPath($nextEvent['Id']); } else { - $result['NextEventId'] = $result['NextEventStartTime'] = $result['NextEventDefVideoPath'] = 0; + $NearEvents['NextEventId'] = $NearEvents['NextEventStartTime'] = $NearEvents['NextEventDefVideoPath'] = 0; } - return $result; + return $NearEvents; } ?> From 7a7a3413d35f5493ffb3d2aa6e8fb915bf3ba137 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Mon, 5 Oct 2020 10:29:42 -0400 Subject: [PATCH 079/199] Always do event change detection whether we are paused or not. Because we might be single-stepping. Change progress to a double as that it what it should be. --- src/zm_eventstream.cpp | 49 +++++++++++++++++++++--------------------- 1 file changed, 24 insertions(+), 25 deletions(-) diff --git a/src/zm_eventstream.cpp b/src/zm_eventstream.cpp index 7b67c738a..a57cebf44 100644 --- a/src/zm_eventstream.cpp +++ b/src/zm_eventstream.cpp @@ -524,18 +524,18 @@ void EventStream::processCommand(const CmdMsg *msg) { struct { uint64_t event_id; - int progress; + double progress; int rate; int zoom; bool paused; } status_data; status_data.event_id = event_data->event_id; - status_data.progress = (int)event_data->frames[curr_frame_id-1].offset; + status_data.progress = event_data->frames[curr_frame_id-1].offset; status_data.rate = replay_rate; status_data.zoom = zoom; status_data.paused = paused; - Debug(2, "Event:%" PRIu64 ", Paused:%d, progress:%d Rate:%d, Zoom:%d", + Debug(2, "Event:%" PRIu64 ", Paused:%d, progress:%f Rate:%d, Zoom:%d", status_data.event_id, status_data.paused, status_data.progress, @@ -976,29 +976,28 @@ void EventStream::runStream() { //if ( step != 0 )// Adding 0 is cheaper than an if 0 // curr_frame_id starts at 1 though, so we might skip the first frame? curr_frame_id += step; - - // Detects when we hit end of event and will load the next event or previous event - if ( checkEventLoaded() ) { - // Have change of event - - // This next bit is to determine if we are in the current event time wise - // and whether to show an image saying how long until the next event. - if ( replay_rate > 0 ) { - // This doesn't make sense unless we have hit the end of the event. - time_to_event = event_data->frames[0].timestamp - curr_stream_time; - Debug(1, "replay rate(%d) time_to_event(%f)=frame timestamp:%f - curr_stream_time(%f)", - replay_rate, time_to_event, - event_data->frames[0].timestamp, - curr_stream_time); - - } else if ( replay_rate < 0 ) { - time_to_event = curr_stream_time - event_data->frames[event_data->frame_count-1].timestamp; - Debug(1, "replay rate(%d) time_to_event(%f)=curr_stream_time(%f)-frame timestamp:%f", - replay_rate, time_to_event, curr_stream_time, event_data->frames[event_data->frame_count-1].timestamp); - } // end if forward or reverse - - } // end if checkEventLoaded } // end if !paused + + // Detects when we hit end of event and will load the next event or previous event + if ( checkEventLoaded() ) { + // Have change of event + + // This next bit is to determine if we are in the current event time wise + // and whether to show an image saying how long until the next event. + if ( replay_rate > 0 ) { + // This doesn't make sense unless we have hit the end of the event. + time_to_event = event_data->frames[0].timestamp - curr_stream_time; + Debug(1, "replay rate(%d) time_to_event(%f)=frame timestamp:%f - curr_stream_time(%f)", + replay_rate, time_to_event, + event_data->frames[0].timestamp, + curr_stream_time); + + } else if ( replay_rate < 0 ) { + time_to_event = curr_stream_time - event_data->frames[event_data->frame_count-1].timestamp; + Debug(1, "replay rate(%d) time_to_event(%f)=curr_stream_time(%f)-frame timestamp:%f", + replay_rate, time_to_event, curr_stream_time, event_data->frames[event_data->frame_count-1].timestamp); + } // end if forward or reverse + } // end if checkEventLoaded } // end while ! zm_terminate #if HAVE_LIBAVCODEC if ( type == STREAM_MPEG ) From fa641a0345b1a65fe2478d3bf7a9454d951f43ed Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Mon, 5 Oct 2020 10:30:38 -0400 Subject: [PATCH 080/199] Convert progress to a double instead of int. --- web/ajax/stream.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/web/ajax/stream.php b/web/ajax/stream.php index 297b744c6..057bd3cea 100644 --- a/web/ajax/stream.php +++ b/web/ajax/stream.php @@ -134,10 +134,10 @@ if ( sem_acquire($semaphore,1) !== false ) { case MSG_DATA_EVENT : if ( version_compare( phpversion(), '5.6.0', '<') ) { ZM\Logger::Debug('Using old unpack methods to handle 64bit event id'); - $data = unpack('ltype/ieventlow/ieventhigh/iprogress/irate/izoom/Cpaused', $msg); + $data = unpack('ltype/ieventlow/ieventhigh/dprogress/irate/izoom/Cpaused', $msg); $data['event'] = $data['eventhigh'] << 32 | $data['eventlow']; } else { - $data = unpack('ltype/Qevent/iprogress/irate/izoom/Cpaused', $msg); + $data = unpack('ltype/Qevent/dprogress/irate/izoom/Cpaused', $msg); } $data['rate'] /= RATE_BASE; $data['zoom'] = round($data['zoom']/SCALE_BASE, 1); From 1cf181372f82fee2dacdf31aa4891550b8fadb05 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Mon, 5 Oct 2020 10:30:57 -0400 Subject: [PATCH 081/199] Only load users for logged in sessions --- web/ajax/modals/logout.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/web/ajax/modals/logout.php b/web/ajax/modals/logout.php index 6d2d56c26..d88f9077a 100644 --- a/web/ajax/modals/logout.php +++ b/web/ajax/modals/logout.php @@ -59,6 +59,10 @@ while ( $row = $result->fetch(PDO::FETCH_ASSOC) ) { # This is a dead session continue; } + if ( !isset($_SESSION['username']) ) { + # Not logged in + continue; + } $user = ZM\User::find_one(array('Username'=>$_SESSION['username'])); if ( ! $user ) { ZM\Logger::Debug('User not found for ' . $_SESSION['username']); From 2faedc6248a3006dddc19135ace2dde3171bade2 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Mon, 5 Oct 2020 10:34:52 -0400 Subject: [PATCH 082/199] Sort sessions by access time so that we list active users first --- web/ajax/modals/logout.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/ajax/modals/logout.php b/web/ajax/modals/logout.php index d88f9077a..cce461849 100644 --- a/web/ajax/modals/logout.php +++ b/web/ajax/modals/logout.php @@ -43,7 +43,7 @@ global $CLANG; Date: Mon, 5 Oct 2020 09:37:00 -0500 Subject: [PATCH 083/199] add xmlfooter to video view, replace mootools --- web/skins/classic/views/js/video.js | 21 ++++++++++----------- web/skins/classic/views/video.php | 5 ++--- 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/web/skins/classic/views/js/video.js b/web/skins/classic/views/js/video.js index 5f2df6ee3..dd85acb23 100644 --- a/web/skins/classic/views/js/video.js +++ b/web/skins/classic/views/js/video.js @@ -11,11 +11,11 @@ function downloadVideo(e) { var generateVideoTimer = null; function generateVideoProgress() { - var tickerText = $('videoProgressTicker').get('text'); + var tickerText = $j('#videoProgressTicker').text(); if ( tickerText.length < 1 || tickerText.length > 4 ) { - $('videoProgressTicker').set('text', '.'); + $j('#videoProgressTicker').text('.'); } else { - $('videoProgressTicker').appendText('.'); + $j('videoProgressTicker').append('.'); } } @@ -24,14 +24,13 @@ function generateVideoResponse( respObj, respText ) { } function generateVideo() { - form = $j('#contentForm')[0]; - var parms = 'view=request&request=event&action=video'; - parms += '&'+$(form).toQueryString(); - var query = new Request.JSON({url: thisUrl, method: 'post', data: parms, onSuccess: generateVideoResponse}); - query.send(); - $('videoProgress').removeClass('hidden'); - $('videoProgress').setProperty('class', 'warnText'); - $('videoProgressText').set('text', videoGenProgressString); + var form = $j('#videoForm').serialize(); + $j.getJSON(thisUrl + '?view=request&request=event&action=video', form) + .done(generateVideoResponse) + .fail(logAjaxFail); + $j('#videoProgress').removeClass('hidden'); + $j('#videoProgress').addClass('warnText'); + $j('#videoProgressText').text(videoGenProgressString); generateVideoProgress(); generateVideoTimer = generateVideoProgress.periodical(500); } diff --git a/web/skins/classic/views/video.php b/web/skins/classic/views/video.php index f2099a445..99a5a35e0 100644 --- a/web/skins/classic/views/video.php +++ b/web/skins/classic/views/video.php @@ -122,7 +122,7 @@ if ( isset($_REQUEST['showIndex']) ) { -
+ @@ -231,5 +231,4 @@ if ( isset($_REQUEST['showIndex']) ) { ?> - - + From c5459020c9b7f5551ef9787fa4589b18cfd3159f Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Mon, 5 Oct 2020 12:11:11 -0400 Subject: [PATCH 084/199] implement value check & correct on replay_rate for VARPLAY --- src/zm_eventstream.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/zm_eventstream.cpp b/src/zm_eventstream.cpp index a57cebf44..0e28cf0c6 100644 --- a/src/zm_eventstream.cpp +++ b/src/zm_eventstream.cpp @@ -359,6 +359,13 @@ void EventStream::processCommand(const CmdMsg *msg) { paused = false; } replay_rate = ntohs(((unsigned char)msg->msg_data[2]<<8)|(unsigned char)msg->msg_data[1])-32768; + if ( replay_rate > 50 * ZM_RATE_BASE ) { + Warning("requested replay rate (%d) is too high. We only support up to 50x", replay_rate); + replay_rate = 50 * ZM_RATE_BASE; + } else if ( replay_rate < -50*ZM_RATE_BASE ) { + Warning("requested replay rate (%d) is too low. We only support up to -50x", replay_rate); + replay_rate = -50 * ZM_RATE_BASE; + } break; case CMD_STOP : Debug(1, "Got STOP command"); From 419a03db2522efce6f408f911d8541581920dfdd Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Mon, 5 Oct 2020 12:11:39 -0400 Subject: [PATCH 085/199] Add debugging for min_section_length keeping us in ALERT --- src/zm_monitor.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/zm_monitor.cpp b/src/zm_monitor.cpp index 8674e5498..5b0aa99cd 100644 --- a/src/zm_monitor.cpp +++ b/src/zm_monitor.cpp @@ -1448,8 +1448,8 @@ bool Monitor::Analyse() { int new_motion_score = DetectMotion(*snap_image, zoneSet); Debug(3, - "After motion detection, last_motion_score(%d), new motion score(%d)", - last_motion_score, new_motion_score + "After motion detection, score(%d), last_motion_score(%d), new motion score(%d)", + score, last_motion_score, new_motion_score ); last_motion_score = new_motion_score; } @@ -1675,6 +1675,8 @@ bool Monitor::Analyse() { } else { shared_data->state = state = TAPE; } + } else { + Debug(1, "Not leaving ALERT beacuse image_count(%d)-last_alarm_count(%d) > post_event_count(%d) and timestamp.tv_sec(%d) - recording.tv_src(%d) >= min_section_length(%d)", image_count, last_alarm_count, post_event_count, timestamp->tv_sec, video_store_data->recording.tv_sec, min_section_length); } } // end if ALARM or ALERT From 6c24cd0c70d7ee057d60c9d8f9f1f17ecc328633 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Mon, 5 Oct 2020 13:14:44 -0400 Subject: [PATCH 086/199] When playing backwards, say time to previous event instead of next. Instead of defaulting to -2x when hitting the rewind button, start with -1x. --- src/zm_eventstream.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/zm_eventstream.cpp b/src/zm_eventstream.cpp index 0e28cf0c6..8263d04e7 100644 --- a/src/zm_eventstream.cpp +++ b/src/zm_eventstream.cpp @@ -418,6 +418,8 @@ void EventStream::processCommand(const CmdMsg *msg) { paused = false; // Set play rate switch ( replay_rate ) { + case -1 * ZM_RATE_BASE : + replay_rate = -2 * ZM_RATE_BASE; case -2 * ZM_RATE_BASE : replay_rate = -5 * ZM_RATE_BASE; break; @@ -432,7 +434,7 @@ void EventStream::processCommand(const CmdMsg *msg) { replay_rate = -50 * ZM_RATE_BASE; break; default : - replay_rate = -2 * ZM_RATE_BASE; + replay_rate = -1 * ZM_RATE_BASE; break; } break; @@ -866,7 +868,9 @@ void EventStream::runStream() { if ( actual_delta_time > 1 ) { Debug(1, "Sending time to next event frame"); static char frame_text[64]; - snprintf(frame_text, sizeof(frame_text), "Time to next event = %d seconds", (int)time_to_event); + + snprintf(frame_text, sizeof(frame_text), "Time to %s event = %d seconds", + (replay_rate > 0 ? "next" : "previous" ), (int)time_to_event); if ( !sendTextFrame(frame_text) ) zm_terminate = true; } else { From 059d7d388fa0610d727eab9a3fef406ee3f25779 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Mon, 5 Oct 2020 13:15:39 -0400 Subject: [PATCH 087/199] Make centerCoord take a font size parameter to fix centering when using large font. --- src/zm_image.cpp | 8 ++++---- src/zm_image.h | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/zm_image.cpp b/src/zm_image.cpp index 0a4cca08f..b2707dd52 100644 --- a/src/zm_image.cpp +++ b/src/zm_image.cpp @@ -1850,10 +1850,10 @@ void Image::Delta( const Image &image, Image* targetimage) const { #endif } -const Coord Image::centreCoord( const char *text ) const { +const Coord Image::centreCoord( const char *text, int size=1 ) const { int index = 0; int line_no = 0; - int text_len = strlen( text ); + int text_len = strlen(text); int line_len = 0; int max_line_len = 0; const char *line = text; @@ -1869,8 +1869,8 @@ const Coord Image::centreCoord( const char *text ) const { line = text+index; line_no++; } - int x = (width - (max_line_len * ZM_CHAR_WIDTH) ) / 2; - int y = (height - (line_no * LINE_HEIGHT) ) / 2; + int x = (width - (max_line_len * ZM_CHAR_WIDTH * size) ) / 2; + int y = (height - (line_no * LINE_HEIGHT * size) ) / 2; return Coord(x, y); } diff --git a/src/zm_image.h b/src/zm_image.h index 8f86c3e30..3e07e41eb 100644 --- a/src/zm_image.h +++ b/src/zm_image.h @@ -263,7 +263,7 @@ public: //Image *Delta( const Image &image ) const; void Delta( const Image &image, Image* targetimage) const; - const Coord centreCoord( const char *text ) const; + const Coord centreCoord( const char *text, const int size ) const; void MaskPrivacy( const unsigned char *p_bitmask, const Rgb pixel_colour=0x00222222 ); void Annotate( const char *p_text, const Coord &coord, const unsigned int size=1, const Rgb fg_colour=RGB_WHITE, const Rgb bg_colour=RGB_BLACK ); Image *HighlightEdges( Rgb colour, unsigned int p_colours, unsigned int p_subpixelorder, const Box *limits=0 ); From 5dd83d41fab9cebe88fa68d886ed9863b61de673 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Mon, 5 Oct 2020 13:15:58 -0400 Subject: [PATCH 088/199] Add LabelSize to get label_size from monitor --- src/zm_monitor.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/zm_monitor.h b/src/zm_monitor.h index f1db76195..4b6ec5088 100644 --- a/src/zm_monitor.h +++ b/src/zm_monitor.h @@ -505,6 +505,8 @@ public: inline time_t getStartupTime() const { return shared_data->startup_time; } inline void setStartupTime( time_t p_time ) { shared_data->startup_time = p_time; } + int LabelSize() { return label_size; } + void actionReload(); void actionEnable(); void actionDisable(); From 71085d9724fb5cb7f7fda18f15214b7b9981f1b8 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Mon, 5 Oct 2020 13:16:22 -0400 Subject: [PATCH 089/199] Clear the textframe before Annotating it. --- src/zm_stream.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/zm_stream.cpp b/src/zm_stream.cpp index 05236c3ba..63a5a4a0a 100644 --- a/src/zm_stream.cpp +++ b/src/zm_stream.cpp @@ -252,7 +252,8 @@ bool StreamBase::sendTextFrame(const char *frame_text) { monitor->Width(), monitor->Height(), scale, frame_text); Image image(monitor->Width(), monitor->Height(), monitor->Colours(), monitor->SubpixelOrder()); - image.Annotate(frame_text, image.centreCoord(frame_text)); + image.Clear(); + image.Annotate(frame_text, image.centreCoord(frame_text, monitor->LabelSize()), monitor->LabelSize()); if ( scale != 100 ) { image.Scale(scale); From c43011ba1864857abe466130bfd342282401d0ba Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Mon, 5 Oct 2020 13:33:57 -0400 Subject: [PATCH 090/199] don't send keepalive when we have sent a textFrame --- src/zm_eventstream.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/zm_eventstream.cpp b/src/zm_eventstream.cpp index 8263d04e7..afd92f6d4 100644 --- a/src/zm_eventstream.cpp +++ b/src/zm_eventstream.cpp @@ -873,6 +873,7 @@ void EventStream::runStream() { (replay_rate > 0 ? "next" : "previous" ), (int)time_to_event); if ( !sendTextFrame(frame_text) ) zm_terminate = true; + send_frame = false; // In case keepalive was set } else { Debug(1, "Not Sending time to next event frame because actual delta time is %f", actual_delta_time); } From 321de3c6045d243b80359a426279df3a7d3b614b Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Mon, 5 Oct 2020 13:59:44 -0500 Subject: [PATCH 091/199] only update changed elements in video view --- web/skins/classic/views/js/video.js | 28 +++++++++++++--------------- web/skins/classic/views/video.php | 21 ++++----------------- 2 files changed, 17 insertions(+), 32 deletions(-) diff --git a/web/skins/classic/views/js/video.js b/web/skins/classic/views/js/video.js index dd85acb23..a4ce159a5 100644 --- a/web/skins/classic/views/js/video.js +++ b/web/skins/classic/views/js/video.js @@ -8,29 +8,27 @@ function downloadVideo(e) { window.location.replace(thisUrl+'?view='+currentView+'&eid='+eventId+'&downloadIndex='+index); } -var generateVideoTimer = null; +function generateVideoResponse( data, responseText ) { + console.log(data); -function generateVideoProgress() { - var tickerText = $j('#videoProgressTicker').text(); - if ( tickerText.length < 1 || tickerText.length > 4 ) { - $j('#videoProgressTicker').text('.'); + var generated = (data.result=='Ok') ? 1 : 0; + var fullUrl = thisUrl + '?view=' + currentView + '&eid=' + eventId + '&generated=' + generated; + + $j('#videoProgress').removeClass( 'text-warning' ); + if ( generated ) { + $j('#videoProgress').addClass( 'text-success' ); + $j('#videoProgress').text(exportSucceededString); + $j( "#videoTable" ).load( fullUrl+ ' #videoTable' ); } else { - $j('videoProgressTicker').append('.'); + $j('#videoProgress').addClass( 'text-danger' ); + $j('#videoProgress').text(exportFailedString); } } -function generateVideoResponse( respObj, respText ) { - window.location.replace(thisUrl+'?view='+currentView+'&eid='+eventId+'&generated='+((respObj.result=='Ok')?1:0)); -} - function generateVideo() { var form = $j('#videoForm').serialize(); $j.getJSON(thisUrl + '?view=request&request=event&action=video', form) .done(generateVideoResponse) .fail(logAjaxFail); - $j('#videoProgress').removeClass('hidden'); - $j('#videoProgress').addClass('warnText'); - $j('#videoProgressText').text(videoGenProgressString); - generateVideoProgress(); - generateVideoTimer = generateVideoProgress.periodical(500); + $j('#videoProgress').removeClass('invisible'); } diff --git a/web/skins/classic/views/video.php b/web/skins/classic/views/video.php index 99a5a35e0..1a3812634 100644 --- a/web/skins/classic/views/video.php +++ b/web/skins/classic/views/video.php @@ -148,23 +148,10 @@ if ( isset($_REQUEST['showIndex']) ) { - -

- - +

- - -

- + - + - + - +
- Id().'&width='.$width.'&height='.$height.'&showIndex='.$index, 'zmVideo'.$event->Id().'-'.$scale, array('videoview', $width, $height), translate('View') ); ?> + Id().'&width='.$width.'&height='.$height.'&showIndex='.$index, translate('View') ); ?>  /  From f93450f9ea91a7ff90bb6b66e6ddf2b6bbc469cc Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Mon, 5 Oct 2020 14:44:45 -0500 Subject: [PATCH 092/199] remove plugin support for viewing downloads --- web/skins/classic/views/js/video.js | 10 ---------- web/skins/classic/views/video.php | 25 +++++++++++-------------- 2 files changed, 11 insertions(+), 24 deletions(-) diff --git a/web/skins/classic/views/js/video.js b/web/skins/classic/views/js/video.js index a4ce159a5..58378e986 100644 --- a/web/skins/classic/views/js/video.js +++ b/web/skins/classic/views/js/video.js @@ -1,13 +1,3 @@ -function deleteVideo(e) { - index = e.getAttribute('data-file-index'); - window.location.replace(thisUrl+'?view='+currentView+'&eid='+eventId+'&deleteIndex='+index); -} - -function downloadVideo(e) { - index = e.getAttribute('data-file-index'); - window.location.replace(thisUrl+'?view='+currentView+'&eid='+eventId+'&downloadIndex='+index); -} - function generateVideoResponse( data, responseText ) { console.log(data); diff --git a/web/skins/classic/views/video.php b/web/skins/classic/views/video.php index 1a3812634..a8c63604e 100644 --- a/web/skins/classic/views/video.php +++ b/web/skins/classic/views/video.php @@ -153,13 +153,7 @@ if ( isset($_REQUEST['showIndex']) ) {

- -

- + @@ -172,6 +166,12 @@ if ( isset($_REQUEST['showIndex']) ) { + + 0 ) { @@ -197,23 +197,20 @@ if ( isset($_REQUEST['showIndex']) ) {
No Video Files Found - Id().'&width='.$width.'&height='.$height.'&showIndex='.$index, translate('View') ); ?> -  /  - -  /  - + +  /  +
From c1c407ea3924519c8a312f47333f4f460e4e66fc Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Mon, 5 Oct 2020 15:55:42 -0400 Subject: [PATCH 093/199] debug new offset as well when SEEKING --- src/zm_eventstream.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/zm_eventstream.cpp b/src/zm_eventstream.cpp index 8eaa9cc8f..aa0040bf7 100644 --- a/src/zm_eventstream.cpp +++ b/src/zm_eventstream.cpp @@ -507,7 +507,8 @@ void EventStream::processCommand(const CmdMsg *msg) { // offset is in seconds int offset = ((unsigned char)msg->msg_data[1]<<24)|((unsigned char)msg->msg_data[2]<<16)|((unsigned char)msg->msg_data[3]<<8)|(unsigned char)msg->msg_data[4]; curr_frame_id = (int)(event_data->frame_count*offset/event_data->duration); - Debug(1, "Got SEEK command, to %d (new cfid: %d)", offset, curr_frame_id); + Debug(1, "Got SEEK command, to %d (new current frame id: %d offset %.f)", + offset, curr_frame_id, event_data->frames[curr_frame_id-1].offset); send_frame = true; break; } From 93ecb87caa7ceecaef7781b9181382c44c976b0c Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Mon, 5 Oct 2020 13:16:22 -0400 Subject: [PATCH 094/199] Clear the textframe before Annotating it. --- src/zm_stream.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/zm_stream.cpp b/src/zm_stream.cpp index 258e04d52..2fa82ad7a 100644 --- a/src/zm_stream.cpp +++ b/src/zm_stream.cpp @@ -236,7 +236,8 @@ bool StreamBase::sendTextFrame(const char *frame_text) { monitor->Width(), monitor->Height(), scale, frame_text); Image image(monitor->Width(), monitor->Height(), monitor->Colours(), monitor->SubpixelOrder()); - image.Annotate(frame_text, image.centreCoord(frame_text)); + image.Clear(); + image.Annotate(frame_text, image.centreCoord(frame_text, monitor->LabelSize()), monitor->LabelSize()); if ( scale != 100 ) { image.Scale(scale); From 1c2dd92d310e5c46ce9196bfde1dfb2df4428663 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Mon, 5 Oct 2020 13:15:58 -0400 Subject: [PATCH 095/199] Add LabelSize to get label_size from monitor --- src/zm_monitor.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/zm_monitor.h b/src/zm_monitor.h index 5c6a60c91..7358390b9 100644 --- a/src/zm_monitor.h +++ b/src/zm_monitor.h @@ -494,6 +494,8 @@ public: inline time_t getStartupTime() const { return shared_data->startup_time; } inline void setStartupTime( time_t p_time ) { shared_data->startup_time = p_time; } + int LabelSize() { return label_size; } + void actionReload(); void actionEnable(); void actionDisable(); From b27eac3cbffd70b8ed10bbc5bc11456785dcbe53 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Mon, 5 Oct 2020 13:15:39 -0400 Subject: [PATCH 096/199] Make centerCoord take a font size parameter to fix centering when using large font. --- src/zm_image.cpp | 8 ++++---- src/zm_image.h | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/zm_image.cpp b/src/zm_image.cpp index 1b8b33c8a..6129707f1 100644 --- a/src/zm_image.cpp +++ b/src/zm_image.cpp @@ -1850,10 +1850,10 @@ void Image::Delta( const Image &image, Image* targetimage) const { #endif } -const Coord Image::centreCoord( const char *text ) const { +const Coord Image::centreCoord( const char *text, int size=1 ) const { int index = 0; int line_no = 0; - int text_len = strlen( text ); + int text_len = strlen(text); int line_len = 0; int max_line_len = 0; const char *line = text; @@ -1869,8 +1869,8 @@ const Coord Image::centreCoord( const char *text ) const { line = text+index; line_no++; } - int x = (width - (max_line_len * ZM_CHAR_WIDTH) ) / 2; - int y = (height - (line_no * LINE_HEIGHT) ) / 2; + int x = (width - (max_line_len * ZM_CHAR_WIDTH * size) ) / 2; + int y = (height - (line_no * LINE_HEIGHT * size) ) / 2; return Coord(x, y); } diff --git a/src/zm_image.h b/src/zm_image.h index 1b8f614b9..c8a81c460 100644 --- a/src/zm_image.h +++ b/src/zm_image.h @@ -263,7 +263,7 @@ public: //Image *Delta( const Image &image ) const; void Delta( const Image &image, Image* targetimage) const; - const Coord centreCoord( const char *text ) const; + const Coord centreCoord( const char *text, const int size ) const; void MaskPrivacy( const unsigned char *p_bitmask, const Rgb pixel_colour=0x00222222 ); void Annotate( const char *p_text, const Coord &coord, const unsigned int size=1, const Rgb fg_colour=RGB_WHITE, const Rgb bg_colour=RGB_BLACK ); Image *HighlightEdges( Rgb colour, unsigned int p_colours, unsigned int p_subpixelorder, const Box *limits=0 ); From 9c7ebf8c9e7aee7fe77b0993096e9aa4d59efa85 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Mon, 5 Oct 2020 15:44:07 -0500 Subject: [PATCH 097/199] unpopup video view --- web/skins/classic/views/js/event.js | 2 +- web/skins/classic/views/js/video.js | 24 ++++++++++++++++++++++++ web/skins/classic/views/js/video.js.php | 1 + web/skins/classic/views/video.php | 24 +++++++++++++----------- 4 files changed, 39 insertions(+), 12 deletions(-) diff --git a/web/skins/classic/views/js/event.js b/web/skins/classic/views/js/event.js index 313b8bad1..83c7c2090 100644 --- a/web/skins/classic/views/js/event.js +++ b/web/skins/classic/views/js/event.js @@ -1034,7 +1034,7 @@ function showFrameStats() { } function videoEvent() { - createPopup('?view=video&eid='+eventData.Id, 'zmVideo', 'video', eventData.Width, eventData.Height); + window.location.assign('?view=video&eid='+eventData.Id); } // Called on each event load because each event can be a different width diff --git a/web/skins/classic/views/js/video.js b/web/skins/classic/views/js/video.js index 58378e986..2a28cff07 100644 --- a/web/skins/classic/views/js/video.js +++ b/web/skins/classic/views/js/video.js @@ -22,3 +22,27 @@ function generateVideo() { .fail(logAjaxFail); $j('#videoProgress').removeClass('invisible'); } + +function initPage() { + var backBtn = $j('#backBtn'); + var videoBtn = $j('#videoBtn'); + + videoBtn.prop('disabled', !opt_ffmpeg); + + // Manage the BACK button + document.getElementById("backBtn").addEventListener("click", function onBackClick(evt) { + evt.preventDefault(); + window.history.back(); + }); + + // Manage the REFRESH Button + document.getElementById("refreshBtn").addEventListener("click", function onRefreshClick(evt) { + evt.preventDefault(); + window.location.reload(true); + }); + + // Don't enable the back button if there is no previous zm page to go back to + backBtn.prop('disabled', !document.referrer.length); +} + +$j(document).ready(initPage); diff --git a/web/skins/classic/views/js/video.js.php b/web/skins/classic/views/js/video.js.php index e9bb78878..2936502fa 100644 --- a/web/skins/classic/views/js/video.js.php +++ b/web/skins/classic/views/js/video.js.php @@ -6,3 +6,4 @@ var eventId = 'Id() ?>'; var videoGenSuccessString = ''; var videoGenFailedString = ''; var videoGenProgressString = ''; +var opt_ffmpeg = ; diff --git a/web/skins/classic/views/video.php b/web/skins/classic/views/video.php index a8c63604e..a4c01273f 100644 --- a/web/skins/classic/views/video.php +++ b/web/skins/classic/views/video.php @@ -102,12 +102,17 @@ $focusWindow = true; xhtmlHeaders(__FILE__, translate('Video')); ?> +
-
checked="checked"/>
-
+ From ed5f6b262573ebb9c7163b0a98d90e760061471c Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Mon, 12 Oct 2020 12:16:52 -0500 Subject: [PATCH 140/199] convert shutdown popup to modal --- web/ajax/modals/shutdown.php | 64 ++++++++++++++++++++++++ web/skins/classic/includes/functions.php | 6 +-- web/skins/classic/js/skin.js | 15 ++++++ 3 files changed, 82 insertions(+), 3 deletions(-) create mode 100644 web/ajax/modals/shutdown.php diff --git a/web/ajax/modals/shutdown.php b/web/ajax/modals/shutdown.php new file mode 100644 index 000000000..0cfea0111 --- /dev/null +++ b/web/ajax/modals/shutdown.php @@ -0,0 +1,64 @@ +'.implode('
', $output).'

'.PHP_EOL; +} + +$cancel_str = ''; +if ( isset($_POST['when']) and ($_POST['when'] != 'NOW') and ($action != 'cancel') ) { + $cancel_str = '

You may cancel this shutdown by clicking '.translate('Cancel').'

'.PHP_EOL; +} + +$cancel_btn = ''; +if ( isset($_POST['when']) and ($_POST['when'] != 'NOW') and ($action != 'cancel') ) { + $cancel_btn = ''.PHP_EOL; +} + +?> + diff --git a/web/skins/classic/includes/functions.php b/web/skins/classic/includes/functions.php index dc97e295a..70bb8d163 100644 --- a/web/skins/classic/includes/functions.php +++ b/web/skins/classic/includes/functions.php @@ -756,9 +756,9 @@ function getStatusBtnHTML($status) { //$result .= ''.PHP_EOL; if ( ZM_SYSTEM_SHUTDOWN ) { - $result .= ''.PHP_EOL; + $result .= ''.PHP_EOL; } } else if ( canView('System') ) { diff --git a/web/skins/classic/js/skin.js b/web/skins/classic/js/skin.js index a7781b961..df2d45a7e 100644 --- a/web/skins/classic/js/skin.js +++ b/web/skins/classic/js/skin.js @@ -956,3 +956,18 @@ function exportEvent() { .fail(logAjaxFail); $j('#exportProgress').removeClass( 'invisible' ); } + +// Load the Function modal on page load +function getShutdownModal() { + $j.getJSON(thisUrl + '?request=modal&modal=shutdown') + .done(function(data) { + if ( $j('#shutdownModal').length ) { + $j('#shutdownModal').replaceWith(data.html); + } else { + $j("body").append(data.html); + } + // Manage the Shutdown modal + $j('#shutdownModal').modal('show'); + }) + .fail(logAjaxFail); +} From 1db31ba574e16c2bc4e5d879be0d3909d063347f Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Mon, 12 Oct 2020 12:20:21 -0500 Subject: [PATCH 141/199] remove makePopupLink function. Use makeLink instead --- web/includes/functions.php | 29 +++-------------------------- 1 file changed, 3 insertions(+), 26 deletions(-) diff --git a/web/includes/functions.php b/web/includes/functions.php index 9950c4266..f42a1029d 100644 --- a/web/includes/functions.php +++ b/web/includes/functions.php @@ -424,6 +424,9 @@ function deleteEvent($event) { } # CAN EDIT } +/** + * $label must be already escaped. It can't be done here since it sometimes contains HTML tags. + */ function makeLink($url, $label, $condition=1, $options='') { $string = ''; if ( $condition ) { @@ -443,32 +446,6 @@ function makeHelpLink($ohndx) { return $string; } -/** - * $label must be already escaped. It can't be done here since it sometimes contains HTML tags. - */ -function makePopupLink($url, $winName, $winSize, $label, $condition=1, $options='') { - // Avoid double-encoding since some consumers incorrectly pass a pre-escaped URL. - $string = ''; - } else { - $string .= '>'; - } - $string .= $label; - $string .= ''; - return $string; -} - function makeButton($url, $buttonValue, $condition=1, $options='') { $string = ' - + + diff --git a/web/skins/classic/js/skin.js b/web/skins/classic/js/skin.js index faef50c4f..c6171a47a 100644 --- a/web/skins/classic/js/skin.js +++ b/web/skins/classic/js/skin.js @@ -830,6 +830,16 @@ function getShutdownModal() { } // Manage the Shutdown modal $j('#shutdownModal').modal('show'); + // Redirect to the current view after the form is submitted - avoids a blank screen + $j('#shutdownForm').append(''); + $j('#restartBtn').click(function(evt) { + evt.preventDefault(); + $j('#shutdownForm').submit(); + }); + $j('#shutdownBtn').click(function(evt) { + evt.preventDefault(); + $j('#shutdownForm').submit(); + }); }) .fail(logAjaxFail); } diff --git a/web/skins/classic/views/shutdown.php b/web/skins/classic/views/shutdown.php deleted file mode 100644 index 25d5d3d34..000000000 --- a/web/skins/classic/views/shutdown.php +++ /dev/null @@ -1,79 +0,0 @@ - - -
- -
-ZM_PATH_SHUTDOWN is not defined. This is normally configured in /etc/zm/conf.d/01-system-paths.conf
'; - } else if ( !file_exists(ZM_PATH_SHUTDOWN) ) { - echo '
Path does not exist for ZM_PATH_SHUTDOWN. Current value is '.ZM_PATH_SHUTDOWN.'
'; - } else { -?> - -
- -'.implode('
', $output).'

'; - } - if ( isset($_POST['when']) and ($_POST['when'] != 'NOW') and ($action != 'cancel') ) { - echo '

You may cancel this shutdown by clicking '.translate('Cancel').'

'; - } -?> -

Warning

- This command will either shutdown or restart all ZoneMinder Servers
-

-

- - -

-
- - - - - - -
- - -
- - From 89c76ec140cb2ae8ed3e2e15665d9be264ac84ec Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Mon, 12 Oct 2020 14:52:57 -0500 Subject: [PATCH 146/199] no need to clare $view as global --- web/ajax/modals/shutdown.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/web/ajax/modals/shutdown.php b/web/ajax/modals/shutdown.php index 78c133a87..a461f0074 100644 --- a/web/ajax/modals/shutdown.php +++ b/web/ajax/modals/shutdown.php @@ -1,6 +1,4 @@ Date: Tue, 13 Oct 2020 08:42:22 -0400 Subject: [PATCH 147/199] add ZM prefix to Warning --- web/includes/functions.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/includes/functions.php b/web/includes/functions.php index 9950c4266..d2610c3c3 100644 --- a/web/includes/functions.php +++ b/web/includes/functions.php @@ -2093,7 +2093,7 @@ function getStreamHTML($monitor, $options = array()) { if ( $scale < $options['scale'] ) $options['scale'] = $scale; } else { - Warning('Invalid value for width: '.$options['width']); + ZM\Warning('Invalid value for width: '.$options['width']); } } } From 031b41f78a17d801a11400aa07593f12b376db1a Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Tue, 13 Oct 2020 07:59:34 -0500 Subject: [PATCH 148/199] remove the english word popup from lang files --- web/lang/ba_ba.php | 2 +- web/lang/big5_big5.php | 2 +- web/lang/cn_zh.php | 2 +- web/lang/cs_cz.php | 2 +- web/lang/de_de.php | 2 +- web/lang/dk_dk.php | 2 +- web/lang/en_gb.php | 2 +- web/lang/et_ee.php | 2 +- web/lang/he_il.php | 2 +- web/lang/hu_hu.php | 2 +- web/lang/it_it.php | 2 +- web/lang/ja_jp.php | 2 +- web/lang/nl_nl.php | 2 +- web/lang/pl_pl.php | 2 +- web/lang/pt_br.php | 2 +- web/lang/ru_ru.php | 2 +- 16 files changed, 16 insertions(+), 16 deletions(-) diff --git a/web/lang/ba_ba.php b/web/lang/ba_ba.php index 96a3ca4d1..025634982 100644 --- a/web/lang/ba_ba.php +++ b/web/lang/ba_ba.php @@ -989,7 +989,7 @@ $OLANG = array( // 'LANG_DEFAULT' => array( // 'Prompt' => "This is a new prompt for this option", -// 'Help' => "This is some new help for this option which will be displayed in the popup window when the ? is clicked" +// 'Help' => "This is some new help for this option which will be displayed in the window when the ? is clicked" // ), ); diff --git a/web/lang/big5_big5.php b/web/lang/big5_big5.php index 922140698..c757eb98e 100644 --- a/web/lang/big5_big5.php +++ b/web/lang/big5_big5.php @@ -951,7 +951,7 @@ $OLANG = array( // 'LANG_DEFAULT' => array( // 'Prompt' => "This is a new prompt for this option", -// 'Help' => "This is some new help for this option which will be displayed in the popup window when the ? is clicked" +// 'Help' => "This is some new help for this option which will be displayed in the window when the ? is clicked" // ), ); diff --git a/web/lang/cn_zh.php b/web/lang/cn_zh.php index 9cdd9c4f1..09a5c3b27 100644 --- a/web/lang/cn_zh.php +++ b/web/lang/cn_zh.php @@ -989,7 +989,7 @@ $OLANG = array( // 'LANG_DEFAULT' => array( // 'Prompt' => "This is a new prompt for this option", -// 'Help' => "This is some new help for this option which will be displayed in the popup window when the ? is clicked" +// 'Help' => "This is some new help for this option which will be displayed in the window when the ? is clicked" // ), ); diff --git a/web/lang/cs_cz.php b/web/lang/cs_cz.php index c6340ae76..d64b1ff54 100644 --- a/web/lang/cs_cz.php +++ b/web/lang/cs_cz.php @@ -947,7 +947,7 @@ $OLANG = array( // 'LANG_DEFAULT' => array( // 'Prompt' => "This is a new prompt for this option", -// 'Help' => "This is some new help for this option which will be displayed in the popup window when the ? is clicked" +// 'Help' => "This is some new help for this option which will be displayed in the window when the ? is clicked" // ), ); diff --git a/web/lang/de_de.php b/web/lang/de_de.php index e8bb8218a..dbf1310f3 100644 --- a/web/lang/de_de.php +++ b/web/lang/de_de.php @@ -949,7 +949,7 @@ $OLANG = array( // 'LANG_DEFAULT' => array( // 'Prompt' => "This is a new prompt for this option", -// 'Help' => "This is some new help for this option which will be displayed in the popup window when the ? is clicked" +// 'Help' => "This is some new help for this option which will be displayed in the window when the ? is clicked" // ), ); diff --git a/web/lang/dk_dk.php b/web/lang/dk_dk.php index 045b5345e..af11854d4 100644 --- a/web/lang/dk_dk.php +++ b/web/lang/dk_dk.php @@ -973,7 +973,7 @@ $OLANG = array( // 'LANG_DEFAULT' => array( // 'Prompt' => "This is a new prompt for this option", -// 'Help' => "This is some new help for this option which will be displayed in the popup window when the ? is clicked" +// 'Help' => "This is some new help for this option which will be displayed in the window when the ? is clicked" // ), ); diff --git a/web/lang/en_gb.php b/web/lang/en_gb.php index d6394b94e..b80121bed 100644 --- a/web/lang/en_gb.php +++ b/web/lang/en_gb.php @@ -1075,7 +1075,7 @@ $OLANG = array( // 'LANG_DEFAULT' => array( // 'Prompt' => "This is a new prompt for this option", -// 'Help' => "This is some new help for this option which will be displayed in the popup window when the ? is clicked" +// 'Help' => "This is some new help for this option which will be displayed in the window when the ? is clicked" // ), ); diff --git a/web/lang/et_ee.php b/web/lang/et_ee.php index 99a277144..f294aeac8 100644 --- a/web/lang/et_ee.php +++ b/web/lang/et_ee.php @@ -953,7 +953,7 @@ $OLANG = array( // 'LANG_DEFAULT' => array( // 'Prompt' => "This is a new prompt for this option", -// 'Help' => "This is some new help for this option which will be displayed in the popup window when the ? is clicked" +// 'Help' => "This is some new help for this option which will be displayed in the window when the ? is clicked" // ), ); diff --git a/web/lang/he_il.php b/web/lang/he_il.php index ff4440053..ed90d8a08 100644 --- a/web/lang/he_il.php +++ b/web/lang/he_il.php @@ -946,7 +946,7 @@ $OLANG = array( // 'LANG_DEFAULT' => array( // 'Prompt' => "This is a new prompt for this option", -// 'Help' => "This is some new help for this option which will be displayed in the popup window when the ? is clicked" +// 'Help' => "This is some new help for this option which will be displayed in the window when the ? is clicked" // ), ); diff --git a/web/lang/hu_hu.php b/web/lang/hu_hu.php index 7ef51dab3..bcca474bc 100644 --- a/web/lang/hu_hu.php +++ b/web/lang/hu_hu.php @@ -990,7 +990,7 @@ $OLANG = array( // 'LANG_DEFAULT' => array( // 'Prompt' => "This is a new prompt for this option", -// 'Help' => "This is some new help for this option which will be displayed in the popup window when the ? is clicked" +// 'Help' => "This is some new help for this option which will be displayed in the window when the ? is clicked" // ), ); diff --git a/web/lang/it_it.php b/web/lang/it_it.php index 05aa524b0..11154bdbd 100644 --- a/web/lang/it_it.php +++ b/web/lang/it_it.php @@ -953,7 +953,7 @@ $OLANG = array( // 'LANG_DEFAULT' => array( // 'Prompt' => "This is a new prompt for this option", -// 'Help' => "This is some new help for this option which will be displayed in the popup window when the ? is clicked" +// 'Help' => "This is some new help for this option which will be displayed in the window when the ? is clicked" // ), ); diff --git a/web/lang/ja_jp.php b/web/lang/ja_jp.php index 55b13ae0a..94da7ffb8 100644 --- a/web/lang/ja_jp.php +++ b/web/lang/ja_jp.php @@ -948,7 +948,7 @@ $OLANG = array( // 'LANG_DEFAULT' => array( // 'Prompt' => "This is a new prompt for this option", -// 'Help' => "This is some new help for this option which will be displayed in the popup window when the ? is clicked" +// 'Help' => "This is some new help for this option which will be displayed in the window when the ? is clicked" // ), ); diff --git a/web/lang/nl_nl.php b/web/lang/nl_nl.php index be741a6ac..604115572 100644 --- a/web/lang/nl_nl.php +++ b/web/lang/nl_nl.php @@ -948,7 +948,7 @@ $OLANG = array( // 'LANG_DEFAULT' => array( // 'Prompt' => "This is a new prompt for this option", -// 'Help' => "This is some new help for this option which will be displayed in the popup window when the ? is clicked" +// 'Help' => "This is some new help for this option which will be displayed in the window when the ? is clicked" // ), ); diff --git a/web/lang/pl_pl.php b/web/lang/pl_pl.php index a1e8bd27a..b5bc3d949 100644 --- a/web/lang/pl_pl.php +++ b/web/lang/pl_pl.php @@ -942,7 +942,7 @@ $OLANG = array( // 'LANG_DEFAULT' => array( // 'Prompt' => "This is a new prompt for this option", -// 'Help' => "This is some new help for this option which will be displayed in the popup window when the ? is clicked" +// 'Help' => "This is some new help for this option which will be displayed in the window when the ? is clicked" // ), ); diff --git a/web/lang/pt_br.php b/web/lang/pt_br.php index 80ded9e3d..b4f2b2f30 100644 --- a/web/lang/pt_br.php +++ b/web/lang/pt_br.php @@ -887,7 +887,7 @@ $OLANG = array( // 'LANG_DEFAULT' => array( // 'Prompt' => "This is a new prompt for this option", -// 'Help' => "This is some new help for this option which will be displayed in the popup window when the ? is clicked" +// 'Help' => "This is some new help for this option which will be displayed in the window when the ? is clicked" // ), ); diff --git a/web/lang/ru_ru.php b/web/lang/ru_ru.php index 6664e4d97..689ab27d5 100644 --- a/web/lang/ru_ru.php +++ b/web/lang/ru_ru.php @@ -957,7 +957,7 @@ $OLANG = array( // 'LANG_DEFAULT' => array( // 'Prompt' => "This is a new prompt for this option", -// 'Help' => "This is some new help for this option which will be displayed in the popup window when the ? is clicked" +// 'Help' => "This is some new help for this option which will be displayed in the window when the ? is clicked" // ), ); From e4fec8c5ea0bbc7f2389298f678147758b59d729 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Tue, 13 Oct 2020 09:02:38 -0400 Subject: [PATCH 149/199] code style cleanups, most defaulting to 'Id' as the term attr so that we can use an empty filter as a quick jump to event feature --- web/skins/classic/views/filter.php | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/web/skins/classic/views/filter.php b/web/skins/classic/views/filter.php index a15a3b6bb..da9d75f0d 100644 --- a/web/skins/classic/views/filter.php +++ b/web/skins/classic/views/filter.php @@ -39,6 +39,7 @@ if ( isset($_REQUEST['Id']) ) { $fid = validInt($_REQUEST['Id']); } else if ( isset($_REQUEST['filter[Id]']) ) { $fid = validInt($_REQUEST['filter[Id]']); + ZM\Warning("got fid by object id $fid"); } foreach ( ZM\Filter::find(null,array('order'=>'lower(Name)')) as $Filter ) { @@ -59,6 +60,8 @@ if ( !$filter ) { # Update our filter object with whatever changes we have made before saving $filter->set($_REQUEST['filter']); } +} else { + ZM\Logger::Debug('filter: ' . print_r($filter)); } $conjunctionTypes = ZM\getFilterQueryConjunctionTypes(); @@ -222,13 +225,13 @@ if ( (null !== $filter->Concurrent()) and $filter->Concurrent() )

- UserId() ? $filter->UserId() : $user['Id'] -); ?> + echo htmlSelect('filter[UserId]', + ZM\User::Indexed_By_Id(), + $filter->UserId() ? $filter->UserId() : $user['Id'] + ); +?>

@@ -240,7 +243,7 @@ for ( $i=0; $i < count($terms); $i++ ) { if ( ! isset( $term['op'] ) ) $term['op'] = '='; if ( ! isset( $term['attr'] ) ) - $term['attr'] = ''; + $term['attr'] = 'Id'; if ( ! isset( $term['val'] ) ) $term['val'] = ''; if ( ! isset( $term['cnj'] ) ) @@ -352,7 +355,7 @@ for ( $i=0; $i < count($terms); $i++ ) {

From ff14d11fef0ff387b0c494c13cc6e17d784b0a7a Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Tue, 13 Oct 2020 10:07:27 -0400 Subject: [PATCH 150/199] Don't output the filter, just log it! --- web/skins/classic/views/filter.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/skins/classic/views/filter.php b/web/skins/classic/views/filter.php index da9d75f0d..28231453a 100644 --- a/web/skins/classic/views/filter.php +++ b/web/skins/classic/views/filter.php @@ -61,7 +61,7 @@ if ( !$filter ) { $filter->set($_REQUEST['filter']); } } else { - ZM\Logger::Debug('filter: ' . print_r($filter)); + ZM\Logger::Debug('filter: ' . print_r($filter,true)); } $conjunctionTypes = ZM\getFilterQueryConjunctionTypes(); From ba82088b9968e9f095415a848b9dc559d63b95d8 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Wed, 14 Oct 2020 08:51:44 -0500 Subject: [PATCH 151/199] make all the data-on-xxx js bindings functions --- web/skins/classic/js/skin.js | 38 ++++++++++++++++++++++++++++-------- 1 file changed, 30 insertions(+), 8 deletions(-) diff --git a/web/skins/classic/js/skin.js b/web/skins/classic/js/skin.js index c6171a47a..b0a4395cd 100644 --- a/web/skins/classic/js/skin.js +++ b/web/skins/classic/js/skin.js @@ -92,7 +92,17 @@ window.addEventListener("DOMContentLoaded", function onSkinDCL() { el.addEventListener("click", submitTab); }); - // 'data-on-click-this' calls the global function in the attribute value with the element when a click happens. + dataOnClickThis(); + dataOnClick(); + dataOnClickTrue(); + dataOnChangeThis(); + dataOnChange(); + dataOnInput(); + dataOnInputThis(); +}); + +// 'data-on-click-this' calls the global function in the attribute value with the element when a click happens. +function dataOnClickThis() { document.querySelectorAll("a[data-on-click-this], button[data-on-click-this], input[data-on-click-this]").forEach(function attachOnClick(el) { var fnName = el.getAttribute("data-on-click-this"); if ( !window[fnName] ) { @@ -101,8 +111,10 @@ window.addEventListener("DOMContentLoaded", function onSkinDCL() { } el.onclick = window[fnName].bind(el, el); }); +} - // 'data-on-click' calls the global function in the attribute value with no arguments when a click happens. +// 'data-on-click' calls the global function in the attribute value with no arguments when a click happens. +function dataOnClick() { document.querySelectorAll("i[data-on-click], a[data-on-click], button[data-on-click], input[data-on-click]").forEach(function attachOnClick(el) { var fnName = el.getAttribute("data-on-click"); if ( !window[fnName] ) { @@ -114,8 +126,10 @@ window.addEventListener("DOMContentLoaded", function onSkinDCL() { window[fnName](ev); }; }); +} - // 'data-on-click-true' calls the global function in the attribute value with no arguments when a click happens. +// 'data-on-click-true' calls the global function in the attribute value with no arguments when a click happens. +function dataOnClickTrue() { document.querySelectorAll("a[data-on-click-true], button[data-on-click-true], input[data-on-click-true]").forEach(function attachOnClick(el) { var fnName = el.getAttribute("data-on-click-true"); if ( !window[fnName] ) { @@ -126,8 +140,10 @@ window.addEventListener("DOMContentLoaded", function onSkinDCL() { window[fnName](true); }; }); +} - // 'data-on-change-this' calls the global function in the attribute value with the element when a change happens. +// 'data-on-change-this' calls the global function in the attribute value with the element when a change happens. +function dataOnChangeThis() { document.querySelectorAll("select[data-on-change-this], input[data-on-change-this]").forEach(function attachOnChangeThis(el) { var fnName = el.getAttribute("data-on-change-this"); if ( !window[fnName] ) { @@ -136,8 +152,10 @@ window.addEventListener("DOMContentLoaded", function onSkinDCL() { } el.onchange = window[fnName].bind(el, el); }); +} - // 'data-on-change' adds an event listener for the global function in the attribute value when a change happens. +// 'data-on-change' adds an event listener for the global function in the attribute value when a change happens. +function dataOnChange() { document.querySelectorAll("select[data-on-change], input[data-on-change]").forEach(function attachOnChange(el) { var fnName = el.getAttribute("data-on-change"); if ( !window[fnName] ) { @@ -146,8 +164,10 @@ window.addEventListener("DOMContentLoaded", function onSkinDCL() { } el.onchange = window[fnName]; }); +} - // 'data-on-input' adds an event listener for the global function in the attribute value when an input happens. +// 'data-on-input' adds an event listener for the global function in the attribute value when an input happens. +function dataOnInput() { document.querySelectorAll("input[data-on-input]").forEach(function(el) { var fnName = el.getAttribute("data-on-input"); if ( !window[fnName] ) { @@ -156,8 +176,10 @@ window.addEventListener("DOMContentLoaded", function onSkinDCL() { } el.oninput = window[fnName]; }); +} - // 'data-on-input-this' calls the global function in the attribute value with the element when an input happens. +// 'data-on-input-this' calls the global function in the attribute value with the element when an input happens. +function dataOnInputThis() { document.querySelectorAll("input[data-on-input-this]").forEach(function(el) { var fnName = el.getAttribute("data-on-input-this"); if ( !window[fnName] ) { @@ -166,7 +188,7 @@ window.addEventListener("DOMContentLoaded", function onSkinDCL() { } el.oninput = window[fnName].bind(el, el); }); -}); +} function openEvent( eventId, eventFilter ) { var url = '?view=event&eid='+eventId; From 10c0a6617c34b50c8dbd6d9e9898a6056dc9952c Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Wed, 14 Oct 2020 10:39:25 -0400 Subject: [PATCH 152/199] Return Debug to a regular function to match other logging functions. Since we switched to using namespaces we no longer clash with cake_php. --- web/ajax/add_monitors.php | 6 ++--- web/ajax/log.php | 4 ++-- web/ajax/modal.php | 2 +- web/ajax/modals/download.php | 2 +- web/ajax/modals/logout.php | 2 +- web/ajax/status.php | 2 +- web/ajax/stream.php | 20 ++++++++-------- web/api/app/Controller/AppController.php | 2 +- web/api/app/Controller/HostController.php | 8 +++---- web/api/app/Controller/MonitorsController.php | 4 ++-- web/api/app/Model/Event.php | 4 ++-- web/includes/Event.php | 18 +++++++------- web/includes/Filter.php | 6 ++--- web/includes/FilterTerm.php | 10 ++++---- web/includes/Monitor.php | 12 +++++----- web/includes/Storage.php | 2 +- web/includes/actions/events.php | 4 ++-- web/includes/actions/filter.php | 2 +- web/includes/actions/function.php | 2 +- web/includes/actions/monitor.php | 6 ++--- web/includes/actions/shutdown.php | 6 ++--- web/includes/auth.php | 16 ++++++------- web/includes/csrf/csrf-magic.php | 24 +++++++++---------- web/includes/database.php | 6 ++--- web/includes/functions.php | 20 ++++++++-------- web/includes/logger.php | 9 +++---- web/includes/session.php | 4 ++-- web/index.php | 14 +++++------ .../classic/includes/export_functions.php | 4 ++-- web/skins/classic/views/cycle.php | 2 +- web/skins/classic/views/events.php | 12 +++++----- web/skins/classic/views/filter.php | 2 +- web/skins/classic/views/montage.php | 2 +- web/skins/classic/views/onvifprobe.php | 10 ++++---- web/skins/classic/views/options.php | 2 +- .../classic/views/report_event_audit.php | 4 ++-- web/skins/classic/views/timeline.php | 2 +- web/views/archive.php | 2 +- web/views/image.php | 24 +++++++++---------- web/views/view_video.php | 4 ++-- 40 files changed, 144 insertions(+), 143 deletions(-) diff --git a/web/ajax/add_monitors.php b/web/ajax/add_monitors.php index e7048bb4a..952304775 100644 --- a/web/ajax/add_monitors.php +++ b/web/ajax/add_monitors.php @@ -19,11 +19,11 @@ function probe( &$url_bits ) { $cam_list_html = file_get_contents('http://'.$url_bits['host'].':5000/monitoring/'); if ( $cam_list_html ) { - ZM\Logger::Debug("Have content at port 5000/monitoring"); + ZM\Debug("Have content at port 5000/monitoring"); $matches_count = preg_match_all( '/([^<]+)<\/a>/', $cam_list_html, $cam_list ); - ZM\Logger::Debug(print_r($cam_list,true)); + ZM\Debug(print_r($cam_list,true)); } if ( $matches_count ) { for( $index = 0; $index < $matches_count; $index ++ ) { @@ -33,7 +33,7 @@ function probe( &$url_bits ) { if ( ! isset($new_stream['scheme'] ) ) $new_stream['scheme'] = 'http'; $available_streams[] = $new_stream; -ZM\Logger::Debug("Have new stream " . print_r($new_stream,true) ); +ZM\Debug("Have new stream " . print_r($new_stream,true) ); } } else { ZM\Info('No matches'); diff --git a/web/ajax/log.php b/web/ajax/log.php index 16f7ac573..32be2667a 100644 --- a/web/ajax/log.php +++ b/web/ajax/log.php @@ -252,7 +252,7 @@ switch ( $_REQUEST['task'] ) { ZM\Fatal('Can\'t create exports dir at \''.ZM_DIR_EXPORTS.'\''); } $exportPath = ZM_DIR_EXPORTS.'/zm-log-'.$exportKey.$exportExt; - ZM\Logger::Debug("Exporting to $exportPath"); + ZM\Debug("Exporting to $exportPath"); if ( !($exportFP = fopen($exportPath, 'w')) ) ZM\Fatal("Unable to open log export file $exportPath"); $logs = array(); @@ -261,7 +261,7 @@ switch ( $_REQUEST['task'] ) { $log['Server'] = ( $log['ServerId'] and isset($servers_by_Id[$log['ServerId']]) ) ? $servers_by_Id[$log['ServerId']]->Name() : ''; $logs[] = $log; } - ZM\Logger::Debug(count($logs).' lines being exported by '.$sql.implode(',', $values)); + ZM\Debug(count($logs).' lines being exported by '.$sql.implode(',', $values)); switch( $format ) { case 'text' : diff --git a/web/ajax/modal.php b/web/ajax/modal.php index bd96b137f..2794fb0af 100644 --- a/web/ajax/modal.php +++ b/web/ajax/modal.php @@ -8,7 +8,7 @@ if ( empty($_REQUEST['modal']) ) { $modal = validJsStr($_REQUEST['modal']); $data = array(); -ZM\Logger::Debug("Including modals/$modal.php"); +ZM\Debug("Including modals/$modal.php"); # Shouldn't be necessary but at the moment we have last .conf file contents ob_start(); @$result = include('modals/'.$modal.'.php'); diff --git a/web/ajax/modals/download.php b/web/ajax/modals/download.php index 4f19abc0f..7009f8738 100644 --- a/web/ajax/modals/download.php +++ b/web/ajax/modals/download.php @@ -60,7 +60,7 @@ if ( isset($_SESSION['montageReviewFilter']) and !$eids ) { #unset($_SESSION['montageReviewFilter']); #session_write_close(); #} else { -#Logger::Debug("NO montageReviewFilter"); +#Debug("NO montageReviewFilter"); } $exportFormat = ''; diff --git a/web/ajax/modals/logout.php b/web/ajax/modals/logout.php index 655039172..e1c1053c3 100644 --- a/web/ajax/modals/logout.php +++ b/web/ajax/modals/logout.php @@ -69,7 +69,7 @@ while ( $row = $result->fetch(PDO::FETCH_ASSOC) ) { } else { $user = ZM\User::find_one(array('Username'=>$_SESSION['username'])); if ( ! $user ) { - ZM\Logger::Debug('User not found for ' . $_SESSION['username']); + ZM\Debug('User not found for ' . $_SESSION['username']); continue; } $user_cache[$_SESSION['username']] = $user; diff --git a/web/ajax/status.php b/web/ajax/status.php index af754b5f9..54b75b7a3 100644 --- a/web/ajax/status.php +++ b/web/ajax/status.php @@ -336,7 +336,7 @@ function collectData() { } } } - #ZM\Logger::Debug(print_r($data, true)); + #ZM\Debug(print_r($data, true)); return $data; } diff --git a/web/ajax/stream.php b/web/ajax/stream.php index ef29951ee..2c583ba14 100644 --- a/web/ajax/stream.php +++ b/web/ajax/stream.php @@ -31,19 +31,19 @@ if ( sem_acquire($semaphore,1) !== false ) { switch ( $_REQUEST['command'] ) { case CMD_VARPLAY : - ZM\Logger::Debug('Varplaying to '.$_REQUEST['rate']); + ZM\Debug('Varplaying to '.$_REQUEST['rate']); $msg = pack('lcn', MSG_CMD, $_REQUEST['command'], $_REQUEST['rate']+32768); break; case CMD_ZOOMIN : - ZM\Logger::Debug('Zooming to '.$_REQUEST['x'].','.$_REQUEST['y']); + ZM\Debug('Zooming to '.$_REQUEST['x'].','.$_REQUEST['y']); $msg = pack('lcnn', MSG_CMD, $_REQUEST['command'], $_REQUEST['x'], $_REQUEST['y']); break; case CMD_PAN : - ZM\Logger::Debug('Panning to '.$_REQUEST['x'].','.$_REQUEST['y']); + ZM\Debug('Panning to '.$_REQUEST['x'].','.$_REQUEST['y']); $msg = pack('lcnn', MSG_CMD, $_REQUEST['command'], $_REQUEST['x'], $_REQUEST['y']); break; case CMD_SCALE : - ZM\Logger::Debug('Scaling to '.$_REQUEST['scale']); + ZM\Debug('Scaling to '.$_REQUEST['scale']); $msg = pack('lcn', MSG_CMD, $_REQUEST['command'], $_REQUEST['scale']); break; case CMD_SEEK : @@ -53,7 +53,7 @@ if ( sem_acquire($semaphore,1) !== false ) { 1000000*( $_REQUEST['offset']-intval($_REQUEST['offset']))); break; default : - ZM\Logger::Debug('Sending command ' . $_REQUEST['command']); + ZM\Debug('Sending command ' . $_REQUEST['command']); $msg = pack('lc', MSG_CMD, $_REQUEST['command']); break; } @@ -67,7 +67,7 @@ if ( sem_acquire($semaphore,1) !== false ) { // WHY? We will just send another one... // ANSWER: Because otherwise we get a log of errors logged - //ZM\Logger::Debug("$remSockFile does not exist, waiting, current " . (time() - $start_time) . ' seconds' ); + //ZM\Debug("$remSockFile does not exist, waiting, current " . (time() - $start_time) . ' seconds' ); usleep(1000); } @@ -126,16 +126,16 @@ if ( sem_acquire($semaphore,1) !== false ) { $auth_hash = generateAuthHash(ZM_AUTH_HASH_IPS); if ( isset($_REQUEST['auth']) and ($_REQUEST['auth'] != $auth_hash) ) { $data['auth'] = $auth_hash; - ZM\Logger::Debug("including nw auth hash " . $data['auth']); + ZM\Debug("including nw auth hash " . $data['auth']); } else { - ZM\Logger::Debug('Not including nw auth hash becase it hashn\'t changed '.$auth_hash); + ZM\Debug('Not including nw auth hash becase it hashn\'t changed '.$auth_hash); } } ajaxResponse(array('status'=>$data)); break; case MSG_DATA_EVENT : if ( version_compare( phpversion(), '5.6.0', '<') ) { - ZM\Logger::Debug('Using old unpack methods to handle 64bit event id'); + ZM\Debug('Using old unpack methods to handle 64bit event id'); $data = unpack('ltype/ieventlow/ieventhigh/dduration/dprogress/irate/izoom/Cpaused', $msg); $data['event'] = $data['eventhigh'] << 32 | $data['eventlow']; } else { @@ -156,7 +156,7 @@ if ( sem_acquire($semaphore,1) !== false ) { } sem_release($semaphore); } else { - ZM\Logger::Debug('Couldn\'t get semaphore'); + ZM\Debug('Couldn\'t get semaphore'); ajaxResponse(array()); } diff --git a/web/api/app/Controller/AppController.php b/web/api/app/Controller/AppController.php index 737dedacf..ec08bcb22 100644 --- a/web/api/app/Controller/AppController.php +++ b/web/api/app/Controller/AppController.php @@ -105,7 +105,7 @@ class AppController extends Controller { if ( ! is_session_started() ) zm_session_start(); - ZM\Logger::Debug(print_r($_SESSION, true)); + ZM\Debug(print_r($_SESSION, true)); $user = userFromSession(); session_write_close(); } diff --git a/web/api/app/Controller/HostController.php b/web/api/app/Controller/HostController.php index cf6e99b53..b89784818 100644 --- a/web/api/app/Controller/HostController.php +++ b/web/api/app/Controller/HostController.php @@ -50,10 +50,10 @@ class HostController extends AppController { $cred_depr = []; if ( $username && $password ) { - ZM\Logger::Debug('Username and password provided, generating access and refresh tokens'); + ZM\Debug('Username and password provided, generating access and refresh tokens'); $cred = $this->_getCredentials(true, '', $username); // generate refresh } else { - ZM\Logger::Debug('Only generating access token'); + ZM\Debug('Only generating access token'); $cred = $this->_getCredentials(false, $token); // don't generate refresh } @@ -72,7 +72,7 @@ class HostController extends AppController { $login_array['credentials'] = $cred_depr[0]; $login_array['append_password'] = $cred_depr[1]; } else { - ZM\Logger::Debug('Legacy Auth is disabled, not generating auth= credentials'); + ZM\Debug('Legacy Auth is disabled, not generating auth= credentials'); } $login_array['version'] = $ver[0]; @@ -203,7 +203,7 @@ class HostController extends AppController { if ( $mid ) { // Get disk usage for $mid - ZM\Logger::Debug("Executing du -s0 $zm_dir_events/$mid | awk '{print $1}'"); + ZM\Debug("Executing du -s0 $zm_dir_events/$mid | awk '{print $1}'"); $usage = shell_exec("du -s0 $zm_dir_events/$mid | awk '{print $1}'"); } else { $monitors = $this->Monitor->find('all', array( diff --git a/web/api/app/Controller/MonitorsController.php b/web/api/app/Controller/MonitorsController.php index 3818f69d3..fb3b70beb 100644 --- a/web/api/app/Controller/MonitorsController.php +++ b/web/api/app/Controller/MonitorsController.php @@ -178,7 +178,7 @@ class MonitorsController extends AppController { ) ) { if ( !defined('ZM_SERVER_ID')) { - ZM\Logger::Debug("Not defined ZM_SERVER_ID"); + ZM\Debug("Not defined ZM_SERVER_ID"); } $this->daemonControl($this->Monitor->id, 'start'); } @@ -386,7 +386,7 @@ class MonitorsController extends AppController { } $shellcmd = escapeshellcmd("$zm_path_bin/zmdc.pl $command $daemon $args"); - ZM\Logger::Debug("Command $shellcmd"); + ZM\Debug("Command $shellcmd"); $status = exec($shellcmd); $status_text .= $status."\n"; } diff --git a/web/api/app/Model/Event.php b/web/api/app/Model/Event.php index 2c686d79a..22a97f62f 100644 --- a/web/api/app/Model/Event.php +++ b/web/api/app/Model/Event.php @@ -133,10 +133,10 @@ class Event extends AppModel { if ( file_exists($this->Path().'/'.$event['DefaultVideo']) ) { return 1; } else { - ZM\Logger::Debug('File does not exist at ' . $this->Path().'/'.$event['DefaultVideo'] ); + ZM\Debug('File does not exist at ' . $this->Path().'/'.$event['DefaultVideo'] ); } } else { - ZM\Logger::Debug('No DefaultVideo in Event' . $this->Event); + ZM\Debug('No DefaultVideo in Event' . $this->Event); return 0; } } // end function fileExists($event) diff --git a/web/includes/Event.php b/web/includes/Event.php index 23f806354..70eb27d8c 100644 --- a/web/includes/Event.php +++ b/web/includes/Event.php @@ -291,7 +291,7 @@ class Event extends ZM_Object { # The idea here is that we don't really want to use the analysis jpeg as the thumbnail. # The snapshot image will be generated during capturing if ( file_exists($this->Path().'/snapshot.jpg') ) { - Logger::Debug("snapshot exists"); + Debug("snapshot exists"); $frame = null; } else { # Load the frame with the highest score to use as a thumbnail @@ -396,14 +396,14 @@ class Event extends ZM_Object { if ( $frame and !is_array($frame) ) { # Must be an Id - Logger::Debug("Assuming that $frame is an Id"); + Debug("Assuming that $frame is an Id"); $frame = array('FrameId'=>$frame, 'Type'=>'', 'Delta'=>0); } if ( ( !$frame ) and file_exists($eventPath.'/snapshot.jpg') ) { # No frame specified, so look for a snapshot to use $captImage = 'snapshot.jpg'; - Logger::Debug('Frame not specified, using snapshot'); + Debug('Frame not specified, using snapshot'); $frame = array('FrameId'=>'snapshot', 'Type'=>'', 'Delta'=>0); } else { $captImage = sprintf('%0'.ZM_EVENT_IMAGE_DIGITS.'d-analyze.jpg', $frame['FrameId']); @@ -421,11 +421,11 @@ class Event extends ZM_Object { #$command ='ffmpeg -v 0 -i '.$videoPath.' -vf "select=gte(n\\,'.$frame['FrameId'].'),setpts=PTS-STARTPTS" '.$eventPath.'/'.$captImage; $command ='ffmpeg -ss '. $frame['Delta'] .' -i '.$videoPath.' -frames:v 1 '.$eventPath.'/'.$captImage; - Logger::Debug('Running '.$command); + Debug('Running '.$command); $output = array(); $retval = 0; exec($command, $output, $retval); - Logger::Debug("Retval: $retval, output: " . implode("\n", $output)); + Debug("Retval: $retval, output: " . implode("\n", $output)); } else { Error('Can\'t create frame images from video because there is no video file for event '.$Event->Id().' at ' .$Event->Path()); } @@ -529,7 +529,7 @@ class Event extends ZM_Object { return; } } - Logger::Debug("sending command to $url"); + Debug("sending command to $url"); // use key 'http' even if you send the request to https://... $options = array( 'http' => array( @@ -545,7 +545,7 @@ class Event extends ZM_Object { Error("Error restarting zmc using $url"); } $event_data = json_decode($result,true); - Logger::Debug(print_r($event_data['event']['Event'],1)); + Debug(print_r($event_data['event']['Event'],1)); return $event_data['event']['Event']['fileExists']; } catch ( Exception $e ) { Error("Except $e thrown trying to get event data"); @@ -577,7 +577,7 @@ class Event extends ZM_Object { return; } } - Logger::Debug("sending command to $url"); + Debug("sending command to $url"); // use key 'http' even if you send the request to https://... $options = array( 'http' => array( @@ -593,7 +593,7 @@ class Event extends ZM_Object { Error("Error restarting zmc using $url"); } $event_data = json_decode($result,true); - Logger::Debug(print_r($event_data['event']['Event'], 1)); + Debug(print_r($event_data['event']['Event'], 1)); return $event_data['event']['Event']['fileSize']; } catch ( Exception $e ) { Error("Except $e thrown trying to get event data"); diff --git a/web/includes/Filter.php b/web/includes/Filter.php index 34b7196ce..86c72692b 100644 --- a/web/includes/Filter.php +++ b/web/includes/Filter.php @@ -230,7 +230,7 @@ class Filter extends ZM_Object { if ( (!defined('ZM_SERVER_ID')) or (!$Server->Id()) or (ZM_SERVER_ID==$Server->Id()) ) { # Local - Logger::Debug("Controlling filter locally $command for server ".$Server->Id()); + Debug("Controlling filter locally $command for server ".$Server->Id()); daemonControl($command, 'zmfilter.pl', '--filter_id='.$this->{'Id'}.' --daemon'); } else { # Remote case @@ -247,7 +247,7 @@ class Filter extends ZM_Object { } } $url .= '&view=filter&object=filter&action=control&command='.$command.'&Id='.$this->Id().'&ServerId='.$Server->Id(); - Logger::Debug("sending command to $url"); + Debug("sending command to $url"); $data = array(); if ( defined('ZM_ENABLE_CSRF_MAGIC') ) { require_once( 'includes/csrf/csrf-magic.php' ); @@ -278,7 +278,7 @@ class Filter extends ZM_Object { public function execute() { $command = ZM_PATH_BIN.'/zmfilter.pl --filter_id='.escapeshellarg($this->Id()); $result = exec($command, $output, $status); - Logger::Debug("$command status:$status output:".implode("\n", $output)); + Debug("$command status:$status output:".implode("\n", $output)); return $status; } diff --git a/web/includes/FilterTerm.php b/web/includes/FilterTerm.php index 02be63833..1f428fefa 100644 --- a/web/includes/FilterTerm.php +++ b/web/includes/FilterTerm.php @@ -329,14 +329,14 @@ class FilterTerm { public function test($event=null) { if ( !isset($event) ) { # Is a Pre Condition - Logger::Debug("Testing " . $this->attr); + Debug("Testing " . $this->attr); if ( $this->attr == 'DiskPercent' ) { # The logic on this is really ugly. We are going to treat it as an OR foreach ( $this->filter->get_StorageAreas() as $storage ) { $string_to_eval = 'return $storage->disk_usage_percent() '.$this->op.' '.$this->val.';'; try { $ret = eval($string_to_eval); - Logger::Debug("Evalled $string_to_eval = $ret"); + Debug("Evalled $string_to_eval = $ret"); if ( $ret ) return true; } catch ( Throwable $t ) { @@ -348,7 +348,7 @@ class FilterTerm { $string_to_eval = 'return getLoad() '.$this->op.' '.$this->val.';'; try { $ret = eval($string_to_eval); - Logger::Debug("Evaled $string_to_eval = $ret"); + Debug("Evaled $string_to_eval = $ret"); if ( $ret ) return true; } catch ( Throwable $t ) { @@ -374,7 +374,7 @@ class FilterTerm { $string_to_eval = 'return $event->Storage()->disk_usage_percent() '.$this->op.' '.$this->val.';'; try { $ret = eval($string_to_eval); - Logger::Debug("Evalled $string_to_eval = $ret"); + Debug("Evalled $string_to_eval = $ret"); if ( $ret ) return true; } catch ( Throwable $t ) { @@ -385,7 +385,7 @@ class FilterTerm { $string_to_eval = 'return $event->Storage()->disk_usage_blocks() '.$this->op.' '.$this->val.';'; try { $ret = eval($string_to_eval); - Logger::Debug("Evalled $string_to_eval = $ret"); + Debug("Evalled $string_to_eval = $ret"); if ( $ret ) return true; } catch ( Throwable $t ) { diff --git a/web/includes/Monitor.php b/web/includes/Monitor.php index fec452551..d4ed3de99 100644 --- a/web/includes/Monitor.php +++ b/web/includes/Monitor.php @@ -329,7 +329,7 @@ class Monitor extends ZM_Object { return; } } - Logger::Debug('sending command to '.$url); + Debug('sending command to '.$url); $context = stream_context_create(); try { @@ -389,7 +389,7 @@ class Monitor extends ZM_Object { return; } } - Logger::Debug("sending command to $url"); + Debug("sending command to $url"); $context = stream_context_create(); try { @@ -538,7 +538,7 @@ class Monitor extends ZM_Object { if ( $command == 'quit' or $command == 'start' or $command == 'stop' ) { # These are special as we now run zmcontrol as a daemon through zmdc. $status = daemonStatus('zmcontrol.pl', array('--id', $this->{'Id'})); - Logger::Debug("Current status $status"); + Debug("Current status $status"); if ( $status or ( (!defined('ZM_SERVER_ID')) or ( property_exists($this, 'ServerId') and (ZM_SERVER_ID==$this->{'ServerId'}) ) ) ) { daemonControl($command, 'zmcontrol.pl', '--id '.$this->{'Id'}); return; @@ -552,10 +552,10 @@ class Monitor extends ZM_Object { if ( (!defined('ZM_SERVER_ID')) or ( property_exists($this, 'ServerId') and (ZM_SERVER_ID==$this->{'ServerId'}) ) ) { # Local - Logger::Debug('Trying to send options ' . print_r($options, true)); + Debug('Trying to send options ' . print_r($options, true)); $optionString = jsonEncode($options); - Logger::Debug("Trying to send options $optionString"); + Debug("Trying to send options $optionString"); // Either connects to running zmcontrol.pl or runs zmcontrol.pl to send the command. $socket = socket_create(AF_UNIX, SOCK_STREAM, 0); if ( $socket < 0 ) { @@ -589,7 +589,7 @@ class Monitor extends ZM_Object { $url .= '?user='.$_SESSION['username']; } } - Logger::Debug("sending command to $url"); + Debug("sending command to $url"); $context = stream_context_create(); try { diff --git a/web/includes/Storage.php b/web/includes/Storage.php index 2c243d913..71bc021d2 100644 --- a/web/includes/Storage.php +++ b/web/includes/Storage.php @@ -94,7 +94,7 @@ class Storage extends ZM_Object { } $used = $this->disk_used_space(); $usage = round(($used / $total) * 100); - //Logger::Debug("Used $usage = round( ( $used / $total ) * 100 )"); + //Debug("Used $usage = round( ( $used / $total ) * 100 )"); return $usage; } diff --git a/web/includes/actions/events.php b/web/includes/actions/events.php index 41a693ccc..37e747037 100644 --- a/web/includes/actions/events.php +++ b/web/includes/actions/events.php @@ -32,7 +32,7 @@ if ( !canEdit('Events') ) { if ( $action == 'archive' ) { $dbConn->beginTransaction(); $eids = getAffectedIds('eids'); - ZM\Logger::Debug("E IDS" . print_r($eids, true)); + ZM\Debug("E IDS" . print_r($eids, true)); foreach ( $eids as $markEid ) { dbQuery('UPDATE Events SET Archived=? WHERE Id=?', array(1, $markEid)); } @@ -41,7 +41,7 @@ if ( $action == 'archive' ) { } else if ( $action == 'unarchive' ) { $dbConn->beginTransaction(); $eids = getAffectedIds('eids'); - ZM\Logger::Debug("E IDS" . print_r($eids, true)); + ZM\Debug("E IDS" . print_r($eids, true)); foreach ( $eids as $markEid ) { dbQuery('UPDATE Events SET Archived=? WHERE Id=?', array(0, $markEid)); } diff --git a/web/includes/actions/filter.php b/web/includes/actions/filter.php index 2725c70fc..63f4af94e 100644 --- a/web/includes/actions/filter.php +++ b/web/includes/actions/filter.php @@ -64,7 +64,7 @@ if ( isset($_REQUEST['object']) and ( $_REQUEST['object'] == 'filter' ) ) { $_REQUEST['filter']['Background'] = empty($_REQUEST['filter']['Background']) ? 0 : 1; $_REQUEST['filter']['Concurrent'] = empty($_REQUEST['filter']['Concurrent']) ? 0 : 1; $changes = $filter->changes($_REQUEST['filter']); - ZM\Logger::Debug('Changes: ' . print_r($changes,true)); + ZM\Debug('Changes: ' . print_r($changes,true)); if ( $_REQUEST['Id'] and ( $action == 'Save' ) ) { if ( $filter->Background() ) diff --git a/web/includes/actions/function.php b/web/includes/actions/function.php index eb3dc36be..d9c3092ce 100644 --- a/web/includes/actions/function.php +++ b/web/includes/actions/function.php @@ -52,7 +52,7 @@ if ( $action == 'function' ) { $monitor->zmaControl('start'); } } else { - ZM\Logger::Debug('No change to function, not doing anything.'); + ZM\Debug('No change to function, not doing anything.'); } } // end if action $redirect = '?view=console'; diff --git a/web/includes/actions/monitor.php b/web/includes/actions/monitor.php index b1a7d4726..140957046 100644 --- a/web/includes/actions/monitor.php +++ b/web/includes/actions/monitor.php @@ -75,10 +75,10 @@ if ( $action == 'save' ) { if ( $_REQUEST['newMonitor']['ServerId'] == 'auto' ) { $_REQUEST['newMonitor']['ServerId'] = dbFetchOne( 'SELECT Id FROM Servers WHERE Status=\'Running\' ORDER BY FreeMem DESC, CpuLoad ASC LIMIT 1', 'Id'); - ZM\Logger::Debug('Auto selecting server: Got ' . $_REQUEST['newMonitor']['ServerId']); + ZM\Debug('Auto selecting server: Got ' . $_REQUEST['newMonitor']['ServerId']); if ( ( !$_REQUEST['newMonitor'] ) and defined('ZM_SERVER_ID') ) { $_REQUEST['newMonitor']['ServerId'] = ZM_SERVER_ID; - ZM\Logger::Debug('Auto selecting server to ' . ZM_SERVER_ID); + ZM\Debug('Auto selecting server to ' . ZM_SERVER_ID); } } @@ -235,7 +235,7 @@ if ( $action == 'save' ) { $restart = true; } else { - ZM\Logger::Debug('No action due to no changes to Monitor'); + ZM\Debug('No action due to no changes to Monitor'); } # end if count(changes) if ( !$mid ) { diff --git a/web/includes/actions/shutdown.php b/web/includes/actions/shutdown.php index 4d7a4ee78..e3c89600c 100644 --- a/web/includes/actions/shutdown.php +++ b/web/includes/actions/shutdown.php @@ -29,13 +29,13 @@ if ( $action ) { $rc = 0; exec('sudo -n '.ZM_PATH_SHUTDOWN." -P $when 2>&1", $output, $rc); #exec('sudo -n /bin/systemctl poweroff -i 2>&1', $output, $rc); - ZM\Logger::Debug("Shutdown output $rc " . implode("\n",$output)); - #ZM\Logger::Debug("Shutdown output " . shell_exec('/bin/systemctl poweroff -i 2>&1')); + ZM\Debug("Shutdown output $rc " . implode("\n",$output)); + #ZM\Debug("Shutdown output " . shell_exec('/bin/systemctl poweroff -i 2>&1')); } else if ( $action == 'restart' ) { $output = array(); exec('sudo -n '.ZM_PATH_SHUTDOWN." -r $when 2>&1", $output); #exec('sudo -n /bin/systemctl reboot -i 2>&1', $output); - ZM\Logger::Debug("Shutdown output " . implode("\n",$output)); + ZM\Debug("Shutdown output " . implode("\n",$output)); } else if ( $action == 'cancel' ) { $output = array(); exec('sudo '.ZM_PATH_SHUTDOWN.' -c 2>&1', $output); diff --git a/web/includes/auth.php b/web/includes/auth.php index e49f5876b..f7cf7ec82 100644 --- a/web/includes/auth.php +++ b/web/includes/auth.php @@ -72,12 +72,12 @@ function validateUser($username='', $password='') { // We assume we don't need to support mysql < 4.1 // Starting MY SQL 4.1, mysql concats a '*' in front of its password hash // https://blog.pythian.com/hashing-algorithm-in-mysql-password-2/ - ZM\Logger::Debug('Saved password is using MYSQL password function'); + ZM\Debug('Saved password is using MYSQL password function'); $input_password_hash = '*'.strtoupper(sha1(sha1($password, true))); $password_correct = ($user['Password'] == $input_password_hash); break; case 'bcrypt' : - ZM\Logger::Debug('bcrypt signature found, assumed bcrypt password'); + ZM\Debug('bcrypt signature found, assumed bcrypt password'); $password_correct = password_verify($password, $user['Password']); break; case 'mysql+bcrypt' : @@ -85,10 +85,10 @@ function validateUser($username='', $password='') { // this is done so that we don't spend cycles doing two bcrypt password_verify calls // for every wrong password entered. This will only be invoked for passwords zmupdate.pl has // overlay hashed - ZM\Logger::Debug("Detected bcrypt overlay hashing for $username"); + ZM\Debug("Detected bcrypt overlay hashing for $username"); $bcrypt_hash = substr($user['Password'], 4); $mysql_encoded_password = '*'.strtoupper(sha1(sha1($password, true))); - ZM\Logger::Debug("Comparing password $mysql_encoded_password to bcrypt hash: $bcrypt_hash"); + ZM\Debug("Comparing password $mysql_encoded_password to bcrypt hash: $bcrypt_hash"); $password_correct = password_verify($mysql_encoded_password, $bcrypt_hash); break; default: @@ -130,7 +130,7 @@ function validateToken($token, $allowed_token_type='access') { return array(false, 'Incorrect token type'); } } else { - ZM\Logger::Debug('Not comparing token types as [any] was passed'); + ZM\Debug('Not comparing token types as [any] was passed'); } $username = $jwt_payload['user']; @@ -210,7 +210,7 @@ function generateAuthHash($useRemoteAddr, $force=false) { } else { $authKey = ZM_AUTH_HASH_SECRET.$user['Username'].$user['Password'].$local_time[2].$local_time[3].$local_time[4].$local_time[5]; } - #ZM\Logger::Debug("Generated using hour:".$local_time[2] . ' mday:' . $local_time[3] . ' month:'.$local_time[4] . ' year: ' . $local_time[5] ); + #ZM\Debug("Generated using hour:".$local_time[2] . ' mday:' . $local_time[3] . ' month:'.$local_time[4] . ' year: ' . $local_time[5] ); $auth = md5($authKey); $_SESSION['AuthHash'.$_SESSION['remoteAddr']] = $auth; $_SESSION['AuthHashGeneratedAt'] = $time; @@ -248,14 +248,14 @@ function userFromSession() { if ( isset($_SESSION['AuthHash'.$_SESSION['remoteAddr']]) ) $user = getAuthUser($_SESSION['AuthHash'.$_SESSION['remoteAddr']]); else - ZM\Logger::Debug("No auth hash in session, there should have been"); + ZM\Debug("No auth hash in session, there should have been"); } else { # Need to refresh permissions and validate that the user still exists $sql = 'SELECT * FROM Users WHERE Enabled=1 AND Username=?'; $user = dbFetchOne($sql, NULL, array($_SESSION['username'])); } } else { - ZM\Logger::Debug('No username in session'); + ZM\Debug('No username in session'); } return $user; } diff --git a/web/includes/csrf/csrf-magic.php b/web/includes/csrf/csrf-magic.php index edb04002a..b102c565a 100644 --- a/web/includes/csrf/csrf-magic.php +++ b/web/includes/csrf/csrf-magic.php @@ -193,21 +193,21 @@ function csrf_check($fatal = true) { $tokens = ''; do { if (!isset($_POST[$name])) { -#Logger::Debug("POST[$name] is not set"); +#Debug("POST[$name] is not set"); break; #} else { -#Logger::Debug("POST[$name] is set as " . $_POST[$name] ); +#Debug("POST[$name] is set as " . $_POST[$name] ); } // we don't regenerate a token and check it because some token creation // schemes are volatile. $tokens = $_POST[$name]; if (!csrf_check_tokens($tokens)) { -#Logger::Debug("Failed checking tokens"); +#Debug("Failed checking tokens"); break; #} else { -#Logger::Debug("Token passed"); +#Debug("Token passed"); } $ok = true; } while (false); @@ -296,7 +296,7 @@ function csrf_callback($tokens) { // Don't make it too easy for users to inflict a CSRF attack on themselves. echo "

Only try again if you weren't sent to this page by someone as this is potentially a sign of an attack.

"; echo "
$data
"; - ZM\Logger::Debug("Failed csrf check"); + ZM\Debug("Failed csrf check"); } echo "

Debug: $tokens

"; @@ -318,27 +318,27 @@ function csrf_check_tokens($tokens) { * Checks if a token is valid. */ function csrf_check_token($token) { -#Logger::Debug("Checking CSRF token $token"); +#Debug("Checking CSRF token $token"); if (strpos($token, ':') === false) { -#Logger::Debug("Checking CSRF token $token bad because no :"); +#Debug("Checking CSRF token $token bad because no :"); return false; } list($type, $value) = explode(':', $token, 2); if (strpos($value, ',') === false) { -#Logger::Debug("Checking CSRF token $token bad because no ,"); +#Debug("Checking CSRF token $token bad because no ,"); return false; } list($x, $time) = explode(',', $token, 2); if ($GLOBALS['csrf']['expires']) { if (time() > $time + $GLOBALS['csrf']['expires']) { -#Logger::Debug("Checking CSRF token $token bad because expired"); +#Debug("Checking CSRF token $token bad because expired"); return false; } } switch ($type) { case 'sid': { - #Logger::Debug("Checking sid: $value === " . csrf_hash(session_id(), $time) ); + #Debug("Checking sid: $value === " . csrf_hash(session_id(), $time) ); return $value === csrf_hash(session_id(), $time); } case 'cookie': @@ -348,10 +348,10 @@ return false; return $value === csrf_hash($_COOKIE[$n], $time); case 'key': if (!$GLOBALS['csrf']['key']) { - Logger::Debug("Checking key: no key set" ); + Debug("Checking key: no key set" ); return false; } - #Logger::Debug("Checking sid: $value === " . csrf_hash($GLOBALS['csrf']['key'], $time) ); + #Debug("Checking sid: $value === " . csrf_hash($GLOBALS['csrf']['key'], $time) ); return $value === csrf_hash($GLOBALS['csrf']['key'], $time); // We could disable these 'weaker' checks if 'key' was set, but // that doesn't make me feel good then about the cookie-based diff --git a/web/includes/database.php b/web/includes/database.php index 8e621e2f9..3eea672a6 100644 --- a/web/includes/database.php +++ b/web/includes/database.php @@ -105,7 +105,7 @@ function dbLog($sql, $update=false) { global $dbLogLevel; $noExecute = $update && ($dbLogLevel >= DB_LOG_DEBUG); if ( $dbLogLevel > DB_LOG_OFF ) - ZM\Logger::Debug( "SQL-LOG: $sql".($noExecute?' (not executed)':'') ); + ZM\Debug( "SQL-LOG: $sql".($noExecute?' (not executed)':'') ); return( $noExecute ); } @@ -146,7 +146,7 @@ function dbQuery($sql, $params=NULL) { } } else { if ( defined('ZM_DB_DEBUG') ) { - ZM\Logger::Debug("SQL: $sql values:" . ($params?implode(',',$params):'')); + ZM\Debug("SQL: $sql values:" . ($params?implode(',',$params):'')); } $result = $dbConn->query($sql); if ( ! $result ) { @@ -155,7 +155,7 @@ function dbQuery($sql, $params=NULL) { } } if ( defined('ZM_DB_DEBUG') ) { - ZM\Logger::Debug('SQL: '.$sql.' '.($params?implode(',',$params):'').' rows: '.$result->rowCount()); + ZM\Debug('SQL: '.$sql.' '.($params?implode(',',$params):'').' rows: '.$result->rowCount()); } } catch(PDOException $e) { ZM\Error("SQL-ERR '".$e->getMessage()."', statement was '".$sql."' params:" . ($params?implode(',',$params):'')); diff --git a/web/includes/functions.php b/web/includes/functions.php index 32c5c59d3..fe17f5287 100644 --- a/web/includes/functions.php +++ b/web/includes/functions.php @@ -104,7 +104,7 @@ function CORSHeaders() { # Only need CORSHeaders in the event that there are multiple servers in use. # ICON: Might not be true. multi-port? if ( ZM_MIN_STREAMING_PORT ) { - ZM\Logger::Debug('Setting default Access-Control-Allow-Origin from ' . $_SERVER['HTTP_ORIGIN']); + ZM\Debug('Setting default Access-Control-Allow-Origin from ' . $_SERVER['HTTP_ORIGIN']); header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']); header('Access-Control-Allow-Headers: x-requested-with,x-request'); } @@ -117,7 +117,7 @@ function CORSHeaders() { preg_match('/^(https?:\/\/)?'.preg_quote($Server->Name(),'/').'/i', $_SERVER['HTTP_ORIGIN']) ) { $valid = true; - ZM\Logger::Debug('Setting Access-Control-Allow-Origin from '.$_SERVER['HTTP_ORIGIN']); + ZM\Debug('Setting Access-Control-Allow-Origin from '.$_SERVER['HTTP_ORIGIN']); header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']); header('Access-Control-Allow-Headers: x-requested-with,x-request'); break; @@ -392,7 +392,7 @@ function getEventDefaultVideoPath($event) { } function deletePath( $path ) { - ZM\Logger::Debug('Deleting '.$path); + ZM\Debug('Deleting '.$path); if ( is_dir($path) ) { system(escapeshellcmd('rm -rf '.$path)); } else if ( file_exists($path) ) { @@ -791,7 +791,7 @@ function daemonControl($command, $daemon=false, $args=false) { } $string = escapeshellcmd($string); #$string .= ' 2>/dev/null >&- <&- >/dev/null'; - ZM\Logger::Debug('daemonControl '.$string); + ZM\Debug('daemonControl '.$string); exec($string); } @@ -932,7 +932,7 @@ function createVideo($event, $format, $rate, $scale, $overwrite=false) { $command .= ' -o'; $command = escapeshellcmd($command); $result = exec($command, $output, $status); - ZM\Logger::Debug("generating Video $command: result($result outptu:(".implode("\n", $output )." status($status"); + ZM\Debug("generating Video $command: result($result outptu:(".implode("\n", $output )." status($status"); return $status ? '' : rtrim($result); } @@ -1635,17 +1635,17 @@ function coordsToPoints($coords) { function limitPoints(&$points, $min_x, $min_y, $max_x, $max_y) { foreach ( $points as &$point ) { if ( $point['x'] < $min_x ) { - ZM\Logger::Debug('Limiting point x'.$point['x'].' to min_x '.$min_x); + ZM\Debug('Limiting point x'.$point['x'].' to min_x '.$min_x); $point['x'] = $min_x; } else if ( $point['x'] > $max_x ) { - ZM\Logger::Debug('Limiting point x'.$point['x'].' to max_x '.$max_x); + ZM\Debug('Limiting point x'.$point['x'].' to max_x '.$max_x); $point['x'] = $max_x; } if ( $point['y'] < $min_y ) { - ZM\Logger::Debug('Limiting point y'.$point['y'].' to min_y '.$min_y); + ZM\Debug('Limiting point y'.$point['y'].' to min_y '.$min_y); $point['y'] = $min_y; } else if ( $point['y'] > $max_y ) { - ZM\Logger::Debug('Limiting point y'.$point['y'].' to max_y '.$max_y); + ZM\Debug('Limiting point y'.$point['y'].' to max_y '.$max_y); $point['y'] = $max_y; } } // end foreach point @@ -2170,7 +2170,7 @@ function check_timezone() { 'TIME_FORMAT(TIMEDIFF(NOW(), UTC_TIMESTAMP),\'%H%i\')' )); - #Logger::Debug("System timezone offset determine to be: $sys_tzoffset,\x20 + #Debug("System timezone offset determine to be: $sys_tzoffset,\x20 #PHP timezone offset determine to be: $php_tzoffset,\x20 #Mysql timezone offset determine to be: $mysql_tzoffset #"); diff --git a/web/includes/logger.php b/web/includes/logger.php index b616f7458..fb7d58f93 100644 --- a/web/includes/logger.php +++ b/web/includes/logger.php @@ -158,7 +158,7 @@ class Logger { $this->initialised = true; - //Logger::Debug( "LogOpts: level=".self::$codes[$this->level]."/".self::$codes[$this->effectiveLevel].", screen=".self::$codes[$this->termLevel].", database=".self::$codes[$this->databaseLevel].", logfile=".self::$codes[$this->fileLevel]."->".$this->logFile.", weblog=".self::$codes[$this->weblogLevel].", syslog=".self::$codes[$this->syslogLevel] ); + //Debug( "LogOpts: level=".self::$codes[$this->level]."/".self::$codes[$this->effectiveLevel].", screen=".self::$codes[$this->termLevel].", database=".self::$codes[$this->databaseLevel].", logfile=".self::$codes[$this->fileLevel]."->".$this->logFile.", weblog=".self::$codes[$this->weblogLevel].", syslog=".self::$codes[$this->syslogLevel] ); } private function terminate() { @@ -199,9 +199,6 @@ class Logger { return self::$instance; } - public static function Debug( $string ) { - Logger::fetch()->logPrint( Logger::DEBUG, $string ); - } public function id( $id=NULL ) { if ( isset($id) && $this->id != $id ) { @@ -459,6 +456,10 @@ function Dump( &$var, $label='VAR' ) { Logger::fetch()->logPrint( Logger::DEBUG, ob_get_clean() ); } +function Debug( $string ) { + Logger::fetch()->logPrint( Logger::DEBUG, $string ); +} + function Info( $string ) { Logger::fetch()->logPrint( Logger::INFO, $string ); } diff --git a/web/includes/session.php b/web/includes/session.php index 1873923c6..2358567ba 100644 --- a/web/includes/session.php +++ b/web/includes/session.php @@ -25,7 +25,7 @@ function zm_session_start() { } ini_set('session.name', 'ZMSESSID'); - ZM\Logger::Debug('Setting cookie parameters to '.print_r($currentCookieParams, true)); + ZM\Debug('Setting cookie parameters to '.print_r($currentCookieParams, true)); } session_start(); $_SESSION['remoteAddr'] = $_SERVER['REMOTE_ADDR']; // To help prevent session hijacking @@ -37,7 +37,7 @@ function zm_session_start() { session_start(); } else if ( !empty($_SESSION['generated_at']) ) { if ( $_SESSION['generated_at']<($now-(ZM_COOKIE_LIFETIME/2)) ) { - ZM\Logger::Debug('Regenerating session because generated_at ' . $_SESSION['generated_at'] . ' < ' . $now . '-'.ZM_COOKIE_LIFETIME.'/2 = '.($now-ZM_COOKIE_LIFETIME/2)); + ZM\Debug('Regenerating session because generated_at ' . $_SESSION['generated_at'] . ' < ' . $now . '-'.ZM_COOKIE_LIFETIME.'/2 = '.($now-ZM_COOKIE_LIFETIME/2)); zm_session_regenerate_id(); } } diff --git a/web/index.php b/web/index.php index 46140a1a3..52152d7fe 100644 --- a/web/index.php +++ b/web/index.php @@ -56,7 +56,7 @@ require_once('includes/Monitor.php'); if ( 0 and ZM\Logger::fetch()->debugOn() ) { ob_start(); phpinfo(INFO_VARIABLES); - ZM\Logger::Debug(ob_get_contents()); + ZM\Debug(ob_get_contents()); ob_end_clean(); } @@ -82,7 +82,7 @@ define('ZM_BASE_URL', ''); require_once('includes/functions.php'); if ( $_SERVER['REQUEST_METHOD'] == 'OPTIONS' ) { - ZM\Logger::Debug('OPTIONS Method, only doing CORS'); + ZM\Debug('OPTIONS Method, only doing CORS'); # Add Cross domain access headers CORSHeaders(); return; @@ -221,7 +221,7 @@ if ( (!$view and !$request) or ($view == 'console') ) { check_timezone(); } -ZM\Logger::Debug("View: $view Request: $request Action: $action User: " . ( isset($user) ? $user['Username'] : 'none' )); +ZM\Debug("View: $view Request: $request Action: $action User: " . ( isset($user) ? $user['Username'] : 'none' )); if ( ZM_ENABLE_CSRF_MAGIC && ( $action != 'login' ) && @@ -232,14 +232,14 @@ if ( ( $view != 'archive' ) // returns data ) { require_once('includes/csrf/csrf-magic.php'); - #ZM\Logger::Debug("Calling csrf_check with the following values: \$request = \"$request\", \$view = \"$view\", \$action = \"$action\""); + #ZM\Debug("Calling csrf_check with the following values: \$request = \"$request\", \$view = \"$view\", \$action = \"$action\""); csrf_check(); } # Need to include actions because it does auth if ( $action and !$request ) { if ( file_exists('includes/actions/'.$view.'.php') ) { - ZM\Logger::Debug("Including includes/actions/$view.php"); + ZM\Debug("Including includes/actions/$view.php"); require_once('includes/actions/'.$view.'.php'); } else { ZM\Warning("No includes/actions/$view.php for action $action"); @@ -254,7 +254,7 @@ if ( ZM_OPT_USE_AUTH and (!isset($user)) and ($view != 'login') and ($view != 'n header('HTTP/1.1 401 Unauthorized'); exit; } - ZM\Logger::Debug('Redirecting to login'); + ZM\Debug('Redirecting to login'); $view = 'none'; $redirect = ZM_BASE_URL.$_SERVER['PHP_SELF'].'?view=login'; if ( ! $request ) { @@ -271,7 +271,7 @@ if ( ZM_OPT_USE_AUTH and (!isset($user)) and ($view != 'login') and ($view != 'n if ( $redirect ) { - ZM\Logger::Debug("Redirecting to $redirect"); + ZM\Debug("Redirecting to $redirect"); header('Location: '.$redirect); return; } diff --git a/web/skins/classic/includes/export_functions.php b/web/skins/classic/includes/export_functions.php index 052277434..27a346ba4 100644 --- a/web/skins/classic/includes/export_functions.php +++ b/web/skins/classic/includes/export_functions.php @@ -897,7 +897,7 @@ function exportEvents( ZM\Error("Can't create exports dir at '$export_dir'"); return false; } - ZM\Logger::Debug("Successfully created dir '$export_dir'"); + ZM\Debug("Successfully created dir '$export_dir'"); chmod($export_dir, 0700); if ( !chdir($export_dir) ) { ZM\Error("Can't chdir to $export_dir"); @@ -925,7 +925,7 @@ function exportEvents( #continue; $cmd = 'cp -as '.$event->Path().'/'.$file.' '.$export_dir.'/'.$event->Id().'/'.$file. ' 2>&1'; exec($cmd, $output, $return); - ZM\Logger::Debug($cmd.' return code: '.$return.' output: '.print_r($output,true)); + ZM\Debug($cmd.' return code: '.$return.' output: '.print_r($output,true)); } # end foreach event_exportFile } # end foreach event diff --git a/web/skins/classic/views/cycle.php b/web/skins/classic/views/cycle.php index 7e974cd4e..ba97d341c 100644 --- a/web/skins/classic/views/cycle.php +++ b/web/skins/classic/views/cycle.php @@ -122,7 +122,7 @@ if ( isset($_COOKIE['zmCycleHeight']) and $_COOKIE['zmCycleHeight'] ) { session_write_close(); -ZM\Logger::Debug(print_r($options,true)); +ZM\Debug(print_r($options,true)); noCacheHeaders(); xhtmlHeaders(__FILE__, translate('CycleWatch')); diff --git a/web/skins/classic/views/events.php b/web/skins/classic/views/events.php index 7053d0425..3918e9359 100644 --- a/web/skins/classic/views/events.php +++ b/web/skins/classic/views/events.php @@ -42,7 +42,7 @@ if ( isset($_REQUEST['filter'])) { parseSort(); $filterQuery = $filter->querystring(); -ZM\Logger::Debug('Filter '.print_r($filter, true)); +ZM\Debug('Filter '.print_r($filter, true)); if ( $filter->sql() ) { $eventsSql .= ' AND ('.$filter->sql().')'; @@ -58,14 +58,14 @@ $limit = isset($_REQUEST['limit']) ? validInt($_REQUEST['limit']) : $filter['lim if ( $_POST ) { // I think this is basically so that a refresh doesn't repost - ZM\Logger::Debug('Redirecting to ' . $_SERVER['REQUEST_URI']); + ZM\Debug('Redirecting to ' . $_SERVER['REQUEST_URI']); header('Location: ?view=' . $view.htmlspecialchars_decode($filterQuery).htmlspecialchars_decode($sortQuery).$limitQuery.'&page='.$page); exit(); } $failed = !$filter->test_pre_sql_conditions(); if ( $failed ) { - ZM\Logger::Debug('Pre conditions failed, not doing sql'); + ZM\Debug('Pre conditions failed, not doing sql'); } $results = $failed ? null : dbQuery($eventsSql); @@ -75,13 +75,13 @@ if ( ! $results ) { global $error_message; $error_message = dbError($eventsSql); } -ZM\Logger::Debug("Pre conditions succeeded sql return $nEvents events"); +ZM\Debug("Pre conditions succeeded sql return $nEvents events"); if ( !empty($limit) && ($nEvents > $limit) ) { $nEvents = $limit; } $pages = (int)ceil($nEvents/ZM_WEB_EVENTS_PER_PAGE); -#Logger::Debug("Page $page Limit $limit #vents: $nEvents pages: $pages "); +#Debug("Page $page Limit $limit #vents: $nEvents pages: $pages "); if ( !empty($page) ) { if ( $page < 0 ) $page = 1; @@ -212,7 +212,7 @@ if ( $results ) { if ( $limit and (count($events) >= $limit) ) { break; } - ZM\Logger::Debug("Have " . count($events) . " events, limit $limit"); + ZM\Debug("Have " . count($events) . " events, limit $limit"); } foreach ( $events as $event ) { diff --git a/web/skins/classic/views/filter.php b/web/skins/classic/views/filter.php index 28231453a..c19e06ef7 100644 --- a/web/skins/classic/views/filter.php +++ b/web/skins/classic/views/filter.php @@ -61,7 +61,7 @@ if ( !$filter ) { $filter->set($_REQUEST['filter']); } } else { - ZM\Logger::Debug('filter: ' . print_r($filter,true)); + ZM\Debug('filter: ' . print_r($filter,true)); } $conjunctionTypes = ZM\getFilterQueryConjunctionTypes(); diff --git a/web/skins/classic/views/montage.php b/web/skins/classic/views/montage.php index ee6b1dc24..9e53dc23e 100644 --- a/web/skins/classic/views/montage.php +++ b/web/skins/classic/views/montage.php @@ -79,7 +79,7 @@ if ( $layout_id and is_numeric($layout_id) and isset($layoutsById[$layout_id]) ) $Layout = $layoutsById[$layout_id]; $Positions = json_decode($Layout->Positions(), true); } else { - ZM\Logger::Debug('Layout not found'); + ZM\Debug('Layout not found'); } if ( $Layout and ( $Layout->Name() != 'Freeform' ) ) { // Use layout instead of other options diff --git a/web/skins/classic/views/onvifprobe.php b/web/skins/classic/views/onvifprobe.php index 900313e46..96e930fba 100644 --- a/web/skins/classic/views/onvifprobe.php +++ b/web/skins/classic/views/onvifprobe.php @@ -42,7 +42,7 @@ function execONVIF($cmd) { $shell_command" ); } else { - ZM\Logger::Debug('Results from probe: '.implode('
', $output)); + ZM\Debug('Results from probe: '.implode('
', $output)); } return $output; @@ -80,7 +80,7 @@ function probeCameras($localIp) { $camera['monitor']['Notes'] .= $tokens[1].'='.$tokens[2]."\n"; // $camera['location'] = $tokens[2]; } else { - ZM\Logger::Debug('Unknown token '.$tokens[1].' = '.$tokens[2]); + ZM\Debug('Unknown token '.$tokens[1].' = '.$tokens[2]); } } } // end foreach token @@ -119,7 +119,7 @@ function probeProfiles($device_ep, $soapversion, $username, $password) { ); $profiles[] = $profile; } else { - ZM\Logger::Debug("Line did not match preg: $line"); + ZM\Debug("Line did not match preg: $line"); } } // end foreach line } // end if results from execONVIF @@ -187,7 +187,7 @@ if ( !isset($_REQUEST['step']) || ($_REQUEST['step'] == '1') ) { if ( $matches[1] != 'lo' ) { $interfaces[$matches[1]] = $matches[1]; } else { - ZM\Logger::Debug("No match for $line"); + ZM\Debug("No match for $line"); } } } @@ -247,7 +247,7 @@ if ( !isset($_REQUEST['step']) || ($_REQUEST['step'] == '1') ) { #empty($_REQUEST['password']) ) $probe = json_decode(base64_decode($_REQUEST['probe'])); - ZM\Logger::Debug(print_r($probe, true)); + ZM\Debug(print_r($probe, true)); foreach ( $probe as $name=>$value ) { if ( isset($value) ) { $monitor[$name] = $value; diff --git a/web/skins/classic/views/options.php b/web/skins/classic/views/options.php index 147d250e1..cc8b0b568 100644 --- a/web/skins/classic/views/options.php +++ b/web/skins/classic/views/options.php @@ -156,7 +156,7 @@ foreach ( array_map('basename', glob('skins/'.$skin.'/css/*', GLOB_ONLYDIR)) as $userMonitors[] = $monitors[$monitorId]['Name']; } } - ZM\Logger::Debug("monitors: ".$user_row['Username'] . ' ' . $user_row['MonitorIds']. ' :' . print_r($userMonitors, true)); + ZM\Debug("monitors: ".$user_row['Username'] . ' ' . $user_row['MonitorIds']. ' :' . print_r($userMonitors, true)); ?> diff --git a/web/skins/classic/views/report_event_audit.php b/web/skins/classic/views/report_event_audit.php index 6cafaf67e..46c4dc90d 100644 --- a/web/skins/classic/views/report_event_audit.php +++ b/web/skins/classic/views/report_event_audit.php @@ -62,7 +62,7 @@ if ( count($selected_monitor_ids) ) { } parseFilter($filter); $filterQuery = $filter['query']; -ZM\Logger::Debug($filterQuery); +ZM\Debug($filterQuery); $eventsSql = 'SELECT *, UNIX_TIMESTAMP(E.StartTime) AS StartTimeSecs, @@ -94,7 +94,7 @@ while ( $event = $result->fetch(PDO::FETCH_ASSOC) ) { if ( count($EventsByMonitor[$event['MonitorId']]['Events']) ) { $last_event = end($EventsByMonitor[$event['MonitorId']]['Events']); -#Logger::Debug(print_r($last_event,true)); +#Debug(print_r($last_event,true)); $gap = $last_event->EndTimeSecs() - $event['StartTimeSecs']; if ( $gap < $EventsByMonitor[$event['MonitorId']]['MinGap'] ) diff --git a/web/skins/classic/views/timeline.php b/web/skins/classic/views/timeline.php index d0d17d721..264c8128e 100644 --- a/web/skins/classic/views/timeline.php +++ b/web/skins/classic/views/timeline.php @@ -500,7 +500,7 @@ for ( $i = 0; $i < $chart['graph']['width']; $i++ ) { } # end foreach MonitorId } # end foreach x -//ZM\Logger::Debug(print_r( $monEventSlots,true )); +//ZM\Debug(print_r( $monEventSlots,true )); //print_r( $monFrameSlots ); //print_r( $chart ); diff --git a/web/views/archive.php b/web/views/archive.php index 352849ee9..6bd11fbd3 100644 --- a/web/views/archive.php +++ b/web/views/archive.php @@ -55,7 +55,7 @@ if ( !$mimetype ) { $connkey = isset($_REQUEST['connkey'])?$_REQUEST['connkey']:''; $filename = "zmExport_$connkey.$file_ext"; $filename_path = ZM_DIR_EXPORTS.'/'.$filename; -ZM\Logger::Debug("downloading archive from $filename_path"); +ZM\Debug("downloading archive from $filename_path"); if ( is_readable($filename_path) ) { while (ob_get_level()) { ob_end_clean(); diff --git a/web/views/image.php b/web/views/image.php index ff26682c7..4d4788094 100644 --- a/web/views/image.php +++ b/web/views/image.php @@ -87,11 +87,11 @@ if ( empty($_REQUEST['path']) ) { if (file_exists($path_anim_gif)) { // we found the animation gif file $media_type = 'image/gif'; - ZM\Logger::Debug("Animation file found at $path"); + ZM\Debug("Animation file found at $path"); $path = $path_anim_gif; } else if (file_exists($path_image)) { // animation not found, but image found - ZM\Logger::Debug("Image file found at $path"); + ZM\Debug("Image file found at $path"); $path = $path_image; } else { // neither animation nor image found @@ -206,14 +206,14 @@ if ( empty($_REQUEST['path']) ) { $percentage = ($Frame->FrameId() - $previousBulkFrame['FrameId']) / ($nextBulkFrame['FrameId'] - $previousBulkFrame['FrameId']); $Frame->Delta($previousBulkFrame['Delta'] + floor( 100* ( $nextBulkFrame['Delta'] - $previousBulkFrame['Delta'] ) * $percentage )/100); - ZM\Logger::Debug("Got virtual frame from Bulk Frames previous delta: " . $previousBulkFrame['Delta'] . " + nextdelta:" . $nextBulkFrame['Delta'] . ' - ' . $previousBulkFrame['Delta'] . ' * ' . $percentage ); + ZM\Debug("Got virtual frame from Bulk Frames previous delta: " . $previousBulkFrame['Delta'] . " + nextdelta:" . $nextBulkFrame['Delta'] . ' - ' . $previousBulkFrame['Delta'] . ' * ' . $percentage ); } else { ZM\Fatal('No Frame found for event('.$_REQUEST['eid'].') and frame id('.$_REQUEST['fid'].')'); } } // Frame can be non-existent. We have Bulk frames. So now we should try to load the bulk frame $path = $Event->Path().'/'.sprintf('%0'.ZM_EVENT_IMAGE_DIGITS.'d',$Frame->FrameId()).'-'.$show.'.jpg'; - ZM\Logger::Debug("Path: $path"); + ZM\Debug("Path: $path"); } } else { @@ -235,7 +235,7 @@ if ( empty($_REQUEST['path']) ) { } # end if have eid if ( !file_exists($path) ) { - ZM\Logger::Debug("$path does not exist"); + ZM\Debug("$path does not exist"); # Generate the frame JPG if ( ($show == 'capture') and $Event->DefaultVideo() ) { if ( !file_exists($Event->Path().'/'.$Event->DefaultVideo()) ) { @@ -245,11 +245,11 @@ if ( empty($_REQUEST['path']) ) { $command = ZM_PATH_FFMPEG.' -ss '. $Frame->Delta() .' -i '.$Event->Path().'/'.$Event->DefaultVideo().' -frames:v 1 '.$path; #$command ='ffmpeg -ss '. $Frame->Delta() .' -i '.$Event->Path().'/'.$Event->DefaultVideo().' -vf "select=gte(n\\,'.$Frame->FrameId().'),setpts=PTS-STARTPTS" '.$path; #$command ='ffmpeg -v 0 -i '.$Storage->Path().'/'.$Event->Path().'/'.$Event->DefaultVideo().' -vf "select=gte(n\\,'.$Frame->FrameId().'),setpts=PTS-STARTPTS" '.$path; - ZM\Logger::Debug("Running $command"); + ZM\Debug("Running $command"); $output = array(); $retval = 0; exec( $command, $output, $retval ); - ZM\Logger::Debug("Command: $command, retval: $retval, output: " . implode("\n", $output)); + ZM\Debug("Command: $command, retval: $retval, output: " . implode("\n", $output)); if ( ! file_exists( $path ) ) { header('HTTP/1.0 404 Not Found'); ZM\Fatal('Can\'t create frame images from video for this event '.$Event->DefaultVideo() ); @@ -334,7 +334,7 @@ if ( $errorText ) { ZM\Error('No bytes read from '. $path); } } else { - ZM\Logger::Debug("Doing a scaled image: scale($scale) width($width) height($height)"); + ZM\Debug("Doing a scaled image: scale($scale) width($width) height($height)"); $i = 0; if ( ! ( $width && $height ) ) { $i = imagecreatefromjpeg($path); @@ -347,7 +347,7 @@ if ( $errorText ) { $width = ($height * $oldWidth) / $oldHeight; } elseif ( $width != 0 && $height == 0 ) { $height = ($width * $oldHeight) / $oldWidth; -ZM\Logger::Debug("Figuring out height using width: $height = ($width * $oldHeight) / $oldWidth"); +ZM\Debug("Figuring out height using width: $height = ($width * $oldHeight) / $oldWidth"); } if ( $width == $oldWidth && $height == $oldHeight ) { ZM\Warning('No change to width despite scaling.'); @@ -361,7 +361,7 @@ ZM\Logger::Debug("Figuring out height using width: $height = ($width * $oldHeigh header('Content-Disposition: inline; filename="' . $filename . '"'); } if ( !( file_exists($scaled_path) and readfile($scaled_path) ) ) { - ZM\Logger::Debug("Cached scaled image does not exist at $scaled_path or is no good.. Creating it"); + ZM\Debug("Cached scaled image does not exist at $scaled_path or is no good.. Creating it"); ob_start(); if ( !$i ) $i = imagecreatefromjpeg($path); @@ -373,12 +373,12 @@ ZM\Logger::Debug("Figuring out height using width: $height = ($width * $oldHeigh file_put_contents($scaled_path, $scaled_jpeg_data); echo $scaled_jpeg_data; } else { - ZM\Logger::Debug("Sending $scaled_path"); + ZM\Debug("Sending $scaled_path"); $bytes = readfile($scaled_path); if ( !$bytes ) { ZM\Error('No bytes read from '. $scaled_path); } else { - ZM\Logger::Debug("$bytes sent"); + ZM\Debug("$bytes sent"); } } } diff --git a/web/views/view_video.php b/web/views/view_video.php index 56837a5ba..c94f1d9b7 100644 --- a/web/views/view_video.php +++ b/web/views/view_video.php @@ -66,14 +66,14 @@ $end = $size-1; $length = $size; if ( isset($_SERVER['HTTP_RANGE']) ) { - ZM\Logger::Debug('Using Range '.$_SERVER['HTTP_RANGE']); + ZM\Debug('Using Range '.$_SERVER['HTTP_RANGE']); if ( preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches) ) { $begin = intval($matches[1]); if ( !empty($matches[2]) ) { $end = intval($matches[2]); } $length = $end - $begin + 1; - ZM\Logger::Debug("Using Range $begin $end size: $size, length: $length"); + ZM\Debug("Using Range $begin $end size: $size, length: $length"); } } # end if HTTP_RANGE From c3a98c1f4411b6c5eac14dcaa6bd7c8038ce13a9 Mon Sep 17 00:00:00 2001 From: Andrew Bauer Date: Wed, 14 Oct 2020 10:03:33 -0500 Subject: [PATCH 153/199] replace shutdown form submit with ajax --- web/ajax/modals/shutdown.php | 31 +++-------------- web/ajax/shutdown.php | 58 +++++++++++++++++++++++++++++++ web/includes/actions/shutdown.php | 44 ----------------------- web/skins/classic/js/skin.js | 36 ++++++++++++------- web/skins/classic/js/skin.js.php | 1 + 5 files changed, 88 insertions(+), 82 deletions(-) create mode 100644 web/ajax/shutdown.php delete mode 100644 web/includes/actions/shutdown.php diff --git a/web/ajax/modals/shutdown.php b/web/ajax/modals/shutdown.php index a461f0074..c73b442dd 100644 --- a/web/ajax/modals/shutdown.php +++ b/web/ajax/modals/shutdown.php @@ -14,21 +14,6 @@ if ( $error ) { return; } -$output_str = ''; -if ( isset($output) ) { - $output_str = '

'.implode('
', $output).'

'.PHP_EOL; -} - -$cancel_str = ''; -if ( isset($_POST['when']) and ($_POST['when'] != 'NOW') and ($action != 'cancel') ) { - $cancel_str = '

You may cancel this shutdown by clicking '.translate('Cancel').'

'.PHP_EOL; -} - -$cancel_btn = ''; -if ( isset($_POST['when']) and ($_POST['when'] != 'NOW') and ($action != 'cancel') ) { - $cancel_btn = ''.PHP_EOL; -} - ?>