From 8bfdb73d24d63fbf01e38ef3ca424fe62c7a616b Mon Sep 17 00:00:00 2001 From: digital-gnome <31593470+digital-gnome@users.noreply.github.com> Date: Wed, 20 Dec 2017 15:46:03 -0500 Subject: [PATCH 01/19] Fix missing change to StartDateTime Fixes filter loading from events if clicked from last hour link. --- web/skins/classic/views/console.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/skins/classic/views/console.php b/web/skins/classic/views/console.php index 4004e0094..f85cd5afa 100644 --- a/web/skins/classic/views/console.php +++ b/web/skins/classic/views/console.php @@ -37,7 +37,7 @@ $eventCounts = array( 'filter' => array( 'Query' => array( 'terms' => array( - array( 'attr' => 'DateTime', 'op' => '>=', 'val' => '-1 hour' ), + array( 'attr' => 'StartDateTime', 'op' => '>=', 'val' => '-1 hour' ), ) ) ), From 2c1aa2a92f39612408b2203f93121d569ae26bc1 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Wed, 20 Dec 2017 21:22:37 -0500 Subject: [PATCH 02/19] missing ; --- db/zm_create.sql.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/zm_create.sql.in b/db/zm_create.sql.in index 5d15ca59b..b5e58d422 100644 --- a/db/zm_create.sql.in +++ b/db/zm_create.sql.in @@ -277,7 +277,7 @@ CREATE TABLE `Groups` ( --Table structure for table `Groups_Monitors` -- -DROP TABLE IF EXISTS `Groups_Monitors` +DROP TABLE IF EXISTS `Groups_Monitors`; CREATE TABLE `Groups_Monitors` ( `Id` INT(10) unsigned NOT NULL auto_increment, `GroupId` int(10) unsigned NOT NULL, From f036e95793992de52b93f0f4238c09b78f1f9409 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Thu, 21 Dec 2017 16:53:22 -0800 Subject: [PATCH 03/19] fix Moving when Medium Scheme --- scripts/ZoneMinder/lib/ZoneMinder/Event.pm | 32 ++++++++++++++-------- 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/scripts/ZoneMinder/lib/ZoneMinder/Event.pm b/scripts/ZoneMinder/lib/ZoneMinder/Event.pm index e7fa9e296..1194ea56c 100644 --- a/scripts/ZoneMinder/lib/ZoneMinder/Event.pm +++ b/scripts/ZoneMinder/lib/ZoneMinder/Event.pm @@ -154,11 +154,21 @@ sub Path { if ( ! $$event{Path} ) { my $Storage = $event->Storage(); - + $$event{Path} = join('/', $Storage->Path(), $event->RelativePath() ); + } + return $$event{Path}; +} + +sub RelativePath { + my $event = shift; + if ( @_ ) { + $$event{RelativePath} = $_[0]; + } + + if ( ! $$event{RelativePath} ) { if ( $$event{Scheme} eq 'Deep' ) { if ( $event->Time() ) { - $$event{Path} = join('/', - $Storage->Path(), + $$event{RelativePath} = join('/', $event->{MonitorId}, strftime( '%y/%m/%d/%H/%M/%S', localtime($event->Time()) @@ -166,30 +176,28 @@ sub Path { ); } else { Error("Event $$event{Id} has no value for Time(), unable to determine path"); - $$event{Path} = ''; + $$event{RelativePath} = ''; } } elsif ( $$event{Scheme} eq 'Medium' ) { if ( $event->Time() ) { - $$event{Path} = join('/', - $Storage->Path(), + $$event{RelativePath} = join('/', $event->{MonitorId}, strftime( '%Y-%m-%d', localtime($event->Time())), $event->{Id}, ); } else { Error("Event $$event{Id} has no value for Time(), unable to determine path"); - $$event{Path} = ''; + $$event{RelativePath} = ''; } } else { # Shallow - $$event{Path} = join('/', - $Storage->Path(), + $$event{RelativePath} = join('/', $event->{MonitorId}, $event->{Id}, ); } # end if Scheme } # end if ! Path - return $$event{Path}; + return $$event{RelativePath}; } sub GenerateVideo { @@ -337,7 +345,7 @@ sub delete_files { return; } Debug("Deleting files for Event $$event{Id} from $storage_path."); - my $link_path = $$event{MonitorId}."/*/*/*/.".$$event{Id}; + my $link_path = $$event{MonitorId}.'/*/*/*/.'.$$event{Id}; #Debug( "LP1:$link_path" ); my @links = glob($link_path); #Debug( "L:".$links[0].": $!" ); @@ -371,7 +379,7 @@ sub delete_files { } } # end if links } else { - my $command = "/bin/rm -rf ". $event->Path(); + my $command = '/bin/rm -rf '. $storage_path . '/'. $event->RelativePath(); ZoneMinder::General::executeShellCommand( $command ); } } # end sub delete_files From 915ea93348884f0e79977ff7052c3975dd80067b Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Thu, 21 Dec 2017 16:53:46 -0800 Subject: [PATCH 04/19] source remote server when streaming event --- web/includes/Event.php | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/web/includes/Event.php b/web/includes/Event.php index 2f4439609..ab3ca6687 100644 --- a/web/includes/Event.php +++ b/web/includes/Event.php @@ -160,7 +160,16 @@ class Event { public function getStreamSrc( $args=array(), $querySep='&' ) { if ( $this->{'DefaultVideo'} and $args['mode'] != 'jpeg' ) { - return ( ZM_BASE_PATH != '/' ? ZM_BASE_PATH : '' ).'/index.php?view=view_video&eid='.$this->{'Id'}; + $streamSrc = ZM_BASE_PROTOCOL.'://'; + $Monitor = $this->Monitor(); + if ( $Monitor->ServerId() ) { + $Server = $Monitor->Server(); + $streamSrc .= $Server->Hostname(); + } else { + $streamSrc .= $_SERVER['HTTP_HOST']; + } + $streamSrc .= ( ZM_BASE_PATH != '/' ? ZM_BASE_PATH : '' ).'/index.php?view=view_video&eid='.$this->{'Id'}; + return $streamSrc; } $streamSrc = ZM_BASE_URL.ZM_PATH_ZMS; From 9dfad4886d569984b490ecf270e6d3033824efed Mon Sep 17 00:00:00 2001 From: Isaac Date: Fri, 22 Dec 2017 16:12:34 +0100 Subject: [PATCH 05/19] fix saving Monitors --- web/includes/Monitor.php | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/web/includes/Monitor.php b/web/includes/Monitor.php index 157088e83..b3a9ad633 100644 --- a/web/includes/Monitor.php +++ b/web/includes/Monitor.php @@ -293,8 +293,8 @@ private $control_fields = array( } return $filters; } - public function save( $new_values = null ) { + public function save( $new_values = null ) { if ( $new_values ) { foreach ( $new_values as $k=>$v ) { @@ -302,8 +302,10 @@ private $control_fields = array( } } - $sql = 'UPDATE Monitors SET '.implode(', ', array_map( function($field) {return $field.'=?';}, array_keys( $this->defaults ) ) ) . ' WHERE Id=?'; - $values = array_map( function($field){return $this->{$field};}, $this->fields ); + $fields = array_keys( $this->defaults ); + + $sql = 'UPDATE Monitors SET '.implode(', ', array_map( function($field) {return $field.'=?';}, $fields ) ) . ' WHERE Id=?'; + $values = array_map( function($field){return $this->{$field};}, $fields ); $values[] = $this->{'Id'}; dbQuery( $sql, $values ); } // end function save From f51259443c46c0a2753014764399c9566cb49504 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Fri, 22 Dec 2017 09:02:49 -0800 Subject: [PATCH 06/19] fix disk_used_percentage to use db calculated used size --- web/includes/Storage.php | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/web/includes/Storage.php b/web/includes/Storage.php index e14d00e92..5bbdcbbdf 100644 --- a/web/includes/Storage.php +++ b/web/includes/Storage.php @@ -95,11 +95,8 @@ class Storage { Error("disk_total_space returned false for " . $path ); return 0; } - $free = disk_free_space( $path ); - if ( ! $free ) { - Error("disk_free_space returned false for " . $path ); - } - $usage = round(($total - $free) / $total * 100); + $used = $this->disk_used_space(); + $usage = round( ($used / $total) * 100); return $usage; } public function disk_total_space() { From bb8e326392aecd0ecc84ef19153b993d171845fc Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Fri, 22 Dec 2017 09:16:56 -0800 Subject: [PATCH 07/19] Fix not restarting a monitor if it has moved to a different server --- web/api/app/Controller/MonitorsController.php | 466 +++++++++--------- 1 file changed, 226 insertions(+), 240 deletions(-) diff --git a/web/api/app/Controller/MonitorsController.php b/web/api/app/Controller/MonitorsController.php index af9cc8488..c24cd12f2 100644 --- a/web/api/app/Controller/MonitorsController.php +++ b/web/api/app/Controller/MonitorsController.php @@ -13,7 +13,7 @@ class MonitorsController extends AppController { * * @var array */ - public $components = array('Paginator', 'RequestHandler'); + public $components = array('Paginator', 'RequestHandler'); public function beforeFilter() { parent::beforeFilter(); @@ -29,21 +29,21 @@ class MonitorsController extends AppController { * * @return void */ - public function index() { + public function index() { $this->Monitor->recursive = 0; - if ($this->request->params['named']) { - $this->FilterComponent = $this->Components->load('Filter'); - //$conditions = $this->FilterComponent->buildFilter($this->request->params['named']); - $conditions = $this->request->params['named']; - } else { - $conditions = array(); - } + if ($this->request->params['named']) { + $this->FilterComponent = $this->Components->load('Filter'); + //$conditions = $this->FilterComponent->buildFilter($this->request->params['named']); + $conditions = $this->request->params['named']; + } else { + $conditions = array(); + } - $allowedMonitors=preg_split ('@,@', $this->Session->Read('allowedMonitors'),NULL, PREG_SPLIT_NO_EMPTY); - if (!empty($allowedMonitors)) { + $allowedMonitors=preg_split ('@,@', $this->Session->Read('allowedMonitors'),NULL, PREG_SPLIT_NO_EMPTY); + if (!empty($allowedMonitors)) { $conditions['Monitor.Id' ] = $allowedMonitors; - } + } $find_array = array('conditions'=>$conditions,'contain'=>array('Group')); if ( isset( $conditions['GroupId'] ) ) { @@ -70,7 +70,7 @@ class MonitorsController extends AppController { 'monitors' => $monitors, '_serialize' => array('monitors') )); - } + } /** * view method @@ -79,51 +79,51 @@ class MonitorsController extends AppController { * @param string $id * @return void */ - public function view($id = null) { - $this->Monitor->recursive = 0; - if (!$this->Monitor->exists($id)) { - throw new NotFoundException(__('Invalid monitor')); - } - $allowedMonitors=preg_split ('@,@', $this->Session->Read('allowedMonitors'),NULL, PREG_SPLIT_NO_EMPTY); - if (!empty($allowedMonitors)) { - $restricted = array('Monitor.' . $this->Monitor->primaryKey => $allowedMonitors); - } else { - $restricted = ''; - } - - $options = array('conditions' => array( - array('Monitor.' . $this->Monitor->primaryKey => $id), - $restricted - ) - ); - $monitor = $this->Monitor->find('first', $options); - $this->set(array( - 'monitor' => $monitor, - '_serialize' => array('monitor') - )); - } + public function view($id = null) { + $this->Monitor->recursive = 0; + if (!$this->Monitor->exists($id)) { + throw new NotFoundException(__('Invalid monitor')); + } + $allowedMonitors=preg_split ('@,@', $this->Session->Read('allowedMonitors'),NULL, PREG_SPLIT_NO_EMPTY); + if (!empty($allowedMonitors)) { + $restricted = array('Monitor.' . $this->Monitor->primaryKey => $allowedMonitors); + } else { + $restricted = ''; + } + + $options = array('conditions' => array( + array('Monitor.' . $this->Monitor->primaryKey => $id), + $restricted + ) + ); + $monitor = $this->Monitor->find('first', $options); + $this->set(array( + 'monitor' => $monitor, + '_serialize' => array('monitor') + )); + } /** * add method * * @return void */ - public function add() { - if ($this->request->is('post')) { + public function add() { + if ($this->request->is('post')) { - if ($this->Session->Read('systemPermission') != 'Edit') - { - throw new UnauthorizedException(__('Insufficient privileges')); - return; - } + if ($this->Session->Read('systemPermission') != 'Edit') + { + throw new UnauthorizedException(__('Insufficient privileges')); + return; + } - $this->Monitor->create(); - if ($this->Monitor->save($this->request->data)) { - $this->daemonControl($this->Monitor->id, 'start'); - return $this->flash(__('The monitor has been saved.'), array('action' => 'index')); - } - } - } + $this->Monitor->create(); + if ($this->Monitor->save($this->request->data)) { + $this->daemonControl($this->Monitor->id, 'start'); + return $this->flash(__('The monitor has been saved.'), array('action' => 'index')); + } + } + } /** * edit method @@ -132,40 +132,39 @@ class MonitorsController extends AppController { * @param string $id * @return void */ - public function edit($id = null) { - $this->Monitor->id = $id; + public function edit($id = null) { + $this->Monitor->id = $id; - if (!$this->Monitor->exists($id)) { - throw new NotFoundException(__('Invalid monitor')); - } - if ($this->Session->Read('monitorPermission') != 'Edit') - { - throw new UnauthorizedException(__('Insufficient privileges')); - return; - } - if ($this->Monitor->save($this->request->data)) { - $message = 'Saved'; - } else { - $message = 'Error'; - } + if (!$this->Monitor->exists($id)) { + throw new NotFoundException(__('Invalid monitor')); + } + if ($this->Session->Read('monitorPermission') != 'Edit') + { + throw new UnauthorizedException(__('Insufficient privileges')); + return; + } + if ($this->Monitor->save($this->request->data)) { + $message = 'Saved'; + } else { + $message = 'Error'; + } - $this->set(array( - 'message' => $message, - '_serialize' => array('message') - )); + $this->set(array( + 'message' => $message, + '_serialize' => array('message') + )); - // - restart or stop this monitor after change + // - restart or stop this monitor after change $func = $this->Monitor->find('first', array( 'fields' => array('Function'), 'conditions' => array('Id' => $id) ))['Monitor']['Function']; // We don't pass the request data as the monitor object because it may be a subset of the full monitor array - if ( $func == 'None' ) { - $this->daemonControl( $this->Monitor->id, 'stop' ); - } else { - $this->daemonControl( $this->Monitor->id, 'restart' ); + $this->daemonControl( $this->Monitor->id, 'stop' ); + if ( ( $func != 'None' ) and ( $this->Monitor->ServerId == ZM_SERVER_ID ) ) { + $this->daemonControl( $this->Monitor->id, 'start' ); } - } + } // end function edit /** * delete method @@ -174,196 +173,183 @@ class MonitorsController extends AppController { * @param string $id * @return void */ - public function delete($id = null) { - $this->Monitor->id = $id; - if (!$this->Monitor->exists()) { - throw new NotFoundException(__('Invalid monitor')); - } - if ($this->Session->Read('systemPermission') != 'Edit') - { - throw new UnauthorizedException(__('Insufficient privileges')); - return; - } - $this->request->allowMethod('post', 'delete'); + public function delete($id = null) { + $this->Monitor->id = $id; + if (!$this->Monitor->exists()) { + throw new NotFoundException(__('Invalid monitor')); + } + if ($this->Session->Read('systemPermission') != 'Edit') { + throw new UnauthorizedException(__('Insufficient privileges')); + return; + } + $this->request->allowMethod('post', 'delete'); - $this->daemonControl($this->Monitor->id, 'stop'); + $this->daemonControl($this->Monitor->id, 'stop'); - if ($this->Monitor->delete()) { - return $this->flash(__('The monitor has been deleted.'), array('action' => 'index')); - } else { - return $this->flash(__('The monitor could not be deleted. Please, try again.'), array('action' => 'index')); - } - } + if ($this->Monitor->delete()) { + return $this->flash(__('The monitor has been deleted.'), array('action' => 'index')); + } else { + return $this->flash(__('The monitor could not be deleted. Please, try again.'), array('action' => 'index')); + } + } - public function sourceTypes() { - $sourceTypes = $this->Monitor->query("describe Monitors Type;"); + public function sourceTypes() { + $sourceTypes = $this->Monitor->query("describe Monitors Type;"); - preg_match('/^enum\((.*)\)$/', $sourceTypes[0]['COLUMNS']['Type'], $matches); - foreach( explode(',', $matches[1]) as $value ) { - $enum[] = trim( $value, "'" ); - } + preg_match('/^enum\((.*)\)$/', $sourceTypes[0]['COLUMNS']['Type'], $matches); + foreach( explode(',', $matches[1]) as $value ) { + $enum[] = trim( $value, "'" ); + } - $this->set(array( - 'sourceTypes' => $enum, - '_serialize' => array('sourceTypes') - )); - } + $this->set(array( + 'sourceTypes' => $enum, + '_serialize' => array('sourceTypes') + )); + } - // arm/disarm alarms - // expected format: http(s):/portal-api-url/monitors/alarm/id:M/command:C.json - // where M=monitorId - // where C=on|off|status - public function alarm() - { - $id = $this->request->params['named']['id']; - $cmd = strtolower($this->request->params['named']['command']); - if (!$this->Monitor->exists($id)) { - throw new NotFoundException(__('Invalid monitor')); - } - if ( $cmd != 'on' && $cmd != 'off' && $cmd != 'status') - { - throw new BadRequestException(__('Invalid command')); - } - $zm_path_bin = Configure::read('ZM_PATH_BIN'); + // arm/disarm alarms + // expected format: http(s):/portal-api-url/monitors/alarm/id:M/command:C.json + // where M=monitorId + // where C=on|off|status + public function alarm() { + $id = $this->request->params['named']['id']; + $cmd = strtolower($this->request->params['named']['command']); + if (!$this->Monitor->exists($id)) { + throw new NotFoundException(__('Invalid monitor')); + } + if ( $cmd != 'on' && $cmd != 'off' && $cmd != 'status' ) { + throw new BadRequestException(__('Invalid command')); + } + $zm_path_bin = Configure::read('ZM_PATH_BIN'); - switch ($cmd) - { - case "on": - $q = '-a'; - $verbose = "-v"; - break; - case "off": - $q = "-c"; - $verbose = "-v"; - break; - case "status": - $verbose = ""; // zmu has a bug - gives incorrect verbose output in this case - $q = "-s"; - break; - } + switch ($cmd) { + case 'on': + $q = '-a'; + $verbose = '-v'; + break; + case 'off': + $q = '-c'; + $verbose = '-v'; + break; + case 'status': + $verbose = ''; // zmu has a bug - gives incorrect verbose output in this case + $q = '-s'; + break; + } - // form auth key based on auth credentials - $this->loadModel('Config'); - $options = array('conditions' => array('Config.' . $this->Config->primaryKey => 'ZM_OPT_USE_AUTH')); + // form auth key based on auth credentials + $this->loadModel('Config'); + $options = array('conditions' => array('Config.' . $this->Config->primaryKey => 'ZM_OPT_USE_AUTH')); $config = $this->Config->find('first', $options); - $zmOptAuth = $config['Config']['Value']; + $zmOptAuth = $config['Config']['Value']; - $options = array('conditions' => array('Config.' . $this->Config->primaryKey => 'ZM_AUTH_RELAY')); + $options = array('conditions' => array('Config.' . $this->Config->primaryKey => 'ZM_AUTH_RELAY')); $config = $this->Config->find('first', $options); - $zmAuthRelay = $config['Config']['Value']; - - $auth=""; - if ($zmOptAuth) - { - if ($zmAuthRelay == 'hashed') - { - $options = array('conditions' => array('Config.' . $this->Config->primaryKey => 'ZM_AUTH_HASH_SECRET')); - $config = $this->Config->find('first', $options); - $zmAuthHashSecret = $config['Config']['Value']; + $zmAuthRelay = $config['Config']['Value']; + + $auth=''; + if ( $zmOptAuth ) { + if ( $zmAuthRelay == 'hashed' ) { + $options = array('conditions' => array('Config.' . $this->Config->primaryKey => 'ZM_AUTH_HASH_SECRET')); + $config = $this->Config->find('first', $options); + $zmAuthHashSecret = $config['Config']['Value']; - $time = localtime(); - $ak = $zmAuthHashSecret.$this->Session->Read('username').$this->Session->Read('passwordHash').$time[2].$time[3].$time[4].$time[5]; - $ak = md5($ak); - $auth = " -A ".$ak; - } - elseif ($zmAuthRelay == 'plain') - { - $auth = " -U " .$this->Session->Read('username')." -P ".$this->Session->Read('password'); - - } - elseif ($zmAuthRelay == 'none') - { - $auth = " -U " .$this->Session->Read('username'); - } - } - - $shellcmd = escapeshellcmd("$zm_path_bin/zmu $verbose -m$id $q $auth"); - $status = exec ($shellcmd); + $time = localtime(); + $ak = $zmAuthHashSecret.$this->Session->Read('username').$this->Session->Read('passwordHash').$time[2].$time[3].$time[4].$time[5]; + $ak = md5($ak); + $auth = ' -A '.$ak; + } else if ( $zmAuthRelay == 'plain' ) { + $auth = ' -U ' .$this->Session->Read('username').' -P '.$this->Session->Read('password'); + + } else if ( $zmAuthRelay == 'none' ) { + $auth = ' -U ' .$this->Session->Read('username'); + } + } + + $shellcmd = escapeshellcmd("$zm_path_bin/zmu $verbose -m$id $q $auth"); + $status = exec ($shellcmd); - $this->set(array( - 'status' => $status, - '_serialize' => array('status'), - )); + $this->set(array( + 'status' => $status, + '_serialize' => array('status'), + )); + } - - } + // Check if a daemon is running for the monitor id + public function daemonStatus() { + $id = $this->request->params['named']['id']; + $daemon = $this->request->params['named']['daemon']; - // Check if a daemon is running for the monitor id - public function daemonStatus() { - $id = $this->request->params['named']['id']; - $daemon = $this->request->params['named']['daemon']; + if (!$this->Monitor->exists($id)) { + throw new NotFoundException(__('Invalid monitor')); + } - if (!$this->Monitor->exists($id)) { - throw new NotFoundException(__('Invalid monitor')); - } + $monitor = $this->Monitor->find('first', array( + 'fields' => array('Id', 'Type', 'Device'), + 'conditions' => array('Id' => $id) + )); - $monitor = $this->Monitor->find('first', array( - 'fields' => array('Id', 'Type', 'Device'), - 'conditions' => array('Id' => $id) - )); + // Clean up the returned array + $monitor = Set::extract('/Monitor/.', $monitor); - // Clean up the returned array - $monitor = Set::extract('/Monitor/.', $monitor); + // Pass -d for local, otherwise -m + if ($monitor[0]['Type'] == 'Local') { + $args = '-d '. $monitor[0]['Device']; + } else { + $args = '-m '. $monitor[0]['Id']; + } - // Pass -d for local, otherwise -m - if ($monitor[0]['Type'] == 'Local') { - $args = "-d ". $monitor[0]['Device']; - } else { - $args = "-m ". $monitor[0]['Id']; - } + // Build the command, and execute it + $zm_path_bin = Configure::read('ZM_PATH_BIN'); + $command = escapeshellcmd("$zm_path_bin/zmdc.pl status $daemon $args"); + $status = exec( $command ); - // Build the command, and execute it - $zm_path_bin = Configure::read('ZM_PATH_BIN'); - $command = escapeshellcmd("$zm_path_bin/zmdc.pl status $daemon $args"); - $status = exec( $command ); + // If 'not' is present, the daemon is not running, so return false + // https://github.com/ZoneMinder/ZoneMinder/issues/799#issuecomment-108996075 + // Also sending back the status text so we can check if the monitor is in pending + // state which means there may be an error + $statustext = $status; + $status = (strpos($status, 'not')) ? false : true; - // If 'not' is present, the daemon is not running, so return false - // https://github.com/ZoneMinder/ZoneMinder/issues/799#issuecomment-108996075 - // Also sending back the status text so we can check if the monitor is in pending - // state which means there may be an error - $statustext = $status; - $status = (strpos($status, 'not')) ? false : true; + $this->set(array( + 'status' => $status, + 'statustext' => $statustext, + '_serialize' => array('status','statustext'), + )); + } - $this->set(array( - 'status' => $status, - 'statustext' => $statustext, - '_serialize' => array('status','statustext'), - )); - } + public function daemonControl($id, $command, $monitor=null, $daemon=null) { + $args = ''; + $daemons = array(); - public function daemonControl($id, $command, $monitor=null, $daemon=null) { - $args = ''; - $daemons = array(); + if (!$monitor) { + // Need to see if it is local or remote + $monitor = $this->Monitor->find('first', array( + 'fields' => array('Type', 'Function'), + 'conditions' => array('Id' => $id) + )); + $monitor = $monitor['Monitor']; + } - if (!$monitor) { - // Need to see if it is local or remote - $monitor = $this->Monitor->find('first', array( - 'fields' => array('Type', 'Function'), - 'conditions' => array('Id' => $id) - )); - $monitor = $monitor['Monitor']; - } + if ($monitor['Type'] == 'Local') { + $args = '-d ' . $monitor['Device']; + } else { + $args = '-m ' . $id; + } - if ($monitor['Type'] == 'Local') { - $args = "-d " . $monitor['Device']; - } else { - $args = "-m " . $id; - } + if ($monitor['Function'] == 'Monitor') { + array_push($daemons, 'zmc'); + } else { + array_push($daemons, 'zmc', 'zma'); + } + + $zm_path_bin = Configure::read('ZM_PATH_BIN'); - if ($monitor['Function'] == 'Monitor') { - array_push($daemons, 'zmc'); - } else { - array_push($daemons, 'zmc', 'zma'); - } - - $zm_path_bin = Configure::read('ZM_PATH_BIN'); - - foreach ($daemons as $daemon) { - $shellcmd = escapeshellcmd("$zm_path_bin/zmdc.pl $command $daemon $args"); - $status = exec( $shellcmd ); - } - } - -} + foreach ($daemons as $daemon) { + $shellcmd = escapeshellcmd("$zm_path_bin/zmdc.pl $command $daemon $args"); + $status = exec( $shellcmd ); + } + } +} // end class MonitorsController From 0d7fff761c2aa99fba4645d2a06f9353ce9be3de Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Fri, 22 Dec 2017 11:38:42 -0800 Subject: [PATCH 08/19] upgrade find_all to take parameters --- web/includes/Storage.php | 39 +++++++++++++++++++++++++++++++-------- 1 file changed, 31 insertions(+), 8 deletions(-) diff --git a/web/includes/Storage.php b/web/includes/Storage.php index 5bbdcbbdf..44749089a 100644 --- a/web/includes/Storage.php +++ b/web/includes/Storage.php @@ -70,15 +70,38 @@ class Storage { Warning( "Unknown function call Storage->$fn from $file:$line" ); } } - public static function find_all() { - $storage_areas = array(); - $result = dbQuery( 'SELECT * FROM Storage ORDER BY Name'); - $results = $result->fetchALL(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'Storage' ); - foreach ( $results as $row => $obj ) { - $storage_areas[] = $obj; - $storage_cache[$obj->Id()] = $obj; +public static function find_all( $parameters = null, $options = null ) { + $filters = array(); + $sql = 'SELECT * FROM Storage '; + $values = array(); + + if ( $parameters ) { + $fields = array(); + $sql .= 'WHERE '; + foreach ( $parameters as $field => $value ) { + if ( $value == null ) { + $fields[] = $field.' IS NULL'; + } else if ( is_array( $value ) ) { + $func = function(){return '?';}; + $fields[] = $field.' IN ('.implode(',', array_map( $func, $value ) ). ')'; + $values += $value; + + } else { + $fields[] = $field.'=?'; + $values[] = $value; + } + } + $sql .= implode(' AND ', $fields ); } - return $storage_areas; + if ( $options and isset($options['order']) ) { + $sql .= ' ORDER BY ' . $options['order']; + } + $result = dbQuery($sql, $values); + $results = $result->fetchALL(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'Storage'); + foreach ( $results as $row => $obj ) { + $filters[] = $obj; + } + return $filters; } public function disk_usage_percent() { $path = $this->Path(); From 0c350b8f4157f32b5055b50e86f42a7c574144a8 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Fri, 22 Dec 2017 11:38:59 -0800 Subject: [PATCH 09/19] add ServerId to Storage --- db/zm_create.sql.in | 1 + db/zm_update-1.31.18.sql | 12 ++++++++++++ 2 files changed, 13 insertions(+) create mode 100644 db/zm_update-1.31.18.sql diff --git a/db/zm_create.sql.in b/db/zm_create.sql.in index b5e58d422..ef13ab924 100644 --- a/db/zm_create.sql.in +++ b/db/zm_create.sql.in @@ -640,6 +640,7 @@ CREATE TABLE `Storage` ( `Type` enum('local','s3fs') NOT NULL default 'local', `DiskSpace` bigint unsigned default NULL, `Scheme enum('Deep','Medium','Shallow') NOT NULL default 'Medium', + `ServerId` int(10) unsigned, PRIMARY KEY (`Id`) ) ENGINE=@ZM_MYSQL_ENGINE@; diff --git a/db/zm_update-1.31.18.sql b/db/zm_update-1.31.18.sql new file mode 100644 index 000000000..56e15dd3a --- /dev/null +++ b/db/zm_update-1.31.18.sql @@ -0,0 +1,12 @@ + +SET @s = (SELECT IF( + (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = DATABASE() + AND table_name = 'Storage' + AND column_name = 'ServerId' + ) > 0, + "SELECT 'Column ServerId already exists in Storage'", + "ALTER TABLE Storage ADD `ServerId` int(10) unsigned AFTER `Scheme`" + )); + +PREPARE stmt FROM @s; +EXECUTE stmt; From c6bf502ee73f1c20e710dd935803657a2d78127f Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Fri, 22 Dec 2017 11:39:27 -0800 Subject: [PATCH 10/19] only show each Storage area if there are less than 4. --- web/skins/classic/includes/functions.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/web/skins/classic/includes/functions.php b/web/skins/classic/includes/functions.php index 4a2304965..e6a0e1fe4 100644 --- a/web/skins/classic/includes/functions.php +++ b/web/skins/classic/includes/functions.php @@ -320,7 +320,10 @@ if ($reload == 'reload') ob_start(); } $func = function($S){ return ''.$S->Name() . ': ' . $S->disk_usage_percent().'%' . ''; }; #$func = function($S){ return ''.$S->Name() . ': ' . $S->disk_usage_percent().'%' . ''; }; - echo implode( ', ', array_map ( $func, $storage_areas ) ); + if ( count($storage_areas) >= 4 ) + $storage_areas = Storage::find_all( array('ServerId'=>null) ); + if ( count($storage_areas) < 4 ) + echo implode( ', ', array_map ( $func, $storage_areas ) ); echo ' ' . ZM_PATH_MAP .': '. getDiskPercent(ZM_PATH_MAP).'%'; ?> From 2c361de9d3547534023fa702e73185e1b0d2dec1 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Fri, 22 Dec 2017 11:39:43 -0800 Subject: [PATCH 11/19] add Server Storage Areas --- web/skins/classic/views/options.php | 6 +++++- web/skins/classic/views/storage.php | 9 +++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/web/skins/classic/views/options.php b/web/skins/classic/views/options.php index 443fe4337..2ca14f71d 100644 --- a/web/skins/classic/views/options.php +++ b/web/skins/classic/views/options.php @@ -194,7 +194,7 @@ foreach( array_map( 'basename', glob('skins/'.$current_skin.'/css/*',GLOB_ONLYDI +} else if ( $tab == 'servers' ) { ?>
@@ -249,6 +249,7 @@ foreach( array_map( 'basename', glob('skins/'.$current_skin.'/css/*',GLOB_ONLYDI + @@ -260,6 +261,9 @@ foreach( array_map( 'basename', glob('skins/'.$current_skin.'/css/*',GLOB_ONLYDI + Name()), $canEdit ) ?> disabled="disabled"/> diff --git a/web/skins/classic/views/storage.php b/web/skins/classic/views/storage.php index d74ea9079..bca0cdb04 100644 --- a/web/skins/classic/views/storage.php +++ b/web/skins/classic/views/storage.php @@ -43,6 +43,11 @@ $scheme_options = array( 'Shallow' => translate('Shallow'), ); +$servers = Server::find_all(); +$ServersById = array(); +foreach ( $servers as $S ) { + $ServersById[$S->Id()] = $S; +} $focusWindow = true; xhtmlHeaders(__FILE__, translate('Storage')." - ".$newStorage['Name'] ); @@ -67,6 +72,10 @@ xhtmlHeaders(__FILE__, translate('Storage')." - ".$newStorage['Name'] ); + + + + From 74269fea73a53d5a558d1f7fd5c6699144988db4 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Fri, 22 Dec 2017 12:32:45 -0800 Subject: [PATCH 12/19] make montagereview load event images from the server that the storage is located on --- web/includes/functions.php | 1 + web/skins/classic/views/js/montagereview.js | 13 +++++++++++-- web/skins/classic/views/js/montagereview.js.php | 15 +++++++++++++-- web/skins/classic/views/montagereview.php | 2 +- 4 files changed, 26 insertions(+), 5 deletions(-) diff --git a/web/includes/functions.php b/web/includes/functions.php index 10ee34015..fed583f03 100644 --- a/web/includes/functions.php +++ b/web/includes/functions.php @@ -1280,6 +1280,7 @@ function parseFilter( &$filter, $saveToSession=false, $querySep='&' ) { $filter['sql'] .= ' not regexp '.$value; break; case '=[]' : + case 'IN' : $filter['sql'] .= ' in ('.join( ',', $valueList ).')'; break; case '![]' : diff --git a/web/skins/classic/views/js/montagereview.js b/web/skins/classic/views/js/montagereview.js index 0c0237f85..e1f854f66 100644 --- a/web/skins/classic/views/js/montagereview.js +++ b/web/skins/classic/views/js/montagereview.js @@ -55,7 +55,17 @@ function SetImageSource( monId, time ) { if ( eMonId[i] == monId && time >= eStartSecs[i] && time <= eEndSecs[i] ) { var duration = eEndSecs[i]-eStartSecs[i]; var frame = parseInt((time - eStartSecs[i])/(duration)*eventFrames[i])+1; -console.log("SetImageSource: " + time + " duration: " + duration + " frame: " + frame ); + var storage = Storage[eStorageId[i]]; + if ( storage.ServerId ) { + var server = Servers[storage.ServerId]; + if ( server ) { +console.log( server.Hostname + " for event " + eId[i] ); + return location.protocol + '//' + server.Hostname + '/index.php?view=image&eid=' + eId[i] + '&fid='+frame + "&width=" + monitorCanvasObj[monId].width + "&height=" + monitorCanvasObj[monId].height; + } else { + console.log("No server found for " + storage.ServerId ); + } + } + console.log("No storage found for " + eStorageId[i] ); return "index.php?view=image&eid=" + eId[i] + '&fid='+frame + "&width=" + monitorCanvasObj[monId].width + "&height=" + monitorCanvasObj[monId].height; } } // end for @@ -465,7 +475,6 @@ function setSpeed( speed_index ) { currentSpeed = parseFloat(speeds[speed_index]); speedIndex = speed_index; playSecsperInterval = Math.floor( 1000 * currentSpeed * currentDisplayInterval ) / 1000000; -console.log("playSecsPerInterval: " + playSecsperInterval + " = currentspeed:" + currentSpeed + " * " + currentDisplayInterval + " /1000"); showSpeed(speed_index); if ( timerInterval != currentDisplayInterval || currentSpeed == 0 ) timerFire(); // if the timer isn't firing we need to trigger it to update } diff --git a/web/skins/classic/views/js/montagereview.js.php b/web/skins/classic/views/js/montagereview.js.php index b1988ed86..19089a315 100644 --- a/web/skins/classic/views/js/montagereview.js.php +++ b/web/skins/classic/views/js/montagereview.js.php @@ -23,6 +23,7 @@ var imageLoadTimesNeeded=15; // and how many we need var timeLabelsFractOfRow = 0.9; var eMonId = []; var eId = []; +var eStorageId = []; var eStartSecs = []; var eEndSecs = []; var eventFrames = []; // this is going to presume all frames equal durationlength @@ -43,7 +44,6 @@ $index = 0; $anyAlarms = false; if ( ! $initialModeIsLive ) { -Warning($eventsSql); $result = dbQuery( $eventsSql ); if ( ! $result ) { Fatal('SQL-ERR'); @@ -56,6 +56,7 @@ Warning($eventsSql); if ( $maxTimeSecs < $event['CalcEndTimeSecs'] ) $maxTimeSecs = $event['CalcEndTimeSecs']; echo " eMonId[$index]=" . $event['MonitorId'] . "; +eStorageId[$index]=".$event['StorageId'] . "; eId[$index]=" . $event['Id'] . "; eStartSecs[$index]=" . $event['StartTimeSecs'] . "; eEndSecs[$index]=" . $event['CalcEndTimeSecs'] . "; @@ -146,7 +147,17 @@ if ( $mId > 0 ) { echo "var maxScore=$maxScore;\n"; // used to skip frame load if we find no alarms. } // end if initialmodeislive -echo "var monitorName = [];\n"; + +echo "var Storage = []\n"; +foreach ( Storage::find_all() as $Storage ) { +echo 'Storage[' . $Storage->Id() . '] = ' . json_encode($Storage). ";\n"; +} +echo "var Servers = []\n"; +foreach ( Server::find_all() as $Server ) { +echo 'Servers[' . $Server->Id() . '] = ' . json_encode($Server). ";\n"; +} +echo " +var monitorName = [];\n"; echo "var monitorLoading = [];\n"; echo "var monitorImageObject = [];\n"; echo "var monitorImageURL = [];\n"; diff --git a/web/skins/classic/views/montagereview.php b/web/skins/classic/views/montagereview.php index 3452b2f5f..56dadabd1 100644 --- a/web/skins/classic/views/montagereview.php +++ b/web/skins/classic/views/montagereview.php @@ -94,7 +94,7 @@ if (isset($_REQUEST['minTime']) && isset($_REQUEST['maxTime']) && count($display // Note we round up just a bit on the end time as otherwise you get gaps, like 59.78 to 00 in the next second, which can give blank frames when moved through slowly. $eventsSql = ' - SELECT E.Id,E.Name,UNIX_TIMESTAMP(E.StartTime) AS StartTimeSecs, + SELECT E.Id,E.Name,E.StorageId,UNIX_TIMESTAMP(E.StartTime) AS StartTimeSecs, CASE WHEN E.EndTime IS NULL THEN (SELECT UNIX_TIMESTAMP(DATE_ADD(E.StartTime, Interval max(Delta)+0.5 Second)) FROM Frames F WHERE F.EventId=E.Id) ELSE UNIX_TIMESTAMP(E.EndTime) END AS CalcEndTimeSecs, E.Length, From 7fcbd86ba0bd4c7c3b3e4efd27529dc3df274b48 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Fri, 29 Dec 2017 15:29:57 -0500 Subject: [PATCH 13/19] fix auditing Medium directory structures --- scripts/zmaudit.pl.in | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/scripts/zmaudit.pl.in b/scripts/zmaudit.pl.in index 2de067c3e..e1c97e448 100644 --- a/scripts/zmaudit.pl.in +++ b/scripts/zmaudit.pl.in @@ -238,8 +238,13 @@ MAIN: while( $loop ) { } elsif ( $$Storage{Scheme} eq 'Medium' ) { foreach my $event_dir ( glob("$monitor_dir/*/*") ) { next if ! -d $event_dir; - my $Event = $fs_events->{$event} = new ZoneMinder::Event(); - $$Event{Id} = $event; + my ( $date, $event_id ) = $event_dir =~ /^$monitor_dir\/(\d{4}\-\d{2}\-\d{2})\/(\d\+)$/; + if ( ! $event_id ) { + Debug("Unable to parse date/event_id from $event_dir"); + next; + } + my $Event = $fs_events->{$event_id} = new ZoneMinder::Event(); + $$Event{Id} = $event_id; $$Event{Path} = $event_dir; $Event->MonitorId( $monitor_dir ); $Event->StorageId( $Storage->Id() ); From a79017b16888b30d819a14936f02c379b2c06cfa Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Mon, 1 Jan 2018 12:43:47 -0500 Subject: [PATCH 14/19] add a KEY to Events for EndTime and DiskSpace, since we are constantly selecting on those. Insert the Update DiskSpace filter on db creation. --- db/zm_create.sql.in | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/db/zm_create.sql.in b/db/zm_create.sql.in index ef13ab924..b2d62d461 100644 --- a/db/zm_create.sql.in +++ b/db/zm_create.sql.in @@ -209,11 +209,12 @@ CREATE TABLE `Events` ( `StateId` int(10) unsigned NOT NULL, `Orientation` enum('0','90','180','270','hori','vert') NOT NULL default '0', `DiskSpace` bigint unsigned default NULL, - PRIMARY KEY (`Id`,`MonitorId`), + PRIMARY KEY (`Id`), KEY `MonitorId` (`MonitorId`), KEY `StartTime` (`StartTime`), KEY `Frames` (`Frames`), - KEY `Archived` (`Archived`) + KEY `Archived` (`Archived`), + KEY `EndTime_DiskSpace` (`EndTime`,`DiskSpace`) ) ENGINE=@ZM_MYSQL_ENGINE@; -- @@ -670,6 +671,7 @@ insert into Users VALUES (NULL,'admin',password('admin'),'',1,'View','Edit','Edi -- Add a sample filter to purge the oldest 100 events when the disk is 95% full -- insert into Filters values (NULL,'PurgeWhenFull','{"sort_field":"Id","terms":[{"val":0,"attr":"Archived","op":"="},{"cnj":"and","val":95,"attr":"DiskPercent","op":">="}],"limit":100,"sort_asc":1}',0,0,0,0,0,0,'',1,0,1,0); +insert into Filters values (NULL,'Update DiskSpace','{"terms":[{"attr":"DiskSpace","op":"IS","val":"NULL"}],"sort_field":"Id","sort_asc":"1","limit":"100"}',0,0,0,0,0,0,'',1,1,1,0); -- -- Add in some sample control protocol definitions From edd5bd8874f04b921f6a3847a48a4b5345bda305 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Mon, 1 Jan 2018 12:44:09 -0500 Subject: [PATCH 15/19] create the Update DIskSpace filter if it doesn't exist --- db/zm_update-1.31.18.sql | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/db/zm_update-1.31.18.sql b/db/zm_update-1.31.18.sql index 56e15dd3a..fd000bcfa 100644 --- a/db/zm_update-1.31.18.sql +++ b/db/zm_update-1.31.18.sql @@ -10,3 +10,14 @@ SET @s = (SELECT IF( PREPARE stmt FROM @s; EXECUTE stmt; + +SET @s = (SELECT IF( + (SELECT COUNT(*) FROM Filters WHERE Name = 'Update DiskSpace' + AND Query = '{"terms":[{"attr":"DiskSpace","op":"IS","val":"NULL"}],"sort_field":"Id","sort_asc":"1","limit":"100"}' + ) > 0, + "SELECT 'Update Disk Space Filter already exists.'", + "INSERT INTO Filters (Name,Query,UpdateDiskSpace,Background) values ('Update DiskSpace','{\"terms\":[{\"attr\":\"DiskSpace\",\"op\":\"IS\",\"val\":\"NULL\"}],\"sort_field\":\"Id\",\"sort_asc\":\"1\",\"limit\":\"100\"}',1,1)" + )); + +PREPARE stmt FROM @s; +EXECUTE stmt; From 1cd69c69b98b67ecb93c8d95f712589c8d3a7c1c Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Mon, 1 Jan 2018 13:10:39 -0500 Subject: [PATCH 16/19] add defining ZM_SERVER_ID after loading config --- web/api/app/Config/bootstrap.php.in | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/web/api/app/Config/bootstrap.php.in b/web/api/app/Config/bootstrap.php.in index cc096f233..d1cd7857d 100644 --- a/web/api/app/Config/bootstrap.php.in +++ b/web/api/app/Config/bootstrap.php.in @@ -142,6 +142,27 @@ foreach( $configvals as $key => $value) { Configure::write( $key, $value ); } +// For Human-readability, use ZM_SERVER_HOST or ZM_SERVER_NAME in zm.conf, and convert it here to a ZM_SERVER_ID +if ( ! defined('ZM_SERVER_ID') ) { + App::uses('ClassRegistry', 'Utility'); + $ServerModel = ClassRegistry::init('Server'); + if ( defined('ZM_SERVER_NAME') and ZM_SERVER_NAME ) { + $Server = $ServerModel->find( 'first', array( 'conditions'=>array('Name'=>ZM_SERVER_NAME) ) ); + if ( ! $Server ) { + Error('Invalid Multi-Server configration detected. ZM_SERVER_NAME set to ' . ZM_SERVER_NAME . ' in zm.conf, but no corresponding entry found in Servers table.'); + } else { + define( 'ZM_SERVER_ID', $Server['Server']['Id'] ); + } + } else if ( defined('ZM_SERVER_HOST') and ZM_SERVER_HOST ) { + $Server = $ServerModel->find( 'first', array( 'conditions'=>array('Name'=>ZM_SERVER_HOST) ) ); + if ( ! $Server ) { + Error('Invalid Multi-Server configration detected. ZM_SERVER_HOST set to ' . ZM_SERVER_HOST . ' in zm.conf, but no corresponding entry found in Servers table.'); + } else { + define( 'ZM_SERVER_ID', $Server['Server']['Id'] ); + } + } +} + function process_configfile($configFile) { if ( is_readable( $configFile ) ) { $configvals = array(); From 6c07347721065789470c570e151b44a6818a499f Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Mon, 1 Jan 2018 13:19:16 -0500 Subject: [PATCH 17/19] Fix Update DiskSpace Filter adding --- db/zm_create.sql.in | 21 +++++++++++++++++++-- db/zm_update-1.31.18.sql | 4 ++-- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/db/zm_create.sql.in b/db/zm_create.sql.in index b2d62d461..f9ac3b6d2 100644 --- a/db/zm_create.sql.in +++ b/db/zm_create.sql.in @@ -670,8 +670,25 @@ insert into Users VALUES (NULL,'admin',password('admin'),'',1,'View','Edit','Edi -- -- Add a sample filter to purge the oldest 100 events when the disk is 95% full -- -insert into Filters values (NULL,'PurgeWhenFull','{"sort_field":"Id","terms":[{"val":0,"attr":"Archived","op":"="},{"cnj":"and","val":95,"attr":"DiskPercent","op":">="}],"limit":100,"sort_asc":1}',0,0,0,0,0,0,'',1,0,1,0); -insert into Filters values (NULL,'Update DiskSpace','{"terms":[{"attr":"DiskSpace","op":"IS","val":"NULL"}],"sort_field":"Id","sort_asc":"1","limit":"100"}',0,0,0,0,0,0,'',1,1,1,0); + `Id` int(10) unsigned NOT NULL auto_increment, + `Name` varchar(64) NOT NULL default '', + `Query` text NOT NULL, + `AutoArchive` tinyint(3) unsigned NOT NULL default '0', + `AutoVideo` tinyint(3) unsigned NOT NULL default '0', + `AutoUpload` tinyint(3) unsigned NOT NULL default '0', + `AutoEmail` tinyint(3) unsigned NOT NULL default '0', + `AutoMessage` tinyint(3) unsigned NOT NULL default '0', + `AutoExecute` tinyint(3) unsigned NOT NULL default '0', + `AutoExecuteCmd` tinytext, + `AutoDelete` tinyint(3) unsigned NOT NULL default '0', + `AutoMove` tinyint(3) unsigned NOT NULL default '0', + `AutoMoveTo` smallint(5) unsigned NOT NULL default 0, + `UpdateDiskSpace` tinyint(3) unsigned NOT NULL default '0', + `Background` tinyint(1) unsigned NOT NULL default '0', + `Concurrent` tinyint(1) unsigned NOT NULL default '0', + +insert into Filters values (NULL,'PurgeWhenFull','{"sort_field":"Id","terms":[{"val":0,"attr":"Archived","op":"="},{"cnj":"and","val":95,"attr":"DiskPercent","op":">="}],"limit":100,"sort_asc":1}',0/*AutoArchive*/,0/*AutoVideo*/,0/*AutoUpload*/,0/*AutoEmail*/,0/*AutoMessage*/,0/*AutoExecute*/,'',1/*AutoDelete*/,0/*AutoMove*/,0/*MoveTo*/,0/*UpdateDiskSpace*/,1/*Background*/,0/*Concurrent*/); +insert into Filters values (NULL,'Update DiskSpace','{"terms":[{"attr":"DiskSpace","op":"IS","val":"NULL"}]}',0,0,0,0,0,0,'',0,0,0,1,1,0); -- -- Add in some sample control protocol definitions diff --git a/db/zm_update-1.31.18.sql b/db/zm_update-1.31.18.sql index fd000bcfa..5ba3b6caa 100644 --- a/db/zm_update-1.31.18.sql +++ b/db/zm_update-1.31.18.sql @@ -13,10 +13,10 @@ EXECUTE stmt; SET @s = (SELECT IF( (SELECT COUNT(*) FROM Filters WHERE Name = 'Update DiskSpace' - AND Query = '{"terms":[{"attr":"DiskSpace","op":"IS","val":"NULL"}],"sort_field":"Id","sort_asc":"1","limit":"100"}' + AND Query = '{"terms":[{"attr":"DiskSpace","op":"IS","val":"NULL"}]}' ) > 0, "SELECT 'Update Disk Space Filter already exists.'", - "INSERT INTO Filters (Name,Query,UpdateDiskSpace,Background) values ('Update DiskSpace','{\"terms\":[{\"attr\":\"DiskSpace\",\"op\":\"IS\",\"val\":\"NULL\"}],\"sort_field\":\"Id\",\"sort_asc\":\"1\",\"limit\":\"100\"}',1,1)" + "INSERT INTO Filters (Name,Query,UpdateDiskSpace,Background) values ('Update DiskSpace','{\"terms\":[{\"attr\":\"DiskSpace\",\"op\":\"IS\",\"val\":\"NULL\"}]}',1,1)" )); PREPARE stmt FROM @s; From b62343fb2c8adebc6d1f8a6a0182e023a8ddcbde Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Mon, 1 Jan 2018 13:19:30 -0500 Subject: [PATCH 18/19] bump to 1.31.18 --- version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version b/version index 874058d96..d1be1a9fa 100644 --- a/version +++ b/version @@ -1 +1 @@ -1.31.17 +1.31.18 From 1b1b93f8111e50dfcc5ce9f614009a299cfccf68 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Mon, 1 Jan 2018 14:43:02 -0500 Subject: [PATCH 19/19] use CakePHP-Enum-Behavior to add support for ENUMs to the Monitor model. This should fix #48 --- .gitmodules | 3 +++ web/api/app/Config/bootstrap.php.in | 1 + web/api/app/Controller/MonitorsController.php | 22 +++++++++++++------ web/api/app/Model/Monitor.php | 19 ++++++++++++---- web/api/app/Plugin/CakePHP-Enum-Behavior | 1 + web/api/app/View/Monitors/json/add.ctp | 2 ++ web/api/app/View/Monitors/xml/add.ctp | 2 ++ 7 files changed, 39 insertions(+), 11 deletions(-) create mode 160000 web/api/app/Plugin/CakePHP-Enum-Behavior create mode 100644 web/api/app/View/Monitors/json/add.ctp create mode 100644 web/api/app/View/Monitors/xml/add.ctp diff --git a/.gitmodules b/.gitmodules index 0fa8df21a..fc8ea09d6 100644 --- a/.gitmodules +++ b/.gitmodules @@ -2,3 +2,6 @@ path = web/api/app/Plugin/Crud url = https://github.com/FriendsOfCake/crud.git branch = 3.0 +[submodule "web/api/app/Plugin/CakePHP-Enum-Behavior"] + path = web/api/app/Plugin/CakePHP-Enum-Behavior + url = https://github.com/asper/CakePHP-Enum-Behavior.git diff --git a/web/api/app/Config/bootstrap.php.in b/web/api/app/Config/bootstrap.php.in index d1cd7857d..4e2d99c63 100644 --- a/web/api/app/Config/bootstrap.php.in +++ b/web/api/app/Config/bootstrap.php.in @@ -70,6 +70,7 @@ Cache::config('default', array('engine' => 'Apc')); * */ CakePlugin::load('Crud'); +CakePlugin::load('CakePHP-Enum-Behavior'); /** * You can attach event listeners to the request lifecycle as Dispatcher Filter. By default CakePHP bundles two filters: diff --git a/web/api/app/Controller/MonitorsController.php b/web/api/app/Controller/MonitorsController.php index c24cd12f2..0880cc68e 100644 --- a/web/api/app/Controller/MonitorsController.php +++ b/web/api/app/Controller/MonitorsController.php @@ -15,10 +15,13 @@ class MonitorsController extends AppController { */ public $components = array('Paginator', 'RequestHandler'); + public function beforeRender() { + $this->set($this->Monitor->enumValues()); + } public function beforeFilter() { parent::beforeFilter(); $canView = $this->Session->Read('monitorPermission'); - if ($canView =='None') { + if ($canView == 'None') { throw new UnauthorizedException(__('Insufficient Privileges')); return; } @@ -109,10 +112,9 @@ class MonitorsController extends AppController { * @return void */ public function add() { - if ($this->request->is('post')) { + if ( $this->request->is('post') ) { - if ($this->Session->Read('systemPermission') != 'Edit') - { + if ( $this->Session->Read('systemPermission') != 'Edit' ) { throw new UnauthorizedException(__('Insufficient privileges')); return; } @@ -120,8 +122,15 @@ class MonitorsController extends AppController { $this->Monitor->create(); if ($this->Monitor->save($this->request->data)) { $this->daemonControl($this->Monitor->id, 'start'); - return $this->flash(__('The monitor has been saved.'), array('action' => 'index')); + //return $this->flash(__('The monitor has been saved.'), array('action' => 'index')); + $message = 'Saved'; + } else { + $message = 'Error'; } + $this->set(array( + 'message' => $message, + '_serialize' => array('message') + )); } } @@ -138,8 +147,7 @@ class MonitorsController extends AppController { if (!$this->Monitor->exists($id)) { throw new NotFoundException(__('Invalid monitor')); } - if ($this->Session->Read('monitorPermission') != 'Edit') - { + if ($this->Session->Read('monitorPermission') != 'Edit') { throw new UnauthorizedException(__('Insufficient privileges')); return; } diff --git a/web/api/app/Model/Monitor.php b/web/api/app/Model/Monitor.php index 0504dd22a..c9697b694 100644 --- a/web/api/app/Model/Monitor.php +++ b/web/api/app/Model/Monitor.php @@ -86,10 +86,10 @@ class Monitor extends AppModel { ); /** - * * hasMany associations - * * - * * @var array - * */ + * hasMany associations + * + * @var array + */ public $hasAndBelongsToMany = array( 'Group' => array( 'className' => 'Group', @@ -108,5 +108,16 @@ class Monitor extends AppModel { 'counterQuery' => '' ), ); + public $actsAs = array( + 'CakePHP-Enum-Behavior.Enum' => array( + 'Type' => array('Local','Remote','File','Ffmpeg','Libvlc','cURL'), + 'Function' => array('None','Monitor','Modect','Record','Mocord','Nodect'), + 'Orientation' => array('0','90','180','270','hori','vert'), + 'OutputCodec' => array('h264','mjpeg','mpeg1','mpeg2'), + 'OutputContainer' => array('auto','mp4','mkv'), + 'DefaultView' => array('Events','Control'), + 'Status' => array('Unknown','NotRunning','Running','NoSignal','Signal'), + ) + ); } diff --git a/web/api/app/Plugin/CakePHP-Enum-Behavior b/web/api/app/Plugin/CakePHP-Enum-Behavior new file mode 160000 index 000000000..7108489f2 --- /dev/null +++ b/web/api/app/Plugin/CakePHP-Enum-Behavior @@ -0,0 +1 @@ +Subproject commit 7108489f218c54d36d235d3af91d6da2f8311237 diff --git a/web/api/app/View/Monitors/json/add.ctp b/web/api/app/View/Monitors/json/add.ctp new file mode 100644 index 000000000..77d2dd08b --- /dev/null +++ b/web/api/app/View/Monitors/json/add.ctp @@ -0,0 +1,2 @@ +echo json_encode($message); +echo json_encode($monitor); diff --git a/web/api/app/View/Monitors/xml/add.ctp b/web/api/app/View/Monitors/xml/add.ctp new file mode 100644 index 000000000..09fb8979a --- /dev/null +++ b/web/api/app/View/Monitors/xml/add.ctp @@ -0,0 +1,2 @@ +$xml = Xml::fromArray(array('response' => $message)); +echo $xml->asXML();