Merge branch 'master' into storageareas

This commit is contained in:
Isaac Connor 2018-08-31 16:06:13 -04:00
commit 2858564155
13 changed files with 498 additions and 409 deletions

View File

@ -37,7 +37,7 @@ Depends: ${shlibs:Depends}, ${misc:Depends}, ${perl:Depends}
, libphp-serialization-perl , libphp-serialization-perl
, libdate-manip-perl, libmime-lite-perl, libmime-tools-perl, libdbd-mysql-perl , libdate-manip-perl, libmime-lite-perl, libmime-tools-perl, libdbd-mysql-perl
, libwww-perl, libarchive-tar-perl, libarchive-zip-perl, libdevice-serialport-perl , libwww-perl, libarchive-tar-perl, libarchive-zip-perl, libdevice-serialport-perl
, libmodule-load-perl, libsys-mmap-perl, libjson-any-perl , libmodule-load-perl, libsys-mmap-perl, libjson-any-perl, libjson-maybexs-perl
, libnet-sftp-foreign-perl, libio-pty-perl, libexpect-perl , libnet-sftp-foreign-perl, libio-pty-perl, libexpect-perl
, libdata-dump-perl, libclass-std-fast-perl, libsoap-wsdl-perl, libio-socket-multicast-perl, libdigest-sha-perl , libdata-dump-perl, libclass-std-fast-perl, libsoap-wsdl-perl, libio-socket-multicast-perl, libdigest-sha-perl
, libsys-cpu-perl, libsys-meminfo-perl , libsys-cpu-perl, libsys-meminfo-perl

View File

@ -26,7 +26,7 @@
%global _hardened_build 1 %global _hardened_build 1
Name: zoneminder Name: zoneminder
Version: 1.31.45 Version: 1.31.47
Release: 1%{?dist} Release: 1%{?dist}
Summary: A camera monitoring and analysis tool Summary: A camera monitoring and analysis tool
Group: System Environment/Daemons Group: System Environment/Daemons

View File

@ -50,6 +50,7 @@ Depends: ${shlibs:Depends}, ${misc:Depends}, ${perl:Depends}
,libdevice-serialport-perl ,libdevice-serialport-perl
,libimage-info-perl ,libimage-info-perl
,libjson-any-perl ,libjson-any-perl
,libjson-maybexs-perl
,libsys-mmap-perl [!hurd-any] ,libsys-mmap-perl [!hurd-any]
,liburi-encode-perl ,liburi-encode-perl
,libwww-perl ,libwww-perl

View File

@ -32,7 +32,7 @@ Package: libzoneminder-perl
Section: perl Section: perl
Architecture: all Architecture: all
Depends: ${misc:Depends}, ${perl:Depends}, libdbi-perl, Depends: ${misc:Depends}, ${perl:Depends}, libdbi-perl,
libdevice-serialport-perl, libimage-info-perl, libjson-any-perl, libdevice-serialport-perl, libimage-info-perl, libjson-any-perl, libjson-maybexs-perl,
libsys-mmap-perl, liburi-encode-perl, libwww-perl libsys-mmap-perl, liburi-encode-perl, libwww-perl
Description: Perl libraries for ZoneMinder Description: Perl libraries for ZoneMinder
ZoneMinder is a video camera security and surveillance solution. ZoneMinder is a video camera security and surveillance solution.

View File

@ -45,7 +45,7 @@ Package: libzoneminder-perl
Section: perl Section: perl
Architecture: all Architecture: all
Depends: ${misc:Depends}, ${perl:Depends}, libdbi-perl, Depends: ${misc:Depends}, ${perl:Depends}, libdbi-perl,
libdevice-serialport-perl, libimage-info-perl, libjson-any-perl, libdevice-serialport-perl, libimage-info-perl, libjson-any-perl, libjson-maybexs-perl,
libsys-mmap-perl, liburi-encode-perl, libwww-perl libsys-mmap-perl, liburi-encode-perl, libwww-perl
Description: Perl libraries for ZoneMinder Description: Perl libraries for ZoneMinder
ZoneMinder is a video camera security and surveillance solution. ZoneMinder is a video camera security and surveillance solution.

View File

@ -53,6 +53,7 @@ Depends: ${shlibs:Depends}, ${misc:Depends}, ${perl:Depends}
,libdevice-serialport-perl ,libdevice-serialport-perl
,libimage-info-perl ,libimage-info-perl
,libjson-any-perl ,libjson-any-perl
,libjson-maybexs-perl
,libsys-mmap-perl [!hurd-any] ,libsys-mmap-perl [!hurd-any]
,liburi-encode-perl ,liburi-encode-perl
,libwww-perl ,libwww-perl

View File

@ -29,16 +29,16 @@ function do_request($method, $url, $data=array(), $optional_headers = null) {
'method' => $method, 'method' => $method,
'content' => $data 'content' => $data
)); ));
if ($optional_headers !== null) { if ( $optional_headers !== null ) {
$params['http']['header'] = $optional_headers; $params['http']['header'] = $optional_headers;
} }
$ctx = stream_context_create($params); $ctx = stream_context_create($params);
$fp = @fopen($url, 'rb', false, $ctx); $fp = @fopen($url, 'rb', false, $ctx);
if (!$fp) { if ( !$fp ) {
throw new Exception("Problem with $url, $php_errormsg"); throw new Exception("Problem with $url, $php_errormsg");
} }
$response = @stream_get_contents($fp); $response = @stream_get_contents($fp);
if ($response === false) { if ( $response === false ) {
throw new Exception("Problem reading data from $url, $php_errormsg"); throw new Exception("Problem reading data from $url, $php_errormsg");
} }
return $response; return $response;
@ -49,16 +49,16 @@ function do_post_request($url, $data, $optional_headers = null) {
'method' => 'POST', 'method' => 'POST',
'content' => $data 'content' => $data
)); ));
if ($optional_headers !== null) { if ( $optional_headers !== null ) {
$params['http']['header'] = $optional_headers; $params['http']['header'] = $optional_headers;
} }
$ctx = stream_context_create($params); $ctx = stream_context_create($params);
$fp = @fopen($url, 'rb', false, $ctx); $fp = @fopen($url, 'rb', false, $ctx);
if (!$fp) { if ( !$fp ) {
throw new Exception("Problem with $url, $php_errormsg"); throw new Exception("Problem with $url, $php_errormsg");
} }
$response = @stream_get_contents($fp); $response = @stream_get_contents($fp);
if ($response === false) { if ( $response === false ) {
throw new Exception("Problem reading data from $url, $php_errormsg"); throw new Exception("Problem reading data from $url, $php_errormsg");
} }
return $response; return $response;
@ -106,17 +106,17 @@ if ( $action == 'login' && isset($_REQUEST['username']) && ( ZM_AUTH_TYPE == 're
$responseData = json_decode($res,true); $responseData = json_decode($res,true);
// PP - credit: https://github.com/google/recaptcha/blob/master/src/ReCaptcha/Response.php // PP - credit: https://github.com/google/recaptcha/blob/master/src/ReCaptcha/Response.php
// if recaptcha resulted in error, we might have to deny login // if recaptcha resulted in error, we might have to deny login
if (isset($responseData['success']) && $responseData['success'] == false) { if ( isset($responseData['success']) && $responseData['success'] == false ) {
// PP - before we deny auth, let's make sure the error was not 'invalid secret' // PP - before we deny auth, let's make sure the error was not 'invalid secret'
// because that means the user did not configure the secret key correctly // because that means the user did not configure the secret key correctly
// in this case, we prefer to let him login in and display a message to correct // in this case, we prefer to let him login in and display a message to correct
// the key. Unfortunately, there is no way to check for invalid site key in code // the key. Unfortunately, there is no way to check for invalid site key in code
// as it produces the same error as when you don't answer a recaptcha // as it produces the same error as when you don't answer a recaptcha
if (isset($responseData['error-codes']) && is_array($responseData['error-codes'])) { if ( isset($responseData['error-codes']) && is_array($responseData['error-codes']) ) {
if (!in_array('invalid-input-secret',$responseData['error-codes'])) { if ( !in_array('invalid-input-secret',$responseData['error-codes']) ) {
Error('reCaptcha authentication failed'); Error('reCaptcha authentication failed');
userLogout(); userLogout();
$view='login'; $view = 'login';
$refreshParent = true; $refreshParent = true;
return; return;
} else { } else {
@ -140,19 +140,19 @@ if ( $action == 'login' && isset($_REQUEST['username']) && ( ZM_AUTH_TYPE == 're
$view = 'none'; $view = 'none';
} else if ( $action == 'bandwidth' && isset($_REQUEST['newBandwidth']) ) { } else if ( $action == 'bandwidth' && isset($_REQUEST['newBandwidth']) ) {
$_COOKIE['zmBandwidth'] = validStr($_REQUEST['newBandwidth']); $_COOKIE['zmBandwidth'] = validStr($_REQUEST['newBandwidth']);
setcookie( 'zmBandwidth', validStr($_REQUEST['newBandwidth']), time()+3600*24*30*12*10 ); setcookie('zmBandwidth', validStr($_REQUEST['newBandwidth']), time()+3600*24*30*12*10);
$refreshParent = true; $refreshParent = true;
} }
// Event scope actions, view permissions only required // Event scope actions, view permissions only required
if ( canView('Events') ) { if ( canView('Events') ) {
if ( isset( $_REQUEST['object'] ) and ( $_REQUEST['object'] == 'filter' ) ) { if ( isset($_REQUEST['object']) and ( $_REQUEST['object'] == 'filter' ) ) {
if ( $action == 'addterm' ) { if ( $action == 'addterm' ) {
$_REQUEST['filter'] = addFilterTerm( $_REQUEST['filter'], $_REQUEST['line'] ); $_REQUEST['filter'] = addFilterTerm($_REQUEST['filter'], $_REQUEST['line']);
} elseif ( $action == 'delterm' ) { } elseif ( $action == 'delterm' ) {
$_REQUEST['filter'] = delFilterTerm( $_REQUEST['filter'], $_REQUEST['line'] ); $_REQUEST['filter'] = delFilterTerm($_REQUEST['filter'], $_REQUEST['line']);
} else if ( canEdit( 'Events' ) ) { } else if ( canEdit('Events') ) {
if ( $action == 'delete' ) { if ( $action == 'delete' ) {
if ( ! empty($_REQUEST['Id']) ) { if ( ! empty($_REQUEST['Id']) ) {
dbQuery('DELETE FROM Filters WHERE Id=?', array($_REQUEST['Id'])); dbQuery('DELETE FROM Filters WHERE Id=?', array($_REQUEST['Id']));
@ -210,11 +210,13 @@ if ( canView('Events') ) {
dbQuery('UPDATE Events SET Name=? WHERE Id=?', array($_REQUEST['eventName'], $_REQUEST['eid'])); dbQuery('UPDATE Events SET Name=? WHERE Id=?', array($_REQUEST['eventName'], $_REQUEST['eid']));
} else if ( $action == 'eventdetail' ) { } else if ( $action == 'eventdetail' ) {
if ( !empty($_REQUEST['eid']) ) { if ( !empty($_REQUEST['eid']) ) {
dbQuery( 'UPDATE Events SET Cause=?, Notes=? WHERE Id=?', array( $_REQUEST['newEvent']['Cause'], $_REQUEST['newEvent']['Notes'], $_REQUEST['eid'] ) ); dbQuery('UPDATE Events SET Cause=?, Notes=? WHERE Id=?',
array($_REQUEST['newEvent']['Cause'], $_REQUEST['newEvent']['Notes'], $_REQUEST['eid']) );
} else { } else {
$dbConn->beginTransaction(); $dbConn->beginTransaction();
foreach( getAffectedIds('markEid') as $markEid ) { foreach( getAffectedIds('markEid') as $markEid ) {
dbQuery( 'UPDATE Events SET Cause=?, Notes=? WHERE Id=?', array( $_REQUEST['newEvent']['Cause'], $_REQUEST['newEvent']['Notes'], $markEid ) ); dbQuery('UPDATE Events SET Cause=?, Notes=? WHERE Id=?',
array($_REQUEST['newEvent']['Cause'], $_REQUEST['newEvent']['Notes'], $markEid) );
} }
$dbConn->commit(); $dbConn->commit();
} }
@ -226,7 +228,7 @@ if ( canView('Events') ) {
dbQuery('UPDATE Events SET Archived=? WHERE Id=?', array($archiveVal, $_REQUEST['eid'])); dbQuery('UPDATE Events SET Archived=? WHERE Id=?', array($archiveVal, $_REQUEST['eid']));
} else { } else {
$dbConn->beginTransaction(); $dbConn->beginTransaction();
foreach( getAffectedIds( 'markEid' ) as $markEid ) { foreach( getAffectedIds('markEid') as $markEid ) {
dbQuery('UPDATE Events SET Archived=? WHERE Id=?', array($archiveVal, $markEid)); dbQuery('UPDATE Events SET Archived=? WHERE Id=?', array($archiveVal, $markEid));
} }
$dbConn->commit(); $dbConn->commit();
@ -234,8 +236,8 @@ if ( canView('Events') ) {
} }
} elseif ( $action == 'delete' ) { } elseif ( $action == 'delete' ) {
$dbConn->beginTransaction(); $dbConn->beginTransaction();
foreach( getAffectedIds( 'markEid' ) as $markEid ) { foreach( getAffectedIds('markEid') as $markEid ) {
deleteEvent( $markEid ); deleteEvent($markEid);
} }
$dbConn->commit(); $dbConn->commit();
$refreshParent = true; $refreshParent = true;
@ -245,45 +247,47 @@ if ( canView('Events') ) {
} // end canView(Events) } // end canView(Events)
// Monitor control actions, require a monitor id and control view permissions for that monitor // Monitor control actions, require a monitor id and control view permissions for that monitor
if ( !empty($_REQUEST['mid']) && canView( 'Control', $_REQUEST['mid'] ) ) { if ( !empty($_REQUEST['mid']) && canView('Control', $_REQUEST['mid']) ) {
require_once( 'control_functions.php' ); require_once('control_functions.php');
require_once( 'Monitor.php' ); require_once('Monitor.php');
$mid = validInt($_REQUEST['mid']); $mid = validInt($_REQUEST['mid']);
if ( $action == 'control' ) { if ( $action == 'control' ) {
$monitor = new Monitor( $mid ); $monitor = new Monitor($mid);
$ctrlCommand = buildControlCommand( $monitor ); $ctrlCommand = buildControlCommand($monitor);
sendControlCommand( $monitor->Id(), $ctrlCommand ); sendControlCommand($monitor->Id(), $ctrlCommand);
} elseif ( $action == 'settings' ) { } else if ( $action == 'settings' ) {
$args = ' -m ' . escapeshellarg($mid); $args = ' -m ' . escapeshellarg($mid);
$args .= ' -B' . escapeshellarg($_REQUEST['newBrightness']); $args .= ' -B' . escapeshellarg($_REQUEST['newBrightness']);
$args .= ' -C' . escapeshellarg($_REQUEST['newContrast']); $args .= ' -C' . escapeshellarg($_REQUEST['newContrast']);
$args .= ' -H' . escapeshellarg($_REQUEST['newHue']); $args .= ' -H' . escapeshellarg($_REQUEST['newHue']);
$args .= ' -O' . escapeshellarg($_REQUEST['newColour']); $args .= ' -O' . escapeshellarg($_REQUEST['newColour']);
$zmuCommand = getZmuCommand( $args ); $zmuCommand = getZmuCommand($args);
$zmuOutput = exec( $zmuCommand ); $zmuOutput = exec($zmuCommand);
list( $brightness, $contrast, $hue, $colour ) = explode( ' ', $zmuOutput ); list($brightness, $contrast, $hue, $colour) = explode(' ', $zmuOutput);
dbQuery( 'UPDATE Monitors SET Brightness = ?, Contrast = ?, Hue = ?, Colour = ? WHERE Id = ?', array($brightness, $contrast, $hue, $colour, $mid)); dbQuery(
'UPDATE Monitors SET Brightness = ?, Contrast = ?, Hue = ?, Colour = ? WHERE Id = ?',
array($brightness, $contrast, $hue, $colour, $mid));
} }
} }
// Control capability actions, require control edit permissions // Control capability actions, require control edit permissions
if ( canEdit('Control') ) { if ( canEdit('Control') ) {
if ( $action == 'controlcap' ) { if ( $action == 'controlcap' ) {
require_once( 'Control.php' ); require_once('Control.php');
$Control = new Control( !empty($_REQUEST['cid']) ? $_REQUEST['cid'] : null ); $Control = new Control( !empty($_REQUEST['cid']) ? $_REQUEST['cid'] : null );
//$changes = getFormChanges( $control, $_REQUEST['newControl'], $types, $columns ); //$changes = getFormChanges( $control, $_REQUEST['newControl'], $types, $columns );
$Control->save( $_REQUEST['newControl'] ); $Control->save($_REQUEST['newControl']);
$refreshParent = true; $refreshParent = true;
$view = 'none'; $view = 'none';
} elseif ( $action == 'delete' ) { } elseif ( $action == 'delete' ) {
if ( isset($_REQUEST['markCids']) ) { if ( isset($_REQUEST['markCids']) ) {
foreach( $_REQUEST['markCids'] as $markCid ) { foreach( $_REQUEST['markCids'] as $markCid ) {
dbQuery( 'delete from Controls where Id = ?', array($markCid) ); dbQuery('DELETE FROM Controls WHERE Id = ?', array($markCid));
dbQuery( 'update Monitors set Controllable = 0, ControlId = 0 where ControlId = ?', array($markCid) ); dbQuery('UPDATE Monitors SET Controllable = 0, ControlId = 0 WHERE ControlId = ?', array($markCid));
$refreshParent = true; $refreshParent = true;
} }
} }
@ -293,59 +297,59 @@ if ( canEdit('Control') ) {
if ( isset($_REQUEST['object']) and $_REQUEST['object'] == 'Monitor' ) { if ( isset($_REQUEST['object']) and $_REQUEST['object'] == 'Monitor' ) {
if ( $action == 'save' ) { if ( $action == 'save' ) {
foreach ( $_REQUEST['mids'] as $mid ) { foreach ( $_REQUEST['mids'] as $mid ) {
$mid = ValidInt( $mid ); $mid = ValidInt($mid);
if ( ! canEdit('Monitors', $mid ) ) { if ( ! canEdit('Monitors', $mid) ) {
Warning("Cannot edit monitor $mid"); Warning("Cannot edit monitor $mid");
continue; continue;
} }
$Monitor = new Monitor( $mid ); $Monitor = new Monitor($mid);
if ( $Monitor->Type() != 'WebSite' ) { if ( $Monitor->Type() != 'WebSite' ) {
$Monitor->zmaControl('stop'); $Monitor->zmaControl('stop');
$Monitor->zmcControl('stop'); $Monitor->zmcControl('stop');
} }
$Monitor->save( $_REQUEST['newMonitor'] ); $Monitor->save($_REQUEST['newMonitor']);
if ($Monitor->Function() != 'None' && $Monitor->Type() != 'WebSite' ) { if ( $Monitor->Function() != 'None' && $Monitor->Type() != 'WebSite' ) {
$Monitor->zmcControl('start'); $Monitor->zmcControl('start');
if ( $Monitor->Enabled() ) { if ( $Monitor->Enabled() ) {
$Monitor->zmaControl('start'); $Monitor->zmaControl('start');
} }
} }
} // end foreach mid } // end foreach mid
$refreshParent = true; $refreshParent = true;
} // end if action == save } // end if action == save
} // end if object is Monitor } // end if object is Monitor
// Monitor edit actions, require a monitor id and edit permissions for that monitor // Monitor edit actions, require a monitor id and edit permissions for that monitor
if ( !empty($_REQUEST['mid']) && canEdit( 'Monitors', $_REQUEST['mid'] ) ) { if ( !empty($_REQUEST['mid']) && canEdit('Monitors', $_REQUEST['mid']) ) {
$mid = validInt($_REQUEST['mid']); $mid = validInt($_REQUEST['mid']);
if ( $action == 'function' ) { if ( $action == 'function' ) {
$monitor = dbFetchOne( 'SELECT * FROM Monitors WHERE Id=?', NULL, array($mid) ); $monitor = dbFetchOne('SELECT * FROM Monitors WHERE Id=?', NULL, array($mid));
$newFunction = validStr($_REQUEST['newFunction']); $newFunction = validStr($_REQUEST['newFunction']);
# Because we use a checkbox, it won't get passed in the request. So not being in _REQUEST means 0 # Because we use a checkbox, it won't get passed in the request. So not being in _REQUEST means 0
$newEnabled = ( !isset( $_REQUEST['newEnabled'] ) or $_REQUEST['newEnabled'] != '1' ) ? '0' : '1'; $newEnabled = ( !isset($_REQUEST['newEnabled']) or $_REQUEST['newEnabled'] != '1' ) ? '0' : '1';
$oldFunction = $monitor['Function']; $oldFunction = $monitor['Function'];
$oldEnabled = $monitor['Enabled']; $oldEnabled = $monitor['Enabled'];
if ( $newFunction != $oldFunction || $newEnabled != $oldEnabled ) { if ( $newFunction != $oldFunction || $newEnabled != $oldEnabled ) {
dbQuery( 'UPDATE Monitors SET Function=?, Enabled=? WHERE Id=?', array( $newFunction, $newEnabled, $mid ) ); dbQuery('UPDATE Monitors SET Function=?, Enabled=? WHERE Id=?',
array($newFunction, $newEnabled, $mid));
$monitor['Function'] = $newFunction; $monitor['Function'] = $newFunction;
$monitor['Enabled'] = $newEnabled; $monitor['Enabled'] = $newEnabled;
if ( daemonCheck() && $monitor['Type'] != 'WebSite' ) { if ( daemonCheck() && ($monitor['Type'] != 'WebSite') ) {
$restart = ($oldFunction == 'None') || ($newFunction == 'None') || ($newEnabled != $oldEnabled); $restart = ($oldFunction == 'None') || ($newFunction == 'None') || ($newEnabled != $oldEnabled);
zmaControl( $monitor, 'stop' ); zmaControl($monitor, 'stop');
zmcControl( $monitor, $restart?'restart':'' ); zmcControl($monitor, $restart?'restart':'');
zmaControl( $monitor, 'start' ); zmaControl($monitor, 'start');
} }
$refreshParent = true; $refreshParent = true;
} }
} elseif ( $action == 'zone' && isset( $_REQUEST['zid'] ) ) { } else if ( $action == 'zone' && isset($_REQUEST['zid']) ) {
$zid = validInt($_REQUEST['zid']); $zid = validInt($_REQUEST['zid']);
$monitor = dbFetchOne( 'SELECT * FROM Monitors WHERE Id=?', NULL, array($mid) ); $monitor = dbFetchOne('SELECT * FROM Monitors WHERE Id=?', NULL, array($mid));
if ( !empty($zid) ) { if ( !empty($zid) ) {
$zone = dbFetchOne( 'SELECT * FROM Zones WHERE MonitorId=? AND Id=?', NULL, array( $mid, $zid ) ); $zone = dbFetchOne('SELECT * FROM Zones WHERE MonitorId=? AND Id=?', NULL, array($mid, $zid));
} else { } else {
$zone = array(); $zone = array();
} }
@ -365,74 +369,74 @@ if ( !empty($_REQUEST['mid']) && canEdit( 'Monitors', $_REQUEST['mid'] ) ) {
unset( $_REQUEST['newZone']['Points'] ); unset( $_REQUEST['newZone']['Points'] );
$types = array(); $types = array();
$changes = getFormChanges( $zone, $_REQUEST['newZone'], $types ); $changes = getFormChanges($zone, $_REQUEST['newZone'], $types);
if ( count( $changes ) ) { if ( count($changes) ) {
if ( $zid > 0 ) { if ( $zid > 0 ) {
dbQuery( 'UPDATE Zones SET '.implode( ', ', $changes ).' WHERE MonitorId=? AND Id=?', array( $mid, $zid) ); dbQuery('UPDATE Zones SET '.implode(', ', $changes).' WHERE MonitorId=? AND Id=?', array($mid, $zid));
} else { } else {
dbQuery( 'INSERT INTO Zones SET MonitorId=?, '.implode( ', ', $changes ), array( $mid ) ); dbQuery('INSERT INTO Zones SET MonitorId=?, '.implode(', ', $changes), array($mid));
} }
if ( daemonCheck() && $monitor['Type'] != 'WebSite' ) { if ( daemonCheck() && ($monitor['Type'] != 'WebSite') ) {
if ( $_REQUEST['newZone']['Type'] == 'Privacy' ) { if ( $_REQUEST['newZone']['Type'] == 'Privacy' ) {
zmaControl( $monitor, 'stop' ); zmaControl($monitor, 'stop');
zmcControl( $monitor, 'restart' ); zmcControl($monitor, 'restart');
zmaControl( $monitor, 'start' ); zmaControl($monitor, 'start');
} else { } else {
zmaControl( $mid, 'restart' ); zmaControl($monitor, 'restart');
} }
} }
if ( $_REQUEST['newZone']['Type'] == 'Privacy' && $monitor['Controllable'] ) { if ( ($_REQUEST['newZone']['Type'] == 'Privacy') && $monitor['Controllable'] ) {
require_once( 'control_functions.php' ); require_once('control_functions.php');
sendControlCommand( $mid, 'quit' ); sendControlCommand($mid, 'quit');
} }
$refreshParent = true; $refreshParent = true;
} }
$view = 'none'; $view = 'none';
} elseif ( $action == 'plugin' && isset($_REQUEST['pl'])) { } elseif ( $action == 'plugin' && isset($_REQUEST['pl']) ) {
$sql='SELECT * FROM PluginsConfig WHERE MonitorId=? AND ZoneId=? AND pluginName=?'; $sql = 'SELECT * FROM PluginsConfig WHERE MonitorId=? AND ZoneId=? AND pluginName=?';
$pconfs=dbFetchAll( $sql, NULL, array( $mid, $_REQUEST['zid'], $_REQUEST['pl'] ) ); $pconfs=dbFetchAll($sql, NULL, array($mid, $_REQUEST['zid'], $_REQUEST['pl']));
$changes=0; $changes = 0;
foreach( $pconfs as $pconf ) { foreach ( $pconfs as $pconf ) {
$value=$_REQUEST['pluginOpt'][$pconf['Name']]; $value = $_REQUEST['pluginOpt'][$pconf['Name']];
if(array_key_exists($pconf['Name'], $_REQUEST['pluginOpt']) && ($pconf['Value']!=$value)) { if ( array_key_exists($pconf['Name'], $_REQUEST['pluginOpt']) && ($pconf['Value'] != $value) ) {
dbQuery('UPDATE PluginsConfig SET Value=? WHERE id=?', array( $value, $pconf['Id'] ) ); dbQuery('UPDATE PluginsConfig SET Value=? WHERE id=?', array($value, $pconf['Id']));
$changes++; $changes++;
} }
} }
if($changes>0) { if ( $changes > 0 ) {
if ( daemonCheck() && $monitor['Type'] != 'WebSite' ) { if ( daemonCheck() && ($monitor['Type'] != 'WebSite') ) {
zmaControl( $mid, 'restart' ); zmaControl($mid, 'restart');
} }
$refreshParent = true; $refreshParent = true;
} }
$view = 'none'; $view = 'none';
} elseif ( $action == 'sequence' && isset($_REQUEST['smid']) ) { } elseif ( ($action == 'sequence') && isset($_REQUEST['smid']) ) {
$smid = validInt($_REQUEST['smid']); $smid = validInt($_REQUEST['smid']);
$monitor = dbFetchOne( 'select * from Monitors where Id = ?', NULL, array($mid) ); $monitor = dbFetchOne('SELECT * FROM Monitors WHERE Id = ?', NULL, array($mid));
$smonitor = dbFetchOne( 'select * from Monitors where Id = ?', NULL, array($smid) ); $smonitor = dbFetchOne('SELECT * FROM Monitors WHERE Id = ?', NULL, array($smid));
dbQuery( 'update Monitors set Sequence=? where Id=?', array( $smonitor['Sequence'], $monitor['Id'] ) ); dbQuery('UPDATE Monitors SET Sequence=? WHERE Id=?', array($smonitor['Sequence'], $monitor['Id']));
dbQuery( 'update Monitors set Sequence=? WHERE Id=?', array( $monitor['Sequence'], $smonitor['Id'] ) ); dbQuery('UPDATE Monitors SET Sequence=? WHERE Id=?', array($monitor['Sequence'], $smonitor['Id']));
$refreshParent = true; $refreshParent = true;
fixSequences(); fixSequences();
} elseif ( $action == 'delete' ) { } elseif ( $action == 'delete' ) {
if ( isset($_REQUEST['markZids']) ) { if ( isset($_REQUEST['markZids']) ) {
$deletedZid = 0; $deletedZid = 0;
foreach( $_REQUEST['markZids'] as $markZid ) { foreach ( $_REQUEST['markZids'] as $markZid ) {
$zone = dbFetchOne( 'select * from Zones where Id=?', NULL, array($markZid) ); $zone = dbFetchOne('SELECT * FROM Zones WHERE Id=?', NULL, array($markZid));
dbQuery( 'delete from Zones WHERE MonitorId=? AND Id=?', array( $mid, $markZid) ); dbQuery('DELETE FROM Zones WHERE MonitorId=? AND Id=?', array($mid, $markZid));
$deletedZid = 1; $deletedZid = 1;
} }
if ( $deletedZid ) { if ( $deletedZid ) {
if ( daemonCheck() && $monitor['Type'] != 'WebSite' ) { if ( daemonCheck() && $monitor['Type'] != 'WebSite' ) {
if ( $zone['Type'] == 'Privacy' ) { if ( $zone['Type'] == 'Privacy' ) {
zmaControl( $mid, 'stop' ); zmaControl($mid, 'stop');
zmcControl( $mid, 'restart' ); zmcControl($mid, 'restart');
zmaControl( $mid, 'start' ); zmaControl($mid, 'start');
} else { } else {
zmaControl( $mid, 'restart' ); zmaControl($mid, 'restart');
} }
} // end if daemonCheck() } // end if daemonCheck()
$refreshParent = true; $refreshParent = true;
@ -442,15 +446,15 @@ if ( !empty($_REQUEST['mid']) && canEdit( 'Monitors', $_REQUEST['mid'] ) ) {
} // end if $mid and canEdit($mid) } // end if $mid and canEdit($mid)
// Monitor edit actions, monitor id derived, require edit permissions for that monitor // Monitor edit actions, monitor id derived, require edit permissions for that monitor
if ( canEdit( 'Monitors' ) ) { if ( canEdit('Monitors') ) {
if ( $action == 'monitor' ) { if ( $action == 'monitor' ) {
$mid = 0; $mid = 0;
if ( !empty($_REQUEST['mid']) ) { if ( !empty($_REQUEST['mid']) ) {
$mid = validInt($_REQUEST['mid']); $mid = validInt($_REQUEST['mid']);
$monitor = dbFetchOne( 'SELECT * FROM Monitors WHERE Id=?', NULL, array($mid) ); $monitor = dbFetchOne('SELECT * FROM Monitors WHERE Id=?', NULL, array($mid));
if ( ZM_OPT_X10 ) { if ( ZM_OPT_X10 ) {
$x10Monitor = dbFetchOne( 'SELECT * FROM TriggersX10 WHERE MonitorId=?', NULL, array($mid) ); $x10Monitor = dbFetchOne('SELECT * FROM TriggersX10 WHERE MonitorId=?', NULL, array($mid));
if ( !$x10Monitor ) if ( !$x10Monitor )
$x10Monitor = array(); $x10Monitor = array();
} }
@ -476,18 +480,19 @@ if ( canEdit( 'Monitors' ) ) {
); );
if ( $_REQUEST['newMonitor']['ServerId'] == 'auto' ) { 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'); $_REQUEST['newMonitor']['ServerId'] = dbFetchOne(
Logger::Debug("Auto selecting server: Got " . $_REQUEST['newMonitor']['ServerId'] ); 'SELECT Id FROM Servers WHERE Status=\'Running\' ORDER BY FreeMem DESC, CpuLoad ASC LIMIT 1', 'Id');
Logger::Debug('Auto selecting server: Got ' . $_REQUEST['newMonitor']['ServerId'] );
if ( ( ! $_REQUEST['newMonitor'] ) and defined('ZM_SERVER_ID') ) { if ( ( ! $_REQUEST['newMonitor'] ) and defined('ZM_SERVER_ID') ) {
$_REQUEST['newMonitor']['ServerId'] = ZM_SERVER_ID; $_REQUEST['newMonitor']['ServerId'] = ZM_SERVER_ID;
Logger::Debug("Auto selecting server to " . ZM_SERVER_ID); Logger::Debug('Auto selecting server to ' . ZM_SERVER_ID);
} }
} }
$columns = getTableColumns('Monitors'); $columns = getTableColumns('Monitors');
$changes = getFormChanges($monitor, $_REQUEST['newMonitor'], $types, $columns); $changes = getFormChanges($monitor, $_REQUEST['newMonitor'], $types, $columns);
if ( count( $changes ) ) { if ( count($changes) ) {
if ( $mid ) { if ( $mid ) {
# If we change anything that changes the shared mem size, zma can complain. So let's stop first. # If we change anything that changes the shared mem size, zma can complain. So let's stop first.
@ -495,19 +500,19 @@ if ( canEdit( 'Monitors' ) ) {
zmaControl($monitor, 'stop'); zmaControl($monitor, 'stop');
zmcControl($monitor, 'stop'); zmcControl($monitor, 'stop');
} }
dbQuery( 'UPDATE Monitors SET '.implode( ', ', $changes ).' WHERE Id=?', array($mid) ); dbQuery('UPDATE Monitors SET '.implode(', ', $changes).' WHERE Id=?', array($mid));
// Groups will be added below // Groups will be added below
if ( isset($changes['Name']) or isset($changes['StorageId']) ) { if ( isset($changes['Name']) or isset($changes['StorageId']) ) {
$OldStorage = new Storage( $monitor['StorageId'] ); $OldStorage = new Storage($monitor['StorageId']);
$saferOldName = basename( $monitor['Name'] ); $saferOldName = basename($monitor['Name']);
if ( file_exists( $OldStorage->Path().'/'.$saferOldName ) ) if ( file_exists($OldStorage->Path().'/'.$saferOldName) )
unlink( $OldStorage->Path().'/'.$saferOldName ); unlink($OldStorage->Path().'/'.$saferOldName);
$NewStorage = new Storage( $_REQUEST['newMonitor']['StorageId'] ); $NewStorage = new Storage($_REQUEST['newMonitor']['StorageId']);
if ( ! file_exists( $NewStorage->Path().'/'.$mid ) ) if ( ! file_exists($NewStorage->Path().'/'.$mid) )
mkdir( $NewStorage->Path().'/'.$mid, 0755 ); mkdir($NewStorage->Path().'/'.$mid, 0755);
$saferNewName = basename( $_REQUEST['newMonitor']['Name'] ); $saferNewName = basename($_REQUEST['newMonitor']['Name']);
symlink( $mid, $NewStorage->Path().'/'.$saferNewName ); symlink($mid, $NewStorage->Path().'/'.$saferNewName);
} }
if ( isset($changes['Width']) || isset($changes['Height']) ) { if ( isset($changes['Width']) || isset($changes['Height']) ) {
$newW = $_REQUEST['newMonitor']['Width']; $newW = $_REQUEST['newMonitor']['Width'];
@ -517,15 +522,15 @@ if ( canEdit( 'Monitors' ) ) {
$oldH = $monitor['Height']; $oldH = $monitor['Height'];
$oldA = $oldW * $oldH; $oldA = $oldW * $oldH;
$zones = dbFetchAll( 'SELECT * FROM Zones WHERE MonitorId=?', NULL, array($mid) ); $zones = dbFetchAll('SELECT * FROM Zones WHERE MonitorId=?', NULL, array($mid));
foreach ( $zones as $zone ) { foreach ( $zones as $zone ) {
$newZone = $zone; $newZone = $zone;
$points = coordsToPoints( $zone['Coords'] ); $points = coordsToPoints($zone['Coords']);
for ( $i = 0; $i < count($points); $i++ ) { for ( $i = 0; $i < count($points); $i++ ) {
$points[$i]['x'] = intval(($points[$i]['x']*($newW-1))/($oldW-1)); $points[$i]['x'] = intval(($points[$i]['x']*($newW-1))/($oldW-1));
$points[$i]['y'] = intval(($points[$i]['y']*($newH-1))/($oldH-1)); $points[$i]['y'] = intval(($points[$i]['y']*($newH-1))/($oldH-1));
} }
$newZone['Coords'] = pointsToCoords( $points ); $newZone['Coords'] = pointsToCoords($points);
$newZone['Area'] = intval(round(($zone['Area']*$newA)/$oldA)); $newZone['Area'] = intval(round(($zone['Area']*$newA)/$oldA));
$newZone['MinAlarmPixels'] = intval(round(($newZone['MinAlarmPixels']*$newA)/$oldA)); $newZone['MinAlarmPixels'] = intval(round(($newZone['MinAlarmPixels']*$newA)/$oldA));
$newZone['MaxAlarmPixels'] = intval(round(($newZone['MaxAlarmPixels']*$newA)/$oldA)); $newZone['MaxAlarmPixels'] = intval(round(($newZone['MaxAlarmPixels']*$newA)/$oldA));
@ -534,41 +539,43 @@ if ( canEdit( 'Monitors' ) ) {
$newZone['MinBlobPixels'] = intval(round(($newZone['MinBlobPixels']*$newA)/$oldA)); $newZone['MinBlobPixels'] = intval(round(($newZone['MinBlobPixels']*$newA)/$oldA));
$newZone['MaxBlobPixels'] = intval(round(($newZone['MaxBlobPixels']*$newA)/$oldA)); $newZone['MaxBlobPixels'] = intval(round(($newZone['MaxBlobPixels']*$newA)/$oldA));
$changes = getFormChanges( $zone, $newZone, $types ); $changes = getFormChanges($zone, $newZone, $types);
if ( count( $changes ) ) { if ( count($changes) ) {
dbQuery( 'update Zones set '.implode( ', ', $changes ).' WHERE MonitorId=? AND Id=?', array( $mid, $zone['Id'] ) ); dbQuery('UPDATE Zones SET '.implode(', ', $changes).' WHERE MonitorId=? AND Id=?',
array($mid, $zone['Id']));
} }
} } // end foreach zone
} } // end if width and height
$restart = true; $restart = true;
} else if ( ! $user['MonitorIds'] ) { // Can only create new monitors if we are not restricted to specific monitors } else if ( ! $user['MonitorIds'] ) {
// Can only create new monitors if we are not restricted to specific monitors
# FIXME This is actually a race condition. Should lock the table. # FIXME This is actually a race condition. Should lock the table.
$maxSeq = dbFetchOne('SELECT MAX(Sequence) AS MaxSequence FROM Monitors', 'MaxSequence'); $maxSeq = dbFetchOne('SELECT MAX(Sequence) AS MaxSequence FROM Monitors', 'MaxSequence');
$changes[] = 'Sequence = '.($maxSeq+1); $changes[] = 'Sequence = '.($maxSeq+1);
if ( dbQuery( 'INSERT INTO Monitors SET '.implode( ', ', $changes ) ) ) { if ( dbQuery('INSERT INTO Monitors SET '.implode(', ', $changes)) ) {
$mid = dbInsertId(); $mid = dbInsertId();
$zoneArea = $_REQUEST['newMonitor']['Width'] * $_REQUEST['newMonitor']['Height']; $zoneArea = $_REQUEST['newMonitor']['Width'] * $_REQUEST['newMonitor']['Height'];
dbQuery( "insert into Zones set MonitorId = ?, Name = 'All', Type = 'Active', Units = 'Percent', NumCoords = 4, Coords = ?, Area=?, AlarmRGB = 0xff0000, CheckMethod = 'Blobs', MinPixelThreshold = 25, MinAlarmPixels=?, MaxAlarmPixels=?, FilterX = 3, FilterY = 3, MinFilterPixels=?, MaxFilterPixels=?, MinBlobPixels=?, MinBlobs = 1", array( $mid, sprintf( "%d,%d %d,%d %d,%d %d,%d", 0, 0, $_REQUEST['newMonitor']['Width']-1, 0, $_REQUEST['newMonitor']['Width']-1, $_REQUEST['newMonitor']['Height']-1, 0, $_REQUEST['newMonitor']['Height']-1 ), $zoneArea, intval(($zoneArea*3)/100), intval(($zoneArea*75)/100), intval(($zoneArea*3)/100), intval(($zoneArea*75)/100), intval(($zoneArea*2)/100) ) ); dbQuery("INSERT INTO Zones SET MonitorId = ?, Name = 'All', Type = 'Active', Units = 'Percent', NumCoords = 4, Coords = ?, Area=?, AlarmRGB = 0xff0000, CheckMethod = 'Blobs', MinPixelThreshold = 25, MinAlarmPixels=?, MaxAlarmPixels=?, FilterX = 3, FilterY = 3, MinFilterPixels=?, MaxFilterPixels=?, MinBlobPixels=?, MinBlobs = 1", array( $mid, sprintf( "%d,%d %d,%d %d,%d %d,%d", 0, 0, $_REQUEST['newMonitor']['Width']-1, 0, $_REQUEST['newMonitor']['Width']-1, $_REQUEST['newMonitor']['Height']-1, 0, $_REQUEST['newMonitor']['Height']-1 ), $zoneArea, intval(($zoneArea*3)/100), intval(($zoneArea*75)/100), intval(($zoneArea*3)/100), intval(($zoneArea*75)/100), intval(($zoneArea*2)/100) ) );
//$view = 'none'; //$view = 'none';
$Storage = new Storage( $_REQUEST['newMonitor']['StorageId'] ); $Storage = new Storage($_REQUEST['newMonitor']['StorageId']);
mkdir( $Storage->Path().'/'.$mid, 0755 ); mkdir($Storage->Path().'/'.$mid, 0755);
$saferName = basename($_REQUEST['newMonitor']['Name']); $saferName = basename($_REQUEST['newMonitor']['Name']);
symlink( $mid, $Storage->Path().'/'.$saferName ); symlink($mid, $Storage->Path().'/'.$saferName);
} else { } else {
Error("Error saving new Monitor."); Error('Error saving new Monitor.');
return; return;
} }
} else { } else {
Error("Users with Monitors restrictions cannot create new monitors."); Error('Users with Monitors restrictions cannot create new monitors.');
return; return;
} }
$restart = true; $restart = true;
} else { } else {
Logger::Debug("No action due to no changes to Monitor"); Logger::Debug('No action due to no changes to Monitor');
} # end if count(changes) } # end if count(changes)
if ( if (
@ -589,21 +596,21 @@ if ( canEdit( 'Monitors' ) ) {
} // end if there has been a change of groups } // end if there has been a change of groups
if ( ZM_OPT_X10 ) { if ( ZM_OPT_X10 ) {
$x10Changes = getFormChanges( $x10Monitor, $_REQUEST['newX10Monitor'] ); $x10Changes = getFormChanges($x10Monitor, $_REQUEST['newX10Monitor']);
if ( count( $x10Changes ) ) { if ( count($x10Changes) ) {
if ( $x10Monitor && isset($_REQUEST['newX10Monitor']) ) { if ( $x10Monitor && isset($_REQUEST['newX10Monitor']) ) {
dbQuery( 'update TriggersX10 set '.implode( ', ', $x10Changes ).' where MonitorId=?', array($mid) ); dbQuery('UPDATE TriggersX10 SET '.implode(', ', $x10Changes).' WHERE MonitorId=?', array($mid));
} elseif ( !$user['MonitorIds'] ) { } elseif ( !$user['MonitorIds'] ) {
if ( !$x10Monitor ) { if ( !$x10Monitor ) {
dbQuery( 'insert into TriggersX10 set MonitorId = ?, '.implode( ', ', $x10Changes ), array( $mid ) ); dbQuery('INSERT INTO TriggersX10 SET MonitorId = ?, '.implode(', ', $x10Changes), array($mid));
} else { } else {
dbQuery( 'delete from TriggersX10 where MonitorId = ?', array($mid) ); dbQuery('DELETE FROM TriggersX10 WHERE MonitorId = ?', array($mid));
} }
} }
$restart = true; $restart = true;
} } # end if has x10Changes
} } # end if ZM_OPT_X10
if ( $restart ) { if ( $restart ) {
@ -616,8 +623,8 @@ if ( canEdit( 'Monitors' ) ) {
} }
if ( $new_monitor->Controllable() ) { if ( $new_monitor->Controllable() ) {
require_once( 'control_functions.php' ); require_once('control_functions.php');
sendControlCommand( $mid, 'quit' ); sendControlCommand($mid, 'quit');
} }
// really should thump zmwatch and maybe zmtrigger too. // really should thump zmwatch and maybe zmtrigger too.
//daemonControl( 'restart', 'zmwatch.pl' ); //daemonControl( 'restart', 'zmwatch.pl' );
@ -626,11 +633,11 @@ if ( canEdit( 'Monitors' ) ) {
$view = 'none'; $view = 'none';
} elseif ( $action == 'delete' ) { } elseif ( $action == 'delete' ) {
if ( isset($_REQUEST['markMids']) && !$user['MonitorIds'] ) { if ( isset($_REQUEST['markMids']) && !$user['MonitorIds'] ) {
require_once( 'Monitor.php' ); require_once('Monitor.php');
foreach( $_REQUEST['markMids'] as $markMid ) { foreach ( $_REQUEST['markMids'] as $markMid ) {
if ( canEdit('Monitors', $markMid) ) { if ( canEdit('Monitors', $markMid) ) {
// This could be faster as a select all // This could be faster as a select all
if ( $monitor = dbFetchOne( 'SELECT * FROM Monitors WHERE Id = ?', NULL, array($markMid) ) ) { if ( $monitor = dbFetchOne('SELECT * FROM Monitors WHERE Id = ?', NULL, array($markMid)) ) {
$Monitor = new Monitor($monitor); $Monitor = new Monitor($monitor);
$Monitor->delete(); $Monitor->delete();
} // end if monitor found in db } // end if monitor found in db
@ -641,15 +648,17 @@ if ( canEdit( 'Monitors' ) ) {
} }
// Device view actions // Device view actions
if ( canEdit( 'Devices' ) ) { if ( canEdit('Devices') ) {
if ( $action == 'device' ) { if ( $action == 'device' ) {
if ( !empty($_REQUEST['command']) ) { if ( !empty($_REQUEST['command']) ) {
setDeviceStatusX10( $_REQUEST['key'], $_REQUEST['command'] ); setDeviceStatusX10($_REQUEST['key'], $_REQUEST['command']);
} elseif ( isset( $_REQUEST['newDevice'] ) ) { } else if ( isset($_REQUEST['newDevice']) ) {
if ( isset($_REQUEST['did']) ) { if ( isset($_REQUEST['did']) ) {
dbQuery( 'update Devices set Name=?, KeyString=? where Id=?', array($_REQUEST['newDevice']['Name'], $_REQUEST['newDevice']['KeyString'], $_REQUEST['did']) ); dbQuery('UPDATE Devices SET Name=?, KeyString=? WHERE Id=?',
array($_REQUEST['newDevice']['Name'], $_REQUEST['newDevice']['KeyString'], $_REQUEST['did']) );
} else { } else {
dbQuery( 'insert into Devices set Name=?, KeyString=?', array( $_REQUEST['newDevice']['Name'], $_REQUEST['newDevice']['KeyString'] ) ); dbQuery('INSERT INTO Devices SET Name=?, KeyString=?',
array($_REQUEST['newDevice']['Name'], $_REQUEST['newDevice']['KeyString']) );
} }
$refreshParent = true; $refreshParent = true;
$view = 'none'; $view = 'none';
@ -657,7 +666,7 @@ if ( canEdit( 'Devices' ) ) {
} elseif ( $action == 'delete' ) { } elseif ( $action == 'delete' ) {
if ( isset($_REQUEST['markDids']) ) { if ( isset($_REQUEST['markDids']) ) {
foreach( $_REQUEST['markDids'] as $markDid ) { foreach( $_REQUEST['markDids'] as $markDid ) {
dbQuery( 'delete from Devices where Id=?', array($markDid) ); dbQuery('DELETE FROM Devices WHERE Id=?', array($markDid));
$refreshParent = true; $refreshParent = true;
} }
} }
@ -665,47 +674,59 @@ if ( canEdit( 'Devices' ) ) {
} // end if canedit devices } // end if canedit devices
// Group view actions // Group view actions
if ( canView( 'Groups' ) && $action == 'setgroup' ) { if ( canView('Groups') && ($action == 'setgroup') ) {
if ( !empty($_REQUEST['gid']) ) { if ( !empty($_REQUEST['gid']) ) {
setcookie( 'zmGroup', validInt($_REQUEST['gid']), time()+3600*24*30*12*10 ); setcookie('zmGroup', validInt($_REQUEST['gid']), time()+3600*24*30*12*10);
} else { } else {
setcookie( 'zmGroup', '', time()-3600*24*2 ); setcookie('zmGroup', '', time()-3600*24*2);
} }
$refreshParent = true; $refreshParent = true;
} }
// Group edit actions // Group edit actions
# Should probably verify that each monitor id is a valid monitor, that we have access to. However at the moment, you have to have System permissions to do this # Should probably verify that each monitor id is a valid monitor, that we have access to.
if ( canEdit( 'Groups' ) ) { # However at the moment, you have to have System permissions to do this
if ( canEdit('Groups') ) {
if ( $action == 'group' ) { if ( $action == 'group' ) {
$monitors = empty( $_POST['newGroup']['MonitorIds'] ) ? '' : implode(',', $_POST['newGroup']['MonitorIds']); $monitors = empty($_POST['newGroup']['MonitorIds']) ? '' : implode(',', $_POST['newGroup']['MonitorIds']);
$group_id = null; $group_id = null;
if ( !empty($_POST['gid']) ) { if ( !empty($_POST['gid']) ) {
$group_id = $_POST['gid']; $group_id = $_POST['gid'];
dbQuery( 'UPDATE Groups SET Name=?, ParentId=? WHERE Id=?', dbQuery(
array($_POST['newGroup']['Name'], ( $_POST['newGroup']['ParentId'] == '' ? null : $_POST['newGroup']['ParentId'] ), $group_id) ); 'UPDATE Groups SET Name=?, ParentId=? WHERE Id=?',
dbQuery( 'DELETE FROM Groups_Monitors WHERE GroupId=?', array($group_id) ); array(
$_POST['newGroup']['Name'],
( $_POST['newGroup']['ParentId'] == '' ? null : $_POST['newGroup']['ParentId'] ),
$group_id,
)
);
dbQuery('DELETE FROM Groups_Monitors WHERE GroupId=?', array($group_id));
} else { } else {
dbQuery( 'INSERT INTO Groups (Name,ParentId) VALUES (?,?)', dbQuery(
array( $_POST['newGroup']['Name'], ( $_POST['newGroup']['ParentId'] == '' ? null : $_POST['newGroup']['ParentId'] ) ) ); 'INSERT INTO Groups (Name,ParentId) VALUES (?,?)',
$group_id=dbInsertId(); array(
$_POST['newGroup']['Name'],
( $_POST['newGroup']['ParentId'] == '' ? null : $_POST['newGroup']['ParentId'] ),
)
);
$group_id = dbInsertId();
} }
if ( $group_id ) { if ( $group_id ) {
foreach ( $_POST['newGroup']['MonitorIds'] as $mid ) { foreach ( $_POST['newGroup']['MonitorIds'] as $mid ) {
dbQuery( 'INSERT INTO Groups_Monitors (GroupId,MonitorId) VALUES (?,?)', array($group_id, $mid) ); dbQuery('INSERT INTO Groups_Monitors (GroupId,MonitorId) VALUES (?,?)', array($group_id, $mid));
} }
} }
$view = 'none'; $view = 'none';
$refreshParent = true; $refreshParent = true;
} else if ( $action == 'delete' ) { } else if ( $action == 'delete' ) {
if ( !empty($_REQUEST['gid']) ) { if ( !empty($_REQUEST['gid']) ) {
if ( is_array( $_REQUEST['gid'] ) ) { if ( is_array($_REQUEST['gid']) ) {
foreach( $_REQUEST['gid'] as $gid ) { foreach ( $_REQUEST['gid'] as $gid ) {
$Group = new Group( $gid ); $Group = new Group($gid);
$Group->delete(); $Group->delete();
} }
} else { } else {
$Group = new Group( $_REQUEST['gid'] ); $Group = new Group($_REQUEST['gid'] );
$Group->delete(); $Group->delete();
} }
} }
@ -714,23 +735,23 @@ if ( canEdit( 'Groups' ) ) {
} // end if can edit groups } // end if can edit groups
// System edit actions // System edit actions
if ( canEdit( 'System' ) ) { if ( canEdit('System') ) {
if ( isset( $_REQUEST['object'] ) ) { if ( isset($_REQUEST['object']) ) {
if ( $_REQUEST['object'] == 'MontageLayout' ) { if ( $_REQUEST['object'] == 'MontageLayout' ) {
require_once('MontageLayout.php'); require_once('MontageLayout.php');
if ( $action == 'Save' ) { if ( $action == 'Save' ) {
$Layout = null; $Layout = null;
if ( $_REQUEST['Name'] != '' ) { if ( $_REQUEST['Name'] != '' ) {
$Layout = new MontageLayout(); $Layout = new MontageLayout();
$Layout->Name( $_REQUEST['Name'] ); $Layout->Name($_REQUEST['Name']);
} else { } else {
$Layout = new MontageLayout( $_REQUEST['zmMontageLayout'] ); $Layout = new MontageLayout($_REQUEST['zmMontageLayout']);
} }
$Layout->Positions( $_REQUEST['Positions'] ); $Layout->Positions($_REQUEST['Positions']);
$Layout->save(); $Layout->save();
session_start(); session_start();
$_SESSION['zmMontageLayout'] = $Layout->Id(); $_SESSION['zmMontageLayout'] = $Layout->Id();
setcookie('zmMontageLayout', $Layout->Id(), 1 ); setcookie('zmMontageLayout', $Layout->Id(), 1);
session_write_close(); session_write_close();
$redirect = ZM_BASE_URL.$_SERVER['PHP_SELF'].'?view=montage'; $redirect = ZM_BASE_URL.$_SERVER['PHP_SELF'].'?view=montage';
} // end if save } // end if save
@ -738,19 +759,24 @@ if ( canEdit( 'System' ) ) {
} else if ( $_REQUEST['object'] == 'server' ) { } else if ( $_REQUEST['object'] == 'server' ) {
if ( $action == 'Save' ) { if ( $action == 'Save' ) {
if ( !empty($_REQUEST['id']) ) if ( !empty($_REQUEST['id']) ) {
$dbServer = dbFetchOne( 'SELECT * FROM Servers WHERE Id=?', NULL, array($_REQUEST['id']) ); $dbServer = dbFetchOne(
else 'SELECT * FROM Servers WHERE Id=?',
NULL,
array($_REQUEST['id']) );
} else {
$dbServer = array(); $dbServer = array();
}
$types = array(); $types = array();
$changes = getFormChanges( $dbServer, $_REQUEST['newServer'], $types ); $changes = getFormChanges($dbServer, $_REQUEST['newServer'], $types);
if ( count( $changes ) ) { if ( count($changes) ) {
if ( !empty($_REQUEST['id']) ) { if ( !empty($_REQUEST['id']) ) {
dbQuery( 'UPDATE Servers SET '.implode( ', ', $changes ).' WHERE Id = ?', array($_REQUEST['id']) ); dbQuery('UPDATE Servers SET '.implode(', ', $changes).' WHERE Id = ?',
array($_REQUEST['id']) );
} else { } else {
dbQuery( 'INSERT INTO Servers set '.implode( ', ', $changes ) ); dbQuery('INSERT INTO Servers SET '.implode(', ', $changes));
} }
$refreshParent = true; $refreshParent = true;
} }
@ -758,27 +784,27 @@ if ( canEdit( 'System' ) ) {
} else if ( $action == 'delete' ) { } else if ( $action == 'delete' ) {
if ( !empty($_REQUEST['markIds']) ) { if ( !empty($_REQUEST['markIds']) ) {
foreach( $_REQUEST['markIds'] as $Id ) foreach( $_REQUEST['markIds'] as $Id )
dbQuery( 'DELETE FROM Servers WHERE Id=?', array($Id) ); dbQuery('DELETE FROM Servers WHERE Id=?', array($Id));
} }
$refreshParent = true; $refreshParent = true;
} else { } else {
Error( "Unknown action $action in saving Server" ); Error("Unknown action $action in saving Server");
} }
} else if ( $_REQUEST['object'] == 'storage' ) { } else if ( $_REQUEST['object'] == 'storage' ) {
if ( $action == 'Save' ) { if ( $action == 'Save' ) {
if ( !empty($_REQUEST['id']) ) if ( !empty($_REQUEST['id']) )
$dbStorage = dbFetchOne( 'SELECT * FROM Storage WHERE Id=?', NULL, array($_REQUEST['id']) ); $dbStorage = dbFetchOne('SELECT * FROM Storage WHERE Id=?', NULL, array($_REQUEST['id']));
else else
$dbStorage = array(); $dbStorage = array();
$types = array(); $types = array();
$changes = getFormChanges( $dbStorage, $_REQUEST['newStorage'], $types ); $changes = getFormChanges($dbStorage, $_REQUEST['newStorage'], $types);
if ( count( $changes ) ) { if ( count($changes) ) {
if ( !empty($_REQUEST['id']) ) { if ( !empty($_REQUEST['id']) ) {
dbQuery( 'UPDATE Storage SET '.implode( ', ', $changes ).' WHERE Id = ?', array($_REQUEST['id']) ); dbQuery('UPDATE Storage SET '.implode(', ', $changes).' WHERE Id = ?', array($_REQUEST['id']));
} else { } else {
dbQuery( 'INSERT INTO Storage set '.implode( ', ', $changes ) ); dbQuery('INSERT INTO Storage set '.implode(', ', $changes));
} }
$refreshParent = true; $refreshParent = true;
} }
@ -786,11 +812,11 @@ if ( canEdit( 'System' ) ) {
} else if ( $action == 'delete' ) { } else if ( $action == 'delete' ) {
if ( !empty($_REQUEST['markIds']) ) { if ( !empty($_REQUEST['markIds']) ) {
foreach( $_REQUEST['markIds'] as $Id ) foreach( $_REQUEST['markIds'] as $Id )
dbQuery( 'DELETE FROM Storage WHERE Id=?', array($Id) ); dbQuery('DELETE FROM Storage WHERE Id=?', array($Id));
} }
$refreshParent = true; $refreshParent = true;
} else { } else {
Error( "Unknown action $action in saving Storage" ); Error("Unknown action $action in saving Storage");
} }
} # end if isset($_REQUEST['object'] ) } # end if isset($_REQUEST['object'] )
@ -804,7 +830,7 @@ if ( canEdit( 'System' ) ) {
} }
case 'ignore' : case 'ignore' :
{ {
dbQuery( "update Config set Value = '".ZM_DYN_LAST_VERSION."' where Name = 'ZM_DYN_CURR_VERSION'" ); dbQuery("UPDATE Config SET Value = '".ZM_DYN_LAST_VERSION."' WHERE Name = 'ZM_DYN_CURR_VERSION'");
break; break;
} }
case 'hour' : case 'hour' :
@ -819,12 +845,12 @@ if ( canEdit( 'System' ) ) {
} elseif ( $option == 'week' ) { } elseif ( $option == 'week' ) {
$nextReminder += 7*24*60*60; $nextReminder += 7*24*60*60;
} }
dbQuery( "update Config set Value = '".$nextReminder."' where Name = 'ZM_DYN_NEXT_REMINDER'" ); dbQuery("UPDATE Config SET Value = '".$nextReminder."' WHERE Name = 'ZM_DYN_NEXT_REMINDER'");
break; break;
} }
case 'never' : case 'never' :
{ {
dbQuery( "update Config set Value = '0' where Name = 'ZM_CHECK_FOR_UPDATES'" ); dbQuery("UPDATE Config SET Value = '0' WHERE Name = 'ZM_CHECK_FOR_UPDATES'");
break; break;
} }
} }
@ -852,53 +878,51 @@ if ( canEdit( 'System' ) ) {
} elseif ( $option == 'month' ) { } elseif ( $option == 'month' ) {
$nextReminder += 30*24*60*60; $nextReminder += 30*24*60*60;
} }
dbQuery( "update Config set Value = '".$nextReminder."' where Name = 'ZM_DYN_DONATE_REMINDER_TIME'" ); dbQuery("UPDATE Config SET Value = '".$nextReminder."' WHERE Name = 'ZM_DYN_DONATE_REMINDER_TIME'");
break; break;
} }
case 'never' : case 'never' :
case 'already' : case 'already' :
{ {
dbQuery( "update Config set Value = '0' where Name = 'ZM_DYN_SHOW_DONATE_REMINDER'" ); dbQuery("UPDATE Config SET Value = '0' WHERE Name = 'ZM_DYN_SHOW_DONATE_REMINDER'");
break; break;
} }
} // end switch option } // end switch option
} }
if ( $action == 'privacy' && isset($_REQUEST['option'] ) ) { if ( ($action == 'privacy') && isset($_REQUEST['option']) ) {
$option = $_REQUEST['option']; switch( $_REQUEST['option'] ) {
switch( $option ) {
case 'decline' : case 'decline' :
{ {
dbQuery( "update Config set Value = '0' where Name = 'ZM_SHOW_PRIVACY'" ); dbQuery("UPDATE Config SET Value = '0' WHERE Name = 'ZM_SHOW_PRIVACY'");
dbQuery( "update Config set Value = '0' where Name = 'ZM_TELEMETRY_DATA'" ); dbQuery("UPDATE Config SET Value = '0' WHERE Name = 'ZM_TELEMETRY_DATA'");
$view = 'console';
$redirect = ZM_BASE_URL.$_SERVER['PHP_SELF'].'?view=console'; $redirect = ZM_BASE_URL.$_SERVER['PHP_SELF'].'?view=console';
break; break;
} }
case 'accept' : case 'accept' :
{ {
dbQuery( "update Config set Value = '0' where Name = 'ZM_SHOW_PRIVACY'" ); dbQuery("UPDATE Config SET Value = '0' WHERE Name = 'ZM_SHOW_PRIVACY'");
dbQuery( "update Config set Value = '1' where Name = 'ZM_TELEMETRY_DATA'" ); dbQuery("UPDATE Config SET Value = '1' WHERE Name = 'ZM_TELEMETRY_DATA'");
$view = 'console';
$redirect = ZM_BASE_URL.$_SERVER['PHP_SELF'].'?view=console'; $redirect = ZM_BASE_URL.$_SERVER['PHP_SELF'].'?view=console';
break; break;
} }
default: # Enable the privacy statement if we somehow submit something other than accept or decline default: # Enable the privacy statement if we somehow submit something other than accept or decline
dbQuery( "update Config set Value = '1' where Name = 'ZM_SHOW_PRIVACY'" ); dbQuery("UPDATE Config SET Value = '1' WHERE Name = 'ZM_SHOW_PRIVACY'");
} // end switch option } // end switch option
return;
} }
if ( $action == 'options' && isset($_REQUEST['tab']) ) { if ( $action == 'options' && isset($_REQUEST['tab']) ) {
$configCat = $configCats[$_REQUEST['tab']]; $configCat = $configCats[$_REQUEST['tab']];
$changed = false; $changed = false;
foreach ( $configCat as $name=>$value ) { foreach ( $configCat as $name=>$value ) {
unset( $newValue ); unset($newValue);
if ( $value['Type'] == 'boolean' && empty($_REQUEST['newConfig'][$name]) ) { if ( $value['Type'] == 'boolean' && empty($_REQUEST['newConfig'][$name]) ) {
$newValue = 0; $newValue = 0;
} else if ( isset($_REQUEST['newConfig'][$name]) ) { } else if ( isset($_REQUEST['newConfig'][$name]) ) {
$newValue = preg_replace( "/\r\n/", "\n", stripslashes( $_REQUEST['newConfig'][$name] ) ); $newValue = preg_replace("/\r\n/", "\n", stripslashes($_REQUEST['newConfig'][$name]));
} }
if ( isset($newValue) && ($newValue != $value['Value']) ) { if ( isset($newValue) && ($newValue != $value['Value']) ) {
dbQuery( 'UPDATE Config SET Value=? WHERE Name=?', array( $newValue, $name ) ); dbQuery('UPDATE Config SET Value=? WHERE Name=?', array($newValue, $name));
$changed = true; $changed = true;
} }
} }
@ -924,29 +948,30 @@ if ( canEdit( 'System' ) ) {
} }
$redirect = ZM_BASE_URL.$_SERVER['PHP_SELF'].'?view=options&tab='.$_REQUEST['tab']; $redirect = ZM_BASE_URL.$_SERVER['PHP_SELF'].'?view=options&tab='.$_REQUEST['tab'];
} }
loadConfig( false ); loadConfig(false);
return;
} elseif ( $action == 'user' ) { } elseif ( $action == 'user' ) {
if ( !empty($_REQUEST['uid']) ) if ( !empty($_REQUEST['uid']) )
$dbUser = dbFetchOne( "SELECT * FROM Users WHERE Id=?", NULL, array($_REQUEST['uid']) ); $dbUser = dbFetchOne('SELECT * FROM Users WHERE Id=?', NULL, array($_REQUEST['uid']));
else else
$dbUser = array(); $dbUser = array();
$types = array(); $types = array();
$changes = getFormChanges( $dbUser, $_REQUEST['newUser'], $types ); $changes = getFormChanges($dbUser, $_REQUEST['newUser'], $types);
if ( $_REQUEST['newUser']['Password'] ) if ( $_REQUEST['newUser']['Password'] )
$changes['Password'] = 'Password = password('.dbEscape($_REQUEST['newUser']['Password']).')'; $changes['Password'] = 'Password = password('.dbEscape($_REQUEST['newUser']['Password']).')';
else else
unset( $changes['Password'] ); unset($changes['Password']);
if ( count( $changes ) ) { if ( count($changes) ) {
if ( !empty($_REQUEST['uid']) ) { if ( !empty($_REQUEST['uid']) ) {
dbQuery( 'update Users set '.implode( ', ', $changes ).' where Id = ?', array($_REQUEST['uid']) ); dbQuery('UPDATE Users SET '.implode(', ', $changes).' WHERE Id = ?', array($_REQUEST['uid']));
# If we are updating the logged in user, then update our session user data. # If we are updating the logged in user, then update our session user data.
if ( $user and ( $dbUser['Username'] == $user['Username'] ) ) if ( $user and ( $dbUser['Username'] == $user['Username'] ) )
userLogin( $dbUser['Username'], $dbUser['Password'] ); userLogin($dbUser['Username'], $dbUser['Password']);
} else { } else {
dbQuery( 'insert into Users set '.implode( ', ', $changes ) ); dbQuery('INSERT INTO Users SET '.implode(', ', $changes));
} }
$refreshParent = true; $refreshParent = true;
} }
@ -954,29 +979,28 @@ if ( canEdit( 'System' ) ) {
} elseif ( $action == 'state' ) { } elseif ( $action == 'state' ) {
if ( !empty($_REQUEST['runState']) ) { if ( !empty($_REQUEST['runState']) ) {
//if ( $cookies ) session_write_close(); //if ( $cookies ) session_write_close();
packageControl( $_REQUEST['runState'] ); packageControl($_REQUEST['runState']);
$refreshParent = true; $refreshParent = true;
} }
} elseif ( $action == 'save' ) { } elseif ( $action == 'save' ) {
if ( !empty($_REQUEST['runState']) || !empty($_REQUEST['newState']) ) { if ( !empty($_REQUEST['runState']) || !empty($_REQUEST['newState']) ) {
$sql = 'SELECT Id,Function,Enabled FROM Monitors ORDER BY Id'; $sql = 'SELECT Id,Function,Enabled FROM Monitors ORDER BY Id';
$definitions = array(); $definitions = array();
foreach( dbFetchAll( $sql ) as $monitor ) foreach( dbFetchAll($sql) as $monitor ) {
{
$definitions[] = $monitor['Id'].':'.$monitor['Function'].':'.$monitor['Enabled']; $definitions[] = $monitor['Id'].':'.$monitor['Function'].':'.$monitor['Enabled'];
} }
$definition = join( ',', $definitions ); $definition = join(',', $definitions);
if ( $_REQUEST['newState'] ) if ( $_REQUEST['newState'] )
$_REQUEST['runState'] = $_REQUEST['newState']; $_REQUEST['runState'] = $_REQUEST['newState'];
dbQuery( 'replace into States set Name=?, Definition=?', array( $_REQUEST['runState'],$definition) ); dbQuery('REPLACE INTO States SET Name=?, Definition=?', array($_REQUEST['runState'],$definition));
} }
} elseif ( $action == 'delete' ) { } elseif ( $action == 'delete' ) {
if ( isset($_REQUEST['runState']) ) if ( isset($_REQUEST['runState']) )
dbQuery( 'delete from States where Name=?', array($_REQUEST['runState']) ); dbQuery('DELETE FROM States WHERE Name=?', array($_REQUEST['runState']));
if ( isset($_REQUEST['markUids']) ) { if ( isset($_REQUEST['markUids']) ) {
foreach( $_REQUEST['markUids'] as $markUid ) foreach( $_REQUEST['markUids'] as $markUid )
dbQuery( 'delete from Users where Id = ?', array($markUid) ); dbQuery('DELETE FROM Users WHERE Id = ?', array($markUid));
if ( $markUid == $user['Id'] ) if ( $markUid == $user['Id'] )
userLogout(); userLogout();
} }
@ -985,17 +1009,17 @@ if ( canEdit( 'System' ) ) {
if ( ZM_USER_SELF_EDIT && $action == 'user' ) { if ( ZM_USER_SELF_EDIT && $action == 'user' ) {
$uid = $user['Id']; $uid = $user['Id'];
$dbUser = dbFetchOne( 'SELECT Id, Password, Language FROM Users WHERE Id = ?', NULL, array($uid) ); $dbUser = dbFetchOne('SELECT Id, Password, Language FROM Users WHERE Id = ?', NULL, array($uid));
$types = array(); $types = array();
$changes = getFormChanges( $dbUser, $_REQUEST['newUser'], $types ); $changes = getFormChanges($dbUser, $_REQUEST['newUser'], $types);
if ( !empty($_REQUEST['newUser']['Password']) ) if ( !empty($_REQUEST['newUser']['Password']) )
$changes['Password'] = 'Password = password('.dbEscape($_REQUEST['newUser']['Password']).')'; $changes['Password'] = 'Password = password('.dbEscape($_REQUEST['newUser']['Password']).')';
else else
unset( $changes['Password'] ); unset($changes['Password']);
if ( count( $changes ) ) { if ( count($changes) ) {
dbQuery( 'update Users set '.implode( ', ', $changes ).' where Id=?', array($uid) ); dbQuery('UPDATE Users SET '.implode(', ', $changes).' WHERE Id=?', array($uid));
$refreshParent = true; $refreshParent = true;
} }
$view = 'none'; $view = 'none';
@ -1004,8 +1028,8 @@ if ( canEdit( 'System' ) ) {
if ( $action == 'reset' ) { if ( $action == 'reset' ) {
session_start(); session_start();
$_SESSION['zmEventResetTime'] = strftime( STRF_FMT_DATETIME_DB ); $_SESSION['zmEventResetTime'] = strftime(STRF_FMT_DATETIME_DB);
setcookie( 'zmEventResetTime', $_SESSION['zmEventResetTime'], time()+3600*24*30*12*10 ); setcookie('zmEventResetTime', $_SESSION['zmEventResetTime'], time()+3600*24*30*12*10);
session_write_close(); session_write_close();
} }

View File

@ -139,9 +139,9 @@ function dbQuery( $sql, $params=NULL ) {
} }
if ( defined('ZM_DB_DEBUG') ) { if ( defined('ZM_DB_DEBUG') ) {
if ( $params ) if ( $params )
Warning("SQL: $sql" . implode(',',$params) . ' rows: '.$result->rowCount() ); Logger::Debug("SQL: $sql" . implode(',',$params) . ' rows: '.$result->rowCount() );
else else
Warning("SQL: $sql: rows:" . $result->rowCount() ); Logger::Debug("SQL: $sql: rows:" . $result->rowCount() );
} }
} catch(PDOException $e) { } catch(PDOException $e) {
Error( "SQL-ERR '".$e->getMessage()."', statement was '".$sql."' params:" . ($params?implode(',',$params):'') ); Error( "SQL-ERR '".$e->getMessage()."', statement was '".$sql."' params:" . ($params?implode(',',$params):'') );

View File

@ -18,17 +18,17 @@
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
// //
error_reporting( E_ALL ); error_reporting(E_ALL);
$debug = false; $debug = false;
if ( $debug ) { if ( $debug ) {
// Use these for debugging, though not both at once! // Use these for debugging, though not both at once!
phpinfo( INFO_VARIABLES ); phpinfo(INFO_VARIABLES);
//error_reporting( E_ALL ); //error_reporting( E_ALL );
} }
// Use new style autoglobals where possible // Use new style autoglobals where possible
if ( version_compare( phpversion(), '4.1.0', '<') ) { if ( version_compare(phpversion(), '4.1.0', '<') ) {
$_SESSION = &$HTTP_SESSION_VARS; $_SESSION = &$HTTP_SESSION_VARS;
$_SERVER = &$HTTP_SERVER_VARS; $_SERVER = &$HTTP_SERVER_VARS;
} }
@ -36,20 +36,20 @@ if ( version_compare( phpversion(), '4.1.0', '<') ) {
// Useful debugging lines for mobile devices // Useful debugging lines for mobile devices
if ( false ) { if ( false ) {
ob_start(); ob_start();
phpinfo( INFO_VARIABLES ); phpinfo(INFO_VARIABLES);
$fp = fopen( '/tmp/env.html', 'w' ); $fp = fopen('/tmp/env.html', 'w');
fwrite( $fp, ob_get_contents() ); fwrite($fp, ob_get_contents());
fclose( $fp ); fclose($fp);
ob_end_clean(); ob_end_clean();
} }
require_once( 'includes/config.php' ); require_once('includes/config.php');
require_once( 'includes/logger.php' ); require_once('includes/logger.php');
require_once( 'includes/Server.php' ); require_once('includes/Server.php');
require_once( 'includes/Storage.php' ); require_once('includes/Storage.php');
require_once( 'includes/Event.php' ); require_once('includes/Event.php');
require_once( 'includes/Group.php' ); require_once('includes/Group.php');
require_once( 'includes/Monitor.php' ); require_once('includes/Monitor.php');
if ( if (
@ -61,13 +61,13 @@ if (
} else { } else {
$protocol = 'http'; $protocol = 'http';
} }
define( 'ZM_BASE_PROTOCOL', $protocol ); define('ZM_BASE_PROTOCOL', $protocol);
// Absolute URL's are unnecessary and break compatibility with reverse proxies // Absolute URL's are unnecessary and break compatibility with reverse proxies
// define( "ZM_BASE_URL", $protocol.'://'.$_SERVER['HTTP_HOST'] ); // define( "ZM_BASE_URL", $protocol.'://'.$_SERVER['HTTP_HOST'] );
// Use relative URL's instead // Use relative URL's instead
define( 'ZM_BASE_URL', '' ); define('ZM_BASE_URL', '');
// Check time zone is set // Check time zone is set
if (!ini_get('date.timezone') || !date_default_timezone_set(ini_get('date.timezone'))) { if (!ini_get('date.timezone') || !date_default_timezone_set(ini_get('date.timezone'))) {
@ -85,10 +85,10 @@ if ( isset($_GET['skin']) ) {
$skin = 'classic'; $skin = 'classic';
} }
$skins = array_map( 'basename', glob('skins/*', GLOB_ONLYDIR ) ); $skins = array_map('basename', glob('skins/*', GLOB_ONLYDIR));
if ( ! in_array( $skin, $skins ) ) { if ( ! in_array($skin, $skins) ) {
Error( "Invalid skin '$skin' setting to " . $skins[0] ); Error("Invalid skin '$skin' setting to " . $skins[0]);
$skin = $skins[0]; $skin = $skins[0];
} }
@ -96,25 +96,25 @@ if ( isset($_GET['css']) ) {
$css = $_GET['css']; $css = $_GET['css'];
} elseif ( isset($_COOKIE['zmCSS']) ) { } elseif ( isset($_COOKIE['zmCSS']) ) {
$css = $_COOKIE['zmCSS']; $css = $_COOKIE['zmCSS'];
} elseif (defined('ZM_CSS_DEFAULT')) { } elseif ( defined('ZM_CSS_DEFAULT') ) {
$css = ZM_CSS_DEFAULT; $css = ZM_CSS_DEFAULT;
} else { } else {
$css = 'classic'; $css = 'classic';
} }
$css_skins = array_map( 'basename', glob('skins/'.$skin.'/css/*',GLOB_ONLYDIR) ); $css_skins = array_map('basename', glob('skins/'.$skin.'/css/*',GLOB_ONLYDIR));
if ( ! in_array( $css, $css_skins ) ) { if ( !in_array($css, $css_skins) ) {
Error( "Invalid skin css '$css' setting to " . $css_skins[0] ); Error("Invalid skin css '$css' setting to " . $css_skins[0]);
$css = $css_skins[0]; $css = $css_skins[0];
} }
define( 'ZM_BASE_PATH', dirname( $_SERVER['REQUEST_URI'] ) ); define('ZM_BASE_PATH', dirname($_SERVER['REQUEST_URI']));
define( 'ZM_SKIN_PATH', "skins/$skin" ); define('ZM_SKIN_PATH', "skins/$skin");
define( 'ZM_SKIN_NAME', $skin ); define('ZM_SKIN_NAME', $skin);
$skinBase = array(); // To allow for inheritance of skins $skinBase = array(); // To allow for inheritance of skins
if ( !file_exists( ZM_SKIN_PATH ) ) if ( !file_exists(ZM_SKIN_PATH) )
Fatal( "Invalid skin '$skin'" ); Fatal("Invalid skin '$skin'");
$skinBase[] = $skin; $skinBase[] = $skin;
$currentCookieParams = session_get_cookie_params(); $currentCookieParams = session_get_cookie_params();
@ -127,25 +127,25 @@ session_set_cookie_params(
true true
); );
ini_set( 'session.name', 'ZMSESSID' ); ini_set('session.name', 'ZMSESSID');
session_start(); session_start();
if ( !isset($_SESSION['skin']) || isset($_REQUEST['skin']) || !isset($_COOKIE['zmSkin']) || $_COOKIE['zmSkin'] != $skin ) { if ( !isset($_SESSION['skin']) || isset($_REQUEST['skin']) || !isset($_COOKIE['zmSkin']) || $_COOKIE['zmSkin'] != $skin ) {
$_SESSION['skin'] = $skin; $_SESSION['skin'] = $skin;
setcookie( 'zmSkin', $skin, time()+3600*24*30*12*10 ); setcookie('zmSkin', $skin, time()+3600*24*30*12*10);
} }
if ( !isset($_SESSION['css']) || isset($_REQUEST['css']) || !isset($_COOKIE['zmCSS']) || $_COOKIE['zmCSS'] != $css ) { if ( !isset($_SESSION['css']) || isset($_REQUEST['css']) || !isset($_COOKIE['zmCSS']) || $_COOKIE['zmCSS'] != $css ) {
$_SESSION['css'] = $css; $_SESSION['css'] = $css;
setcookie( 'zmCSS', $css, time()+3600*24*30*12*10 ); setcookie('zmCSS', $css, time()+3600*24*30*12*10);
} }
if ( ZM_OPT_USE_AUTH ) { if ( ZM_OPT_USE_AUTH ) {
if ( isset( $_SESSION['user'] ) ) { if ( isset($_SESSION['user']) ) {
$user = $_SESSION['user']; $user = $_SESSION['user'];
} else { } else {
unset( $user ); unset($user);
} }
} else { } else {
$user = $defaultUser; $user = $defaultUser;
@ -154,9 +154,9 @@ if ( ZM_OPT_USE_AUTH ) {
# Any file/page that sets session variables must re-open it. # Any file/page that sets session variables must re-open it.
session_write_close(); session_write_close();
require_once( 'includes/lang.php' ); require_once('includes/lang.php');
require_once( 'includes/functions.php' ); require_once('includes/functions.php');
require_once( 'includes/auth.php' ); require_once('includes/auth.php');
# Running is global but only do the daemonCheck if it is actually needed # Running is global but only do the daemonCheck if it is actually needed
$running = null; $running = null;
@ -179,20 +179,20 @@ $request = null;
if ( isset($_REQUEST['request']) ) if ( isset($_REQUEST['request']) )
$request = detaintPath($_REQUEST['request']); $request = detaintPath($_REQUEST['request']);
foreach ( getSkinIncludes( 'skin.php' ) as $includeFile ) foreach ( getSkinIncludes('skin.php') as $includeFile )
require_once $includeFile; require_once $includeFile;
if ( ZM_OPT_USE_AUTH ) { if ( ZM_OPT_USE_AUTH ) {
if ( ZM_AUTH_HASH_LOGINS ) { if ( ZM_AUTH_HASH_LOGINS ) {
if ( empty($user) && ! empty($_REQUEST['auth']) ) { if ( empty($user) && ! empty($_REQUEST['auth']) ) {
if ( $authUser = getAuthUser( $_REQUEST['auth'] ) ) { if ( $authUser = getAuthUser($_REQUEST['auth']) ) {
userLogin( $authUser['Username'], $authUser['Password'], true ); userLogin($authUser['Username'], $authUser['Password'], true);
} }
} }
} }
if ( ! empty($user) ) { if ( !empty($user) ) {
// generate it once here, while session is open. Value will be cached in session and return when called later on // generate it once here, while session is open. Value will be cached in session and return when called later on
generateAuthHash( ZM_AUTH_HASH_IPS ); generateAuthHash(ZM_AUTH_HASH_IPS);
} }
} }
@ -205,24 +205,31 @@ isset($view) || $view = NULL;
isset($request) || $request = NULL; isset($request) || $request = NULL;
isset($action) || $action = NULL; isset($action) || $action = NULL;
if ( ZM_ENABLE_CSRF_MAGIC && $action != 'login' && $view != 'view_video' && $request != 'control' && $view != 'frames' && $view != 'archive' ) { Logger::Debug("View: $view Request: $request Action: $action");
if (
ZM_ENABLE_CSRF_MAGIC &&
( $action != 'login' ) &&
( $view != 'view_video' ) &&
( $view != 'image' ) &&
( $request != 'control' ) &&
( $view != 'frames' ) &&
( $view != 'archive' )
) {
require_once( 'includes/csrf/csrf-magic.php' ); require_once( 'includes/csrf/csrf-magic.php' );
#Logger::Debug("Calling csrf_check with the following values: \$request = \"$request\", \$view = \"$view\", \$action = \"$action\""); #Logger::Debug("Calling csrf_check with the following values: \$request = \"$request\", \$view = \"$view\", \$action = \"$action\"");
csrf_check(); csrf_check();
} }
# Need to include actions because it does auth # Need to include actions because it does auth
require_once( 'includes/actions.php' ); require_once('includes/actions.php');
# If I put this here, it protects all views and popups, but it has to go after actions.php because actions.php does the actual logging in. # If I put this here, it protects all views and popups, but it has to go after actions.php because actions.php does the actual logging in.
if ( ZM_OPT_USE_AUTH and ! isset($user) ) { if ( ZM_OPT_USE_AUTH and !isset($user) ) {
Logger::Debug("Redirecting to login" ); Logger::Debug('Redirecting to login');
$view = 'login'; $view = 'login';
$request = null; $request = null;
} } else if ( ZM_SHOW_PRIVACY && ($action != 'privacy') && ($view !='options') && (!$request) && canEdit('System') ) {
Logger::Debug('Redirecting to privacy');
if ( ZM_SHOW_PRIVACY && canEdit('System') ) {
Logger::Debug("Redirecting to privacy" );
$view = 'privacy'; $view = 'privacy';
$request = null; $request = null;
} }
@ -233,17 +240,17 @@ if ( $redirect ) {
} }
if ( $request ) { if ( $request ) {
foreach ( getSkinIncludes( 'ajax/'.$request.'.php', true, true ) as $includeFile ) { foreach ( getSkinIncludes('ajax/'.$request.'.php', true, true) as $includeFile ) {
if ( !file_exists( $includeFile ) ) if ( !file_exists($includeFile) )
Fatal( "Request '$request' does not exist" ); Fatal("Request '$request' does not exist");
require_once $includeFile; require_once $includeFile;
} }
return; return;
} else { } else {
if ( $includeFiles = getSkinIncludes( 'views/'.$view.'.php', true, true ) ) { if ( $includeFiles = getSkinIncludes('views/'.$view.'.php', true, true) ) {
foreach ( $includeFiles as $includeFile ) { foreach ( $includeFiles as $includeFile ) {
if ( !file_exists( $includeFile ) ) if ( !file_exists($includeFile) )
Fatal( "View '$view' does not exist" ); Fatal("View '$view' does not exist");
require_once $includeFile; require_once $includeFile;
} }
// If the view overrides $view to 'error', and the user is not logged in, then the // If the view overrides $view to 'error', and the user is not logged in, then the
@ -251,14 +258,14 @@ if ( $request ) {
// The login view should handle redirecting to the correct location afterward. // The login view should handle redirecting to the correct location afterward.
if ( $view == 'error' && !isset($user) ) { if ( $view == 'error' && !isset($user) ) {
$view = 'login'; $view = 'login';
foreach ( getSkinIncludes( 'views/login.php', true, true ) as $includeFile ) foreach ( getSkinIncludes('views/login.php', true, true) as $includeFile )
require_once $includeFile; require_once $includeFile;
} }
} }
// If the view is missing or the view still returned error with the user logged in, // If the view is missing or the view still returned error with the user logged in,
// then it is not recoverable. // then it is not recoverable.
if ( !$includeFiles || $view == 'error' ) { if ( !$includeFiles || $view == 'error' ) {
foreach ( getSkinIncludes( 'views/error.php', true, true ) as $includeFile ) foreach ( getSkinIncludes('views/error.php', true, true) as $includeFile )
require_once $includeFile; require_once $includeFile;
} }
} }

View File

@ -180,7 +180,7 @@ function changeScale() {
function changeReplayMode() { function changeReplayMode() {
var replayMode = $('replayMode').get('value'); var replayMode = $('replayMode').get('value');
Cookie.write( 'replayMode', replayMode, { duration: 10*365 }); Cookie.write('replayMode', replayMode, { duration: 10*365 });
refreshWindow(); refreshWindow();
} }
@ -195,6 +195,8 @@ var zmsBroke = false; //Use alternate navigation if zms has crashed
function getCmdResponse( respObj, respText ) { function getCmdResponse( respObj, respText ) {
if ( checkStreamForErrors( "getCmdResponse", respObj ) ) { if ( checkStreamForErrors( "getCmdResponse", respObj ) ) {
console.log('Got an error from getCmdResponse'); console.log('Got an error from getCmdResponse');
console.log(respObj);
console.log(respText);
zmsBroke = true; zmsBroke = true;
return; return;
} }
@ -202,18 +204,24 @@ function getCmdResponse( respObj, respText ) {
zmsBroke = false; zmsBroke = false;
if ( streamCmdTimer ) if ( streamCmdTimer )
streamCmdTimer = clearTimeout( streamCmdTimer ); streamCmdTimer = clearTimeout(streamCmdTimer);
streamStatus = respObj.status; streamStatus = respObj.status;
if (streamStatus.progress >= Math.round(parseFloat(eventData.Length))) streamStatus.progress = parseFloat(eventData.Length); //Limit progress to reality if ( streamStatus.progress >= Math.round(parseFloat(eventData.Length)) )
streamStatus.progress = parseFloat(eventData.Length); //Limit progress to reality
var eventId = streamStatus.event; var eventId = streamStatus.event;
if ( eventId != lastEventId && lastEventId != 0) { //Doesn't run on first load, prevents a double hit on event and nearEvents ajax if ( lastEventId ) {
eventQuery( eventId ); if ( eventId != lastEventId ) {
initialAlarmCues(eventId); //zms uses this instead of a page reload, must call ajax+render //Doesn't run on first load, prevents a double hit on event and nearEvents ajax
lastEventId = eventId; eventQuery(eventId);
initialAlarmCues(eventId); //zms uses this instead of a page reload, must call ajax+render
lastEventId = eventId;
}
} else {
lastEventId = eventId; //Only fires on first load.
} }
if (lastEventId == 0) lastEventId = eventId; //Only fires on first load.
if ( streamStatus.paused == true ) { if ( streamStatus.paused == true ) {
streamPause( ); streamPause( );
} else { } else {
@ -239,18 +247,24 @@ function getCmdResponse( respObj, respText ) {
streamCmdTimer = streamQuery.delay( streamTimeout ); //Timeout is refresh rate for progressBox and time display streamCmdTimer = streamQuery.delay( streamTimeout ); //Timeout is refresh rate for progressBox and time display
} }
var streamReq = new Request.JSON( { url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'chain', onSuccess: getCmdResponse } ); var streamReq = new Request.JSON( {
url: thisUrl,
method: 'get',
timeout: AJAX_TIMEOUT,
link: 'chain',
onSuccess: getCmdResponse
} );
function pauseClicked() { function pauseClicked() {
if (vid) { if ( vid ) {
vid.pause(); vid.pause();
} else { } else {
streamReq.send( streamParms+"&command="+CMD_PAUSE ); streamReq.send(streamParms+"&command="+CMD_PAUSE);
streamPause(); streamPause();
} }
} }
function vjsPause () { function vjsPause() {
stopFastRev(); stopFastRev();
streamPause(); streamPause();
} }
@ -267,8 +281,8 @@ function streamPause( ) {
} }
function playClicked( ) { function playClicked( ) {
if (vid) { if ( vid ) {
if (vid.paused()) { if ( vid.paused() ) {
vid.play(); vid.play();
} else { } else {
vjsPlay(); //handles fast forward and rewind vjsPlay(); //handles fast forward and rewind
@ -279,7 +293,7 @@ function playClicked( ) {
} }
} }
function vjsPlay () { //catches if we change mode programatically function vjsPlay() { //catches if we change mode programatically
stopFastRev(); stopFastRev();
$j('#rateValue').html(vid.playbackRate()); $j('#rateValue').html(vid.playbackRate());
streamPlay(); streamPlay();
@ -302,13 +316,14 @@ function streamFastFwd( action ) {
setButtonState( $('slowFwdBtn'), 'unavail' ); setButtonState( $('slowFwdBtn'), 'unavail' );
setButtonState( $('slowRevBtn'), 'unavail' ); setButtonState( $('slowRevBtn'), 'unavail' );
setButtonState( $('fastRevBtn'), 'inactive' ); setButtonState( $('fastRevBtn'), 'inactive' );
if (vid) { if ( vid ) {
if (revSpeed != .5) stopFastRev(); if ( revSpeed != .5 ) stopFastRev();
vid.playbackRate(rates[rates.indexOf(vid.playbackRate()*100)-1]/100); vid.playbackRate(rates[rates.indexOf(vid.playbackRate()*100)-1]/100);
if (rates.indexOf(vid.playbackRate()*100)-1 == -1) setButtonState($('fastFwdBtn'), 'unavail'); if ( rates.indexOf(vid.playbackRate()*100)-1 == -1 )
setButtonState($('fastFwdBtn'), 'unavail');
$j('#rateValue').html(vid.playbackRate()); $j('#rateValue').html(vid.playbackRate());
} else { } else {
streamReq.send( streamParms+"&command="+CMD_FASTFWD ); streamReq.send(streamParms+"&command="+CMD_FASTFWD);
} }
} }
@ -317,22 +332,22 @@ var intervalRewind;
var revSpeed = .5; var revSpeed = .5;
function streamSlowFwd( action ) { function streamSlowFwd( action ) {
if (vid) { if ( vid ) {
vid.currentTime(vid.currentTime() + spf); vid.currentTime(vid.currentTime() + spf);
} else { } else {
streamReq.send( streamParms+"&command="+CMD_SLOWFWD ); streamReq.send(streamParms+"&command="+CMD_SLOWFWD);
} }
} }
function streamSlowRev( action ) { function streamSlowRev( action ) {
if (vid) { if ( vid ) {
vid.currentTime(vid.currentTime() - spf); vid.currentTime(vid.currentTime() - spf);
} else { } else {
streamReq.send( streamParms+"&command="+CMD_SLOWREV ); streamReq.send(streamParms+"&command="+CMD_SLOWREV);
} }
} }
function stopFastRev () { function stopFastRev() {
clearInterval(intervalRewind); clearInterval(intervalRewind);
vid.playbackRate(1); vid.playbackRate(1);
revSpeed = .5; revSpeed = .5;
@ -345,9 +360,9 @@ function streamFastRev( action ) {
setButtonState( $('slowFwdBtn'), 'unavail' ); setButtonState( $('slowFwdBtn'), 'unavail' );
setButtonState( $('slowRevBtn'), 'unavail' ); setButtonState( $('slowRevBtn'), 'unavail' );
setButtonState( $('fastRevBtn'), 'active' ); setButtonState( $('fastRevBtn'), 'active' );
if (vid) { //There is no reverse play with mp4. Set the speed to 0 and manualy set the time back. if ( vid ) { //There is no reverse play with mp4. Set the speed to 0 and manualy set the time back.
revSpeed = rates[rates.indexOf(revSpeed*100)-1]/100; revSpeed = rates[rates.indexOf(revSpeed*100)-1]/100;
if (rates.indexOf(revSpeed*100) == 0) { if ( rates.indexOf(revSpeed*100) == 0 ) {
setButtonState( $('fastRevBtn'), 'unavail' ); setButtonState( $('fastRevBtn'), 'unavail' );
} }
clearInterval(intervalRewind); clearInterval(intervalRewind);
@ -367,9 +382,12 @@ function streamFastRev( action ) {
} }
function streamPrev(action) { function streamPrev(action) {
if (action) { if ( action ) {
$j(".vjsMessage").remove(); $j(".vjsMessage").remove();
if (vid && PrevEventDefVideoPath.indexOf("view_video") > 0) { location.replace(thisUrl + '?view=event&eid=' + prevEventId + filterQuery + sortQuery);
return;
if ( vid && PrevEventDefVideoPath.indexOf("view_video") > 0 ) {
CurEventDefVideoPath = PrevEventDefVideoPath; CurEventDefVideoPath = PrevEventDefVideoPath;
eventQuery(prevEventId); eventQuery(prevEventId);
} else if (zmsBroke || (vid && PrevEventDefVideoPath.indexOf("view_video") < 0) || $j("#vjsMessage").length || PrevEventDefVideoPath.indexOf("view_video") > 0) {//zms broke, leaving videojs, last event, moving to videojs } else if (zmsBroke || (vid && PrevEventDefVideoPath.indexOf("view_video") < 0) || $j("#vjsMessage").length || PrevEventDefVideoPath.indexOf("view_video") > 0) {//zms broke, leaving videojs, last event, moving to videojs
@ -382,20 +400,25 @@ function streamPrev(action) {
} }
function streamNext(action) { function streamNext(action) {
if (action) { if ( action ) {
$j(".vjsMessage").remove();//This shouldn't happen $j(".vjsMessage").remove();//This shouldn't happen
if (nextEventId == 0) { //handles deleting last event. if ( nextEventId == 0 ) { //handles deleting last event.
pauseClicked(); pauseClicked();
let hideContainer = $j('#eventVideo'); let hideContainer = $j('#eventVideo');
let hideStream = $j(vid ? "#videoobj" : "#evtStream").height() + (vid ? 0 :$j("#progressBar").height()); let hideStream = $j(vid ? "#videoobj" : "#evtStream").height() + (vid ? 0 :$j("#progressBar").height());
hideContainer.prepend('<p class="vjsMessage" style="height: ' + hideStream + 'px; line-height: ' + hideStream + 'px;">No more events</p>'); hideContainer.prepend('<p class="vjsMessage" style="height: ' + hideStream + 'px; line-height: ' + hideStream + 'px;">No more events</p>');
if (vid == null) zmsBroke = true; if ( vid == null ) zmsBroke = true;
return; return;
} }
if (vid && NextEventDefVideoPath.indexOf("view_video") > 0) { //on and staying with videojs // We used to try to dynamically update all the bits in the page, which is really complex
// How about we just reload the page?
//
location.replace(thisUrl + '?view=event&eid=' + nextEventId + filterQuery + sortQuery);
return;
if ( vid && ( NextEventDefVideoPath.indexOf("view_video") > 0 ) ) { //on and staying with videojs
CurEventDefVideoPath = NextEventDefVideoPath; CurEventDefVideoPath = NextEventDefVideoPath;
eventQuery(nextEventId); eventQuery(nextEventId);
} else if (zmsBroke || (vid && NextEventDefVideoPath.indexOf("view_video") < 0) || NextEventDefVideoPath.indexOf("view_video") > 0) {//reload zms, leaving vjs, moving to vjs } else if ( zmsBroke || (vid && NextEventDefVideoPath.indexOf("view_video") < 0) || NextEventDefVideoPath.indexOf("view_video") > 0) {//reload zms, leaving vjs, moving to vjs
location.replace(thisUrl + '?view=event&eid=' + nextEventId + filterQuery + sortQuery); location.replace(thisUrl + '?view=event&eid=' + nextEventId + filterQuery + sortQuery);
} else { } else {
streamReq.send(streamParms+"&command="+CMD_NEXT); streamReq.send(streamParms+"&command="+CMD_NEXT);

View File

@ -114,6 +114,7 @@ if ( monitorType != 'WebSite' ) {
method: 'get', method: 'get',
timeout: AJAX_TIMEOUT, timeout: AJAX_TIMEOUT,
link: 'chain', link: 'chain',
onError: getStreamCmdError,
onSuccess: getStreamCmdResponse, onSuccess: getStreamCmdResponse,
onFailure: getStreamCmdFailure onFailure: getStreamCmdFailure
} ); } );
@ -122,22 +123,28 @@ if ( monitorType != 'WebSite' ) {
var streamStatus; var streamStatus;
function getStreamCmdFailure(xhr) { function getStreamCmdError(text,error) {
console.log(xhr); console.log(error);
// Error are normally due to failed auth. reload the page.
window.location.reload();
} }
function getStreamCmdResponse( respObj, respText ) { function getStreamCmdFailure(xhr) {
console.log(xhr);
}
function getStreamCmdResponse(respObj, respText) {
watchdogOk("stream"); watchdogOk("stream");
console.log('stream');
if ( streamCmdTimer ) if ( streamCmdTimer )
streamCmdTimer = clearTimeout( streamCmdTimer ); streamCmdTimer = clearTimeout(streamCmdTimer);
if ( respObj.result == 'Ok' ) { if ( respObj.result == 'Ok' ) {
// The get status command can get backed up, in which case we won't be able to get the semaphore and will exit. // The get status command can get backed up, in which case we won't be able to get the semaphore and will exit.
if ( respObj.status ) { if ( respObj.status ) {
streamStatus = respObj.status; streamStatus = respObj.status;
$('fpsValue').set( 'text', streamStatus.fps ); $('fpsValue').set('text', streamStatus.fps);
setAlarmState( streamStatus.state ); setAlarmState(streamStatus.state);
$('levelValue').set( 'text', streamStatus.level ); $('levelValue').set('text', streamStatus.level);
if ( streamStatus.level > 95 ) if ( streamStatus.level > 95 )
$('levelValue').className = "alarm"; $('levelValue').className = "alarm";
else if ( streamStatus.level > 80 ) else if ( streamStatus.level > 80 )
@ -145,34 +152,34 @@ function getStreamCmdResponse( respObj, respText ) {
else else
$('levelValue').className = "ok"; $('levelValue').className = "ok";
var delayString = secsToTime( streamStatus.delay ); var delayString = secsToTime(streamStatus.delay);
if ( streamStatus.paused == true ) { if ( streamStatus.paused == true ) {
$('modeValue').set( 'text', "Paused" ); $('modeValue').set('text', 'Paused');
$('rate').addClass( 'hidden' ); $('rate').addClass('hidden');
$('delayValue').set( 'text', delayString ); $('delayValue').set('text', delayString);
$('delay').removeClass( 'hidden' ); $('delay').removeClass('hidden');
$('level').removeClass( 'hidden' ); $('level').removeClass('hidden');
streamCmdPause( false ); streamCmdPause(false);
} else if ( streamStatus.delayed == true ) { } else if ( streamStatus.delayed == true ) {
$('modeValue').set( 'text', "Replay" ); $('modeValue').set('text', 'Replay');
$('rateValue').set( 'text', streamStatus.rate ); $('rateValue').set('text', streamStatus.rate);
$('rate').removeClass( 'hidden' ); $('rate').removeClass('hidden');
$('delayValue').set( 'text', delayString ); $('delayValue').set('text', delayString);
$('delay').removeClass( 'hidden' ); $('delay').removeClass('hidden');
$('level').removeClass( 'hidden' ); $('level').removeClass('hidden');
if ( streamStatus.rate == 1 ) { if ( streamStatus.rate == 1 ) {
streamCmdPlay( false ); streamCmdPlay(false);
} else if ( streamStatus.rate > 0 ) { } else if ( streamStatus.rate > 0 ) {
if ( streamStatus.rate < 1 ) if ( streamStatus.rate < 1 )
streamCmdSlowFwd( false ); streamCmdSlowFwd(false);
else else
streamCmdFastFwd( false ); streamCmdFastFwd(false);
} else { } else {
if ( streamStatus.rate > -1 ) if ( streamStatus.rate > -1 )
streamCmdSlowRev( false ); streamCmdSlowRev(false);
else else
streamCmdFastRev( false ); streamCmdFastRev(false);
} // rate } // rate
} else { } else {
$('modeValue').set( 'text', "Live" ); $('modeValue').set( 'text', "Live" );
@ -209,16 +216,19 @@ function getStreamCmdResponse( respObj, respText ) {
} // end if canEditMonitors } // end if canEditMonitors
if ( streamStatus.auth ) { if ( streamStatus.auth ) {
console.log("Haev a new auth hash" + streamStatus.auth); console.log("Have a new auth hash" + streamStatus.auth);
// Try to reload the image stream. // Try to reload the image stream.
var streamImg = $('liveStream'); var streamImg = $('liveStream');
if ( streamImg ) if ( streamImg )
streamImg.src = streamImg.src.replace( /auth=\w+/i, 'auth='+streamStatus.auth ); streamImg.src = streamImg.src.replace(/auth=\w+/i, 'auth='+streamStatus.auth);
} // end if haev a new auth hash } // end if have a new auth hash
} // end if respObj.status } // end if respObj.status
} else { } else {
checkStreamForErrors("getStreamCmdResponse",respObj);//log them checkStreamForErrors("getStreamCmdResponse", respObj);//log them
// Try to reload the image stream. // Try to reload the image stream.
// If it's an auth error, we should reload the whole page.
window.location.reload();
if ( 0 ) {
var streamImg = $('liveStream'+monitorId); var streamImg = $('liveStream'+monitorId);
if ( streamImg ) { if ( streamImg ) {
streamImg.src = streamImg.src.replace(/rand=\d+/i,'rand='+Math.floor((Math.random() * 1000000) )); streamImg.src = streamImg.src.replace(/rand=\d+/i,'rand='+Math.floor((Math.random() * 1000000) ));
@ -226,6 +236,7 @@ function getStreamCmdResponse( respObj, respText ) {
} else { } else {
console.log("Unable to find streamImg liveStream"); console.log("Unable to find streamImg liveStream");
} }
}
} }
var streamCmdTimeout = statusRefreshTimeout; var streamCmdTimeout = statusRefreshTimeout;
@ -360,14 +371,14 @@ if ( monitorType != 'WebSite' ) {
var statusCmdTimer = null; var statusCmdTimer = null;
} }
function getStatusCmdResponse( respObj, respText ) { function getStatusCmdResponse(respObj, respText) {
watchdogOk("status"); watchdogOk("status");
if ( statusCmdTimer ) if ( statusCmdTimer )
statusCmdTimer = clearTimeout( statusCmdTimer ); statusCmdTimer = clearTimeout(statusCmdTimer);
if ( respObj.result == 'Ok' ) { if ( respObj.result == 'Ok' ) {
$('fpsValue').set( 'text', respObj.monitor.FrameRate ); $('fpsValue').set('text', respObj.monitor.FrameRate);
setAlarmState( respObj.monitor.Status ); setAlarmState(respObj.monitor.Status);
} else } else
checkStreamForErrors("getStatusCmdResponse", respObj); checkStreamForErrors("getStatusCmdResponse", respObj);
@ -401,19 +412,19 @@ function getAlarmCmdResponse( respObj, respText ) {
} }
function cmdDisableAlarms() { function cmdDisableAlarms() {
alarmCmdReq.send( alarmCmdParms+"&command=disableAlarms" ); alarmCmdReq.send(alarmCmdParms+"&command=disableAlarms");
} }
function cmdEnableAlarms() { function cmdEnableAlarms() {
alarmCmdReq.send( alarmCmdParms+"&command=enableAlarms" ); alarmCmdReq.send(alarmCmdParms+"&command=enableAlarms");
} }
function cmdForceAlarm() { function cmdForceAlarm() {
alarmCmdReq.send( alarmCmdParms+"&command=forceAlarm" ); alarmCmdReq.send(alarmCmdParms+"&command=forceAlarm");
} }
function cmdCancelForcedAlarm() { function cmdCancelForcedAlarm() {
alarmCmdReq.send( alarmCmdParms+"&command=cancelForcedAlarm" ); alarmCmdReq.send(alarmCmdParms+"&command=cancelForcedAlarm");
return false; return false;
} }
@ -429,7 +440,13 @@ function getActResponse( respObj, respText ) {
function deleteEvent( event, eventId ) { function deleteEvent( event, eventId ) {
var actParms = "view=request&request=event&action=delete&id="+eventId; var actParms = "view=request&request=event&action=delete&id="+eventId;
var actReq = new Request.JSON( { url: thisUrl, method: 'post', timeout: 3000, data: actParms, onSuccess: getActResponse } ); var actReq = new Request.JSON( {
url: thisUrl,
method: 'post',
timeout: 3000,
data: actParms,
onSuccess: getActResponse
} );
actReq.send(); actReq.send();
event.stop(); event.stop();
} }
@ -444,7 +461,7 @@ if ( monitorType != 'WebSite' ) {
} }
function highlightRow( row ) { function highlightRow( row ) {
$(row).toggleClass( 'highlight' ); $(row).toggleClass('highlight');
} }
function getEventCmdResponse( respObj, respText ) { function getEventCmdResponse( respObj, respText ) {
@ -649,7 +666,7 @@ var watchdogFunctions = {
//Make sure the various refreshes are still taking effect //Make sure the various refreshes are still taking effect
function watchdogCheck( type ) { function watchdogCheck( type ) {
if ( watchdogInactive[type] ) { if ( watchdogInactive[type] ) {
console.log( "Detected streamWatch of type: " + type + " stopped, restarting" ); console.log("Detected streamWatch of type: " + type + " stopped, restarting");
watchdogFunctions[type](); watchdogFunctions[type]();
watchdogInactive[type] = false; watchdogInactive[type] = false;
} else { } else {
@ -662,7 +679,7 @@ function watchdogOk( type ) {
} }
function reloadWebSite() { function reloadWebSite() {
document.getElementById('imageFeed').innerHTML = document.getElementById('imageFeed').innerHTML; document.getElementById('imageFeed').innerHTML = document.getElementById('imageFeed').innerHTML;
} }
function initPage() { function initPage() {
@ -683,16 +700,16 @@ function initPage() {
if ( !streamImg ) if ( !streamImg )
streamImg = $('imageFeed').getElement('object'); streamImg = $('imageFeed').getElement('object');
if ( streamMode == "single" ) { if ( streamMode == "single" ) {
streamImg.addEvent( 'click', fetchImage.pass( streamImg ) ); streamImg.addEvent('click', fetchImage.pass(streamImg));
fetchImage.pass( streamImg ).periodical( imageRefreshTimeout ); fetchImage.pass(streamImg).periodical(imageRefreshTimeout);
} else } else
streamImg.addEvent( 'click', function( event ) { handleClick( event ); } ); streamImg.addEvent('click', function(event) { handleClick(event); });
} }
if ( refreshApplet && appletRefreshTime ) if ( refreshApplet && appletRefreshTime )
appletRefresh.delay( appletRefreshTime*1000 ); appletRefresh.delay(appletRefreshTime*1000);
if (scale == "auto") changeScale(); if ( scale == "auto" ) changeScale();
if (window.history.length == 1) { if ( window.history.length == 1 ) {
$j('#closeControl').html(''); $j('#closeControl').html('');
} }
} else if ( monitorRefresh > 0 ) { } else if ( monitorRefresh > 0 ) {
@ -701,4 +718,4 @@ function initPage() {
} }
// Kick everything off // Kick everything off
window.addEvent( 'domready', initPage ); window.addEvent('domready', initPage);

View File

@ -40,7 +40,7 @@ require_once('includes/Event.php');
require_once('includes/Frame.php'); require_once('includes/Frame.php');
// Compatibility for PHP 5.4 // Compatibility for PHP 5.4
if (!function_exists('imagescale')) { if ( !function_exists('imagescale') ) {
function imagescale($image, $new_width, $new_height = -1, $mode = 0) { function imagescale($image, $new_width, $new_height = -1, $mode = 0) {
$mode; // Not supported $mode; // Not supported
@ -70,17 +70,18 @@ if ( empty($_REQUEST['path']) ) {
if ( !empty($_REQUEST['eid']) ) { if ( !empty($_REQUEST['eid']) ) {
$Event = Event::find_one(array('Id'=>$_REQUEST['eid'])); $Event = Event::find_one(array('Id'=>$_REQUEST['eid']));
if ( ! $Event ) { if ( !$Event ) {
header('HTTP/1.0 404 Not Found'); header('HTTP/1.0 404 Not Found');
Fatal('Event ' . $_REQUEST['eid'].' Not found'); Fatal('Event '.$_REQUEST['eid'].' Not found');
return; return;
} }
if ( $_REQUEST['fid'] == 'snapshot' ) { if ( $_REQUEST['fid'] == 'snapshot' ) {
$Frame = Frame::find_one(array('EventId'=>$_REQUEST['eid'], 'Score'=>$Event->MaxScore())); $Frame = Frame::find_one(array('EventId'=>$_REQUEST['eid'], 'Score'=>$Event->MaxScore()));
if ( ! $Frame ) if ( !$Frame )
$Frame = Frame::find_one(array('EventId'=>$_REQUEST['eid'])); $Frame = Frame::find_one(array('EventId'=>$_REQUEST['eid']));
if ( ! $Frame ) { if ( !$Frame ) {
Warning("No frame found for event " + $_REQUEST['eid']);
$Frame = new Frame(); $Frame = new Frame();
$Frame->Delta(1); $Frame->Delta(1);
$Frame->FrameId('snapshot'); $Frame->FrameId('snapshot');
@ -123,14 +124,14 @@ Logger::Debug("Got virtual frame from Bulk Frames previous delta: " . $previousB
} else { } else {
# If we are only specifying fid, then the fid must be the primary key into the frames table. But when the event is specified, then it is the frame # # If we are only specifying fid, then the fid must be the primary key into the frames table. But when the event is specified, then it is the frame #
$Frame = Frame::find_one(array('Id'=>$_REQUEST['fid'])); $Frame = Frame::find_one(array('Id'=>$_REQUEST['fid']));
if ( ! $Frame ) { if ( !$Frame ) {
header('HTTP/1.0 404 Not Found'); header('HTTP/1.0 404 Not Found');
Fatal('Frame ' . $_REQUEST['fid'] . ' Not Found'); Fatal('Frame ' . $_REQUEST['fid'] . ' Not Found');
return; return;
} }
$Event = Event::find_one(array('Id'=>$Frame->EventId())); $Event = Event::find_one(array('Id'=>$Frame->EventId()));
if ( ! $Event ) { if ( !$Event ) {
header('HTTP/1.0 404 Not Found'); header('HTTP/1.0 404 Not Found');
Fatal('Event ' . $Frame->EventId() . ' Not Found'); Fatal('Event ' . $Frame->EventId() . ' Not Found');
return; return;
@ -138,11 +139,11 @@ Logger::Debug("Got virtual frame from Bulk Frames previous delta: " . $previousB
$path = $Event->Path().'/'.sprintf('%0'.ZM_EVENT_IMAGE_DIGITS.'d',$Frame->FrameId()).'-'.$show.'.jpg'; $path = $Event->Path().'/'.sprintf('%0'.ZM_EVENT_IMAGE_DIGITS.'d',$Frame->FrameId()).'-'.$show.'.jpg';
} # end if have eid } # end if have eid
if ( ! file_exists($path) ) { if ( !file_exists($path) ) {
Logger::Debug("$path does not exist"); Logger::Debug("$path does not exist");
# Generate the frame JPG # Generate the frame JPG
if ( $show == 'capture' and $Event->DefaultVideo() ) { if ( ($show == 'capture') and $Event->DefaultVideo() ) {
if ( ! file_exists($Event->Path().'/'.$Event->DefaultVideo()) ) { if ( !file_exists($Event->Path().'/'.$Event->DefaultVideo()) ) {
header('HTTP/1.0 404 Not Found'); header('HTTP/1.0 404 Not Found');
Fatal("Can't create frame images from video because there is no video file for this event at (".$Event->Path().'/'.$Event->DefaultVideo() ); Fatal("Can't create frame images from video because there is no video file for this event at (".$Event->Path().'/'.$Event->DefaultVideo() );
} }
@ -190,52 +191,52 @@ Logger::Debug("Got virtual frame from Bulk Frames previous delta: " . $previousB
} else { } else {
$errorText = 'Invalid image path'; $errorText = 'Invalid image path';
} }
if ( ! file_exists($path) ) { if ( !file_exists($path) ) {
header('HTTP/1.0 404 Not Found'); header('HTTP/1.0 404 Not Found');
Fatal("Image not found at $path"); Fatal("Image not found at $path");
} }
} }
$scale=0; $scale = 0;
if ( !empty($_REQUEST['scale']) ) { if ( !empty($_REQUEST['scale']) ) {
if ( is_numeric($_REQUEST['scale']) ) { if ( is_numeric($_REQUEST['scale']) ) {
$x = $_REQUEST['scale']; $x = $_REQUEST['scale'];
if ( $x >= 1 and $x <= 400 ) if ( $x >= 1 and $x <= 400 )
$scale=$x; $scale = $x;
} }
} }
$width=0; $width = 0;
if ( !empty($_REQUEST['width']) ) { if ( !empty($_REQUEST['width']) ) {
if ( is_numeric($_REQUEST['width']) ) { if ( is_numeric($_REQUEST['width']) ) {
$x = $_REQUEST['width']; $x = $_REQUEST['width'];
if ( $x >= 10 and $x <= 8000 ) if ( $x >= 10 and $x <= 8000 )
$width=$x; $width = $x;
} }
} }
$height=0; $height = 0;
if ( !empty($_REQUEST['height']) ) { if ( !empty($_REQUEST['height']) ) {
if ( is_numeric($_REQUEST['height']) ) { if ( is_numeric($_REQUEST['height']) ) {
$x = $_REQUEST['height']; $x = $_REQUEST['height'];
if ( $x >= 10 and $x <= 8000 ) if ( $x >= 10 and $x <= 8000 )
$height=$x; $height = $x;
} }
} }
header('Content-type: image/jpeg');
# This is so that Save Image As give a useful filename
if ( $Event ) {
$filename = $Event->MonitorId().'_'.$Event->Id().'_'.$Frame->FrameId().'.jpg';
header('Content-Disposition: inline; filename="' . $filename . '"');
}
ob_clean();
flush();
if ( $errorText ) { if ( $errorText ) {
Error($errorText); Error($errorText);
} else { } else {
# Clears the output buffer. Not sure what is there, but have had troubles.
ob_end_clean();
header('Content-type: image/jpeg');
if ( ( $scale==0 || $scale==100 ) && $width==0 && $height==0 ) { if ( ( $scale==0 || $scale==100 ) && $width==0 && $height==0 ) {
# This is so that Save Image As give a useful filename
if ( $Event ) {
$filename = $Event->MonitorId().'_'.$Event->Id().'_'.$Frame->FrameId().'.jpg';
header('Content-Disposition: inline; filename="' . $filename . '"');
}
ob_clean();
flush();
if ( !readfile($path) ) { if ( !readfile($path) ) {
Error('No bytes read from '. $path); Error('No bytes read from '. $path);
} }
@ -254,17 +255,23 @@ if ( $errorText ) {
} elseif ( $width != 0 && $height == 0 ) { } elseif ( $width != 0 && $height == 0 ) {
$height = ($width * $oldHeight) / $oldWidth; $height = ($width * $oldHeight) / $oldWidth;
} }
if ( $width == $oldWidth && $height == $oldHeight) { if ( $width == $oldWidth && $height == $oldHeight ) {
Warning('No change to width despite scaling.'); Warning('No change to width despite scaling.');
} }
} }
# Slight optimisation, thumbnails always specify width and height, so we can cache them. # Slight optimisation, thumbnails always specify width and height, so we can cache them.
$scaled_path = preg_replace('/\.jpg$/', "-${width}x${height}.jpg", $path ); $scaled_path = preg_replace('/\.jpg$/', "-${width}x${height}.jpg", $path);
if ( ! file_exists($scaled_path) or ! readfile($scaled_path) ) { if ( $Event ) {
$filename = $Event->MonitorId().'_'.$Event->Id().'_'.$Frame->FrameId()."-${width}x${height}.jpg";
header('Content-Disposition: inline; filename="' . $filename . '"');
}
//ob_clean();
//flush();
if ( !( file_exists($scaled_path) and readfile($scaled_path) ) ) {
Logger::Debug("Cached scaled image does not exist at $scaled_path or is no good.. Creating it"); Logger::Debug("Cached scaled image does not exist at $scaled_path or is no good.. Creating it");
ob_start(); ob_start();
if ( ! $i ) if ( !$i )
$i = imagecreatefromjpeg($path); $i = imagecreatefromjpeg($path);
$iScale = imagescale($i, $width, $height); $iScale = imagescale($i, $width, $height);
imagejpeg($iScale); imagejpeg($iScale);
@ -274,6 +281,15 @@ if ( $errorText ) {
file_put_contents($scaled_path, $scaled_jpeg_data); file_put_contents($scaled_path, $scaled_jpeg_data);
ob_end_clean(); ob_end_clean();
echo $scaled_jpeg_data; echo $scaled_jpeg_data;
} else {
Logger::Debug("Sending $scaled_path");
$bytes = readfile($scaled_path);
if ( !$bytes ) {
Error('No bytes read from '. $scaled_path);
} else {
Logger::Debug("$bytes sent");
}
} }
} }
} }
exit();

View File

@ -25,7 +25,7 @@
// Does not support scaling at this time. // Does not support scaling at this time.
// //
if ( !canView( 'Events' ) ) { if ( !canView('Events') ) {
$view = 'error'; $view = 'error';
return; return;
} }
@ -37,12 +37,12 @@ $path = '';
$Event = null; $Event = null;
if ( ! empty($_REQUEST['eid'] ) ) { if ( ! empty($_REQUEST['eid']) ) {
$Event = new Event( $_REQUEST['eid'] ); $Event = new Event($_REQUEST['eid']);
$path = $Event->Path().'/'.$Event->DefaultVideo(); $path = $Event->Path().'/'.$Event->DefaultVideo();
Logger::Debug("Path: $path"); Logger::Debug("Path: $path");
} else if ( ! empty($_REQUEST['event_id'] ) ) { } else if ( ! empty($_REQUEST['event_id']) ) {
$Event = new Event( $_REQUEST['event_id'] ); $Event = new Event($_REQUEST['event_id']);
$path = $Event->Path().'/'.$Event->DefaultVideo(); $path = $Event->Path().'/'.$Event->DefaultVideo();
Logger::Debug("Path: $path"); Logger::Debug("Path: $path");
} else { } else {
@ -50,7 +50,7 @@ if ( ! empty($_REQUEST['eid'] ) ) {
} }
if ( $errorText ) { if ( $errorText ) {
Error( $errorText ); Error($errorText);
header('HTTP/1.0 404 Not Found'); header('HTTP/1.0 404 Not Found');
die(); die();
} }
@ -67,12 +67,12 @@ $begin = 0;
$end = $size-1; $end = $size-1;
$length = $size; $length = $size;
if ( isset( $_SERVER['HTTP_RANGE'] ) ) { if ( isset($_SERVER['HTTP_RANGE']) ) {
Logger::Debug("Using Range " . $_SERVER['HTTP_RANGE'] ); Logger::Debug('Using Range ' . $_SERVER['HTTP_RANGE']);
if ( preg_match( '/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches) ) { if ( preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches) ) {
$begin = intval( $matches[1] ); $begin = intval($matches[1]);
if ( ! empty( $matches[2]) ) { if ( ! empty($matches[2]) ) {
$end = intval( $matches[2] ); $end = intval($matches[2]);
} }
$length = $end - $begin + 1; $length = $end - $begin + 1;
Logger::Debug("Using Range $begin $end size: $size, length: $length"); Logger::Debug("Using Range $begin $end size: $size, length: $length");
@ -102,10 +102,10 @@ ob_clean();
flush(); flush();
$cur = $begin; $cur = $begin;
fseek( $fh, $begin, 0 ); fseek($fh, $begin, 0);
while( $length && ( ! feof( $fh ) ) && ( connection_status() == 0 ) ) { while( $length && ( !feof($fh) ) && ( connection_status() == 0 ) ) {
$amount = min( 1024*16, $length ); $amount = min(1024*16, $length);
print fread( $fh, $amount ); print fread( $fh, $amount );
$length -= $amount; $length -= $amount;
@ -114,5 +114,5 @@ while( $length && ( ! feof( $fh ) ) && ( connection_status() == 0 ) ) {
flush(); flush();
} }
fclose( $fh ); fclose($fh);
exit(); exit();