trivial updates (#1887)

* merge some trivial updates from storageareas

* fix the code to do zm.conf.new
This commit is contained in:
Isaac Connor 2017-05-16 14:16:32 -04:00 committed by GitHub
parent eef5e5cd90
commit dd75c4676b
10 changed files with 1707 additions and 1735 deletions

View File

@ -838,14 +838,16 @@ else(zmconfgen_result EQUAL 0)
endif(zmconfgen_result EQUAL 0)
# Install zm.conf
install(CODE "
if (NOT EXISTS \"${ZM_CONFIG_DIR}/zm.conf\")
file(INSTALL \"${CMAKE_CURRENT_BINARY_DIR}/zm.conf\" DESTINATION \"${ZM_CONFIG_DIR}\")
else (NOT EXISTS \"${ZM_CONFIG_DIR}/zm.conf\")
file(RENAME \"${CMAKE_CURRENT_BINARY_DIR}/zm.conf\" \"${CMAKE_CURRENT_BINARY_DIR}/zm.conf.new\")
file(INSTALL \"${CMAKE_CURRENT_BINARY_DIR}/zm.conf.new\" DESTINATION \"${ZM_CONFIG_DIR}\")
endif()
")
if (NOT EXISTS "${ZM_CONFIG_DIR}/zm.conf")
message(STATUS "No zm.conf at ${CMAKE_CURRENT_BINARY_DIR}/zm.conf. Will install a new zm.conf")
install(FILES "${CMAKE_CURRENT_BINARY_DIR}/zm.conf" DESTINATION "${ZM_CONFIG_DIR}")
else (NOT EXISTS "${ZM_CONFIG_DIR}/zm.conf")
message(STATUS "Found zm.conf at ${CMAKE_CURRENT_BINARY_DIR}/zm.conf. Not overwriting. Installing zm.conf.new instead.")
file(RENAME "${CMAKE_CURRENT_BINARY_DIR}/zm.conf" "${CMAKE_CURRENT_BINARY_DIR}/zm.conf.new")
install(FILES "${CMAKE_CURRENT_BINARY_DIR}/zm.conf.new" DESTINATION "${ZM_CONFIG_DIR}")
file(RENAME "${CMAKE_CURRENT_BINARY_DIR}/zm.conf.new" "${CMAKE_CURRENT_BINARY_DIR}/zm.conf")
endif()
#")
# Uninstall target

View File

@ -6,7 +6,7 @@ if ( empty($_REQUEST['id']) && empty($_REQUEST['eids']) ) {
if ( canView( 'Events' ) ) {
switch ( $_REQUEST['action'] ) {
case "video" : {
case 'video' : {
if ( empty($_REQUEST['videoFormat']) ) {
ajaxError( "Video Generation Failure, no format given" );
} elseif ( empty($_REQUEST['rate']) ) {
@ -77,11 +77,9 @@ if ( canView( 'Events' ) ) {
}
}
if ( canEdit( 'Events' ) )
{
switch ( $_REQUEST['action'] )
{
case "rename" :
if ( canEdit( 'Events' ) ) {
switch ( $_REQUEST['action'] ) {
case 'rename' :
{
if ( !empty($_REQUEST['eventName']) )
dbQuery( 'UPDATE Events SET Name = ? WHERE Id = ?', array( $_REQUEST['eventName'], $_REQUEST['id'] ) );
@ -90,24 +88,29 @@ if ( canEdit( 'Events' ) )
ajaxResponse( array( 'refreshEvent'=>true, 'refreshParent'=>true ) );
break;
}
case "eventdetail" :
case 'eventdetail' :
{
dbQuery( 'UPDATE Events SET Cause = ?, Notes = ? WHERE Id = ?', array( $_REQUEST['newEvent']['Cause'], $_REQUEST['newEvent']['Notes'], $_REQUEST['id'] ) );
ajaxResponse( array( 'refreshEvent'=>true, 'refreshParent'=>true ) );
break;
}
case "archive" :
case "unarchive" :
case 'archive' :
case 'unarchive' :
{
$archiveVal = ($_REQUEST['action'] == "archive")?1:0;
dbQuery( 'UPDATE Events SET Archived = ? WHERE Id = ?', array( $archiveVal, $_REQUEST['id']) );
ajaxResponse( array( 'refreshEvent'=>true, 'refreshParent'=>false ) );
break;
}
case "delete" :
case 'delete' :
{
deleteEvent( $_REQUEST['id'] );
ajaxResponse( array( 'refreshEvent'=>false, 'refreshParent'=>true ) );
$Event = new Event( $_REQUEST['id'] );
if ( ! $Event->Id() ) {
ajaxResponse( array( 'refreshEvent'=>false, 'refreshParent'=>true, 'message'=> 'Event not found.' ) );
} else {
$Event->delete();
ajaxResponse( array( 'refreshEvent'=>false, 'refreshParent'=>true ) );
}
break;
}
}

View File

@ -2,418 +2,395 @@
$statusData = array(
"system" => array(
"permission" => "System",
"table" => "Monitors",
"limit" => 1,
"elements" => array(
"MonitorCount" => array( "sql" => "count(*)" ),
"ActiveMonitorCount" => array( "sql" => "count(if(Function != 'None',1,NULL))" ),
"State" => array( "func" => "daemonCheck()?".translate('Running').":".translate('Stopped') ),
"Load" => array( "func" => "getLoad()" ),
"Disk" => array( "func" => "getDiskPercent()" ),
"permission" => "System",
"table" => "Monitors",
"limit" => 1,
"elements" => array(
"MonitorCount" => array( "sql" => "count(*)" ),
"ActiveMonitorCount" => array( "sql" => "count(if(Function != 'None',1,NULL))" ),
"State" => array( "func" => "daemonCheck()?".translate('Running').":".translate('Stopped') ),
"Load" => array( "func" => "getLoad()" ),
"Disk" => array( "func" => "getDiskPercent()" ),
),
),
),
"monitor" => array(
"permission" => "Monitors",
"table" => "Monitors",
"limit" => 1,
"selector" => "Monitors.Id",
"elements" => array(
"Id" => array( "sql" => "Monitors.Id" ),
"Name" => array( "sql" => "Monitors.Name" ),
"Type" => true,
"Function" => true,
"Enabled" => true,
"LinkedMonitors" => true,
"Triggers" => true,
"Device" => true,
"Channel" => true,
"Format" => true,
"Host" => true,
"Port" => true,
"Path" => true,
"Width" => array( "sql" => "Monitors.Width" ),
"Height" => array( "sql" => "Monitors.Height" ),
"Palette" => true,
"Orientation" => true,
"Brightness" => true,
"Contrast" => true,
"Hue" => true,
"Colour" => true,
"EventPrefix" => true,
"LabelFormat" => true,
"LabelX" => true,
"LabelY" => true,
"LabelSize" => true,
"ImageBufferCount" => true,
"WarmupCount" => true,
"PreEventCount" => true,
"PostEventCount" => true,
"AlarmFrameCount" => true,
"SectionLength" => true,
"FrameSkip" => true,
"MotionFrameSkip" => true,
"MaxFPS" => true,
"AlarmMaxFPS" => true,
"FPSReportInterval" => true,
"RefBlendPerc" => true,
"Controllable" => true,
"ControlId" => true,
"ControlDevice" => true,
"ControlAddress" => true,
"AutoStopTimeout" => true,
"TrackMotion" => true,
"TrackDelay" => true,
"ReturnLocation" => true,
"ReturnDelay" => true,
"DefaultView" => true,
"DefaultRate" => true,
"DefaultScale" => true,
"WebColour" => true,
"Sequence" => true,
"MinEventId" => array( "sql" => "(SELECT min(Events.Id) FROM Events WHERE Events.MonitorId = Monitors.Id" ),
"MaxEventId" => array( "sql" => "(SELECT max(Events.Id) FROM Events WHERE Events.MonitorId = Monitors.Id" ),
"TotalEvents" => array( "sql" => "(SELECT count(Events.Id) FROM Events WHERE Events.MonitorId = Monitors.Id" ),
"Status" => array( "zmu" => "-m ".escapeshellarg($_REQUEST['id'][0])." -s" ),
"FrameRate" => array( "zmu" => "-m ".escapeshellarg($_REQUEST['id'][0])." -f" ),
"permission" => "Monitors",
"table" => "Monitors",
"limit" => 1,
"selector" => "Monitors.Id",
"elements" => array(
"Id" => array( "sql" => "Monitors.Id" ),
"Name" => array( "sql" => "Monitors.Name" ),
"Type" => true,
"Function" => true,
"Enabled" => true,
"LinkedMonitors" => true,
"Triggers" => true,
"Device" => true,
"Channel" => true,
"Format" => true,
"Host" => true,
"Port" => true,
"Path" => true,
"Width" => array( "sql" => "Monitors.Width" ),
"Height" => array( "sql" => "Monitors.Height" ),
"Palette" => true,
"Orientation" => true,
"Brightness" => true,
"Contrast" => true,
"Hue" => true,
"Colour" => true,
"EventPrefix" => true,
"LabelFormat" => true,
"LabelX" => true,
"LabelY" => true,
"LabelSize" => true,
"ImageBufferCount" => true,
"WarmupCount" => true,
"PreEventCount" => true,
"PostEventCount" => true,
"AlarmFrameCount" => true,
"SectionLength" => true,
"FrameSkip" => true,
"MotionFrameSkip" => true,
"MaxFPS" => true,
"AlarmMaxFPS" => true,
"FPSReportInterval" => true,
"RefBlendPerc" => true,
"Controllable" => true,
"ControlId" => true,
"ControlDevice" => true,
"ControlAddress" => true,
"AutoStopTimeout" => true,
"TrackMotion" => true,
"TrackDelay" => true,
"ReturnLocation" => true,
"ReturnDelay" => true,
"DefaultView" => true,
"DefaultRate" => true,
"DefaultScale" => true,
"WebColour" => true,
"Sequence" => true,
"MinEventId" => array( "sql" => "(SELECT min(Events.Id) FROM Events WHERE Events.MonitorId = Monitors.Id" ),
"MaxEventId" => array( "sql" => "(SELECT max(Events.Id) FROM Events WHERE Events.MonitorId = Monitors.Id" ),
"TotalEvents" => array( "sql" => "(SELECT count(Events.Id) FROM Events WHERE Events.MonitorId = Monitors.Id" ),
"Status" => array( "zmu" => "-m ".escapeshellarg($_REQUEST['id'][0])." -s" ),
"FrameRate" => array( "zmu" => "-m ".escapeshellarg($_REQUEST['id'][0])." -f" ),
),
),
"events" => array(
"permission" => "Events",
"table" => "Events",
"selector" => "Events.MonitorId",
"elements" => array(
"Id" => true,
"Name" => true,
"Cause" => true,
"Notes" => true,
"StartTime" => true,
"StartTimeShort" => array( "sql" => "date_format( StartTime, '".MYSQL_FMT_DATETIME_SHORT."' )" ),
"EndTime" => true,
"Width" => true,
"Height" => true,
"Length" => true,
"Frames" => true,
"AlarmFrames" => true,
"TotScore" => true,
"AvgScore" => true,
"MaxScore" => true,
),
),
"event" => array(
"permission" => "Events",
"table" => "Events",
"limit" => 1,
"selector" => "Events.Id",
"elements" => array(
"Id" => array( "sql" => "Events.Id" ),
"MonitorId" => true,
"Name" => true,
"Cause" => true,
"StartTime" => true,
"StartTimeShort" => array( "sql" => "date_format( StartTime, '".MYSQL_FMT_DATETIME_SHORT."' )" ),
"EndTime" => true,
"Width" => true,
"Height" => true,
"Length" => true,
"Frames" => true,
"DefaultVideo" => true,
"AlarmFrames" => true,
"TotScore" => true,
"AvgScore" => true,
"MaxScore" => true,
"Archived" => true,
"Videoed" => true,
"Uploaded" => true,
"Emailed" => true,
"Messaged" => true,
"Executed" => true,
"Notes" => true,
"MinFrameId" => array( "sql" => "(SELECT min(Frames.FrameId) FROM Frames WHERE EventId=Events.Id)" ),
"MaxFrameId" => array( "sql" => "(SELECT max(Frames.FrameId) FROM Frames WHERE Events.Id = Frames.EventId)" ),
"MinFrameDelta" => array( "sql" => "(SELECT min(Frames.Delta) FROM Frames WHERE Events.Id = Frames.EventId)" ),
"MaxFrameDelta" => array( "sql" => "(SELECT max(Frames.Delta) FROM Frames WHERE Events.Id = Frames.EventId)" ),
//"Path" => array( "postFunc" => "getEventPath" ),
),
),
"frame" => array(
"permission" => "Events",
"table" => "Frames",
"limit" => 1,
"selector" => array( array( "table" => "Events", "join" => "Events.Id = Frames.EventId", "selector"=>"Events.Id" ), "Frames.FrameId" ),
"elements" => array(
//"Id" => array( "sql" => "Frames.FrameId" ),
"FrameId" => true,
"EventId" => true,
"Type" => true,
"TimeStamp" => true,
"TimeStampShort" => array( "sql" => "date_format( StartTime, '".MYSQL_FMT_DATETIME_SHORT."' )" ),
"Delta" => true,
"Score" => true,
//"Image" => array( "postFunc" => "getFrameImage" ),
),
),
"frameimage" => array(
"permission" => "Events",
"func" => "getFrameImage()"
),
"nearframe" => array(
"permission" => "Events",
"func" => "getNearFrame()"
),
"nearevents" => array(
"permission" => "Events",
"func" => "getNearEvents()"
)
);
),
"events" => array(
"permission" => "Events",
"table" => "Events",
"selector" => "Events.MonitorId",
"elements" => array(
"Id" => true,
"Name" => true,
"Cause" => true,
"Notes" => true,
"StartTime" => true,
"StartTimeShort" => array( "sql" => "date_format( StartTime, '".MYSQL_FMT_DATETIME_SHORT."' )" ),
"EndTime" => true,
"Width" => true,
"Height" => true,
"Length" => true,
"Frames" => true,
"AlarmFrames" => true,
"TotScore" => true,
"AvgScore" => true,
"MaxScore" => true,
),
),
"event" => array(
"permission" => "Events",
"table" => "Events",
"limit" => 1,
"selector" => "Events.Id",
"elements" => array(
"Id" => array( "sql" => "Events.Id" ),
"MonitorId" => true,
"Name" => true,
"Cause" => true,
"StartTime" => true,
"StartTimeShort" => array( "sql" => "date_format( StartTime, '".MYSQL_FMT_DATETIME_SHORT."' )" ),
"EndTime" => true,
"Width" => true,
"Height" => true,
"Length" => true,
"Frames" => true,
"DefaultVideo" => true,
"AlarmFrames" => true,
"TotScore" => true,
"AvgScore" => true,
"MaxScore" => true,
"Archived" => true,
"Videoed" => true,
"Uploaded" => true,
"Emailed" => true,
"Messaged" => true,
"Executed" => true,
"Notes" => true,
"MinFrameId" => array( "sql" => "(SELECT min(Frames.FrameId) FROM Frames WHERE EventId=Events.Id)" ),
"MaxFrameId" => array( "sql" => "(SELECT max(Frames.FrameId) FROM Frames WHERE Events.Id = Frames.EventId)" ),
"MinFrameDelta" => array( "sql" => "(SELECT min(Frames.Delta) FROM Frames WHERE Events.Id = Frames.EventId)" ),
"MaxFrameDelta" => array( "sql" => "(SELECT max(Frames.Delta) FROM Frames WHERE Events.Id = Frames.EventId)" ),
//"Path" => array( "postFunc" => "getEventPath" ),
),
),
"frame" => array(
"permission" => "Events",
"table" => "Frames",
"limit" => 1,
"selector" => array( array( "table" => "Events", "join" => "Events.Id = Frames.EventId", "selector"=>"Events.Id" ), "Frames.FrameId" ),
"elements" => array(
//"Id" => array( "sql" => "Frames.FrameId" ),
"FrameId" => true,
"EventId" => true,
"Type" => true,
"TimeStamp" => true,
"TimeStampShort" => array( "sql" => "date_format( StartTime, '".MYSQL_FMT_DATETIME_SHORT."' )" ),
"Delta" => true,
"Score" => true,
//"Image" => array( "postFunc" => "getFrameImage" ),
),
),
"frameimage" => array(
"permission" => "Events",
"func" => "getFrameImage()"
),
"nearframe" => array(
"permission" => "Events",
"func" => "getNearFrame()"
),
"nearevents" => array(
"permission" => "Events",
"func" => "getNearEvents()"
)
);
function collectData()
{
global $statusData;
function collectData() {
global $statusData;
$entitySpec = &$statusData[strtolower(validJsStr($_REQUEST['entity']))];
#print_r( $entitySpec );
if ( !canView( $entitySpec['permission'] ) )
ajaxError( 'Unrecognised action or insufficient permissions' );
$entitySpec = &$statusData[strtolower(validJsStr($_REQUEST['entity']))];
#print_r( $entitySpec );
if ( !canView( $entitySpec['permission'] ) )
ajaxError( 'Unrecognised action or insufficient permissions' );
if ( !empty($entitySpec['func']) )
{
$data = eval( "return( ".$entitySpec['func']." );" );
if ( !empty($entitySpec['func']) ) {
$data = eval( "return( ".$entitySpec['func']." );" );
} else {
$data = array();
$postFuncs = array();
$fieldSql = array();
$joinSql = array();
$groupSql = array();
$elements = &$entitySpec['elements'];
$lc_elements = array_change_key_case( $elements );
$id = false;
if ( isset($_REQUEST['id']) )
if ( !is_array($_REQUEST['id']) )
$id = array( validJsStr($_REQUEST['id']) );
else
$id = array_values( $_REQUEST['id'] );
if ( !isset($_REQUEST['element']) )
$_REQUEST['element'] = array_keys( $elements );
else if ( !is_array($_REQUEST['element']) )
$_REQUEST['element'] = array( validJsStr($_REQUEST['element']) );
if ( isset($entitySpec['selector']) ) {
if ( !is_array($entitySpec['selector']) )
$entitySpec['selector'] = array( $entitySpec['selector'] );
foreach( $entitySpec['selector'] as $selector )
if ( is_array( $selector ) && isset($selector['table']) && isset($selector['join']) )
$joinSql[] = "left join ".$selector['table']." on ".$selector['join'];
}
else
{
$data = array();
$postFuncs = array();
$fieldSql = array();
$joinSql = array();
$groupSql = array();
$elements = &$entitySpec['elements'];
$lc_elements = array_change_key_case( $elements );
$id = false;
if ( isset($_REQUEST['id']) )
if ( !is_array($_REQUEST['id']) )
$id = array( validJsStr($_REQUEST['id']) );
else
$id = array_values( $_REQUEST['id'] );
if ( !isset($_REQUEST['element']) )
$_REQUEST['element'] = array_keys( $elements );
else if ( !is_array($_REQUEST['element']) )
$_REQUEST['element'] = array( validJsStr($_REQUEST['element']) );
if ( isset($entitySpec['selector']) )
{
if ( !is_array($entitySpec['selector']) )
$entitySpec['selector'] = array( $entitySpec['selector'] );
foreach( $entitySpec['selector'] as $selector )
if ( is_array( $selector ) && isset($selector['table']) && isset($selector['join']) )
$joinSql[] = "left join ".$selector['table']." on ".$selector['join'];
foreach ( $_REQUEST['element'] as $element ) {
if ( !($elementData = $lc_elements[strtolower($element)]) )
ajaxError( "Bad ".validJsStr($_REQUEST['entity'])." element ".$element );
if ( isset($elementData['func']) )
$data[$element] = eval( "return( ".$elementData['func']." );" );
else if ( isset($elementData['postFunc']) )
$postFuncs[$element] = $elementData['postFunc'];
else if ( isset($elementData['zmu']) )
$data[$element] = exec( escapeshellcmd( getZmuCommand( " ".$elementData['zmu'] ) ) );
else {
if ( isset($elementData['sql']) )
$fieldSql[] = $elementData['sql']." as ".$element;
else
$fieldSql[] = $element;
if ( isset($elementData['table']) && isset($elementData['join']) ) {
$joinSql[] = "left join ".$elementData['table']." on ".$elementData['join'];
}
foreach ( $_REQUEST['element'] as $element )
{
if ( !($elementData = $lc_elements[strtolower($element)]) )
ajaxError( "Bad ".validJsStr($_REQUEST['entity'])." element ".$element );
if ( isset($elementData['func']) )
$data[$element] = eval( "return( ".$elementData['func']." );" );
else if ( isset($elementData['postFunc']) )
$postFuncs[$element] = $elementData['postFunc'];
else if ( isset($elementData['zmu']) )
$data[$element] = exec( escapeshellcmd( getZmuCommand( " ".$elementData['zmu'] ) ) );
else
{
if ( isset($elementData['sql']) )
$fieldSql[] = $elementData['sql']." as ".$element;
else
$fieldSql[] = $element;
if ( isset($elementData['table']) && isset($elementData['join']) )
{
$joinSql[] = "left join ".$elementData['table']." on ".$elementData['join'];
}
if ( isset($elementData['group']) )
{
$groupSql[] = $elementData['group'];
}
}
}
if ( count($fieldSql) )
{
$sql = "select ".join( ", ", $fieldSql )." from ".$entitySpec['table'];
if ( $joinSql )
$sql .= " ".join( " ", array_unique( $joinSql ) );
if ( $id && !empty($entitySpec['selector']) )
{
$index = 0;
$where = array();
$values = array();
foreach( $entitySpec['selector'] as $selector ) {
if ( is_array( $selector ) ) {
$where[] = $selector['selector'].' = ?';
$values[] = validInt($id[$index]);
} else {
$where[] = $selector.' = ?';
$values[] = validInt($id[$index]);
}
$index++;
}
$sql .= " where ".join( " and ", $where );
}
if ( $groupSql )
$sql .= " group by ".join( ",", array_unique( $groupSql ) );
if ( !empty($_REQUEST['sort']) )
$sql .= " order by ".$_REQUEST['sort'];
if ( !empty($entitySpec['limit']) )
$limit = $entitySpec['limit'];
elseif ( !empty($_REQUEST['count']) )
$limit = validInt($_REQUEST['count']);
$limit_offset="";
if ( !empty($_REQUEST['offset']) )
$limit_offset = validInt($_REQUEST['offset']) . ", ";
if ( !empty( $limit ) )
$sql .= " limit ".$limit_offset.$limit;
if ( isset($limit) && $limit == 1 ) {
if ( $sqlData = dbFetchOne( $sql, NULL, $values ) ) {
foreach ( $postFuncs as $element=>$func )
$sqlData[$element] = eval( 'return( '.$func.'( $sqlData ) );' );
$data = array_merge( $data, $sqlData );
}
} else {
$count = 0;
foreach( dbFetchAll( $sql, NULL, $values ) as $sqlData ) {
foreach ( $postFuncs as $element=>$func )
$sqlData[$element] = eval( 'return( '.$func.'( $sqlData ) );' );
$data[] = $sqlData;
if ( isset($limi) && ++$count >= $limit )
break;
}
}
if ( isset($elementData['group']) ) {
$groupSql[] = $elementData['group'];
}
}
}
#print_r( $data );
return( $data );
if ( count($fieldSql) ) {
$sql = "select ".join( ", ", $fieldSql )." from ".$entitySpec['table'];
if ( $joinSql )
$sql .= " ".join( " ", array_unique( $joinSql ) );
if ( $id && !empty($entitySpec['selector']) ) {
$index = 0;
$where = array();
$values = array();
foreach( $entitySpec['selector'] as $selector ) {
if ( is_array( $selector ) ) {
$where[] = $selector['selector'].' = ?';
$values[] = validInt($id[$index]);
} else {
$where[] = $selector.' = ?';
$values[] = validInt($id[$index]);
}
$index++;
}
$sql .= " where ".join( " and ", $where );
}
if ( $groupSql )
$sql .= " GROUP BY ".join( ",", array_unique( $groupSql ) );
if ( !empty($_REQUEST['sort']) )
$sql .= " order by ".$_REQUEST['sort'];
if ( !empty($entitySpec['limit']) )
$limit = $entitySpec['limit'];
elseif ( !empty($_REQUEST['count']) )
$limit = validInt($_REQUEST['count']);
$limit_offset="";
if ( !empty($_REQUEST['offset']) )
$limit_offset = validInt($_REQUEST['offset']) . ", ";
if ( !empty( $limit ) )
$sql .= " limit ".$limit_offset.$limit;
if ( isset($limit) && $limit == 1 ) {
if ( $sqlData = dbFetchOne( $sql, NULL, $values ) ) {
foreach ( $postFuncs as $element=>$func )
$sqlData[$element] = eval( 'return( '.$func.'( $sqlData ) );' );
$data = array_merge( $data, $sqlData );
}
} else {
$count = 0;
foreach( dbFetchAll( $sql, NULL, $values ) as $sqlData ) {
foreach ( $postFuncs as $element=>$func )
$sqlData[$element] = eval( 'return( '.$func.'( $sqlData ) );' );
$data[] = $sqlData;
if ( isset($limi) && ++$count >= $limit )
break;
}
}
}
}
#print_r( $data );
return( $data );
}
$data = collectData();
if ( !isset($_REQUEST['layout']) )
{
$_REQUEST['layout'] = "json";
if ( !isset($_REQUEST['layout']) ) {
$_REQUEST['layout'] = "json";
}
switch( $_REQUEST['layout'] )
{
case 'xml NOT CURRENTLY SUPPORTED' :
switch( $_REQUEST['layout'] ) {
case 'xml NOT CURRENTLY SUPPORTED' :
{
header("Content-type: application/xml" );
echo( '<?xml version="1.0" encoding="iso-8859-1"?>'."\n" );
echo "<".strtolower($_REQUEST['entity']).">\n";
foreach ( $data as $key=>$value )
{
$key = strtolower( $key );
echo "<$key>".htmlentities($value)."</$key>\n";
}
echo "</".strtolower($_REQUEST['entity']).">\n";
break;
header("Content-type: application/xml" );
echo( '<?xml version="1.0" encoding="iso-8859-1"?>'."\n" );
echo "<".strtolower($_REQUEST['entity']).">\n";
foreach ( $data as $key=>$value ) {
$key = strtolower( $key );
echo "<$key>".htmlentities($value)."</$key>\n";
}
echo "</".strtolower($_REQUEST['entity']).">\n";
break;
}
case 'json' :
case 'json' :
{
$response = array( strtolower(validJsStr($_REQUEST['entity'])) => $data );
if ( isset($_REQUEST['loopback']) )
$response['loopback'] = validJsStr($_REQUEST['loopback']);
ajaxResponse( $response );
break;
$response = array( strtolower(validJsStr($_REQUEST['entity'])) => $data );
if ( isset($_REQUEST['loopback']) )
$response['loopback'] = validJsStr($_REQUEST['loopback']);
ajaxResponse( $response );
break;
}
case 'text' :
case 'text' :
{
header("Content-type: text/plain" );
echo join( " ", array_values( $data ) );
break;
header("Content-type: text/plain" );
echo join( " ", array_values( $data ) );
break;
}
}
function getFrameImage()
{
$eventId = $_REQUEST['id'][0];
$frameId = $_REQUEST['id'][1];
function getFrameImage() {
$eventId = $_REQUEST['id'][0];
$frameId = $_REQUEST['id'][1];
$sql = 'select * from Frames where EventId = ? and FrameId = ?';
if ( !($frame = dbFetchOne( $sql, NULL, array( $eventId, $frameId ) )) )
{
$frame = array();
$frame['EventId'] = $eventId;
$frame['FrameId'] = $frameId;
$frame['Type'] = "Virtual";
}
$event = dbFetchOne( 'select * from Events where Id = ?', NULL, array( $frame['EventId'] ) );
$frame['Image'] = getImageSrc( $event, $frame, SCALE_BASE );
return( $frame );
$sql = 'select * from Frames where EventId = ? and FrameId = ?';
if ( !($frame = dbFetchOne( $sql, NULL, array( $eventId, $frameId ) )) ) {
$frame = array();
$frame['EventId'] = $eventId;
$frame['FrameId'] = $frameId;
$frame['Type'] = "Virtual";
}
$event = dbFetchOne( 'select * from Events where Id = ?', NULL, array( $frame['EventId'] ) );
$frame['Image'] = getImageSrc( $event, $frame, SCALE_BASE );
return( $frame );
}
function getNearFrame()
{
$eventId = $_REQUEST['id'][0];
$frameId = $_REQUEST['id'][1];
function getNearFrame() {
$eventId = $_REQUEST['id'][0];
$frameId = $_REQUEST['id'][1];
$sql = 'select FrameId from Frames where EventId = ? and FrameId <= ? order by FrameId desc limit 1';
if ( !$nearFrameId = dbFetchOne( $sql, 'FrameId', array( $eventId, $frameId ) ) )
{
$sql = 'select * from Frames where EventId = ? and FrameId > ? order by FrameId asc limit 1';
if ( !$nearFrameId = dbFetchOne( $sql, 'FrameId', array( $eventId, $frameId ) ) )
{
return( array() );
}
$sql = 'select FrameId from Frames where EventId = ? and FrameId <= ? order by FrameId desc limit 1';
if ( !$nearFrameId = dbFetchOne( $sql, 'FrameId', array( $eventId, $frameId ) ) ) {
$sql = 'select * from Frames where EventId = ? and FrameId > ? order by FrameId asc limit 1';
if ( !$nearFrameId = dbFetchOne( $sql, 'FrameId', array( $eventId, $frameId ) ) ) {
return( array() );
}
$_REQUEST['entity'] = "frame";
$_REQUEST['id'][1] = $nearFrameId;
return( collectData() );
}
$_REQUEST['entity'] = "frame";
$_REQUEST['id'][1] = $nearFrameId;
return( collectData() );
}
function getNearEvents()
{
global $user, $sortColumn, $sortOrder;
function getNearEvents() {
global $user, $sortColumn, $sortOrder;
$eventId = $_REQUEST['id'];
$event = dbFetchOne( 'select * from Events where Id = ?', NULL, array( $eventId ) );
$eventId = $_REQUEST['id'];
$event = dbFetchOne( 'select * from Events where Id = ?', NULL, array( $eventId ) );
parseFilter( $_REQUEST['filter'] );
parseSort();
parseFilter( $_REQUEST['filter'] );
parseSort();
if ( $user['MonitorIds'] )
$midSql = " and MonitorId in (".join( ",", preg_split( '/["\'\s]*,["\'\s]*/', $user['MonitorIds'] ) ).")";
else
$midSql = '';
if ( $user['MonitorIds'] )
$midSql = " and MonitorId in (".join( ",", preg_split( '/["\'\s]*,["\'\s]*/', $user['MonitorIds'] ) ).")";
else
$midSql = '';
$sql = "select E.Id as Id from Events as E inner join Monitors as M on E.MonitorId = M.Id where ".dbEscape($sortColumn)." ".($sortOrder=='asc'?'<=':'>=')." '".$event[$_REQUEST['sort_field']]."'".$_REQUEST['filter']['sql'].$midSql." order by $sortColumn ".($sortOrder=='asc'?'desc':'asc');
$result = dbQuery( $sql );
while ( $id = dbFetchNext( $result, 'Id' ) )
{
if ( $id == $eventId )
{
$prevEvent = dbFetchNext( $result );
break;
}
$sql = "select E.Id as Id from Events as E inner join Monitors as M on E.MonitorId = M.Id where ".dbEscape($sortColumn)." ".($sortOrder=='asc'?'<=':'>=')." '".$event[$_REQUEST['sort_field']]."'".$_REQUEST['filter']['sql'].$midSql." order by $sortColumn ".($sortOrder=='asc'?'desc':'asc');
$result = dbQuery( $sql );
while ( $id = dbFetchNext( $result, 'Id' ) ) {
if ( $id == $eventId ) {
$prevEvent = dbFetchNext( $result );
break;
}
}
$sql = "select E.Id as Id from Events as E inner join Monitors as M on E.MonitorId = M.Id where $sortColumn ".($sortOrder=='asc'?'>=':'<=')." '".$event[$_REQUEST['sort_field']]."'".$_REQUEST['filter']['sql'].$midSql." order by $sortColumn $sortOrder";
$result = dbQuery( $sql );
while ( $id = dbFetchNext( $result, 'Id' ) )
{
if ( $id == $eventId )
{
$nextEvent = dbFetchNext( $result );
break;
}
$sql = "select E.Id as Id from Events as E inner join Monitors as M on E.MonitorId = M.Id where $sortColumn ".($sortOrder=='asc'?'>=':'<=')." '".$event[$_REQUEST['sort_field']]."'".$_REQUEST['filter']['sql'].$midSql." order by $sortColumn $sortOrder";
$result = dbQuery( $sql );
while ( $id = dbFetchNext( $result, 'Id' ) ) {
if ( $id == $eventId ) {
$nextEvent = dbFetchNext( $result );
break;
}
}
$result = array( 'EventId'=>$eventId );
$result['PrevEventId'] = empty($prevEvent)?0:$prevEvent['Id'];
$result['NextEventId'] = empty($nextEvent)?0:$nextEvent['Id'];
$result['PrevEventDefVideoPath'] = empty($prevEvent)?0:(getEventDefaultVideoPath($prevEvent));
$result['NextEventDefVideoPath'] = empty($nextEvent)?0:(getEventDefaultVideoPath($nextEvent));
return( $result );
$result = array( 'EventId'=>$eventId );
$result['PrevEventId'] = empty($prevEvent)?0:$prevEvent['Id'];
$result['NextEventId'] = empty($nextEvent)?0:$nextEvent['Id'];
$result['PrevEventDefVideoPath'] = empty($prevEvent)?0:(getEventDefaultVideoPath($prevEvent));
$result['NextEventDefVideoPath'] = empty($nextEvent)?0:(getEventDefaultVideoPath($nextEvent));
return( $result );
}
?>

View File

@ -126,8 +126,10 @@ class Event {
} # ! ZM_OPT_FAST_DELETE
} # end Event->delete
public function getStreamSrc( $args, $querySep='&amp;' ) {
return ( ZM_BASE_PATH != '/' ? ZM_BASE_PATH : '' ).'/index.php?view=view_video&eid='.$this->{'Id'};
public function getStreamSrc( $args=array(), $querySep='&amp;' ) {
if ( $this->{'DefaultVideo'} ) {
return ( ZM_BASE_PATH != '/' ? ZM_BASE_PATH : '' ).'/index.php?view=view_video&eid='.$this->{'Id'};
}
$streamSrc = ZM_BASE_URL.ZM_PATH_ZMS;
@ -217,12 +219,13 @@ class Event {
return '';
}
$command ='ffmpeg -v 0 -i '.$videoPath.' -vf "select=gte(n\\,'.$frame['FrameId'].'),setpts=PTS-STARTPTS" '.$eventPath.'/'.$captImage;
Logger::Debug( "Running $command" );
#$command ='ffmpeg -v 0 -i '.$videoPath.' -vf "select=gte(n\\,'.$frame['FrameId'].'),setpts=PTS-STARTPTS" '.$eventPath.'/'.$captImage;
$command ='ffmpeg -ss '. $frame['Delta'] .' -i '.$videoPath.' -frames:v 1 '.$eventPath.'/'.$captImage;
Debug( "Running $command" );
$output = array();
$retval = 0;
exec( $command, $output, $retval );
Logger::Debug("Retval: $retval, output: " . implode("\n", $output));
Debug("Retval: $retval, output: " . implode("\n", $output));
} else {
Error("Can't create frame images from video becuase there is no video file for this event (".$Event->DefaultVideo() );
}

View File

@ -34,7 +34,7 @@ class Frame {
return new Event( $this->{'EventId'} );
}
public function __call( $fn, array $args){
if(isset($this->{$fn})){
if( array_key_exists( $fn, $this ) ) {
return $this->{$fn};
#array_unshift($args, $this);
#call_user_func_array( $this->{$fn}, $args);
@ -70,7 +70,7 @@ class Frame {
}
public function getImageSrc( $show='capture' ) {
return $_SERVER['PHP_SELF'].'?view=image&fid='.$this->{'Id'}.'&show='.$show;;
return $_SERVER['PHP_SELF'].'?view=image&fid='.$this->{'Id'}.'&show='.$show.'&filename='.$this->Event()->MonitorId().'_'.$this->{'EventId'}.'_'.$this->{'FrameId'}.'.jpg';
} // end function getImageSrc
public static function find( $parameters = array(), $limit = NULL ) {

View File

@ -3,94 +3,238 @@ require_once( 'database.php' );
require_once( 'Server.php' );
class Monitor {
public function __construct( $IdOrRow ) {
$row = NULL;
if ( $IdOrRow ) {
if ( is_integer( $IdOrRow ) or is_numeric( $IdOrRow ) ) {
$row = dbFetchOne( 'SELECT * FROM Monitors WHERE Id=?', NULL, array( $IdOrRow ) );
if ( ! $row ) {
Error("Unable to load Server record for Id=" . $IdOrRow );
}
} elseif ( is_array( $IdOrRow ) ) {
$row = $IdOrRow;
} else {
Error("Unknown argument passed to Monitor Constructor ($IdOrRow)");
return;
}
} # end if isset($IdOrRow)
if ( $row ) {
foreach ($row as $k => $v) {
$this->{$k} = $v;
}
if ( $this->{'Controllable'} ) {
$s = dbFetchOne( 'SELECT * FROM Controls WHERE Id=?', NULL, array( $this->{'ControlId'} ) );
foreach ($s as $k => $v) {
if ( $k == 'Id' ) {
continue;
}
$this->{$k} = $v;
}
}
private $control_fields = array(
'Name' => '',
'Type' => 'Local',
'Protocol' => NULL,
'CanWake' => '0',
'CanSleep' => '0',
'CanReset' => '0',
'CanZoom' => '0',
'CanAutoZoom' => '0',
'CanZoomAbs' => '0',
'CanZoomRel' => '0',
'CanZoomCon' => '0',
'MinZoomRange' => NULL,
'MaxZoomRange' => NULL,
'MinZoomStep' => NULL,
'MaxZoomStep' => NULL,
'HasZoomSpeed' => '0',
'MinZoomSpeed' => NULL,
'MaxZoomSpeed' => NULL,
'CanFocus' => '0',
'CanAutoFocus' => '0',
'CanFocusAbs' => '0',
'CanFocusRel' => '0',
'CanFocusCon' => '0',
'MinFocusRange' => NULL,
'MaxFocusRange' => NULL,
'MinFocusStep' => NULL,
'MaxFocusStep' => NULL,
'HasFocusSpeed' => '0',
'MinFocusSpeed' => NULL,
'MaxFocusSpeed' => NULL,
'CanIris' => '0',
'CanAutoIris' => '0',
'CanIrisAbs' => '0',
'CanIrisRel' => '0',
'CanIrisCon' => '0',
'MinIrisRange' => NULL,
'MaxIrisRange' => NULL,
'MinIrisStep' => NULL,
'MaxIrisStep' => NULL,
'HasIrisSpeed' => '0',
'MinIrisSpeed' => NULL,
'MaxIrisSpeed' => NULL,
'CanGain' => '0',
'CanAutoGain' => '0',
'CanGainAbs' => '0',
'CanGainRel' => '0',
'CanGainCon' => '0',
'MinGainRange' => NULL,
'MaxGainRange' => NULL,
'MinGainStep' => NULL,
'MaxGainStep' => NULL,
'HasGainSpeed' => '0',
'MinGainSpeed' => NULL,
'MaxGainSpeed' => NULL,
'CanWhite' => '0',
'CanAutoWhite' => '0',
'CanWhiteAbs' => '0',
'CanWhiteRel' => '0',
'CanWhiteCon' => '0',
'MinWhiteRange' => NULL,
'MaxWhiteRange' => NULL,
'MinWhiteStep' => NULL,
'MaxWhiteStep' => NULL,
'HasWhiteSpeed' => '0',
'MinWhiteSpeed' => NULL,
'MaxWhiteSpeed' => NULL,
'HasPresets' => '0',
'NumPresets' => '0',
'HasHomePreset' => '0',
'CanSetPresets' => '0',
'CanMove' => '0',
'CanMoveDiag' => '0',
'CanMoveMap' => '0',
'CanMoveAbs' => '0',
'CanMoveRel' => '0',
'CanMoveCon' => '0',
'CanPan' => '0',
'MinPanRange' => NULL,
'MaxPanRange' => NULL,
'MinPanStep' => NULL,
'MaxPanStep' => NULL,
'HasPanSpeed' => '0',
'MinPanSpeed' => NULL,
'MaxPanSpeed' => NULL,
'HasTurboPan' => '0',
'TurboPanSpeed' => NULL,
'CanTilt' => '0',
'MinTiltRange' => NULL,
'MaxTiltRange' => NULL,
'MinTiltStep' => NULL,
'MaxTiltStep' => NULL,
'HasTiltSpeed' => '0',
'MinTiltSpeed' => NULL,
'MaxTiltSpeed' => NULL,
'HasTurboTilt' => '0',
'TurboTiltSpeed' => NULL,
'CanAutoScan' => '0',
'NumScanPaths' => '0',
);
} else {
Error("No row for Monitor " . $IdOrRow );
}
} // end function __construct
public function Server() {
return new Server( $this->{'ServerId'} );
}
public function __call( $fn, array $args){
if(isset($this->{$fn})){
return $this->{$fn};
#array_unshift($args, $this);
#call_user_func_array( $this->{$fn}, $args);
public function __construct( $IdOrRow = NULL ) {
if ( $IdOrRow ) {
$row = NULL;
if ( is_integer( $IdOrRow ) or is_numeric( $IdOrRow ) ) {
$row = dbFetchOne( 'SELECT * FROM Monitors WHERE Id=?', NULL, array( $IdOrRow ) );
if ( ! $row ) {
Error("Unable to load Server record for Id=" . $IdOrRow );
}
}
public function getStreamSrc( $args, $querySep='&amp;' ) {
if ( isset($this->{'ServerId'}) and $this->{'ServerId'} ) {
$Server = new Server( $this->{'ServerId'} );
$streamSrc = ZM_BASE_PROTOCOL.'://'.$Server->Hostname().ZM_PATH_ZMS;
} elseif ( is_array( $IdOrRow ) ) {
$row = $IdOrRow;
} else {
Error("Unknown argument passed to Monitor Constructor ($IdOrRow)");
return;
}
if ( $row ) {
foreach ($row as $k => $v) {
$this->{$k} = $v;
}
if ( $this->{'Controllable'} ) {
$s = dbFetchOne( 'SELECT * FROM Controls WHERE Id=?', NULL, array( $this->{'ControlId'} ) );
foreach ($s as $k => $v) {
if ( $k == 'Id' ) {
continue;
# The reason for these is that the name overlaps Monitor fields.
} else if ( $k == 'Protocol' ) {
$this->{'ControlProtocol'} = $v;
} else if ( $k == 'Name' ) {
$this->{'ControlName'} = $v;
} else if ( $k == 'Type' ) {
$this->{'ControlType'} = $v;
} else {
$this->{$k} = $v;
}
}
}
} else {
Error('No row for Monitor ' . $IdOrRow );
}
} # end if isset($IdOrRow)
} // end function __construct
public function Server() {
return new Server( $this->{'ServerId'} );
}
public function __call( $fn, array $args){
if ( count( $args ) ) {
$this->{$fn} = $args[0];
}
if ( array_key_exists( $fn, $this ) ) {
return $this->{$fn};
#array_unshift($args, $this);
#call_user_func_array( $this->{$fn}, $args);
} else {
$streamSrc = ZM_BASE_URL.ZM_PATH_ZMS;
}
if ( array_key_exists( $fn, $this->control_fields ) ) {
return $this->control_fields{$fn};
} else {
$args[] = "monitor=".$this->{'Id'};
$backTrace = debug_backtrace();
$file = $backTrace[1]['file'];
$line = $backTrace[1]['line'];
Warning( "Unknown function call Monitor->$fn from $file:$line" );
}
}
}
if ( ZM_OPT_USE_AUTH ) {
if ( ZM_AUTH_RELAY == "hashed" ) {
$args[] = "auth=".generateAuthHash( ZM_AUTH_HASH_IPS );
} elseif ( ZM_AUTH_RELAY == "plain" ) {
$args[] = "user=".$_SESSION['username'];
$args[] = "pass=".$_SESSION['password'];
} elseif ( ZM_AUTH_RELAY == "none" ) {
$args[] = "user=".$_SESSION['username'];
}
}
if ( !in_array( "mode=single", $args ) && !empty($GLOBALS['connkey']) ) {
$args[] = "connkey=".$GLOBALS['connkey'];
}
if ( ZM_RAND_STREAM ) {
$args[] = "rand=".time();
}
public function getStreamSrc( $args, $querySep='&amp;' ) {
if ( isset($this->{'ServerId'}) and $this->{'ServerId'} ) {
$Server = new Server( $this->{'ServerId'} );
$streamSrc = ZM_BASE_PROTOCOL.'://'.$Server->Hostname().ZM_PATH_ZMS;
} else {
$streamSrc = ZM_BASE_URL.ZM_PATH_ZMS;
}
if ( count($args) ) {
$streamSrc .= "?".join( $querySep, $args );
}
$args['monitor'] = $this->{'Id'};
return( $streamSrc );
} // end function etStreamSrc
public function Width() {
if ( $this->Orientation() == '90' or $this->Orientation() == '270' ) {
return $this->{'Height'};
}
return $this->{'Width'};
}
public function Height() {
if ( $this->Orientation() == '90' or $this->Orientation() == '270' ) {
return $this->{'Width'};
}
return $this->{'Height'};
}
if ( ZM_OPT_USE_AUTH ) {
if ( ZM_AUTH_RELAY == 'hashed' ) {
$args['auth'] = generateAuthHash( ZM_AUTH_HASH_IPS );
} elseif ( ZM_AUTH_RELAY == 'plain' ) {
$args['user'] = $_SESSION['username'];
$args['pass'] = $_SESSION['password'];
} elseif ( ZM_AUTH_RELAY == 'none' ) {
$args['user'] = $_SESSION['username'];
}
}
if ( ( (!isset($args['mode'])) or ( $args['mode'] != 'single' ) ) && !empty($GLOBALS['connkey']) ) {
$args['connkey'] = $GLOBALS['connkey'];
}
if ( ZM_RAND_STREAM ) {
$args['rand'] = time();
}
if ( count($args) ) {
$streamSrc .= '?'.http_build_query( $args,'', $querySep );
}
return( $streamSrc );
} // end function getStreamSrc
public function Width() {
if ( $this->Orientation() == '90' or $this->Orientation() == '270' ) {
return $this->{'Height'};
}
return $this->{'Width'};
}
public function Height() {
if ( $this->Orientation() == '90' or $this->Orientation() == '270' ) {
return $this->{'Width'};
}
return $this->{'Height'};
}
public function set( $data ) {
foreach ($data as $k => $v) {
if ( is_array( $v ) ) {
# perhaps should turn into a comma-separated string
$this->{$k} = implode(',',$v);
} else if ( is_string( $v ) ) {
$this->{$k} = trim( $v );
} else if ( is_integer( $v ) ) {
$this->{$k} = $v;
} else if ( is_bool( $v ) ) {
$this->{$k} = $v;
} else {
Error( "Unknown type $k => $v of var " . gettype( $v ) );
$this->{$k} = $v;
}
}
}
}
?>

View File

@ -47,7 +47,7 @@ class Server {
return $this->{'Name'};
}
public function __call( $fn, array $args= NULL){
if(isset($this->{$fn})){
if( array_key_exists( $fn, $this) ) {
return $this->{$fn};
#array_unshift($args, $this);
#call_user_func_array( $this->{$fn}, $args);

View File

@ -65,6 +65,14 @@ class Storage {
}
public function disk_usage_percent() {
$path = $this->Path();
if ( ! $path ) {
Warning("Storage::disk_usage_percent: path is empty");
return 0;
} else if ( ! file_exists( $path ) ) {
Warning("Storage::disk_usage_percent: path $path does not exist");
return 0;
}
$total = disk_total_space( $path );
if ( ! $total ) {
Error("disk_total_space returned false for " . $path );

File diff suppressed because it is too large Load Diff

View File

@ -26,351 +26,314 @@ $GLOBALS['dbLogLevel'] = DB_LOG_OFF;
$GLOBALS['dbConn'] = false;
function dbConnect()
{
global $dbConn;
function dbConnect() {
global $dbConn;
if (strpos(ZM_DB_HOST, ':')) {
// Host variable may carry a port or socket.
list($host, $portOrSocket) = explode(':', ZM_DB_HOST, 2);
if (ctype_digit($portOrSocket)) {
$socket = ':host='.$host . ';port='.$portOrSocket;
} else {
$socket = ':unix_socket='.$portOrSocket;
}
} else {
$socket = ':host='.ZM_DB_HOST;
}
if (strpos(ZM_DB_HOST, ':')) {
// Host variable may carry a port or socket.
list($host, $portOrSocket) = explode(':', ZM_DB_HOST, 2);
if (ctype_digit($portOrSocket)) {
$socket = ':host='.$host . ';port='.$portOrSocket;
} else {
$socket = ':unix_socket='.$portOrSocket;
}
} else {
$socket = ':host='.ZM_DB_HOST;
}
try {
$dbConn = new PDO( ZM_DB_TYPE . $socket . ';dbname='.ZM_DB_NAME, ZM_DB_USER, ZM_DB_PASS );
$dbConn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $ex ) {
echo "Unable to connect to ZM db." . $ex->getMessage();
$dbConn = null;
}
try {
$dbConn = new PDO( ZM_DB_TYPE . $socket . ';dbname='.ZM_DB_NAME, ZM_DB_USER, ZM_DB_PASS );
$dbConn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $ex ) {
echo "Unable to connect to ZM db." . $ex->getMessage();
$dbConn = null;
}
}
dbConnect();
function dbDisconnect()
{
global $dbConn;
$dbConn = null;
function dbDisconnect() {
global $dbConn;
$dbConn = null;
}
function dbLogOff()
{
global $dbLogLevel;
$dbLogLevel = DB_LOG_OFF;
function dbLogOff() {
global $dbLogLevel;
$dbLogLevel = DB_LOG_OFF;
}
function dbLogOn()
{
global $dbLogLevel;
$dbLogLevel = DB_LOG_ONLY;
function dbLogOn() {
global $dbLogLevel;
$dbLogLevel = DB_LOG_ONLY;
}
function dbLogDebug()
{
global $dbLogLevel;
$dbLogLevel = DB_LOG_DEBUG;
function dbLogDebug() {
global $dbLogLevel;
$dbLogLevel = DB_LOG_DEBUG;
}
function dbDebug()
{
dbLogDebug();
function dbDebug() {
dbLogDebug();
}
function dbLog( $sql, $update=false )
{
global $dbLogLevel;
$noExecute = $update && ($dbLogLevel >= DB_LOG_DEBUG);
if ( $dbLogLevel > DB_LOG_OFF )
Logger::Debug( "SQL-LOG: $sql".($noExecute?" (not executed)":"") );
return( $noExecute );
function dbLog( $sql, $update=false ) {
global $dbLogLevel;
$noExecute = $update && ($dbLogLevel >= DB_LOG_DEBUG);
if ( $dbLogLevel > DB_LOG_OFF )
Debug( "SQL-LOG: $sql".($noExecute?" (not executed)":"") );
return( $noExecute );
}
function dbError( $sql )
{
Fatal( "SQL-ERR '".$dbConn->errorInfo()."', statement was '".$sql."'" );
function dbError( $sql ) {
Fatal( "SQL-ERR '".$dbConn->errorInfo()."', statement was '".$sql."'" );
}
function dbEscape( $string )
{
global $dbConn;
if ( version_compare( phpversion(), "4.3.0", "<") )
if ( get_magic_quotes_gpc() )
return( $dbConn->quote( stripslashes( $string ) ) );
else
return( $dbConn->quote( $string ) );
function dbEscape( $string ) {
global $dbConn;
if ( version_compare( phpversion(), "4.3.0", "<") )
if ( get_magic_quotes_gpc() )
return( $dbConn->quote( stripslashes( $string ) ) );
else
if ( get_magic_quotes_gpc() )
return( $dbConn->quote( stripslashes( $string ) ) );
else
return( $dbConn->quote( $string ) );
return( $dbConn->quote( $string ) );
else
if ( get_magic_quotes_gpc() )
return( $dbConn->quote( stripslashes( $string ) ) );
else
return( $dbConn->quote( $string ) );
}
function dbQuery( $sql, $params=NULL ) {
global $dbConn;
if ( dbLog( $sql, true ) )
return;
$result = NULL;
try {
if ( isset($params) ) {
$result = $dbConn->prepare( $sql );
$result->execute( $params );
} else {
$result = $dbConn->query( $sql );
}
} catch(PDOException $e) {
Fatal( "SQL-ERR '".$e->getMessage()."', statement was '".$sql."'" );
global $dbConn;
if ( dbLog( $sql, true ) )
return;
$result = NULL;
try {
if ( isset($params) ) {
$result = $dbConn->prepare( $sql );
$result->execute( $params );
} else {
$result = $dbConn->query( $sql );
}
return( $result );
} catch(PDOException $e) {
Fatal( "SQL-ERR '".$e->getMessage()."', statement was '".$sql."'" );
}
return( $result );
}
function dbFetchOne( $sql, $col=false, $params=NULL )
{
$result = dbQuery( $sql, $params );
if ( ! $result ) {
Fatal( "SQL-ERR dbFetchOne no result, statement was '".$sql."'" . ( $params ? 'params: ' . join(',',$params) : '' ) );
return false;
}
function dbFetchOne( $sql, $col=false, $params=NULL ) {
$result = dbQuery( $sql, $params );
if ( ! $result ) {
Fatal( "SQL-ERR dbFetchOne no result, statement was '".$sql."'" . ( $params ? 'params: ' . join(',',$params) : '' ) );
return false;
}
if ( $result && $dbRow = $result->fetch( PDO::FETCH_ASSOC ) )
return( $col?$dbRow[$col]:$dbRow );
return( false );
if ( $result && $dbRow = $result->fetch( PDO::FETCH_ASSOC ) ) {
if ( $col ) {
if ( ! isset( $dbRow[$col] ) ) {
Warning( "$col does not exist in the returned row" );
}
return $dbRow[$col];
}
return $dbRow;
}
return( false );
}
function dbFetchAll( $sql, $col=false, $params=NULL )
{
$result = dbQuery( $sql, $params );
if ( ! $result ) {
Fatal( "SQL-ERR dbFetchAll no result, statement was '".$sql."'" . ( $params ? 'params: ' .join(',', $params) : '' ) );
return false;
}
function dbFetchAll( $sql, $col=false, $params=NULL ) {
$result = dbQuery( $sql, $params );
if ( ! $result ) {
Fatal( "SQL-ERR dbFetchAll no result, statement was '".$sql."'" . ( $params ? 'params: ' .join(',', $params) : '' ) );
return false;
}
$dbRows = array();
while( $dbRow = $result->fetch( PDO::FETCH_ASSOC ) )
$dbRows[] = $col?$dbRow[$col]:$dbRow;
return( $dbRows );
$dbRows = array();
while( $dbRow = $result->fetch( PDO::FETCH_ASSOC ) )
$dbRows[] = $col?$dbRow[$col]:$dbRow;
return( $dbRows );
}
function dbFetchAssoc( $sql, $indexCol, $dataCol=false )
{
$result = dbQuery( $sql );
function dbFetchAssoc( $sql, $indexCol, $dataCol=false ) {
$result = dbQuery( $sql );
$dbRows = array();
while( $dbRow = $result->fetch( PDO::FETCH_ASSOC ) )
$dbRows[$dbRow[$indexCol]] = $dataCol?$dbRow[$dataCol]:$dbRow;
return( $dbRows );
$dbRows = array();
while( $dbRow = $result->fetch( PDO::FETCH_ASSOC ) )
$dbRows[$dbRow[$indexCol]] = $dataCol?$dbRow[$dataCol]:$dbRow;
return( $dbRows );
}
function dbFetch( $sql, $col=false )
{
return( dbFetchAll( $sql, $col ) );
function dbFetch( $sql, $col=false ) {
return( dbFetchAll( $sql, $col ) );
}
function dbFetchNext( $result, $col=false )
{
if ( $dbRow = $result->fetch( PDO::FETCH_ASSOC ) )
return( $col?$dbRow[$col]:$dbRow );
return( false );
function dbFetchNext( $result, $col=false ) {
if ( $dbRow = $result->fetch( PDO::FETCH_ASSOC ) )
return( $col?$dbRow[$col]:$dbRow );
return( false );
}
function dbNumRows( $sql )
{
$result = dbQuery( $sql );
return( $result->rowCount() );
function dbNumRows( $sql ) {
$result = dbQuery( $sql );
return( $result->rowCount() );
}
function dbInsertId()
{
global $dbConn;
return( $dbConn->lastInsertId() );
function dbInsertId() {
global $dbConn;
return( $dbConn->lastInsertId() );
}
function getEnumValues( $table, $column )
{
$row = dbFetchOne( "describe $table $column" );
preg_match_all( "/'([^']+)'/", $row['Type'], $matches );
return( $matches[1] );
function getEnumValues( $table, $column ) {
$row = dbFetchOne( "describe $table $column" );
preg_match_all( "/'([^']+)'/", $row['Type'], $matches );
return( $matches[1] );
}
function getSetValues( $table, $column )
{
return( getEnumValues( $table, $column ) );
function getSetValues( $table, $column ) {
return( getEnumValues( $table, $column ) );
}
function getUniqueValues( $table, $column, $asString=1 )
{
$values = array();
$sql = "select distinct $column from $table where (not isnull($column) and $column != '') order by $column";
foreach( dbFetchAll( $sql ) as $row )
{
if ( $asString )
$values[$row[$column]] = $row[$column];
else
$values[] = $row[$column];
}
return( $values );
function getUniqueValues( $table, $column, $asString=1 ) {
$values = array();
$sql = "select distinct $column from $table where (not isnull($column) and $column != '') order by $column";
foreach( dbFetchAll( $sql ) as $row ) {
if ( $asString )
$values[$row[$column]] = $row[$column];
else
$values[] = $row[$column];
}
return( $values );
}
function getTableColumns( $table, $asString=1 )
{
$columns = array();
$sql = "describe $table";
foreach( dbFetchAll( $sql ) as $row )
{
if ( $asString )
$columns[$row['Field']] = $row['Type'];
else
$columns[] = $row['Type'];
}
return( $columns );
function getTableColumns( $table, $asString=1 ) {
$columns = array();
$sql = "describe $table";
foreach( dbFetchAll( $sql ) as $row ) {
if ( $asString )
$columns[$row['Field']] = $row['Type'];
else
$columns[] = $row['Type'];
}
return( $columns );
}
function getTableAutoInc( $table )
{
$row = dbFetchOne( "show table status where Name=?", NULL, array($table) );
return( $row['Auto_increment'] );
function getTableAutoInc( $table ) {
$row = dbFetchOne( "show table status where Name=?", NULL, array($table) );
return( $row['Auto_increment'] );
}
function getTableDescription( $table, $asString=1 )
{
$columns = array();
foreach( dbFetchAll( "describe $table" ) as $row )
{
$desc = array(
'name' => $row['Field'],
'required' => ($row['Null']=='NO')?true:false,
'default' => $row['Default'],
'db' => $row,
function getTableDescription( $table, $asString=1 ) {
$columns = array();
foreach( dbFetchAll( "describe $table" ) as $row ) {
$desc = array(
'name' => $row['Field'],
'required' => ($row['Null']=='NO')?true:false,
'default' => $row['Default'],
'db' => $row,
);
if ( preg_match( "/^varchar\((\d+)\)$/", $row['Type'], $matches ) )
{
$desc['type'] = 'text';
$desc['typeAttrib'] = 'varchar';
$desc['maxLength'] = $matches[1];
}
elseif ( preg_match( "/^(\w+)?text$/", $row['Type'], $matches ) )
{
$desc['type'] = 'text';
if (!empty($matches[1]) )
$desc['typeAttrib'] = $matches[1];
switch ( $matches[1] )
{
case 'tiny' :
$desc['maxLength'] = 255;
break;
case 'medium' :
$desc['maxLength'] = 32768;
break;
case '' :
case 'big' :
//$desc['minLength'] = -128;
break;
default :
Error( "Unexpected text qualifier '".$matches[1]."' found for field '".$row['Field']."' in table '".$table."'" );
break;
}
}
elseif ( preg_match( "/^(enum|set)\((.*)\)$/", $row['Type'], $matches ) )
{
$desc['type'] = 'text';
$desc['typeAttrib'] = $matches[1];
preg_match_all( "/'([^']+)'/", $matches[2], $matches );
$desc['values'] = $matches[1];
}
elseif ( preg_match( "/^(\w+)?int\(\d+\)(?:\s+(unsigned))?$/", $row['Type'], $matches ) )
{
$desc['type'] = 'integer';
switch ( $matches[1] )
{
case 'tiny' :
$desc['minValue'] = -128;
$desc['maxValue'] = 127;
break;
case 'small' :
$desc['minValue'] = -32768;
$desc['maxValue'] = 32767;
break;
case 'medium' :
$desc['minValue'] = -8388608;
$desc['maxValue'] = 8388607;
break;
case '' :
$desc['minValue'] = -2147483648;
$desc['maxValue'] = 2147483647;
break;
case 'big' :
//$desc['minValue'] = -128;
//$desc['maxValue'] = 127;
break;
default :
Error( "Unexpected integer qualifier '".$matches[1]."' found for field '".$row['Field']."' in table '".$table."'" );
break;
}
if ( !empty($matches[1]) )
$desc['typeAttrib'] = $matches[1];
if ( $desc['unsigned'] = ( isset($matches[2]) && $matches[2] == 'unsigned' ) )
{
$desc['maxValue'] += (-$desc['minValue']);
$desc['minValue'] = 0;
}
}
elseif ( preg_match( "/^(?:decimal|numeric)\((\d+)(?:,(\d+))?\)(?:\s+(unsigned))?$/", $row['Type'], $matches ) )
{
$desc['type'] = 'fixed';
$desc['range'] = $matches[1];
if ( isset($matches[2]) )
$desc['precision'] = $matches[2];
else
$desc['precision'] = 0;
$desc['unsigned'] = ( isset($matches[3]) && $matches[3] == 'unsigned' );
}
elseif ( preg_match( "/^(datetime|timestamp|date|time)$/", $row['Type'], $matches ) )
{
$desc['type'] = 'datetime';
switch ( $desc['typeAttrib'] = $matches[1] )
{
case 'datetime' :
case 'timestamp' :
$desc['hasDate'] = true;
$desc['hasTime'] = true;
break;
case 'date' :
$desc['hasDate'] = true;
$desc['hasTime'] = false;
break;
case 'time' :
$desc['hasDate'] = false;
$desc['hasTime'] = true;
break;
}
}
else
{
Error( "Can't parse database type '".$row['Type']."' found for field '".$row['Field']."' in table '".$table."'" );
}
if ( $asString )
$columns[$row['Field']] = $desc;
else
$columns[] = $desc;
if ( preg_match( "/^varchar\((\d+)\)$/", $row['Type'], $matches ) ) {
$desc['type'] = 'text';
$desc['typeAttrib'] = 'varchar';
$desc['maxLength'] = $matches[1];
} elseif ( preg_match( "/^(\w+)?text$/", $row['Type'], $matches ) ) {
$desc['type'] = 'text';
if (!empty($matches[1]) )
$desc['typeAttrib'] = $matches[1];
switch ( $matches[1] ) {
case 'tiny' :
$desc['maxLength'] = 255;
break;
case 'medium' :
$desc['maxLength'] = 32768;
break;
case '' :
case 'big' :
//$desc['minLength'] = -128;
break;
default :
Error( "Unexpected text qualifier '".$matches[1]."' found for field '".$row['Field']."' in table '".$table."'" );
break;
}
} elseif ( preg_match( "/^(enum|set)\((.*)\)$/", $row['Type'], $matches ) ) {
$desc['type'] = 'text';
$desc['typeAttrib'] = $matches[1];
preg_match_all( "/'([^']+)'/", $matches[2], $matches );
$desc['values'] = $matches[1];
} elseif ( preg_match( "/^(\w+)?int\(\d+\)(?:\s+(unsigned))?$/", $row['Type'], $matches ) ) {
$desc['type'] = 'integer';
switch ( $matches[1] ) {
case 'tiny' :
$desc['minValue'] = -128;
$desc['maxValue'] = 127;
break;
case 'small' :
$desc['minValue'] = -32768;
$desc['maxValue'] = 32767;
break;
case 'medium' :
$desc['minValue'] = -8388608;
$desc['maxValue'] = 8388607;
break;
case '' :
$desc['minValue'] = -2147483648;
$desc['maxValue'] = 2147483647;
break;
case 'big' :
//$desc['minValue'] = -128;
//$desc['maxValue'] = 127;
break;
default :
Error( "Unexpected integer qualifier '".$matches[1]."' found for field '".$row['Field']."' in table '".$table."'" );
break;
}
if ( !empty($matches[1]) )
$desc['typeAttrib'] = $matches[1];
if ( $desc['unsigned'] = ( isset($matches[2]) && $matches[2] == 'unsigned' ) ) {
$desc['maxValue'] += (-$desc['minValue']);
$desc['minValue'] = 0;
}
} elseif ( preg_match( "/^(?:decimal|numeric)\((\d+)(?:,(\d+))?\)(?:\s+(unsigned))?$/", $row['Type'], $matches ) ) {
$desc['type'] = 'fixed';
$desc['range'] = $matches[1];
if ( isset($matches[2]) )
$desc['precision'] = $matches[2];
else
$desc['precision'] = 0;
$desc['unsigned'] = ( isset($matches[3]) && $matches[3] == 'unsigned' );
} elseif ( preg_match( "/^(datetime|timestamp|date|time)$/", $row['Type'], $matches ) ) {
$desc['type'] = 'datetime';
switch ( $desc['typeAttrib'] = $matches[1] ) {
case 'datetime' :
case 'timestamp' :
$desc['hasDate'] = true;
$desc['hasTime'] = true;
break;
case 'date' :
$desc['hasDate'] = true;
$desc['hasTime'] = false;
break;
case 'time' :
$desc['hasDate'] = false;
$desc['hasTime'] = true;
break;
}
} else {
Error( "Can't parse database type '".$row['Type']."' found for field '".$row['Field']."' in table '".$table."'" );
}
return( $columns );
if ( $asString )
$columns[$row['Field']] = $desc;
else
$columns[] = $desc;
}
return( $columns );
}
function dbFetchMonitor( $mid )
{
return( dbFetchOne( "select * from Monitors where Id = ?", NULL, array($mid) ) );
function dbFetchMonitor( $mid ) {
return( dbFetchOne( "select * from Monitors where Id = ?", NULL, array($mid) ) );
}
function dbFetchGroup( $gid )
{
return( dbFetchOne( "select * from Groups where Id = ?", NULL, array($gid) ) );
function dbFetchGroup( $gid ) {
return( dbFetchOne( "select * from Groups where Id = ?", NULL, array($gid) ) );
}
?>