Merge branch 'storageareas' into record_audio

This commit is contained in:
Isaac Connor 2016-09-20 12:38:47 -04:00
commit bf45f489f7
7 changed files with 167 additions and 164 deletions

View File

@ -28,29 +28,13 @@ use 5.006;
use strict; use strict;
use warnings; use warnings;
require Exporter;
require ZoneMinder::Base; require ZoneMinder::Base;
require ZoneMinder::Object;
require ZoneMinder::Storage;
require ZoneMinder::Server;
our @ISA = qw(Exporter ZoneMinder::Base); #our @ISA = qw(Exporter ZoneMinder::Base);
use parent qw(ZoneMinder::Object);
# Items to export into callers namespace by default. Note: do not export
# names by default without a very good reason. Use EXPORT_OK instead.
# Do not simply export all your public functions/methods/constants.
# This allows declaration use ZoneMinder ':all';
# If you do not need this, moving things directly into @EXPORT or @EXPORT_OK
# will save memory.
our %EXPORT_TAGS = (
'functions' => [ qw(
) ]
);
push( @{$EXPORT_TAGS{all}}, @{$EXPORT_TAGS{$_}} ) foreach keys %EXPORT_TAGS;
our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
our @EXPORT = qw();
our $VERSION = $ZoneMinder::Base::VERSION;
# ========================================================================== # ==========================================================================
# #
@ -61,39 +45,11 @@ our $VERSION = $ZoneMinder::Base::VERSION;
use ZoneMinder::Config qw(:all); use ZoneMinder::Config qw(:all);
use ZoneMinder::Logger qw(:all); use ZoneMinder::Logger qw(:all);
use ZoneMinder::Database qw(:all); use ZoneMinder::Database qw(:all);
require ZoneMinder::Server;
require ZoneMinder::Storage;
use POSIX; use POSIX;
use vars qw/ $table $primary_key /;
sub new { $table = 'Monitors';
my ( $parent, $id, $data ) = @_; $primary_key = 'Id';
my $self = {};
bless $self, $parent;
if ( ( $$self{Id} = $id ) or $data ) {
#$log->debug("loading $parent $id") if $debug or DEBUG_ALL;
$self->load( $data );
}
return $self;
} # end sub new
sub load {
my ( $self, $data ) = @_;
my $type = ref $self;
if ( ! $data ) {
#$log->debug("Object::load Loading from db $type");
$data = $ZoneMinder::Database::dbh->selectrow_hashref( 'SELECT * FROM Monitors WHERE Id=?', {}, $$self{Id} );
if ( ! $data ) {
if ( $ZoneMinder::Database::dbh->errstr ) {
Error( "Failure to load Monitor record for $$self{id}: Reason: " . $ZoneMinder::Database::dbh->errstr );
} # end if
} # end if
} # end if ! $data
if ( $data and %$data ) {
@$self{keys %$data} = values %$data;
} # end if
} # end sub load
sub Server { sub Server {
return new ZoneMinder::Server( $_[0]{ServerId} ); return new ZoneMinder::Server( $_[0]{ServerId} );

View File

@ -73,7 +73,7 @@ class Event {
} }
public function LinkPath() { public function Link_Path() {
if ( ZM_USE_DEEP_STORAGE ) { if ( ZM_USE_DEEP_STORAGE ) {
return $this->{'MonitorId'} .'/'.strftime( "%y/%m/%d/.", $this->Time()).$this->{'Id'}; return $this->{'MonitorId'} .'/'.strftime( "%y/%m/%d/.", $this->Time()).$this->{'Id'};
} }
@ -82,6 +82,7 @@ class Event {
} }
public function delete() { public function delete() {
# This wouldn't work with foreign keys
dbQuery( 'DELETE FROM Events WHERE Id = ?', array($this->{'Id'}) ); dbQuery( 'DELETE FROM Events WHERE Id = ?', array($this->{'Id'}) );
if ( !ZM_OPT_FAST_DELETE ) { if ( !ZM_OPT_FAST_DELETE ) {
dbQuery( 'DELETE FROM Stats WHERE EventId = ?', array($this->{'Id'}) ); dbQuery( 'DELETE FROM Stats WHERE EventId = ?', array($this->{'Id'}) );
@ -90,15 +91,28 @@ class Event {
# Assumption: All events haev a start time # Assumption: All events haev a start time
$start_date = date_parse( $this->{'StartTime'} ); $start_date = date_parse( $this->{'StartTime'} );
if ( ! $start_date ) {
Error("Unable to parse start time for event " . $this->{'Id'} . ' not deleting files.' );
return;
}
$start_date['year'] = $start_date['year'] % 100; $start_date['year'] = $start_date['year'] % 100;
$Storage = $this->Storage(); $Storage = $this->Storage();
# So this is because ZM creates a link under teh day pointing to the time that the event happened. # So this is because ZM creates a link under teh day pointing to the time that the event happened.
if ( ! $this->Link_Path() ) {
Error("Unable to determine link path for event " . $this->{'Id'} . ' not deleting files.' );
return;
}
$eventlink_path = $Storage->Path().'/'.$this->Link_Path(); $eventlink_path = $Storage->Path().'/'.$this->Link_Path();
if ( $id_files = glob( $eventlink_path ) ) { if ( $id_files = glob( $eventlink_path ) ) {
if ( ! $eventPath = readlink($id_files[0]) ) {
Error("Unable to read link at $id_files[0]");
return;
}
# I know we are using arrays here, but really there can only ever be 1 in the array # I know we are using arrays here, but really there can only ever be 1 in the array
$eventPath = preg_replace( '/\.'.$event['Id'].'$/', readlink($id_files[0]), $id_files[0] ); $eventPath = preg_replace( '/\.'.$this->{'Id'}.'$/', $eventPath, $id_files[0] );
deletePath( $eventPath ); deletePath( $eventPath );
deletePath( $id_files[0] ); deletePath( $id_files[0] );
$pathParts = explode( '/', $eventPath ); $pathParts = explode( '/', $eventPath );
@ -118,7 +132,7 @@ class Event {
} # ! ZM_OPT_FAST_DELETE } # ! ZM_OPT_FAST_DELETE
} # end Event->delete } # end Event->delete
public function getStreamSrc( $args, $querySep='&' ) { public function getStreamSrc( $args, $querySep='&' ) {
return ( ZM_BASE_PATH != '/' ? ZM_BASE_PATH : '' ).'/index.php?view=view_video&eid='.$this->{'Id'}; return ( ZM_BASE_PATH != '/' ? ZM_BASE_PATH : '' ).'/index.php?view=view_video&eid='.$this->{'Id'};
$streamSrc = ZM_BASE_URL.ZM_PATH_ZMS; $streamSrc = ZM_BASE_URL.ZM_PATH_ZMS;

View File

@ -1,51 +1,74 @@
<?php <?php
require_once( 'database.php' ); require_once( 'database.php' );
class Storage { class Storage {
public function __construct( $IdOrRow = NULL ) { public function __construct( $IdOrRow = NULL ) {
$row = NULL; $row = NULL;
if ( $IdOrRow ) { if ( $IdOrRow ) {
if ( is_integer( $IdOrRow ) or is_numeric( $IdOrRow ) ) { if ( is_integer( $IdOrRow ) or is_numeric( $IdOrRow ) ) {
$row = dbFetchOne( 'SELECT * FROM Storage WHERE Id=?', NULL, array( $IdOrRow ) ); $row = dbFetchOne( 'SELECT * FROM Storage WHERE Id=?', NULL, array( $IdOrRow ) );
if ( ! $row ) { if ( ! $row ) {
Error("Unable to load Storage record for Id=" . $IdOrRow ); Error("Unable to load Storage record for Id=" . $IdOrRow );
} }
} elseif ( is_array( $IdOrRow ) ) { } elseif ( is_array( $IdOrRow ) ) {
$row = $IdOrRow; $row = $IdOrRow;
} }
}
if ( $row ) {
foreach ($row as $k => $v) {
$this->{$k} = $v;
}
} else {
$this->{'Name'} = '';
$this->{'Path'} = '';
}
} }
if ( $row ) {
foreach ($row as $k => $v) {
$this->{$k} = $v;
}
} else {
$this->{'Name'} = '';
$this->{'Path'} = '';
}
}
public function Path() { public function Path() {
if ( isset( $this->{'Path'} ) and ( $this->{'Path'} != '' ) ) { if ( isset( $this->{'Path'} ) and ( $this->{'Path'} != '' ) ) {
return $this->{'Path'}; return $this->{'Path'};
} else if ( ! isset($this->{'Id'}) ) { } else if ( ! isset($this->{'Id'}) ) {
return ZM_DIR_EVENTS; return ZM_DIR_EVENTS;
}
return $this->{'Name'};
}
public function __call( $fn, array $args= NULL){
if(isset($this->{$fn})){
return $this->{$fn};
#array_unshift($args, $this);
#call_user_func_array( $this->{$fn}, $args);
}
} }
public static function find_all() { return $this->{'Name'};
$storage_areas = array(); }
$result = dbQuery( 'SELECT * FROM Storage ORDER BY Name'); public function Name() {
$results = $result->fetchALL(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'Storage' ); if ( isset( $this->{'Name'} ) and ( $this->{'Name'} != '' ) ) {
foreach ( $results as $row => $obj ) { return $this->{'Name'};
$storage_areas[] = $obj; } else if ( ! isset($this->{'Id'}) ) {
} return 'Default';
return $storage_areas;
} }
return $this->{'Name'};
}
public function __call( $fn, array $args= NULL){
if(isset($this->{$fn})){
return $this->{$fn};
#array_unshift($args, $this);
#call_user_func_array( $this->{$fn}, $args);
}
}
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;
}
return $storage_areas;
}
public function disk_usage_percent() {
$path = $this->Path();
$total = disk_total_space( $path );
if ( ! $total ) {
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);
return $usage;
}
} }
?> ?>

View File

@ -124,36 +124,31 @@ if ( !empty($action) ) {
} }
// Event scope actions, view permissions only required // Event scope actions, view permissions only required
if ( canView( 'Events' ) ) if ( canView( 'Events' ) ) {
{
if ( $action == "filter" ) if ( $action == 'filter' ) {
{ if ( !empty($_REQUEST['subaction']) ) {
if ( !empty($_REQUEST['subaction']) )
{
if ( $_REQUEST['subaction'] == "addterm" ) if ( $_REQUEST['subaction'] == "addterm" )
$_REQUEST['filter'] = addFilterTerm( $_REQUEST['filter'], $_REQUEST['line'] ); $_REQUEST['filter'] = addFilterTerm( $_REQUEST['filter'], $_REQUEST['line'] );
elseif ( $_REQUEST['subaction'] == "delterm" ) elseif ( $_REQUEST['subaction'] == "delterm" )
$_REQUEST['filter'] = delFilterTerm( $_REQUEST['filter'], $_REQUEST['line'] ); $_REQUEST['filter'] = delFilterTerm( $_REQUEST['filter'], $_REQUEST['line'] );
} } elseif ( canEdit( 'Events' ) ) {
elseif ( canEdit( 'Events' ) ) $sql = '';
{ $endSql = '';
if ( !empty($_REQUEST['execute']) ) $filterName = '';
$tempFilterName = "_TempFilter".time(); if ( !empty($_REQUEST['execute']) ) {
if ( isset($tempFilterName) ) { // TempFilterName is used in event listing later on
$filterName = $tempFilterName; $tempFilterName = $filterName = "_TempFilter".time();
} } elseif ( !empty($_REQUEST['newFilterName']) ) {
elseif ( !empty($_REQUEST['newFilterName']) ) {
$filterName = $_REQUEST['newFilterName']; $filterName = $_REQUEST['newFilterName'];
$sql = "replace into Filters set Name = ".dbEscape($filterName).",";
$endSql = '';
} }
else { if ( $filterName ) {
$doUpdate = 1; $sql = "REPLACE INTO Filters SET Name = ".dbEscape($filterName).",";
$sql = "update Filters set"; } else {
$endSql = "where Id = ".$_REQUEST['filterId']; $sql = 'UPDATE Filters SET';
$endSql = "where Id = ".$_REQUEST['Id'];
} }
if ( !empty($filterName) || $doUpdate ) if ( !empty($filterName) || $endSql ) {
{
$_REQUEST['filter']['sort_field'] = validStr($_REQUEST['sort_field']); $_REQUEST['filter']['sort_field'] = validStr($_REQUEST['sort_field']);
$_REQUEST['filter']['sort_asc'] = validStr($_REQUEST['sort_asc']); $_REQUEST['filter']['sort_asc'] = validStr($_REQUEST['sort_asc']);
$_REQUEST['filter']['limit'] = validInt($_REQUEST['limit']); $_REQUEST['filter']['limit'] = validInt($_REQUEST['limit']);
@ -180,9 +175,9 @@ if ( !empty($action) ) {
dbQuery( $sql ); dbQuery( $sql );
$refreshParent = true; $refreshParent = true;
} }
} } // end if canedit events
} } // end if action == filter
} } // end if canview events
// Event scope actions, edit permissions required // Event scope actions, edit permissions required
if ( canEdit( 'Events' ) ) if ( canEdit( 'Events' ) )
@ -223,17 +218,18 @@ if ( !empty($action) ) {
} }
} }
} }
elseif ( $action == "delete" ) elseif ( $action == 'delete' )
{ {
foreach( getAffectedIds( 'markEid' ) as $markEid ) foreach( getAffectedIds( 'markEid' ) as $markEid )
{ {
deleteEvent( $markEid ); deleteEvent( $markEid );
$refreshParent = true; $refreshParent = true;
} }
if ( !empty($_REQUEST['fid']) ) if ( isset( $_REQUEST['object'] ) and ( $_REQUEST['object'] == 'filter' ) ) {
{ if ( !empty($_REQUEST['Id']) ) {
dbQuery( 'DELETE FROM Filters WHERE Id=?', array( $_REQUEST['filterId'] ) ); dbQuery( 'DELETE FROM Filters WHERE Id=?', array( $_REQUEST['Id'] ) );
//$refreshParent = true; //$refreshParent = true;
}
} }
} }
} }

View File

@ -450,6 +450,7 @@ function getEventDefaultVideoPath( $event ) {
} }
function deletePath( $path ) { function deletePath( $path ) {
Error("deletePath $path");
if ( is_dir( $path ) ) { if ( is_dir( $path ) ) {
system( escapeshellcmd( "rm -rf ".$path ) ); system( escapeshellcmd( "rm -rf ".$path ) );
} else { } else {
@ -1220,6 +1221,8 @@ function parseFilter( &$filter, $saveToSession=false, $querySep='&amp;' ) {
$filter['sql'] = ''; $filter['sql'] = '';
$filter['fields'] = ''; $filter['fields'] = '';
$StorageArea = NULL;
if ( isset($filter['terms']) && count($filter['terms']) ) { if ( isset($filter['terms']) && count($filter['terms']) ) {
for ( $i = 0; $i < count($filter['terms']); $i++ ) { for ( $i = 0; $i < count($filter['terms']); $i++ ) {
if ( isset($filter['terms'][$i]['cnj']) ) { if ( isset($filter['terms'][$i]['cnj']) ) {
@ -1270,10 +1273,27 @@ function parseFilter( &$filter, $saveToSession=false, $querySep='&amp;' ) {
$filter['sql'] .= 'E.'.$filter['terms'][$i]['attr']; $filter['sql'] .= 'E.'.$filter['terms'][$i]['attr'];
break; break;
case 'DiskPercent': case 'DiskPercent':
$filter['sql'] .= getDiskPercent(); // Need to specify a storage area, so need to look through other terms looking for a storage area, else we default to ZM_EVENTS_PATH
if ( ! $StorageArea ) {
for ( $j = $i; $j < count($filter['terms']); $j++ ) {
if ( isset($filter['terms'][$i]['attr']) and $filter['terms'][$i]['attr'] == 'StorageId' ) {
$StorageArea = new Storage( $filter['terms'][$i]['val'] );
}
} // end foreach remaining term
} // end no StorageArea found yet
$filter['sql'] .= getDiskPercent( $StorageArea );
break; break;
case 'DiskBlocks': case 'DiskBlocks':
$filter['sql'] .= getDiskBlocks(); // Need to specify a storage area, so need to look through other terms looking for a storage area, else we default to ZM_EVENTS_PATH
if ( ! $StorageArea ) {
for ( $j = $i; $j < count($filter['terms']); $j++ ) {
if ( isset($filter['terms'][$i]['attr']) and $filter['terms'][$i]['attr'] == 'StorageId' ) {
$StorageArea = new Storage( $filter['terms'][$i]['val'] );
}
} // end foreach remaining term
} // end no StorageArea found yet
$filter['sql'] .= getDiskBlocks( $StorageArea );
break; break;
case 'SystemLoad': case 'SystemLoad':
$filter['sql'] .= getLoad(); $filter['sql'] .= getLoad();
@ -1294,6 +1314,10 @@ function parseFilter( &$filter, $saveToSession=false, $querySep='&amp;' ) {
} else { } else {
$value = dbEscape($value); $value = dbEscape($value);
} }
case 'StorageId':
$StorageArea = new Storage( $value );
$value = dbEscape($value);
break;
case 'DateTime': case 'DateTime':
$value = "'".strftime( STRF_FMT_DATETIME_DB, strtotime( $value ) )."'"; $value = "'".strftime( STRF_FMT_DATETIME_DB, strtotime( $value ) )."'";
break; break;
@ -1460,35 +1484,15 @@ function getLoad() {
return( $load[0] ); return( $load[0] );
} }
function getDiskPercent() { function getDiskPercent( $StorageArea = NULL ) {
if ( !empty(ZM_DIR_EVENTS) ) { if ( ! $StorageArea ) $StorageArea = new Storage();
$total = disk_total_space(ZM_DIR_EVENTS);
if ( ! $total ) { return $StorageArea->disk_usage_percent();
Error("disk_total_space returned false for " . ZM_DIR_EVENTS );
return 0;
}
$free = disk_free_space(ZM_DIR_EVENTS);
if ( ! $free ) {
Error("disk_free_space returned false for " . ZM_DIR_EVENTS );
}
$space = round(($total - $free) / $total * 100);
$spaceString = 'Default '.$space.'%';
}
else {
$spaceString = '';
}
$storageAreas = Storage::find_all();
foreach($storageAreas as $storageArea) {
$storageTotal = disk_total_space($storageArea->Path);
$storageFree = disk_free_space($storageArea->Path);
$storageSpace = round(($storageTotal - $storageFree) / $storageTotal * 100);
$spaceString .= ', '.$storageArea->Name.' '.$storageSpace.'%';
}
return( $spaceString );
} }
function getDiskBlocks() { function getDiskBlocks() {
$df = shell_exec( 'df '.ZM_DIR_EVENTS ); if ( ! $StorageArea ) $StorageArea = new Storage();
$df = shell_exec( 'df '.$StorageArea->Path() );
$space = -1; $space = -1;
if ( preg_match( '/\s(\d+)\s+\d+\s+\d+%/ms', $df, $matches ) ) if ( preg_match( '/\s(\d+)\s+\d+\s+\d+%/ms', $df, $matches ) )
$space = $matches[1]; $space = $matches[1];

View File

@ -249,7 +249,14 @@ function getNavBarHTML() {
</div> </div>
<ul class="list-inline"> <ul class="list-inline">
<li><?php echo translate('Load') ?>: <?php echo getLoad() ?></li> <li><?php echo translate('Load') ?>: <?php echo getLoad() ?></li>
<li><?php echo translate('Storage') ?>: <?php echo getDiskPercent() ?></li> <li><?php echo translate('Storage') ?>: <?php
$storage_areas = Storage::find_all();
array_push( $storage_areas, new Storage() );
$func = function($S){ return $S->Name() . ': ' . $S->disk_usage_percent().'%'; };
echo implode( ', ', array_map ( $func, $storage_areas ) );
?></li>
</ul> </ul>
</div> <!-- End .footer --> </div> <!-- End .footer -->

View File

@ -19,23 +19,26 @@
// //
if ( !canView( 'Events' ) ) { if ( !canView( 'Events' ) ) {
$view = "error"; $view = 'error';
return; return;
} }
$selectName = "filterId"; $selectName = 'Id';
$filterNames = array( ''=>translate('ChooseFilter') ); $filterNames = array( ''=>translate('ChooseFilter') );
$dbFilter = NULL;
foreach ( dbFetchAll( "select * from Filters order by Name" ) as $row ) { foreach ( dbFetchAll( "select * from Filters order by Name" ) as $row ) {
$filterNames[$row['Id']] = $row['Name']; $filterNames[$row['Id']] = $row['Name'];
if ( $row['Background'] ) if ( $row['Background'] )
$filterNames[$row['Id']] .= "*"; $filterNames[$row['Id']] .= "*";
if ( $row['Concurrent'] ) if ( $row['Concurrent'] )
$filterNames[$row['Id']] .= "&"; $filterNames[$row['Id']] .= "&";
if ( !empty($_REQUEST['reload']) && isset($_REQUEST['filterId']) && $_REQUEST['filterId'] == $row['Id'] ) if ( !empty($_REQUEST['reload']) && isset($_REQUEST['Id']) && $_REQUEST['Id'] == $row['Id'] ) {
$dbFilter = $row; $dbFilter = $row;
}
} }
$backgroundStr = ""; $backgroundStr = '';
if ( isset($dbFilter) ) { if ( $dbFilter ) {
if ( $dbFilter['Background'] ) if ( $dbFilter['Background'] )
$backgroundStr = '['.strtolower(translate('Background')).']'; $backgroundStr = '['.strtolower(translate('Background')).']';
$_REQUEST['filter'] = jsonDecode( $dbFilter['Query'] ); $_REQUEST['filter'] = jsonDecode( $dbFilter['Query'] );
@ -57,7 +60,7 @@ if ( isset( $_REQUEST['reload'] ) and ! $_REQUEST['reload'] ) {
$dbFilter['AutoUpload'] = isset( $_REQUEST['AutoUpload'] ); $dbFilter['AutoUpload'] = isset( $_REQUEST['AutoUpload'] );
$dbFilter['AutoVideo'] = isset( $_REQUEST['AutoVideo'] ); $dbFilter['AutoVideo'] = isset( $_REQUEST['AutoVideo'] );
$dbFilter['AutoDelete'] = isset( $_REQUEST['AutoDelete'] ); $dbFilter['AutoDelete'] = isset( $_REQUEST['AutoDelete'] );
$dbFilter['Name'] = $_REQUEST['filterId']; $dbFilter['Name'] = $_REQUEST['Id'];
} }
$conjunctionTypes = array( $conjunctionTypes = array(
@ -163,7 +166,7 @@ xhtmlHeaders(__FILE__, translate('EventFilter') );
<input type="hidden" name="action" value=""/> <input type="hidden" name="action" value=""/>
<input type="hidden" name="subaction" value=""/> <input type="hidden" name="subaction" value=""/>
<input type="hidden" name="line" value=""/> <input type="hidden" name="line" value=""/>
<input type="hidden" name="fid" value=""/> <input type="hidden" name="object" value="filter"/>
<hr/> <hr/>
<div id="filterSelector"><label for="<?php echo $selectName ?>"><?php echo translate('UseFilter') ?></label><?php if ( count($filterNames) > 1 ) { echo buildSelect( $selectName, $filterNames, "submitToFilter( this, 1 );" ); } else { ?><select disabled="disabled"><option><?php echo translate('NoSavedFilters') ?></option></select><?php } ?><?php echo $backgroundStr ?></div> <div id="filterSelector"><label for="<?php echo $selectName ?>"><?php echo translate('UseFilter') ?></label><?php if ( count($filterNames) > 1 ) { echo buildSelect( $selectName, $filterNames, "submitToFilter( this, 1 );" ); } else { ?><select disabled="disabled"><option><?php echo translate('NoSavedFilters') ?></option></select><?php } ?><?php echo $backgroundStr ?></div>
<hr/> <hr/>