Php namespace (#2537)

* experiment with namespaces on the Server class

* experiment with namespaces on the Server class

* Implement the ZM namespace on objects

* Implement the ZM namespace on objects

* Implement the ZM namespace on objects
This commit is contained in:
Isaac Connor 2019-02-22 09:19:07 -05:00 committed by GitHub
parent b8117f7fc9
commit 8dd8888975
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
77 changed files with 340 additions and 337 deletions

View File

@ -1,6 +1,6 @@
<?php <?php
$defaultMonitor = new Monitor(); $defaultMonitor = new ZM\Monitor();
$defaultMonitor->set(array( $defaultMonitor->set(array(
'StorageId' => 1, 'StorageId' => 1,
'ServerId' => 'auto', 'ServerId' => 'auto',
@ -19,11 +19,11 @@ function probe( &$url_bits ) {
$cam_list_html = file_get_contents('http://'.$url_bits['host'].':5000/monitoring/'); $cam_list_html = file_get_contents('http://'.$url_bits['host'].':5000/monitoring/');
if ( $cam_list_html ) { if ( $cam_list_html ) {
Logger::Debug("Have content at port 5000/monitoring"); ZM\Logger::Debug("Have content at port 5000/monitoring");
$matches_count = preg_match_all( $matches_count = preg_match_all(
'/<a href="http:\/\/([.[:digit:]]+):([[:digit:]]+)\/\?action=stream" target="_blank">([^<]+)<\/a>/', '/<a href="http:\/\/([.[:digit:]]+):([[:digit:]]+)\/\?action=stream" target="_blank">([^<]+)<\/a>/',
$cam_list_html, $cam_list ); $cam_list_html, $cam_list );
Logger::Debug(print_r($cam_list,true)); ZM\Logger::Debug(print_r($cam_list,true));
} }
if ( $matches_count ) { if ( $matches_count ) {
for( $index = 0; $index < $matches_count; $index ++ ) { for( $index = 0; $index < $matches_count; $index ++ ) {
@ -33,10 +33,10 @@ function probe( &$url_bits ) {
if ( ! isset($new_stream['scheme'] ) ) if ( ! isset($new_stream['scheme'] ) )
$new_stream['scheme'] = 'http'; $new_stream['scheme'] = 'http';
$available_streams[] = $new_stream; $available_streams[] = $new_stream;
Logger::Debug("Have new stream " . print_r($new_stream,true) ); ZM\Logger::Debug("Have new stream " . print_r($new_stream,true) );
} }
} else { } else {
Info('No matches'); ZM\Info('No matches');
} }
if ( 0 ) { if ( 0 ) {
// No port given, do a port scan // No port given, do a port scan
@ -57,7 +57,7 @@ Info("Testing connection to " . $url_bits['host'].':'.$port);
$new_stream['port'] = $port; $new_stream['port'] = $port;
} else { } else {
socket_close($socket); socket_close($socket);
Info("No connection to ".$url_bits['host'] . " on port $port"); ZM\Info("No connection to ".$url_bits['host'] . " on port $port");
continue; continue;
} }
if ( $new_stream ) { if ( $new_stream ) {
@ -65,7 +65,7 @@ Info("Testing connection to " . $url_bits['host'].':'.$port);
$new_stream['scheme'] = 'http'; $new_stream['scheme'] = 'http';
$url = unparse_url($new_stream, array('path'=>'/', 'query'=>'action=snapshot')); $url = unparse_url($new_stream, array('path'=>'/', 'query'=>'action=snapshot'));
list($width, $height, $type, $attr) = getimagesize( $url ); list($width, $height, $type, $attr) = getimagesize( $url );
Info("Got $width x $height from $url"); ZM\Info("Got $width x $height from $url");
$new_stream['Width'] = $width; $new_stream['Width'] = $width;
$new_stream['Height'] = $height; $new_stream['Height'] = $height;
@ -93,9 +93,9 @@ Info("Testing connection to " . $url_bits['host'].':'.$port);
foreach ( $available_streams as &$stream ) { foreach ( $available_streams as &$stream ) {
# check for existence in db. # check for existence in db.
$stream['url'] = unparse_url( $stream, array('path'=>'/','query'=>'action=stream') ); $stream['url'] = unparse_url( $stream, array('path'=>'/','query'=>'action=stream') );
$monitors = Monitor::find( array('Path'=>$stream['url']) ); $monitors = ZM\Monitor::find( array('Path'=>$stream['url']) );
if ( count($monitors) ) { if ( count($monitors) ) {
Info("Found monitors matching " . $stream['url'] ); ZM\Info("Found monitors matching " . $stream['url'] );
$stream['Monitor'] = $monitors[0]; $stream['Monitor'] = $monitors[0];
if ( isset( $stream['Width'] ) and ( $stream['Monitor']->Width() != $stream['Width'] ) ) { if ( isset( $stream['Width'] ) and ( $stream['Monitor']->Width() != $stream['Width'] ) ) {
$stream['Warning'] .= 'Monitor width ('.$stream['Monitor']->Width().') and stream width ('.$stream['Width'].") do not match!\n"; $stream['Warning'] .= 'Monitor width ('.$stream['Monitor']->Width().') and stream width ('.$stream['Width'].") do not match!\n";
@ -135,9 +135,9 @@ if ( canEdit( 'Monitors' ) ) {
if ( 0 ) { if ( 0 ) {
// Shortcut test // Shortcut test
$monitors = Monitor::find( array('Path'=>$_REQUEST['url']) ); $monitors = ZM\Monitor::find( array('Path'=>$_REQUEST['url']) );
if ( count( $monitors ) ) { if ( count( $monitors ) ) {
Info("Monitor found for " . $_REQUEST['url']); ZM\Info("Monitor found for " . $_REQUEST['url']);
$url_bits['url'] = $_REQUEST['url']; $url_bits['url'] = $_REQUEST['url'];
$url_bits['Monitor'] = $monitors[0]; $url_bits['Monitor'] = $monitors[0];
$available_stream[] = $url_bits; $available_stream[] = $url_bits;
@ -174,7 +174,7 @@ if ( 0 ) {
$name = $data[0]; $name = $data[0];
$url = $data[1]; $url = $data[1];
$group = $data[2]; $group = $data[2];
Info("Have the following line data $name $url $group"); ZM\Info("Have the following line data $name $url $group");
$url_bits = null; $url_bits = null;
if ( preg_match('/(\d+)\.(\d+)\.(\d+)\.(\d+)/', $url) ) { if ( preg_match('/(\d+)\.(\d+)\.(\d+)\.(\d+)/', $url) ) {
@ -183,7 +183,7 @@ if ( 0 ) {
$url_bits = parse_url( $url ); $url_bits = parse_url( $url );
} }
if ( ! $url_bits ) { if ( ! $url_bits ) {
Info("Bad url, skipping line $name $url $group"); ZM\Info("Bad url, skipping line $name $url $group");
continue; continue;
} }
@ -207,11 +207,11 @@ if ( 0 ) {
} // end case import } // end case import
default: default:
{ {
Warning("unknown action " . $_REQUEST['action'] ); ZM\Warning("unknown action " . $_REQUEST['action'] );
} // end ddcase default } // end ddcase default
} }
} else { } else {
Warning("Cannot edit monitors" ); ZM\Warning("Cannot edit monitors" );
} }
ajaxError( 'Unrecognised action or insufficient permissions' ); ajaxError( 'Unrecognised action or insufficient permissions' );

View File

@ -1,6 +1,6 @@
<?php <?php
define("MSG_TIMEOUT", 2.0); define('MSG_TIMEOUT', 2.0);
define("MSG_DATA_SIZE", 4+256); define('MSG_DATA_SIZE', 4+256);
if ( canEdit('Monitors') ) { if ( canEdit('Monitors') ) {
$zmuCommand = getZmuCommand(' -m '.validInt($_REQUEST['id'])); $zmuCommand = getZmuCommand(' -m '.validInt($_REQUEST['id']));

View File

@ -1,6 +1,5 @@
<?php <?php
if ( canEdit('Monitors') ) {
if ( canEdit( 'Monitors' ) ) {
switch ( $_REQUEST['action'] ) { switch ( $_REQUEST['action'] ) {
case 'sort' : case 'sort' :
{ {
@ -8,15 +7,15 @@ if ( canEdit( 'Monitors' ) ) {
# Two concurrent sorts could generate odd sortings... so lock the table. # Two concurrent sorts could generate odd sortings... so lock the table.
global $dbConn; global $dbConn;
$dbConn->beginTransaction(); $dbConn->beginTransaction();
$dbConn->exec( 'LOCK TABLES Monitors WRITE' ); $dbConn->exec('LOCK TABLES Monitors WRITE');
for ( $i = 0; $i < count($monitor_ids); $i += 1 ) { for ( $i = 0; $i < count($monitor_ids); $i += 1 ) {
$monitor_id = $monitor_ids[$i]; $monitor_id = $monitor_ids[$i];
$monitor_id = preg_replace( '/^monitor_id-/', '', $monitor_id ); $monitor_id = preg_replace( '/^monitor_id-/', '', $monitor_id );
if ( ( ! $monitor_id ) or ! ( is_integer( $monitor_id ) or ctype_digit( $monitor_id ) ) ) { if ( ( ! $monitor_id ) or ! ( is_integer( $monitor_id ) or ctype_digit( $monitor_id ) ) ) {
Warning( "Got $monitor_id from " . $monitor_ids[$i] ); Warning("Got $monitor_id from " . $monitor_ids[$i]);
continue; continue;
} }
dbQuery( 'UPDATE Monitors SET Sequence=? WHERE Id=?', array( $i, $monitor_id ) ); dbQuery('UPDATE Monitors SET Sequence=? WHERE Id=?', array($i, $monitor_id));
} // end for each monitor_id } // end for each monitor_id
$dbConn->commit(); $dbConn->commit();
$dbConn->exec('UNLOCK TABLES'); $dbConn->exec('UNLOCK TABLES');
@ -25,13 +24,12 @@ if ( canEdit( 'Monitors' ) ) {
} // end case sort } // end case sort
default: default:
{ {
Warning("unknown action " . $_REQUEST['action'] ); ZM\Warning('unknown action ' . $_REQUEST['action']);
} // end ddcase default } // end ddcase default
} }
} else { } else {
Warning("Cannot edit monitors" ); ZM\Warning('Cannot edit monitors');
} }
ajaxError( 'Unrecognised action or insufficient permissions' ); ajaxError('Unrecognised action or insufficient permissions');
?> ?>

View File

@ -8,7 +8,7 @@ if ( empty($_REQUEST['id']) )
if ( canView( 'Control', $_REQUEST['id'] ) ) if ( canView( 'Control', $_REQUEST['id'] ) )
{ {
$monitor = new Monitor( $_REQUEST['id'] ); $monitor = new ZM\Monitor( $_REQUEST['id'] );
$ctrlCommand = buildControlCommand( $monitor ); $ctrlCommand = buildControlCommand( $monitor );

View File

@ -119,7 +119,7 @@ if ( canEdit( 'Events' ) ) {
} }
case 'delete' : case 'delete' :
{ {
$Event = new Event( $_REQUEST['id'] ); $Event = new ZM\Event( $_REQUEST['id'] );
if ( ! $Event->Id() ) { if ( ! $Event->Id() ) {
ajaxResponse( array( 'refreshEvent'=>false, 'refreshParent'=>true, 'message'=> 'Event not found.' ) ); ajaxResponse( array( 'refreshEvent'=>false, 'refreshParent'=>true, 'message'=> 'Event not found.' ) );
} else { } else {

View File

@ -9,7 +9,7 @@ switch ( $_REQUEST['task'] ) {
{ {
// Silently ignore bogus requests // Silently ignore bogus requests
if ( !empty($_POST['level']) && !empty($_POST['message']) ) { if ( !empty($_POST['level']) && !empty($_POST['message']) ) {
logInit(array('id'=>'web_js')); ZM\logInit(array('id'=>'web_js'));
$string = $_POST['message']; $string = $_POST['message'];
@ -21,9 +21,9 @@ switch ( $_REQUEST['task'] ) {
$levels = array_flip(Logger::$codes); $levels = array_flip(Logger::$codes);
if ( !isset($levels[$_POST['level']]) ) if ( !isset($levels[$_POST['level']]) )
Panic("Unexpected logger level '".$_POST['level']."'"); ZM\Panic("Unexpected logger level '".$_POST['level']."'");
$level = $levels[$_POST['level']]; $level = $levels[$_POST['level']];
Logger::fetch()->logPrint($level, $string, $file, $line); ZM\Logger::fetch()->logPrint($level, $string, $file, $line);
} }
ajaxResponse(); ajaxResponse();
break; break;
@ -33,7 +33,7 @@ switch ( $_REQUEST['task'] ) {
if ( !canView('System') ) if ( !canView('System') )
ajaxError('Insufficient permissions to view log entries'); ajaxError('Insufficient permissions to view log entries');
$servers = Server::find(); $servers = ZM\Server::find();
$servers_by_Id = array(); $servers_by_Id = array();
# There is probably a better way to do this. # There is probably a better way to do this.
foreach ( $servers as $server ) { foreach ( $servers as $server ) {
@ -46,7 +46,7 @@ switch ( $_REQUEST['task'] ) {
$limit = 100; $limit = 100;
if ( isset($_REQUEST['limit']) ) { if ( isset($_REQUEST['limit']) ) {
if ( ( !is_integer($_REQUEST['limit']) and !ctype_digit($_REQUEST['limit']) ) ) { if ( ( !is_integer($_REQUEST['limit']) and !ctype_digit($_REQUEST['limit']) ) ) {
Error('Invalid value for limit ' . $_REQUEST['limit']); ZM\Error('Invalid value for limit ' . $_REQUEST['limit']);
} else { } else {
$limit = $_REQUEST['limit']; $limit = $_REQUEST['limit'];
} }
@ -54,7 +54,7 @@ switch ( $_REQUEST['task'] ) {
$sortField = 'TimeKey'; $sortField = 'TimeKey';
if ( isset($_REQUEST['sortField']) ) { if ( isset($_REQUEST['sortField']) ) {
if ( !in_array($_REQUEST['sortField'], $filterFields) and ( $_REQUEST['sortField'] != 'TimeKey' ) ) { if ( !in_array($_REQUEST['sortField'], $filterFields) and ( $_REQUEST['sortField'] != 'TimeKey' ) ) {
Error("Invalid sort field " . $_REQUEST['sortField']); ZM\Error("Invalid sort field " . $_REQUEST['sortField']);
} else { } else {
$sortField = $_REQUEST['sortField']; $sortField = $_REQUEST['sortField'];
} }
@ -76,7 +76,7 @@ switch ( $_REQUEST['task'] ) {
foreach ( $filter as $field=>$value ) { foreach ( $filter as $field=>$value ) {
if ( ! in_array($field, $filterFields) ) { if ( ! in_array($field, $filterFields) ) {
Error("$field is not in valid filter fields"); ZM\Error("$field is not in valid filter fields");
continue; continue;
} }
if ( $field == 'Level' ){ if ( $field == 'Level' ){
@ -105,8 +105,8 @@ switch ( $_REQUEST['task'] ) {
$value = $log[$field]; $value = $log[$field];
if ( $field == 'Level' ) { if ( $field == 'Level' ) {
if ( $value <= Logger::INFO ) if ( $value <= ZM\Logger::INFO )
$options[$field][$value] = Logger::$codes[$value]; $options[$field][$value] = ZM\Logger::$codes[$value];
else else
$options[$field][$value] = 'DB'.$value; $options[$field][$value] = 'DB'.$value;
} else if ( $field == 'ServerId' ) { } else if ( $field == 'ServerId' ) {
@ -146,14 +146,14 @@ switch ( $_REQUEST['task'] ) {
$sortField = 'TimeKey'; $sortField = 'TimeKey';
if ( isset($_POST['sortField']) ) { if ( isset($_POST['sortField']) ) {
if ( ! in_array( $_POST['sortField'], $filterFields ) and ( $_POST['sortField'] != 'TimeKey' ) ) { if ( ! in_array( $_POST['sortField'], $filterFields ) and ( $_POST['sortField'] != 'TimeKey' ) ) {
Error("Invalid sort field " . $_POST['sortField'] ); ZM\Error("Invalid sort field " . $_POST['sortField'] );
} else { } else {
$sortField = $_POST['sortField']; $sortField = $_POST['sortField'];
} }
} }
$sortOrder = (isset($_POST['sortOrder']) and $_POST['sortOrder']) == 'asc' ? 'asc':'desc'; $sortOrder = (isset($_POST['sortOrder']) and $_POST['sortOrder']) == 'asc' ? 'asc':'desc';
$servers = Server::find(); $servers = ZM\Server::find();
$servers_by_Id = array(); $servers_by_Id = array();
# There is probably a better way to do this. # There is probably a better way to do this.
foreach ( $servers as $server ) { foreach ( $servers as $server ) {
@ -164,11 +164,11 @@ switch ( $_REQUEST['task'] ) {
$where = array(); $where = array();
$values = array(); $values = array();
if ( $minTime ) { if ( $minTime ) {
Logger::Debug("MinTime: $minTime"); ZM\Logger::Debug("MinTime: $minTime");
if ( preg_match('/(.+)(\.\d+)/', $minTime, $matches) ) { if ( preg_match('/(.+)(\.\d+)/', $minTime, $matches) ) {
# This handles sub second precision # This handles sub second precision
$minTime = strtotime($matches[1]).$matches[2]; $minTime = strtotime($matches[1]).$matches[2];
Logger::Debug("MinTime: $minTime"); ZM\Logger::Debug("MinTime: $minTime");
} else { } else {
$minTime = strtotime($minTime); $minTime = strtotime($minTime);
} }
@ -214,27 +214,27 @@ switch ( $_REQUEST['task'] ) {
$exportExt = 'xml'; $exportExt = 'xml';
break; break;
default : default :
Fatal("Unrecognised log export format '$format'"); ZM\Fatal("Unrecognised log export format '$format'");
} }
$exportKey = substr(md5(rand()),0,8); $exportKey = substr(md5(rand()),0,8);
$exportFile = "zm-log.$exportExt"; $exportFile = "zm-log.$exportExt";
if ( ! file_exists(ZM_DIR_EXPORTS) ) { if ( ! file_exists(ZM_DIR_EXPORTS) ) {
Logger::Debug('Creating ' . ZM_DIR_EXPORTS); ZM\Logger::Debug('Creating ' . ZM_DIR_EXPORTS);
if ( ! mkdir(ZM_DIR_EXPORTS) ) { if ( ! mkdir(ZM_DIR_EXPORTS) ) {
Fatal("Can't create exports dir at '".ZM_DIR_EXPORTS."'"); ZM\Fatal("Can't create exports dir at '".ZM_DIR_EXPORTS."'");
} }
} }
$exportPath = ZM_DIR_EXPORTS."/zm-log-$exportKey.$exportExt"; $exportPath = ZM_DIR_EXPORTS."/zm-log-$exportKey.$exportExt";
Logger::Debug("Exporting to $exportPath"); ZM\Logger::Debug("Exporting to $exportPath");
if ( !($exportFP = fopen($exportPath, 'w')) ) if ( !($exportFP = fopen($exportPath, 'w')) )
Fatal("Unable to open log export file $exportPath"); ZM\Fatal("Unable to open log export file $exportPath");
$logs = array(); $logs = array();
foreach ( dbFetchAll($sql, NULL, $values) as $log ) { foreach ( dbFetchAll($sql, NULL, $values) as $log ) {
$log['DateTime'] = preg_replace('/^\d+/', strftime( "%Y-%m-%d %H:%M:%S", intval($log['TimeKey']) ), $log['TimeKey']); $log['DateTime'] = preg_replace('/^\d+/', strftime( "%Y-%m-%d %H:%M:%S", intval($log['TimeKey']) ), $log['TimeKey']);
$log['Server'] = ( $log['ServerId'] and isset($servers_by_Id[$log['ServerId']]) ) ? $servers_by_Id[$log['ServerId']]->Name() : ''; $log['Server'] = ( $log['ServerId'] and isset($servers_by_Id[$log['ServerId']]) ) ? $servers_by_Id[$log['ServerId']]->Name() : '';
$logs[] = $log; $logs[] = $log;
} }
Logger::Debug(count($logs)." lines being exported by $sql " . implode(',',$values)); ZM\Logger::Debug(count($logs)." lines being exported by $sql " . implode(',',$values));
switch( $format ) { switch( $format ) {
case 'text' : case 'text' :
@ -318,10 +318,10 @@ switch ( $_REQUEST['task'] ) {
' ); ' );
foreach ( $logs as $log ) { foreach ( $logs as $log ) {
$classLevel = $log['Level']; $classLevel = $log['Level'];
if ( $classLevel < Logger::FATAL ) if ( $classLevel < ZM\Logger::FATAL )
$classLevel = Logger::FATAL; $classLevel = ZM\Logger::FATAL;
elseif ( $classLevel > Logger::DEBUG ) elseif ( $classLevel > ZM\Logger::DEBUG )
$classLevel = Logger::DEBUG; $classLevel = ZM\Logger::DEBUG;
$logClass = 'log-'.strtolower(Logger::$codes[$classLevel]); $logClass = 'log-'.strtolower(Logger::$codes[$classLevel]);
fprintf( $exportFP, " <tr class=\"%s\"><td>%s</td><td>%s</td><td>%s</td><td>%d</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>\n", $logClass, $log['DateTime'], $log['Component'], $log['Server'], $log['Pid'], $log['Code'], $log['Message'], $log['File'], $log['Line'] ); fprintf( $exportFP, " <tr class=\"%s\"><td>%s</td><td>%s</td><td>%s</td><td>%d</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>\n", $logClass, $log['DateTime'], $log['Component'], $log['Server'], $log['Pid'], $log['Code'], $log['Message'], $log['File'], $log['Line'] );
} }
@ -384,10 +384,10 @@ switch ( $_REQUEST['task'] ) {
ajaxError('Insufficient permissions to download logs'); ajaxError('Insufficient permissions to download logs');
if ( empty($_REQUEST['key']) ) if ( empty($_REQUEST['key']) )
Fatal('No log export key given'); ZM\Fatal('No log export key given');
$exportKey = $_REQUEST['key']; $exportKey = $_REQUEST['key'];
if ( empty($_REQUEST['format']) ) if ( empty($_REQUEST['format']) )
Fatal('No log export format given'); ZM\Fatal('No log export format given');
$format = $_REQUEST['format']; $format = $_REQUEST['format'];
switch( $format ) { switch( $format ) {
@ -404,7 +404,7 @@ switch ( $_REQUEST['task'] ) {
$exportExt = 'xml'; $exportExt = 'xml';
break; break;
default : default :
Fatal("Unrecognised log export format '$format'"); ZM\Fatal("Unrecognised log export format '$format'");
} }
$exportFile = "zm-log.$exportExt"; $exportFile = "zm-log.$exportExt";

View File

@ -284,7 +284,7 @@ function collectData() {
if ( in_array($matches[1], $fieldSql) ) { if ( in_array($matches[1], $fieldSql) ) {
$sql .= $matches[1]; $sql .= $matches[1];
} else { } else {
Error('Sort field ' . $matches[1] . ' not in SQL Fields'); ZM\Error('Sort field ' . $matches[1] . ' not in SQL Fields');
} }
if ( count($matches) > 2 ) { if ( count($matches) > 2 ) {
$sql .= ' '.strtoupper($matches[2]); $sql .= ' '.strtoupper($matches[2]);
@ -292,7 +292,7 @@ function collectData() {
$sql .= ' '.strtoupper($matches[3]); $sql .= ' '.strtoupper($matches[3]);
} }
} else { } else {
Error("Sort field didn't match regexp $sort_field"); ZM\Error("Sort field didn't match regexp $sort_field");
} }
} # end foreach sort field } # end foreach sort field
} # end if has sort } # end if has sort
@ -323,7 +323,7 @@ function collectData() {
} }
} }
} }
#Logger::Debug(print_r($data, true)); #ZM\Logger::Debug(print_r($data, true));
return $data; return $data;
} }

View File

@ -20,7 +20,7 @@ if ( sem_acquire($semaphore,1) !== false ) {
$localSocketFile = ZM_PATH_SOCKS.'/zms-'.sprintf('%06d',$_REQUEST['connkey']).'w.sock'; $localSocketFile = ZM_PATH_SOCKS.'/zms-'.sprintf('%06d',$_REQUEST['connkey']).'w.sock';
if ( file_exists( $localSocketFile ) ) { if ( file_exists( $localSocketFile ) ) {
Warning("sock file $localSocketFile already exists?! Is someone else talking to zms?"); ZM\Warning("sock file $localSocketFile already exists?! Is someone else talking to zms?");
// They could be. We can maybe have concurrent requests from a browser. // They could be. We can maybe have concurrent requests from a browser.
} }
if ( ! socket_bind( $socket, $localSocketFile ) ) { if ( ! socket_bind( $socket, $localSocketFile ) ) {
@ -29,23 +29,23 @@ if ( sem_acquire($semaphore,1) !== false ) {
switch ( $_REQUEST['command'] ) { switch ( $_REQUEST['command'] ) {
case CMD_VARPLAY : case CMD_VARPLAY :
Logger::Debug( 'Varplaying to '.$_REQUEST['rate'] ); ZM\Logger::Debug( 'Varplaying to '.$_REQUEST['rate'] );
$msg = pack( 'lcn', MSG_CMD, $_REQUEST['command'], $_REQUEST['rate']+32768 ); $msg = pack( 'lcn', MSG_CMD, $_REQUEST['command'], $_REQUEST['rate']+32768 );
break; break;
case CMD_ZOOMIN : case CMD_ZOOMIN :
Logger::Debug( 'Zooming to '.$_REQUEST['x'].",".$_REQUEST['y'] ); ZM\Logger::Debug( 'Zooming to '.$_REQUEST['x'].",".$_REQUEST['y'] );
$msg = pack( 'lcnn', MSG_CMD, $_REQUEST['command'], $_REQUEST['x'], $_REQUEST['y'] ); $msg = pack( 'lcnn', MSG_CMD, $_REQUEST['command'], $_REQUEST['x'], $_REQUEST['y'] );
break; break;
case CMD_PAN : case CMD_PAN :
Logger::Debug( 'Panning to '.$_REQUEST['x'].",".$_REQUEST['y'] ); ZM\Logger::Debug( 'Panning to '.$_REQUEST['x'].",".$_REQUEST['y'] );
$msg = pack( 'lcnn', MSG_CMD, $_REQUEST['command'], $_REQUEST['x'], $_REQUEST['y'] ); $msg = pack( 'lcnn', MSG_CMD, $_REQUEST['command'], $_REQUEST['x'], $_REQUEST['y'] );
break; break;
case CMD_SCALE : case CMD_SCALE :
Logger::Debug( 'Scaling to '.$_REQUEST['scale'] ); ZM\Logger::Debug( 'Scaling to '.$_REQUEST['scale'] );
$msg = pack( 'lcn', MSG_CMD, $_REQUEST['command'], $_REQUEST['scale'] ); $msg = pack( 'lcn', MSG_CMD, $_REQUEST['command'], $_REQUEST['scale'] );
break; break;
case CMD_SEEK : case CMD_SEEK :
Logger::Debug( 'Seeking to '.$_REQUEST['offset'] ); ZM\Logger::Debug( 'Seeking to '.$_REQUEST['offset'] );
$msg = pack( 'lcN', MSG_CMD, $_REQUEST['command'], $_REQUEST['offset'] ); $msg = pack( 'lcN', MSG_CMD, $_REQUEST['command'], $_REQUEST['offset'] );
break; break;
default : default :
@ -81,18 +81,18 @@ if ( sem_acquire($semaphore,1) !== false ) {
$numSockets = socket_select( $rSockets, $wSockets, $eSockets, intval($timeout/1000), ($timeout%1000)*1000 ); $numSockets = socket_select( $rSockets, $wSockets, $eSockets, intval($timeout/1000), ($timeout%1000)*1000 );
if ( $numSockets === false ) { if ( $numSockets === false ) {
Error('socket_select failed: ' . socket_strerror(socket_last_error()) ); ZM\Error('socket_select failed: ' . socket_strerror(socket_last_error()) );
ajaxError( 'socket_select failed: '.socket_strerror(socket_last_error()) ); ajaxError( 'socket_select failed: '.socket_strerror(socket_last_error()) );
} else if ( $numSockets < 0 ) { } else if ( $numSockets < 0 ) {
Error( "Socket closed $remSockFile" ); ZM\Error( "Socket closed $remSockFile" );
ajaxError( "Socket closed $remSockFile" ); ajaxError( "Socket closed $remSockFile" );
} else if ( $numSockets == 0 ) { } else if ( $numSockets == 0 ) {
Error( "Timed out waiting for msg $remSockFile" ); ZM\Error( "Timed out waiting for msg $remSockFile" );
socket_Set_nonblock($socket); socket_Set_nonblock($socket);
#ajaxError( "Timed out waiting for msg $remSockFile" ); #ajaxError( "Timed out waiting for msg $remSockFile" );
} else if ( $numSockets > 0 ) { } else if ( $numSockets > 0 ) {
if ( count($rSockets) != 1 ) { if ( count($rSockets) != 1 ) {
Error( 'Bogus return from select, '.count($rSockets).' sockets available' ); ZM\Error( 'Bogus return from select, '.count($rSockets).' sockets available' );
ajaxError( 'Bogus return from select, '.count($rSockets).' sockets available' ); ajaxError( 'Bogus return from select, '.count($rSockets).' sockets available' );
} }
} }
@ -122,9 +122,9 @@ if ( sem_acquire($semaphore,1) !== false ) {
case MSG_DATA_WATCH : case MSG_DATA_WATCH :
{ {
$data = unpack( "ltype/imonitor/istate/dfps/ilevel/irate/ddelay/izoom/Cdelayed/Cpaused/Cenabled/Cforced", $msg ); $data = unpack( "ltype/imonitor/istate/dfps/ilevel/irate/ddelay/izoom/Cdelayed/Cpaused/Cenabled/Cforced", $msg );
Logger::Debug("FPS: " . $data['fps'] ); ZM\Logger::Debug("FPS: " . $data['fps'] );
$data['fps'] = round( $data['fps'], 2 ); $data['fps'] = round( $data['fps'], 2 );
Logger::Debug("FPS: " . $data['fps'] ); ZM\Logger::Debug("FPS: " . $data['fps'] );
$data['rate'] /= RATE_BASE; $data['rate'] /= RATE_BASE;
$data['delay'] = round( $data['delay'], 2 ); $data['delay'] = round( $data['delay'], 2 );
$data['zoom'] = round( $data['zoom']/SCALE_BASE, 1 ); $data['zoom'] = round( $data['zoom']/SCALE_BASE, 1 );
@ -161,7 +161,7 @@ if ( sem_acquire($semaphore,1) !== false ) {
} }
sem_release($semaphore); sem_release($semaphore);
} else { } else {
Logger::Debug("Couldn't get semaphore"); ZM\Logger::Debug("Couldn't get semaphore");
ajaxResponse( array() ); ajaxResponse( array() );
} }

View File

@ -1,4 +1,5 @@
<?php <?php
namespace ZM;
$event_cache = array(); $event_cache = array();

View File

@ -1,4 +1,5 @@
<?php <?php
namespace ZM;
class Filter { class Filter {

View File

@ -1,4 +1,5 @@
<?php <?php
namespace ZM;
require_once( 'database.php' ); require_once( 'database.php' );
require_once( 'Event.php' ); require_once( 'Event.php' );

View File

@ -1,4 +1,5 @@
<?php <?php
namespace ZM;
$group_cache = array(); $group_cache = array();

View File

@ -1,4 +1,5 @@
<?php <?php
namespace ZM;
require_once('database.php'); require_once('database.php');
require_once('Server.php'); require_once('Server.php');

View File

@ -1,4 +1,5 @@
<?php <?php
namespace ZM;
require_once('database.php'); require_once('database.php');
@ -98,9 +99,9 @@ class MontageLayout {
} }
$result = dbQuery($sql, $values); $result = dbQuery($sql, $values);
if ( $result ) { if ( $result ) {
$results = $result->fetchALL(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'MontageLayout'); $results = $result->fetchALL();
foreach ( $results as $row => $obj ) { foreach ( $results as $row ) {
$filters[] = $obj; $filters[] = new MontageLayout($row);
} }
} }
return $filters; return $filters;

View File

@ -1,8 +1,10 @@
<?php <?php
namespace ZM;
require_once('database.php'); require_once('database.php');
$server_cache = array(); $server_cache = array();
class Server { class Server {
private $defaults = array( private $defaults = array(
'Id' => null, 'Id' => null,

View File

@ -1,5 +1,7 @@
<?php <?php
namespace ZM;
require_once('database.php'); require_once('database.php');
require_once('Event.php');
$storage_cache = array(); $storage_cache = array();
class Storage { class Storage {

View File

@ -20,7 +20,7 @@
if ( $action == 'delete' ) { if ( $action == 'delete' ) {
if ( ! canEdit('Monitors') ) { if ( ! canEdit('Monitors') ) {
Warning("No permission to delete monitors"); ZM\Warning('No permission to delete monitors');
return; return;
} }
@ -30,7 +30,7 @@ if ( $action == 'delete' ) {
if ( canEdit('Monitors', $markMid) ) { if ( canEdit('Monitors', $markMid) ) {
// This could be faster as a select all // This could be faster as a select all
if ( $monitor = dbFetchOne('SELECT * FROM Monitors WHERE Id = ?', NULL, array($markMid)) ) { if ( $monitor = dbFetchOne('SELECT * FROM Monitors WHERE Id = ?', NULL, array($markMid)) ) {
$Monitor = new Monitor($monitor); $Monitor = new ZM\Monitor($monitor);
$Monitor->delete(); $Monitor->delete();
} // end if monitor found in db } // end if monitor found in db
} // end if canedit this monitor } // end if canedit this monitor

View File

@ -20,11 +20,11 @@
// Monitor control actions, require a monitor id and control view permissions for that monitor // Monitor control actions, require a monitor id and control view permissions for that monitor
if ( empty($_REQUEST['mid']) ) { if ( empty($_REQUEST['mid']) ) {
Warning("Settings requires a monitor id"); ZM\Warning('Settings requires a monitor id');
return; return;
} }
if ( ! canView('Control', $_REQUEST['mid']) ) { if ( ! canView('Control', $_REQUEST['mid']) ) {
Warning("Settings requires the Control permission"); ZM\Warning('Settings requires the Control permission');
return; return;
} }
@ -32,7 +32,7 @@ require_once('control_functions.php');
require_once('Monitor.php'); require_once('Monitor.php');
$mid = validInt($_REQUEST['mid']); $mid = validInt($_REQUEST['mid']);
if ( $action == 'control' ) { if ( $action == 'control' ) {
$monitor = new Monitor($mid); $monitor = new ZM\Monitor($mid);
$ctrlCommand = buildControlCommand($monitor); $ctrlCommand = buildControlCommand($monitor);
sendControlCommand($monitor->Id(), $ctrlCommand); sendControlCommand($monitor->Id(), $ctrlCommand);

View File

@ -20,13 +20,13 @@
if ( !canEdit('Control') ) { if ( !canEdit('Control') ) {
Warning("Need Control permissions to edit control capabilities"); ZM\Warning('Need Control permissions to edit control capabilities');
return; return;
} // end if !canEdit Controls } // end if !canEdit Controls
if ( $action == 'controlcap' ) { if ( $action == 'controlcap' ) {
require_once('includes/Control.php'); require_once('includes/Control.php');
$Control = new Control( !empty($_REQUEST['cid']) ? $_REQUEST['cid'] : null ); $Control = new ZM\Control( !empty($_REQUEST['cid']) ? $_REQUEST['cid'] : null );
//$changes = getFormChanges( $control, $_REQUEST['newControl'], $types, $columns ); //$changes = getFormChanges( $control, $_REQUEST['newControl'], $types, $columns );
$Control->save($_REQUEST['newControl']); $Control->save($_REQUEST['newControl']);

View File

@ -20,16 +20,15 @@
if ( !canEdit('Control') ) { if ( !canEdit('Control') ) {
Warning("Need Control permissions to edit control capabilities"); ZM\Warning('Need Control permissions to edit control capabilities');
return; return;
} // end if !canEdit Controls } // end if !canEdit Controls
}
if ( $action == 'delete' ) { if ( $action == 'delete' ) {
if ( isset($_REQUEST['markCids']) ) { if ( isset($_REQUEST['markCids']) ) {
foreach( $_REQUEST['markCids'] as $markCid ) { foreach( $_REQUEST['markCids'] as $markCid ) {
dbQuery('DELETE FROM Controls WHERE Id = ?', array($markCid));
dbQuery('UPDATE Monitors SET Controllable = 0, ControlId = 0 WHERE ControlId = ?', array($markCid)); dbQuery('UPDATE Monitors SET Controllable = 0, ControlId = 0 WHERE ControlId = ?', array($markCid));
dbQuery('DELETE FROM Controls WHERE Id = ?', array($markCid));
$refreshParent = true; $refreshParent = true;
} }
} }

View File

@ -20,7 +20,7 @@
// Device view actions // Device view actions
if ( !canEdit('Devices') ) { if ( !canEdit('Devices') ) {
Warning("No devices permission in editing device"); ZM\Warning('No devices permission in editing device');
return; return;
} // end if !canEdit(Devices) } // end if !canEdit(Devices)
@ -39,7 +39,7 @@ if ( $action == 'device' ) {
$view = 'none'; $view = 'none';
} }
} else { } else {
Error("Unknown action in device"); ZM\Error('Unknown action in device');
} // end if action } // end if action
?> ?>

View File

@ -20,7 +20,7 @@
// Device view actions // Device view actions
if ( !canEdit('Devices') ) { if ( !canEdit('Devices') ) {
Warning("No devices permission in editing device"); ZM\Warning('No devices permission in editing device');
return; return;
} // end if !canEdit(Devices) } // end if !canEdit(Devices)

View File

@ -19,7 +19,7 @@
// //
if ( !canEdit('System') ) { if ( !canEdit('System') ) {
Warning("Need System permissions to update donation"); ZM\Warning('Need System permissions to update donation');
return; return;
} }

View File

@ -20,7 +20,7 @@
// If there is an action on an event, then we must have an id. // If there is an action on an event, then we must have an id.
if ( !empty($_REQUEST['eid']) ) { if ( !empty($_REQUEST['eid']) ) {
Warning("No eid in action on event view"); ZM\Warning('No eid in action on event view');
return; return;
} }

View File

@ -19,13 +19,13 @@
// //
if ( !isset($_REQUEST['markEids']) ) { if ( !isset($_REQUEST['markEids']) ) {
Warning('Events actions require eids'); ZM\Warning('Events actions require eids');
return; return;
} }
// Event scope actions, view permissions only required // Event scope actions, view permissions only required
if ( !canEdit('Events') ) { if ( !canEdit('Events') ) {
Warning("Events actions require Edit permissions"); ZM\Warning('Events actions require Edit permissions');
return; return;
} // end if ! canEdit(Events) } // end if ! canEdit(Events)

View File

@ -19,13 +19,13 @@
// //
if ( !isset($_REQUEST['markEids']) ) { if ( !isset($_REQUEST['markEids']) ) {
Warning('Events actions require eids'); ZM\Warning('Events actions require eids');
return; return;
} }
// Event scope actions, view permissions only required // Event scope actions, view permissions only required
if ( !canEdit('Events') ) { if ( !canEdit('Events') ) {
Warning("Events actions require Edit permissions"); ZM\Warning('Events actions require Edit permissions');
return; return;
} // end if ! canEdit(Events) } // end if ! canEdit(Events)

View File

@ -20,7 +20,7 @@
// Event scope actions, view permissions only required // Event scope actions, view permissions only required
if ( !canView('Events') ) { if ( !canView('Events') ) {
Warning('You do not have permission to view Events.'); ZM\Warning('You do not have permission to view Events.');
return; return;
} }
@ -32,7 +32,7 @@ if ( isset($_REQUEST['object']) and ( $_REQUEST['object'] == 'filter' ) ) {
} else if ( canEdit('Events') ) { } else if ( canEdit('Events') ) {
require_once('includes/Filter.php'); require_once('includes/Filter.php');
$filter = new Filter($_REQUEST['Id']); $filter = new ZM\Filter($_REQUEST['Id']);
if ( $action == 'delete' ) { if ( $action == 'delete' ) {
if ( !empty($_REQUEST['Id']) ) { if ( !empty($_REQUEST['Id']) ) {
@ -42,7 +42,7 @@ if ( isset($_REQUEST['object']) and ( $_REQUEST['object'] == 'filter' ) ) {
$filter->delete(); $filter->delete();
} else { } else {
Error("No filter id passed when deleting"); ZM\Error("No filter id passed when deleting");
} }
} else if ( ( $action == 'Save' ) or ( $action == 'SaveAs' ) or ( $action == 'execute' ) ) { } else if ( ( $action == 'Save' ) or ( $action == 'SaveAs' ) or ( $action == 'execute' ) ) {
@ -98,7 +98,7 @@ if ( isset($_REQUEST['object']) and ( $_REQUEST['object'] == 'filter' ) ) {
) { ) {
$filter->control($_REQUEST['command'], $_REQUEST['ServerId']); $filter->control($_REQUEST['command'], $_REQUEST['ServerId']);
} else { } else {
Error('Invalid command for filter ('.$_REQUEST['command'].')'); ZM\Error('Invalid command for filter ('.$_REQUEST['command'].')');
} }
} // end if save or execute } // end if save or execute
} // end if canEdit(Events) } // end if canEdit(Events)

View File

@ -21,12 +21,12 @@
// Monitor edit actions, require a monitor id and edit permissions for that monitor // Monitor edit actions, require a monitor id and edit permissions for that monitor
if ( empty($_REQUEST['mid']) ) { if ( empty($_REQUEST['mid']) ) {
Error("Must specify mid"); ZM\Error('Must specify mid');
return; return;
} }
$mid = validInt($_REQUEST['mid']); $mid = validInt($_REQUEST['mid']);
if ( !canEdit('Monitors', $mid) ) { if ( !canEdit('Monitors', $mid) ) {
Error("You do not have permission to edit monitor $mid"); ZM\Error("You do not have permission to edit monitor $mid");
return; return;
} }
@ -52,7 +52,7 @@ if ( $action == 'function' ) {
} }
$refreshParent = true; $refreshParent = true;
} else { } else {
Logger::Debug("No change to function, not doing anything."); ZM\Logger::Debug('No change to function, not doing anything.');
} }
} // end if action } // end if action
$view = 'none'; $view = 'none';

View File

@ -22,7 +22,7 @@
# Should probably verify that each monitor id is a valid monitor, that we have access to. # Should probably verify that each monitor id is a valid monitor, that we have access to.
# However at the moment, you have to have System permissions to do this # However at the moment, you have to have System permissions to do this
if ( ! canEdit('Groups') ) { if ( ! canEdit('Groups') ) {
Warning("Need group edit permissions to edit groups"); ZM\Warning('Need group edit permissions to edit groups');
return; return;
} }

View File

@ -33,13 +33,13 @@ if ( ($action == 'setgroup') && canView('Groups')) {
# Should probably verify that each monitor id is a valid monitor, that we have access to. # Should probably verify that each monitor id is a valid monitor, that we have access to.
# However at the moment, you have to have System permissions to do this # However at the moment, you have to have System permissions to do this
if ( ! canEdit('Groups') ) { if ( ! canEdit('Groups') ) {
Warning("Need group edit permissions to edit groups"); ZM\Warning('Need group edit permissions to edit groups');
return; return;
} }
if ( $action == 'delete' ) { if ( $action == 'delete' ) {
if ( !empty($_REQUEST['gid']) ) { if ( !empty($_REQUEST['gid']) ) {
foreach ( Group::find(array('Id'=>$_REQUEST['gid'])) as $Group ) { foreach ( ZM\Group::find(array('Id'=>$_REQUEST['gid'])) as $Group ) {
$Group->delete(); $Group->delete();
} }
} }

View File

@ -25,10 +25,10 @@ if ( isset($_REQUEST['object']) and $_REQUEST['object'] == 'Monitor' ) {
foreach ( $_REQUEST['mids'] as $mid ) { foreach ( $_REQUEST['mids'] as $mid ) {
$mid = ValidInt($mid); $mid = ValidInt($mid);
if ( ! canEdit('Monitors', $mid) ) { if ( ! canEdit('Monitors', $mid) ) {
Warning("Cannot edit monitor $mid"); ZM\Warning("Cannot edit monitor $mid");
continue; continue;
} }
$Monitor = new Monitor($mid); $Monitor = new ZM\Monitor($mid);
if ( $Monitor->Type() != 'WebSite' ) { if ( $Monitor->Type() != 'WebSite' ) {
$Monitor->zmaControl('stop'); $Monitor->zmaControl('stop');
$Monitor->zmcControl('stop'); $Monitor->zmcControl('stop');
@ -47,7 +47,7 @@ if ( isset($_REQUEST['object']) and $_REQUEST['object'] == 'Monitor' ) {
// Monitor edit actions, monitor id derived, require edit permissions for that monitor // Monitor edit actions, monitor id derived, require edit permissions for that monitor
if ( ! canEdit('Monitors') ) { if ( ! canEdit('Monitors') ) {
Warning("Monitor actions require Monitors Permissions"); ZM\Warning("Monitor actions require Monitors Permissions");
return; return;
} }
@ -68,7 +68,7 @@ if ( $action == 'monitor' ) {
$x10Monitor = array(); $x10Monitor = array();
} }
} }
$Monitor = new Monitor($monitor); $Monitor = new ZM\Monitor($monitor);
// Define a field type for anything that's not simple text equivalent // Define a field type for anything that's not simple text equivalent
$types = array( $types = array(
@ -86,10 +86,10 @@ if ( $action == 'monitor' ) {
if ( $_REQUEST['newMonitor']['ServerId'] == 'auto' ) { if ( $_REQUEST['newMonitor']['ServerId'] == 'auto' ) {
$_REQUEST['newMonitor']['ServerId'] = dbFetchOne( $_REQUEST['newMonitor']['ServerId'] = dbFetchOne(
'SELECT Id FROM Servers WHERE Status=\'Running\' ORDER BY FreeMem DESC, CpuLoad ASC LIMIT 1', 'Id'); 'SELECT Id FROM Servers WHERE Status=\'Running\' ORDER BY FreeMem DESC, CpuLoad ASC LIMIT 1', 'Id');
Logger::Debug('Auto selecting server: Got ' . $_REQUEST['newMonitor']['ServerId'] ); ZM\Logger::Debug('Auto selecting server: Got ' . $_REQUEST['newMonitor']['ServerId'] );
if ( ( ! $_REQUEST['newMonitor'] ) and defined('ZM_SERVER_ID') ) { if ( ( ! $_REQUEST['newMonitor'] ) and defined('ZM_SERVER_ID') ) {
$_REQUEST['newMonitor']['ServerId'] = ZM_SERVER_ID; $_REQUEST['newMonitor']['ServerId'] = ZM_SERVER_ID;
Logger::Debug('Auto selecting server to ' . ZM_SERVER_ID); ZM\Logger::Debug('Auto selecting server to ' . ZM_SERVER_ID);
} }
} }
@ -107,12 +107,12 @@ if ( $action == 'monitor' ) {
dbQuery('UPDATE Monitors SET '.implode(', ', $changes).' WHERE Id=?', array($mid)); dbQuery('UPDATE Monitors SET '.implode(', ', $changes).' WHERE Id=?', array($mid));
// Groups will be added below // Groups will be added below
if ( isset($changes['Name']) or isset($changes['StorageId']) ) { if ( isset($changes['Name']) or isset($changes['StorageId']) ) {
$OldStorage = new Storage($monitor['StorageId']); $OldStorage = new ZM\Storage($monitor['StorageId']);
$saferOldName = basename($monitor['Name']); $saferOldName = basename($monitor['Name']);
if ( file_exists($OldStorage->Path().'/'.$saferOldName) ) if ( file_exists($OldStorage->Path().'/'.$saferOldName) )
unlink($OldStorage->Path().'/'.$saferOldName); unlink($OldStorage->Path().'/'.$saferOldName);
$NewStorage = new Storage($_REQUEST['newMonitor']['StorageId']); $NewStorage = new ZM\Storage($_REQUEST['newMonitor']['StorageId']);
if ( ! file_exists($NewStorage->Path().'/'.$mid) ) if ( ! file_exists($NewStorage->Path().'/'.$mid) )
mkdir($NewStorage->Path().'/'.$mid, 0755); mkdir($NewStorage->Path().'/'.$mid, 0755);
$saferNewName = basename($_REQUEST['newMonitor']['Name']); $saferNewName = basename($_REQUEST['newMonitor']['Name']);
@ -164,24 +164,24 @@ if ( $action == 'monitor' ) {
$zoneArea = $_REQUEST['newMonitor']['Width'] * $_REQUEST['newMonitor']['Height']; $zoneArea = $_REQUEST['newMonitor']['Width'] * $_REQUEST['newMonitor']['Height'];
dbQuery("INSERT INTO Zones SET MonitorId = ?, Name = 'All', Type = 'Active', Units = 'Percent', NumCoords = 4, Coords = ?, Area=?, AlarmRGB = 0xff0000, CheckMethod = 'Blobs', MinPixelThreshold = 25, MinAlarmPixels=?, MaxAlarmPixels=?, FilterX = 3, FilterY = 3, MinFilterPixels=?, MaxFilterPixels=?, MinBlobPixels=?, MinBlobs = 1", array( $mid, sprintf( "%d,%d %d,%d %d,%d %d,%d", 0, 0, $_REQUEST['newMonitor']['Width']-1, 0, $_REQUEST['newMonitor']['Width']-1, $_REQUEST['newMonitor']['Height']-1, 0, $_REQUEST['newMonitor']['Height']-1 ), $zoneArea, intval(($zoneArea*3)/100), intval(($zoneArea*75)/100), intval(($zoneArea*3)/100), intval(($zoneArea*75)/100), intval(($zoneArea*2)/100) ) ); dbQuery("INSERT INTO Zones SET MonitorId = ?, Name = 'All', Type = 'Active', Units = 'Percent', NumCoords = 4, Coords = ?, Area=?, AlarmRGB = 0xff0000, CheckMethod = 'Blobs', MinPixelThreshold = 25, MinAlarmPixels=?, MaxAlarmPixels=?, FilterX = 3, FilterY = 3, MinFilterPixels=?, MaxFilterPixels=?, MinBlobPixels=?, MinBlobs = 1", array( $mid, sprintf( "%d,%d %d,%d %d,%d %d,%d", 0, 0, $_REQUEST['newMonitor']['Width']-1, 0, $_REQUEST['newMonitor']['Width']-1, $_REQUEST['newMonitor']['Height']-1, 0, $_REQUEST['newMonitor']['Height']-1 ), $zoneArea, intval(($zoneArea*3)/100), intval(($zoneArea*75)/100), intval(($zoneArea*3)/100), intval(($zoneArea*75)/100), intval(($zoneArea*2)/100) ) );
//$view = 'none'; //$view = 'none';
$Storage = new Storage($_REQUEST['newMonitor']['StorageId']); $Storage = new ZM\Storage($_REQUEST['newMonitor']['StorageId']);
mkdir($Storage->Path().'/'.$mid, 0755); mkdir($Storage->Path().'/'.$mid, 0755);
$saferName = basename($_REQUEST['newMonitor']['Name']); $saferName = basename($_REQUEST['newMonitor']['Name']);
symlink($mid, $Storage->Path().'/'.$saferName); symlink($mid, $Storage->Path().'/'.$saferName);
} else { } else {
Error('Error saving new Monitor.'); ZM\Error('Error saving new Monitor.');
$error_message = dbError($sql); $error_message = dbError($sql);
return; return;
} }
} else { } else {
Error('Users with Monitors restrictions cannot create new monitors.'); ZM\Error('Users with Monitors restrictions cannot create new monitors.');
return; return;
} }
$restart = true; $restart = true;
} else { } else {
Logger::Debug('No action due to no changes to Monitor'); ZM\Logger::Debug('No action due to no changes to Monitor');
} # end if count(changes) } # end if count(changes)
if ( if (
@ -220,7 +220,7 @@ if ( $action == 'monitor' ) {
if ( $restart ) { if ( $restart ) {
$new_monitor = new Monitor($mid); $new_monitor = new ZM\Monitor($mid);
//fixDevices(); //fixDevices();
if ( $new_monitor->Type() != 'WebSite' ) { if ( $new_monitor->Type() != 'WebSite' ) {
@ -238,6 +238,6 @@ if ( $action == 'monitor' ) {
} // end if restart } // end if restart
$view = 'none'; $view = 'none';
} else { } else {
Warning("Unknown action $action in Monitor"); ZM\Warning("Unknown action $action in Monitor");
} // end if action == Delete } // end if action == Delete
?> ?>

View File

@ -22,7 +22,7 @@ if ( isset($_REQUEST['object']) ) {
if ( $_REQUEST['object'] == 'MontageLayout' ) { if ( $_REQUEST['object'] == 'MontageLayout' ) {
// System edit actions // System edit actions
if ( ! canEdit('System') ) { if ( ! canEdit('System') ) {
Warning("Need System permissions to edit layouts"); ZM\Warning('Need System permissions to edit layouts');
return; return;
} }
require_once('includes/MontageLayout.php'); require_once('includes/MontageLayout.php');

View File

@ -20,7 +20,7 @@
// System edit actions // System edit actions
if ( !canEdit('System') ) { if ( !canEdit('System') ) {
Warning("Must have System permissions to perform options actions"); ZM\Warning('Must have System permissions to perform options actions');
return; return;
} }

View File

@ -19,7 +19,7 @@
// //
if ( !canEdit('System') ) { if ( !canEdit('System') ) {
Warning("Need System permissions to update privacy"); ZM\Warning('Need System permissions to update privacy');
return; return;
} }

View File

@ -20,7 +20,7 @@
// System edit actions // System edit actions
if ( ! canEdit('System') ) { if ( ! canEdit('System') ) {
Warning("Need System permissions to add servers"); ZM\Warning('Need System permissions to add servers');
return; return;
} }
@ -48,6 +48,6 @@ if ( $action == 'Save' ) {
} }
$view = 'none'; $view = 'none';
} else { } else {
Error("Unknown action $action in saving Server"); ZM\Error("Unknown action $action in saving Server");
} }
?> ?>

View File

@ -21,11 +21,11 @@
// Monitor control actions, require a monitor id and control view permissions for that monitor // Monitor control actions, require a monitor id and control view permissions for that monitor
if ( empty($_REQUEST['mid']) ) { if ( empty($_REQUEST['mid']) ) {
Warning("Settings requires a monitor id"); ZM\Warning('Settings requires a monitor id');
return; return;
} }
if ( ! canView('Control', $_REQUEST['mid']) ) { if ( ! canView('Control', $_REQUEST['mid']) ) {
Warning("Settings requires the Control permission"); ZM\Warning('Settings requires the Control permission');
return; return;
} }

View File

@ -20,7 +20,7 @@
// System edit actions // System edit actions
if ( !canEdit('System') ) { if ( !canEdit('System') ) {
Warning('Need System Permission to edit states'); ZM\Warning('Need System Permission to edit states');
return; return;
} }
if ( $action == 'state' ) { if ( $action == 'state' ) {

View File

@ -20,7 +20,7 @@
// System edit actions // System edit actions
if ( ! canEdit('System') ) { if ( ! canEdit('System') ) {
Warning("Need System permission to edit Storage"); ZM\Warning('Need System permission to edit Storage');
return; return;
} }
@ -43,7 +43,7 @@ if ( $action == 'Save' ) {
} }
$view = 'none'; $view = 'none';
} else { } else {
Error("Unknown action $action in saving Storage"); ZM\Error("Unknown action $action in saving Storage");
} }
?> ?>

View File

@ -20,7 +20,7 @@
// System edit actions // System edit actions
if ( !canEdit('System') ) { if ( !canEdit('System') ) {
Warning("Need System permissions to update version"); ZM\Warning('Need System permissions to update version');
return; return;
} }
if ( $action == 'version' && isset($_REQUEST['option']) ) { if ( $action == 'version' && isset($_REQUEST['option']) ) {

View File

@ -20,7 +20,7 @@
if ( !empty($_REQUEST['mid']) && canEdit('Monitors', $_REQUEST['mid']) ) { if ( !empty($_REQUEST['mid']) && canEdit('Monitors', $_REQUEST['mid']) ) {
$mid = validInt($_REQUEST['mid']); $mid = validInt($_REQUEST['mid']);
$monitor = new Monitor($mid); $monitor = new ZM\Monitor($mid);
if ( $action == 'delete' ) { if ( $action == 'delete' ) {
if ( isset($_REQUEST['markZids']) ) { if ( isset($_REQUEST['markZids']) ) {

View File

@ -87,7 +87,7 @@ function userLogin($username='', $password='', $passwordHashed=false) {
} }
$_SESSION['remoteAddr'] = $_SERVER['REMOTE_ADDR']; // To help prevent session hijacking $_SESSION['remoteAddr'] = $_SERVER['REMOTE_ADDR']; // To help prevent session hijacking
if ( $dbUser = dbFetchOne($sql, NULL, $sql_values) ) { if ( $dbUser = dbFetchOne($sql, NULL, $sql_values) ) {
Info("Login successful for user \"$username\""); ZM\Info("Login successful for user \"$username\"");
$_SESSION['user'] = $user = $dbUser; $_SESSION['user'] = $user = $dbUser;
unset($_SESSION['loginFailed']); unset($_SESSION['loginFailed']);
if ( ZM_AUTH_TYPE == 'builtin' ) { if ( ZM_AUTH_TYPE == 'builtin' ) {
@ -95,7 +95,7 @@ function userLogin($username='', $password='', $passwordHashed=false) {
} }
session_regenerate_id(); session_regenerate_id();
} else { } else {
Warning("Login denied for user \"$username\""); ZM\Warning("Login denied for user \"$username\"");
$_SESSION['loginFailed'] = true; $_SESSION['loginFailed'] = true;
unset($user); unset($user);
} }
@ -106,7 +106,7 @@ function userLogin($username='', $password='', $passwordHashed=false) {
function userLogout() { function userLogout() {
global $user; global $user;
Info('User "'.$user['Username'].'" logged out'); ZM\Info('User "'.$user['Username'].'" logged out');
session_start(); session_start();
unset($_SESSION['user']); unset($_SESSION['user']);
unset($user); unset($user);
@ -119,7 +119,7 @@ function getAuthUser($auth) {
if ( ZM_AUTH_HASH_IPS ) { if ( ZM_AUTH_HASH_IPS ) {
$remoteAddr = $_SERVER['REMOTE_ADDR']; $remoteAddr = $_SERVER['REMOTE_ADDR'];
if ( !$remoteAddr ) { if ( !$remoteAddr ) {
Error("Can't determine remote address for authentication, using empty string"); ZM\Error("Can't determine remote address for authentication, using empty string");
$remoteAddr = ''; $remoteAddr = '';
} }
} }
@ -145,7 +145,7 @@ function getAuthUser($auth) {
} // end foreach hour } // end foreach hour
} // end foreach user } // end foreach user
} // end if using auth hash } // end if using auth hash
Error("Unable to authenticate user from auth hash '$auth'"); ZM\Error("Unable to authenticate user from auth hash '$auth'");
return false; return false;
} // end getAuthUser($auth) } // end getAuthUser($auth)
@ -213,7 +213,7 @@ function is_session_started() {
return session_id() === '' ? FALSE : TRUE; return session_id() === '' ? FALSE : TRUE;
} }
} else { } else {
Warning("php_sapi_name === 'cli'"); ZM\Warning("php_sapi_name === 'cli'");
} }
return FALSE; return FALSE;
} }

View File

@ -138,7 +138,7 @@ define( 'MYSQL_FMT_DATETIME_SHORT', '%y/%m/%d %H:%i:%S' ); // MySQL date_format
require_once( 'database.php' ); require_once( 'database.php' );
require_once( 'logger.php' ); require_once( 'logger.php' );
loadConfig(); loadConfig();
Logger::fetch()->initialise(); ZM\Logger::fetch()->initialise();
$GLOBALS['defaultUser'] = array( $GLOBALS['defaultUser'] = array(
'Username' => 'admin', 'Username' => 'admin',

View File

@ -93,7 +93,7 @@ function dbLog( $sql, $update=false ) {
global $dbLogLevel; global $dbLogLevel;
$noExecute = $update && ($dbLogLevel >= DB_LOG_DEBUG); $noExecute = $update && ($dbLogLevel >= DB_LOG_DEBUG);
if ( $dbLogLevel > DB_LOG_OFF ) if ( $dbLogLevel > DB_LOG_OFF )
Logger::Debug( "SQL-LOG: $sql".($noExecute?" (not executed)":"") ); ZM\Logger::Debug( "SQL-LOG: $sql".($noExecute?" (not executed)":"") );
return( $noExecute ); return( $noExecute );
} }
@ -104,7 +104,7 @@ function dbError( $sql ) {
return ''; return '';
$message = "SQL-ERR '".implode("\n",$dbConn->errorInfo())."', statement was '".$sql."'"; $message = "SQL-ERR '".implode("\n",$dbConn->errorInfo())."', statement was '".$sql."'";
Error($message); ZM\Error($message);
return $message; return $message;
} }
@ -130,32 +130,32 @@ function dbQuery( $sql, $params=NULL ) {
try { try {
if ( isset($params) ) { if ( isset($params) ) {
if ( ! $result = $dbConn->prepare( $sql ) ) { if ( ! $result = $dbConn->prepare( $sql ) ) {
Error("SQL: Error preparing $sql: " . $pdo->errorInfo); ZM\Error("SQL: Error preparing $sql: " . $pdo->errorInfo);
return NULL; return NULL;
} }
if ( ! $result->execute( $params ) ) { if ( ! $result->execute( $params ) ) {
Error("SQL: Error executing $sql: " . implode(',', $result->errorInfo() ) ); ZM\Error("SQL: Error executing $sql: " . implode(',', $result->errorInfo() ) );
return NULL; return NULL;
} }
} else { } else {
if ( defined('ZM_DB_DEBUG') ) { if ( defined('ZM_DB_DEBUG') ) {
Logger::Debug("SQL: $sql values:" . ($params?implode(',',$params):'') ); ZM\Logger::Debug("SQL: $sql values:" . ($params?implode(',',$params):'') );
} }
$result = $dbConn->query($sql); $result = $dbConn->query($sql);
if ( ! $result ) { if ( ! $result ) {
Error("SQL: Error preparing $sql: " . $pdo->errorInfo); ZM\Error("SQL: Error preparing $sql: " . $pdo->errorInfo);
return NULL; return NULL;
} }
} }
if ( defined('ZM_DB_DEBUG') ) { if ( defined('ZM_DB_DEBUG') ) {
if ( $params ) if ( $params )
Logger::Debug("SQL: $sql" . implode(',',$params) . ' rows: '.$result->rowCount() ); ZM\Logger::Debug("SQL: $sql" . implode(',',$params) . ' rows: '.$result->rowCount() );
else else
Logger::Debug("SQL: $sql: rows:" . $result->rowCount() ); ZM\Logger::Debug("SQL: $sql: rows:" . $result->rowCount() );
} }
} catch(PDOException $e) { } catch(PDOException $e) {
Error( "SQL-ERR '".$e->getMessage()."', statement was '".$sql."' params:" . ($params?implode(',',$params):'') ); ZM\Error( "SQL-ERR '".$e->getMessage()."', statement was '".$sql."' params:" . ($params?implode(',',$params):'') );
return NULL; return NULL;
} }
return $result; return $result;
@ -164,7 +164,7 @@ function dbQuery( $sql, $params=NULL ) {
function dbFetchOne( $sql, $col=false, $params=NULL ) { function dbFetchOne( $sql, $col=false, $params=NULL ) {
$result = dbQuery( $sql, $params ); $result = dbQuery( $sql, $params );
if ( ! $result ) { if ( ! $result ) {
Error( "SQL-ERR dbFetchOne no result, statement was '".$sql."'" . ( $params ? 'params: ' . join(',',$params) : '' ) ); ZM\Error( "SQL-ERR dbFetchOne no result, statement was '".$sql."'" . ( $params ? 'params: ' . join(',',$params) : '' ) );
return false; return false;
} }
if ( ! $result->rowCount() ) { if ( ! $result->rowCount() ) {
@ -175,7 +175,7 @@ function dbFetchOne( $sql, $col=false, $params=NULL ) {
if ( $result && $dbRow = $result->fetch(PDO::FETCH_ASSOC) ) { if ( $result && $dbRow = $result->fetch(PDO::FETCH_ASSOC) ) {
if ( $col ) { if ( $col ) {
if ( ! array_key_exists($col, $dbRow) ) { if ( ! array_key_exists($col, $dbRow) ) {
Warning("$col does not exist in the returned row " . print_r($dbRow, true)); ZM\Warning("$col does not exist in the returned row " . print_r($dbRow, true));
} }
return $dbRow[$col]; return $dbRow[$col];
} }
@ -187,7 +187,7 @@ function dbFetchOne( $sql, $col=false, $params=NULL ) {
function dbFetchAll( $sql, $col=false, $params=NULL ) { function dbFetchAll( $sql, $col=false, $params=NULL ) {
$result = dbQuery( $sql, $params ); $result = dbQuery( $sql, $params );
if ( ! $result ) { if ( ! $result ) {
Error( "SQL-ERR dbFetchAll no result, statement was '".$sql."'" . ( $params ? 'params: ' .join(',', $params) : '' ) ); ZM\Error( "SQL-ERR dbFetchAll no result, statement was '".$sql."'" . ( $params ? 'params: ' .join(',', $params) : '' ) );
return false; return false;
} }
@ -294,7 +294,7 @@ function getTableDescription( $table, $asString=1 ) {
//$desc['minLength'] = -128; //$desc['minLength'] = -128;
break; break;
default : default :
Error( "Unexpected text qualifier '".$matches[1]."' found for field '".$row['Field']."' in table '".$table."'" ); ZM\Error( "Unexpected text qualifier '".$matches[1]."' found for field '".$row['Field']."' in table '".$table."'" );
break; break;
} }
} elseif ( preg_match( "/^(enum|set)\((.*)\)$/", $row['Type'], $matches ) ) { } elseif ( preg_match( "/^(enum|set)\((.*)\)$/", $row['Type'], $matches ) ) {
@ -326,7 +326,7 @@ function getTableDescription( $table, $asString=1 ) {
//$desc['maxValue'] = 127; //$desc['maxValue'] = 127;
break; break;
default : default :
Error( "Unexpected integer qualifier '".$matches[1]."' found for field '".$row['Field']."' in table '".$table."'" ); ZM\Error( "Unexpected integer qualifier '".$matches[1]."' found for field '".$row['Field']."' in table '".$table."'" );
break; break;
} }
if ( !empty($matches[1]) ) if ( !empty($matches[1]) )
@ -361,7 +361,7 @@ function getTableDescription( $table, $asString=1 ) {
break; break;
} }
} else { } else {
Error( "Can't parse database type '".$row['Type']."' found for field '".$row['Field']."' in table '".$table."'" ); ZM\Error( "Can't parse database type '".$row['Type']."' found for field '".$row['Field']."' in table '".$table."'" );
} }
if ( $asString ) if ( $asString )

View File

@ -90,12 +90,12 @@ function CORSHeaders() {
# The following is left for future reference/use. # The following is left for future reference/use.
$valid = false; $valid = false;
$Servers = Server::find(); $Servers = ZM\Server::find();
if ( sizeof($Servers) < 1 ) { if ( sizeof($Servers) < 1 ) {
# Only need CORSHeaders in the event that there are multiple servers in use. # Only need CORSHeaders in the event that there are multiple servers in use.
# ICON: Might not be true. multi-port? # ICON: Might not be true. multi-port?
if ( ZM_MIN_STREAMING_PORT ) { if ( ZM_MIN_STREAMING_PORT ) {
Logger::Debug("Setting default Access-Control-Allow-Origin from " . $_SERVER['HTTP_ORIGIN']); ZM\Logger::Debug('Setting default Access-Control-Allow-Origin from ' . $_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']); header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Headers: x-requested-with,x-request'); header('Access-Control-Allow-Headers: x-requested-with,x-request');
} }
@ -108,14 +108,14 @@ function CORSHeaders() {
preg_match('/^(https?:\/\/)?'.preg_quote($Server->Name(),'/').'/i', $_SERVER['HTTP_ORIGIN']) preg_match('/^(https?:\/\/)?'.preg_quote($Server->Name(),'/').'/i', $_SERVER['HTTP_ORIGIN'])
) { ) {
$valid = true; $valid = true;
Logger::Debug("Setting Access-Control-Allow-Origin from " . $_SERVER['HTTP_ORIGIN']); ZM\Logger::Debug("Setting Access-Control-Allow-Origin from " . $_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']); header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Headers: x-requested-with,x-request'); header('Access-Control-Allow-Headers: x-requested-with,x-request');
break; break;
} }
} }
if ( !$valid ) { if ( !$valid ) {
Warning($_SERVER['HTTP_ORIGIN'] . ' is not found in servers list.'); ZM\Warning($_SERVER['HTTP_ORIGIN'] . ' is not found in servers list.');
} }
} }
} }
@ -409,7 +409,7 @@ function getZmuCommand( $args ) {
} }
function getEventDefaultVideoPath( $event ) { function getEventDefaultVideoPath( $event ) {
$Event = new Event( $event ); $Event = new ZM\Event( $event );
return $Event->getStreamSrc( array( 'mode'=>'mpeg', 'format'=>'h264' ) ); return $Event->getStreamSrc( array( 'mode'=>'mpeg', 'format'=>'h264' ) );
} }
@ -424,15 +424,15 @@ function deletePath( $path ) {
function deleteEvent( $event ) { function deleteEvent( $event ) {
if ( empty($event) ) { if ( empty($event) ) {
Error( 'Empty event passed to deleteEvent.'); ZM\Error('Empty event passed to deleteEvent.');
return; return;
} }
if ( gettype($event) != 'array' ) { if ( gettype($event) != 'array' ) {
# $event could be an eid, so turn it into an event hash # $event could be an eid, so turn it into an event hash
$event = new Event( $event ); $event = new ZM\Event( $event );
} else { } else {
Logger::Debug("Event type: " . gettype($event)); ZM\Logger::Debug("Event type: " . gettype($event));
} }
global $user; global $user;
@ -527,7 +527,7 @@ function htmlOptions($contents, $values) {
if ( isset($option['disabled']) ) { if ( isset($option['disabled']) ) {
$disabled = $option['disabled']; $disabled = $option['disabled'];
Error("Setting to disabled"); ZM\Error("Setting to disabled");
} }
} else if ( is_object($option) ) { } else if ( is_object($option) ) {
$text = $option->Name(); $text = $option->Name();
@ -556,7 +556,7 @@ function buildSelect( $name, $contents, $behaviours=false ) {
elseif ( isset($_REQUEST[$arr]) ) elseif ( isset($_REQUEST[$arr]) )
$value = $_REQUEST[$arr]; $value = $_REQUEST[$arr];
if ( !preg_match_all( '/\[\s*[\'"]?(\w+)["\']?\s*\]/', $matches[2], $matches ) ) { if ( !preg_match_all( '/\[\s*[\'"]?(\w+)["\']?\s*\]/', $matches[2], $matches ) ) {
Fatal( "Can't parse selector '$name'" ); ZM\Fatal( "Can't parse selector '$name'" );
} }
for ( $i = 0; $i < count($matches[1]); $i++ ) { for ( $i = 0; $i < count($matches[1]); $i++ ) {
$idx = $matches[1][$i]; $idx = $matches[1][$i];
@ -833,17 +833,17 @@ function daemonControl( $command, $daemon=false, $args=false ) {
} }
$string = escapeshellcmd( $string ); $string = escapeshellcmd( $string );
#$string .= ' 2>/dev/null >&- <&- >/dev/null'; #$string .= ' 2>/dev/null >&- <&- >/dev/null';
Logger::Debug("daemonControl $string"); ZM\Logger::Debug("daemonControl $string");
exec( $string ); exec( $string );
} }
function zmcControl($monitor, $mode=false) { function zmcControl($monitor, $mode=false) {
$Monitor = new Monitor( $monitor ); $Monitor = new ZM\Monitor( $monitor );
return $Monitor->zmcControl($mode); return $Monitor->zmcControl($mode);
} }
function zmaControl($monitor, $mode=false) { function zmaControl($monitor, $mode=false) {
$Monitor = new Monitor($monitor); $Monitor = new ZM\Monitor($monitor);
return $Monitor->zmaControl($mode); return $Monitor->zmaControl($mode);
} }
@ -916,7 +916,7 @@ function zmaCheck( $monitor ) {
} }
function getImageSrc( $event, $frame, $scale=SCALE_BASE, $captureOnly=false, $overwrite=false ) { function getImageSrc( $event, $frame, $scale=SCALE_BASE, $captureOnly=false, $overwrite=false ) {
$Event = new Event( $event ); $Event = new ZM\Event( $event );
return $Event->getImageSrc( $frame, $scale, $captureOnly, $overwrite ); return $Event->getImageSrc( $frame, $scale, $captureOnly, $overwrite );
} }
@ -940,7 +940,7 @@ function createListThumbnail( $event, $overwrite=false ) {
$scale = (SCALE_BASE*ZM_WEB_LIST_THUMB_HEIGHT)/$event['Height']; $scale = (SCALE_BASE*ZM_WEB_LIST_THUMB_HEIGHT)/$event['Height'];
$thumbWidth = reScale( $event['Width'], $scale ); $thumbWidth = reScale( $event['Width'], $scale );
} else { } else {
Fatal( "No thumbnail width or height specified, please check in Options->Web" ); ZM\Fatal( "No thumbnail width or height specified, please check in Options->Web" );
} }
$imageData = getImageSrc( $event, $frame, $scale, false, $overwrite ); $imageData = getImageSrc( $event, $frame, $scale, false, $overwrite );
@ -1196,11 +1196,11 @@ function parseFilter(&$filter, $saveToSession=false, $querySep='&amp;') {
if ( ! $StorageArea ) { if ( ! $StorageArea ) {
for ( $j = 0; $j < count($terms); $j++ ) { for ( $j = 0; $j < count($terms); $j++ ) {
if ( isset($terms[$j]['attr']) and $terms[$j]['attr'] == 'StorageId' and isset($terms[$j]['val']) ) { if ( isset($terms[$j]['attr']) and $terms[$j]['attr'] == 'StorageId' and isset($terms[$j]['val']) ) {
$StorageArea = new Storage($terms[$j]['val']); $StorageArea = new ZM\Storage($terms[$j]['val']);
break; break;
} }
} // end foreach remaining term } // end foreach remaining term
if ( ! $StorageArea ) $StorageArea = new Storage(); if ( ! $StorageArea ) $StorageArea = new ZM\Storage();
} // end no StorageArea found yet } // end no StorageArea found yet
$filter['sql'] .= getDiskPercent( $StorageArea->Path() ); $filter['sql'] .= getDiskPercent( $StorageArea->Path() );
@ -1210,7 +1210,7 @@ function parseFilter(&$filter, $saveToSession=false, $querySep='&amp;') {
if ( ! $StorageArea ) { if ( ! $StorageArea ) {
for ( $j = $i; $j < count($terms); $j++ ) { for ( $j = $i; $j < count($terms); $j++ ) {
if ( isset($terms[$i]['attr']) and $terms[$i]['attr'] == 'StorageId' and isset($terms[$j]['val']) ) { if ( isset($terms[$i]['attr']) and $terms[$i]['attr'] == 'StorageId' and isset($terms[$j]['val']) ) {
$StorageArea = new Storage($terms[$i]['val']); $StorageArea = new ZM\Storage($terms[$i]['val']);
} }
} // end foreach remaining term } // end foreach remaining term
} // end no StorageArea found yet } // end no StorageArea found yet
@ -1242,7 +1242,7 @@ function parseFilter(&$filter, $saveToSession=false, $querySep='&amp;') {
} }
break; break;
case 'StorageId': case 'StorageId':
$StorageArea = new Storage( $value ); $StorageArea = new ZM\Storage( $value );
if ( $value != 'NULL' ) if ( $value != 'NULL' )
$value = dbEscape($value); $value = dbEscape($value);
break; break;
@ -1462,7 +1462,7 @@ function getDiskPercent($path = ZM_DIR_EVENTS) {
} }
function getDiskBlocks() { function getDiskBlocks() {
if ( ! $StorageArea ) $StorageArea = new Storage(); if ( ! $StorageArea ) $StorageArea = new ZM\Storage();
$df = shell_exec( 'df '.escapeshellarg($StorageArea->Path() )); $df = shell_exec( 'df '.escapeshellarg($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 ) )
@ -1847,17 +1847,17 @@ function coordsToPoints( $coords ) {
function limitPoints( &$points, $min_x, $min_y, $max_x, $max_y ) { function limitPoints( &$points, $min_x, $min_y, $max_x, $max_y ) {
foreach ( $points as &$point ) { foreach ( $points as &$point ) {
if ( $point['x'] < $min_x ) { if ( $point['x'] < $min_x ) {
Logger::Debug('Limiting point x'.$point['x'].' to min_x ' . $min_x ); ZM\Logger::Debug('Limiting point x'.$point['x'].' to min_x ' . $min_x );
$point['x'] = $min_x; $point['x'] = $min_x;
} else if ( $point['x'] > $max_x ) { } else if ( $point['x'] > $max_x ) {
Logger::Debug('Limiting point x'.$point['x'].' to max_x ' . $max_x ); ZM\Logger::Debug('Limiting point x'.$point['x'].' to max_x ' . $max_x );
$point['x'] = $max_x; $point['x'] = $max_x;
} }
if ( $point['y'] < $min_y ) { if ( $point['y'] < $min_y ) {
Logger::Debug('Limiting point y'.$point['y'].' to min_y ' . $min_y ); ZM\Logger::Debug('Limiting point y'.$point['y'].' to min_y ' . $min_y );
$point['y'] = $min_y; $point['y'] = $min_y;
} else if ( $point['y'] > $max_y ) { } else if ( $point['y'] > $max_y ) {
Logger::Debug('Limiting point y'.$point['y'].' to max_y ' . $max_y ); ZM\Logger::Debug('Limiting point y'.$point['y'].' to max_y ' . $max_y );
$point['y'] = $max_y; $point['y'] = $max_y;
} }
} // end foreach point } // end foreach point
@ -1912,13 +1912,13 @@ function initX10Status() {
if ( !isset($x10_status) ) { if ( !isset($x10_status) ) {
$socket = socket_create( AF_UNIX, SOCK_STREAM, 0 ); $socket = socket_create( AF_UNIX, SOCK_STREAM, 0 );
if ( $socket < 0 ) { if ( $socket < 0 ) {
Fatal( 'socket_create() failed: '.socket_strerror($socket) ); ZM\Fatal( 'socket_create() failed: '.socket_strerror($socket) );
} }
$sock_file = ZM_PATH_SOCKS.'/zmx10.sock'; $sock_file = ZM_PATH_SOCKS.'/zmx10.sock';
if ( @socket_connect( $socket, $sock_file ) ) { if ( @socket_connect( $socket, $sock_file ) ) {
$command = 'status'; $command = 'status';
if ( !socket_write( $socket, $command ) ) { if ( !socket_write( $socket, $command ) ) {
Fatal( "Can't write to control socket: ".socket_strerror(socket_last_error($socket)) ); ZM\Fatal( "Can't write to control socket: ".socket_strerror(socket_last_error($socket)) );
} }
socket_shutdown( $socket, 1 ); socket_shutdown( $socket, 1 );
$x10Output = ''; $x10Output = '';
@ -1954,13 +1954,13 @@ function getDeviceStatusX10( $key ) {
function setDeviceStatusX10( $key, $status ) { function setDeviceStatusX10( $key, $status ) {
$socket = socket_create( AF_UNIX, SOCK_STREAM, 0 ); $socket = socket_create( AF_UNIX, SOCK_STREAM, 0 );
if ( $socket < 0 ) { if ( $socket < 0 ) {
Fatal( 'socket_create() failed: '.socket_strerror($socket) ); ZM\Fatal( 'socket_create() failed: '.socket_strerror($socket) );
} }
$sock_file = ZM_PATH_SOCKS.'/zmx10.sock'; $sock_file = ZM_PATH_SOCKS.'/zmx10.sock';
if ( @socket_connect( $socket, $sock_file ) ) { if ( @socket_connect( $socket, $sock_file ) ) {
$command = "$status;$key"; $command = "$status;$key";
if ( !socket_write( $socket, $command ) ) { if ( !socket_write( $socket, $command ) ) {
Fatal( "Can't write to control socket: ".socket_strerror(socket_last_error($socket)) ); ZM\Fatal( "Can't write to control socket: ".socket_strerror(socket_last_error($socket)) );
} }
socket_shutdown( $socket, 1 ); socket_shutdown( $socket, 1 );
$x10Response = socket_read( $socket, 256 ); $x10Response = socket_read( $socket, 256 );
@ -1983,18 +1983,18 @@ function logState() {
$state = 'ok'; $state = 'ok';
$levelCounts = array( $levelCounts = array(
Logger::FATAL => array( ZM_LOG_ALERT_FAT_COUNT, ZM_LOG_ALARM_FAT_COUNT ), ZM\Logger::FATAL => array( ZM_LOG_ALERT_FAT_COUNT, ZM_LOG_ALARM_FAT_COUNT ),
Logger::ERROR => array( ZM_LOG_ALERT_ERR_COUNT, ZM_LOG_ALARM_ERR_COUNT ), ZM\Logger::ERROR => array( ZM_LOG_ALERT_ERR_COUNT, ZM_LOG_ALARM_ERR_COUNT ),
Logger::WARNING => array( ZM_LOG_ALERT_WAR_COUNT, ZM_LOG_ALARM_WAR_COUNT ), ZM\Logger::WARNING => array( ZM_LOG_ALERT_WAR_COUNT, ZM_LOG_ALARM_WAR_COUNT ),
); );
# This is an expensive request, as it has to hit every row of the Logs Table # This is an expensive request, as it has to hit every row of the Logs Table
$sql = 'SELECT Level, COUNT(Level) AS LevelCount FROM Logs WHERE Level < '.Logger::INFO.' AND TimeKey > unix_timestamp(now() - interval '.ZM_LOG_CHECK_PERIOD.' second) GROUP BY Level ORDER BY Level ASC'; $sql = 'SELECT Level, COUNT(Level) AS LevelCount FROM Logs WHERE Level < '.ZM\Logger::INFO.' AND TimeKey > unix_timestamp(now() - interval '.ZM_LOG_CHECK_PERIOD.' second) GROUP BY Level ORDER BY Level ASC';
$counts = dbFetchAll($sql); $counts = dbFetchAll($sql);
if ( $counts ) { if ( $counts ) {
foreach ( $counts as $count ) { foreach ( $counts as $count ) {
if ( $count['Level'] <= Logger::PANIC ) if ( $count['Level'] <= ZM\Logger::PANIC )
$count['Level'] = Logger::FATAL; $count['Level'] = ZM\Logger::FATAL;
if ( !($levelCount = $levelCounts[$count['Level']]) ) { if ( !($levelCount = $levelCounts[$count['Level']]) ) {
Error('Unexpected Log level '.$count['Level']); Error('Unexpected Log level '.$count['Level']);
next; next;
@ -2026,15 +2026,15 @@ function checkJsonError($value) {
$value = var_export($value,true); $value = var_export($value,true);
switch( json_last_error() ) { switch( json_last_error() ) {
case JSON_ERROR_DEPTH : case JSON_ERROR_DEPTH :
Fatal( "Unable to decode JSON string '$value', maximum stack depth exceeded" ); ZM\Fatal( "Unable to decode JSON string '$value', maximum stack depth exceeded" );
case JSON_ERROR_CTRL_CHAR : case JSON_ERROR_CTRL_CHAR :
Fatal( "Unable to decode JSON string '$value', unexpected control character found" ); ZM\Fatal( "Unable to decode JSON string '$value', unexpected control character found" );
case JSON_ERROR_STATE_MISMATCH : case JSON_ERROR_STATE_MISMATCH :
Fatal( "Unable to decode JSON string '$value', invalid or malformed JSON" ); ZM\Fatal( "Unable to decode JSON string '$value', invalid or malformed JSON" );
case JSON_ERROR_SYNTAX : case JSON_ERROR_SYNTAX :
Fatal( "Unable to decode JSON string '$value', syntax error" ); ZM\Fatal( "Unable to decode JSON string '$value', syntax error" );
default : default :
Fatal( "Unable to decode JSON string '$value', unexpected error ".json_last_error() ); ZM\Fatal( "Unable to decode JSON string '$value', unexpected error ".json_last_error() );
case JSON_ERROR_NONE: case JSON_ERROR_NONE:
break; break;
} }
@ -2122,7 +2122,7 @@ define( 'HTTP_STATUS_BAD_REQUEST', 400 );
define( 'HTTP_STATUS_FORBIDDEN', 403 ); define( 'HTTP_STATUS_FORBIDDEN', 403 );
function ajaxError( $message, $code=HTTP_STATUS_OK ) { function ajaxError( $message, $code=HTTP_STATUS_OK ) {
Error( $message ); ZM\Error( $message );
if ( function_exists( 'ajaxCleanup' ) ) if ( function_exists( 'ajaxCleanup' ) )
ajaxCleanup(); ajaxCleanup();
if ( $code == HTTP_STATUS_OK ) { if ( $code == HTTP_STATUS_OK ) {
@ -2168,7 +2168,7 @@ function cache_bust( $file ) {
if ( file_exists(ZM_DIR_CACHE.'/'.$cacheFile) or symlink(ZM_PATH_WEB.'/'.$file, ZM_DIR_CACHE.'/'.$cacheFile) ) { if ( file_exists(ZM_DIR_CACHE.'/'.$cacheFile) or symlink(ZM_PATH_WEB.'/'.$file, ZM_DIR_CACHE.'/'.$cacheFile) ) {
return 'cache/'.$cacheFile; return 'cache/'.$cacheFile;
} else { } else {
Warning("Failed linking $file to $cacheFile"); ZM\Warning("Failed linking $file to $cacheFile");
} }
return $file; return $file;
} }
@ -2292,7 +2292,7 @@ function getStreamHTML( $monitor, $options = array() ) {
$monitor->Name()); $monitor->Name());
} else { } else {
if ( $options['mode'] == 'stream' ) { if ( $options['mode'] == 'stream' ) {
Info( 'The system has fallen back to single jpeg mode for streaming. Consider enabling Cambozola or upgrading the client browser.' ); ZM\Info( 'The system has fallen back to single jpeg mode for streaming. Consider enabling Cambozola or upgrading the client browser.' );
} }
$options['mode'] = 'single'; $options['mode'] = 'single';
$streamSrc = $monitor->getStreamSrc( $options ); $streamSrc = $monitor->getStreamSrc( $options );
@ -2308,7 +2308,7 @@ function getStreamMode( ) {
$streamMode = 'jpeg'; $streamMode = 'jpeg';
} else { } else {
$streamMode = 'single'; $streamMode = 'single';
Info( 'The system has fallen back to single jpeg mode for streaming. Consider enabling Cambozola or upgrading the client browser.' ); ZM\Info( 'The system has fallen back to single jpeg mode for streaming. Consider enabling Cambozola or upgrading the client browser.' );
} }
return $streamMode; return $streamMode;
} // end function getStreamMode } // end function getStreamMode
@ -2349,13 +2349,13 @@ function check_timezone() {
#"); #");
if ( $sys_tzoffset != $php_tzoffset ) if ( $sys_tzoffset != $php_tzoffset )
Fatal("ZoneMinder is not installed properly: php's date.timezone does not match the system timezone!"); ZM\Fatal("ZoneMinder is not installed properly: php's date.timezone does not match the system timezone!");
if ( $sys_tzoffset != $mysql_tzoffset ) if ( $sys_tzoffset != $mysql_tzoffset )
Error("ZoneMinder is not installed properly: mysql's timezone does not match the system timezone! Event lists will display incorrect times."); ZM\Error("ZoneMinder is not installed properly: mysql's timezone does not match the system timezone! Event lists will display incorrect times.");
if (!ini_get('date.timezone') || !date_default_timezone_set(ini_get('date.timezone'))) if (!ini_get('date.timezone') || !date_default_timezone_set(ini_get('date.timezone')))
Fatal( "ZoneMinder is not installed properly: php's date.timezone is not set to a valid timezone" ); ZM\Fatal( "ZoneMinder is not installed properly: php's date.timezone is not set to a valid timezone" );
} }

View File

@ -1,5 +1,6 @@
<?php <?php
namespace ZM;
require_once( 'config.php' ); require_once( 'config.php' );
class Logger { class Logger {

View File

@ -17,6 +17,7 @@
// along with this program; if not, write to the Free Software // along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
// //
namespace ZM;
error_reporting(E_ALL); error_reporting(E_ALL);

View File

@ -265,7 +265,7 @@ function getNavBarHTML($reload = null) {
<li><a href="?view=options"><?php echo translate('Options') ?></a></li> <li><a href="?view=options"><?php echo translate('Options') ?></a></li>
<li> <li>
<?php <?php
if ( logToDatabase() > Logger::NOLOG ) { if ( ZM\logToDatabase() > ZM\Logger::NOLOG ) {
if ( ! ZM_RUN_AUDIT ) { if ( ! ZM_RUN_AUDIT ) {
# zmaudit can clean the logs, but if we aren't running it, then we should clecan them regularly # zmaudit can clean the logs, but if we aren't running it, then we should clecan them regularly
dbQuery('DELETE FROM Logs WHERE TimeKey < unix_timestamp( NOW() - interval '.ZM_LOG_DATABASE_LIMIT.') LIMIT 100'); dbQuery('DELETE FROM Logs WHERE TimeKey < unix_timestamp( NOW() - interval '.ZM_LOG_DATABASE_LIMIT.') LIMIT 100');
@ -355,13 +355,13 @@ if ($reload == 'reload') ob_start();
?> ?>
<li><?php echo translate('Storage') ?>: <li><?php echo translate('Storage') ?>:
<?php <?php
$storage_areas = Storage::find(); $storage_areas = ZM\Storage::find();
$storage_paths = null; $storage_paths = null;
foreach ( $storage_areas as $area ) { foreach ( $storage_areas as $area ) {
$storage_paths[$area->Path()] = $area; $storage_paths[$area->Path()] = $area;
} }
if ( ! isset($storage_paths[ZM_DIR_EVENTS]) ) { if ( ! isset($storage_paths[ZM_DIR_EVENTS]) ) {
array_push( $storage_areas, new Storage() ); array_push( $storage_areas, new ZM\Storage() );
} }
$func = function($S){ $func = function($S){
$class = ''; $class = '';

View File

@ -18,7 +18,7 @@
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
// //
$servers = Server::find(null, array('order'=>'lower(Name)')); $servers = ZM\Server::find(null, array('order'=>'lower(Name)'));
$ServersById = array(); $ServersById = array();
foreach ( $servers as $S ) { foreach ( $servers as $S ) {
$ServersById[$S->Id()] = $S; $ServersById[$S->Id()] = $S;
@ -37,7 +37,7 @@ foreach ( array('Group','Function','ServerId','StorageId','Status','MonitorId','
} }
session_write_close(); session_write_close();
$storage_areas = Storage::find(); $storage_areas = ZM\Storage::find();
$StorageById = array(); $StorageById = array();
foreach ( $storage_areas as $S ) { foreach ( $storage_areas as $S ) {
$StorageById[$S->Id()] = $S; $StorageById[$S->Id()] = $S;
@ -52,7 +52,7 @@ $html =
'; ';
$GroupsById = array(); $GroupsById = array();
foreach ( Group::find() as $G ) { foreach ( ZM\Group::find() as $G ) {
$GroupsById[$G->Id()] = $G; $GroupsById[$G->Id()] = $G;
} }
@ -61,8 +61,8 @@ if ( count($GroupsById) ) {
$html .= '<span id="groupControl"><label>'. translate('Group') .'</label>'; $html .= '<span id="groupControl"><label>'. translate('Group') .'</label>';
# This will end up with the group_id of the deepest selection # This will end up with the group_id of the deepest selection
$group_id = isset($_SESSION['Group']) ? $_SESSION['Group'] : null; $group_id = isset($_SESSION['Group']) ? $_SESSION['Group'] : null;
$html .= Group::get_group_dropdown(); $html .= ZM\Group::get_group_dropdown();
$groupSql = Group::get_group_sql($group_id); $groupSql = ZM\Group::get_group_sql($group_id);
$html .= '</span>'; $html .= '</span>';
} }
@ -188,12 +188,12 @@ $html .= htmlSelect( 'Status[]', $status_options,
for ( $i = 0; $i < count($monitors); $i++ ) { for ( $i = 0; $i < count($monitors); $i++ ) {
if ( !visibleMonitor($monitors[$i]['Id']) ) { if ( !visibleMonitor($monitors[$i]['Id']) ) {
Warning('Monitor '.$monitors[$i]['Id'].' is not visible'); ZM\Logger::Warning('Monitor '.$monitors[$i]['Id'].' is not visible');
continue; continue;
} }
if ( isset($_SESSION['MonitorName']) ) { if ( isset($_SESSION['MonitorName']) ) {
$Monitor = new Monitor($monitors[$i]); $Monitor = new ZM\Monitor($monitors[$i]);
ini_set('track_errors', 'on'); ini_set('track_errors', 'on');
$php_errormsg = ''; $php_errormsg = '';
$regexp = $_SESSION['MonitorName']; $regexp = $_SESSION['MonitorName'];
@ -209,7 +209,7 @@ $html .= htmlSelect( 'Status[]', $status_options,
} }
if ( isset($_SESSION['Source']) ) { if ( isset($_SESSION['Source']) ) {
$Monitor = new Monitor($monitors[$i]); $Monitor = new ZM\Monitor($monitors[$i]);
ini_set('track_errors', 'on'); ini_set('track_errors', 'on');
$php_errormsg = ''; $php_errormsg = '';
$regexp = $_SESSION['Source']; $regexp = $_SESSION['Source'];

View File

@ -18,7 +18,7 @@
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
// //
if ( !canEdit( 'Monitors' ) ) { if ( !canEdit('Monitors') ) {
$view = 'error'; $view = 'error';
return; return;
} }
@ -61,8 +61,8 @@ xhtmlHeaders(__FILE__, translate('AddMonitors'));
<th>Group</th> <th>Group</th>
</tr> </tr>
<tr title="Example Data"> <tr title="Example Data">
<td>Example Name MN1-30 INQ37.01</td> <td>Example Name Driveway</td>
<td>http://10.34.152.20:2001/?action=stream</td> <td>http://192.168.1.0/?action=stream</td>
<td>MN1</td> <td>MN1</td>
</tr> </tr>
</table> </table>
@ -80,7 +80,7 @@ xhtmlHeaders(__FILE__, translate('AddMonitors'));
?> ?>
</td></tr> </td></tr>
<?php <?php
$servers = Server::find(); $servers = ZM\Server::find();
$ServersById = array(); $ServersById = array();
foreach ( $servers as $S ) { foreach ( $servers as $S ) {
$ServersById[$S->Id()] = $S; $ServersById[$S->Id()] = $S;
@ -92,7 +92,7 @@ xhtmlHeaders(__FILE__, translate('AddMonitors'));
</td></tr> </td></tr>
<?php <?php
} }
$storage_areas = Storage::find(); $storage_areas = ZM\Storage::find();
$StorageById = array(); $StorageById = array();
foreach ( $storage_areas as $S ) { foreach ( $storage_areas as $S ) {
$StorageById[$S->Id()] = $S; $StorageById[$S->Id()] = $S;

View File

@ -230,7 +230,7 @@ ob_end_clean();
echo $table_head; echo $table_head;
for( $monitor_i = 0; $monitor_i < count($displayMonitors); $monitor_i += 1 ) { for( $monitor_i = 0; $monitor_i < count($displayMonitors); $monitor_i += 1 ) {
$monitor = $displayMonitors[$monitor_i]; $monitor = $displayMonitors[$monitor_i];
$Monitor = new Monitor($monitor); $Monitor = new ZM\Monitor($monitor);
if ( $monitor_i and ( $monitor_i % 100 == 0 ) ) { if ( $monitor_i and ( $monitor_i % 100 == 0 ) ) {
echo '</table>'; echo '</table>';
@ -275,7 +275,7 @@ for( $monitor_i = 0; $monitor_i < count($displayMonitors); $monitor_i += 1 ) {
<span class="glyphicon glyphicon-dot <?php echo $dot_class ?>" aria-hidden="true"></span><a <?php echo ($stream_available ? 'href="?view=watch&amp;mid='.$monitor['Id'].'">' : '>') . $monitor['Name'] ?></a><br/><div class="small text-nowrap text-muted"> <span class="glyphicon glyphicon-dot <?php echo $dot_class ?>" aria-hidden="true"></span><a <?php echo ($stream_available ? 'href="?view=watch&amp;mid='.$monitor['Id'].'">' : '>') . $monitor['Name'] ?></a><br/><div class="small text-nowrap text-muted">
<?php echo implode('<br/>', <?php echo implode('<br/>',
array_map(function($group_id){ array_map(function($group_id){
$Group = Group::find_one(array('Id'=>$group_id)); $Group = ZM\Group::find_one(array('Id'=>$group_id));
if ( $Group ) { if ( $Group ) {
$Groups = $Group->Parents(); $Groups = $Group->Parents();
array_push( $Groups, $Group ); array_push( $Groups, $Group );
@ -305,7 +305,7 @@ for( $monitor_i = 0; $monitor_i < count($displayMonitors); $monitor_i += 1 ) {
</div></td> </div></td>
<?php <?php
if ( count($servers) ) { ?> if ( count($servers) ) { ?>
<td class="colServer"><?php $Server = isset($ServersById[$monitor['ServerId']]) ? $ServersById[$monitor['ServerId']] : new Server( $monitor['ServerId'] ); echo $Server->Name(); ?></td> <td class="colServer"><?php $Server = isset($ServersById[$monitor['ServerId']]) ? $ServersById[$monitor['ServerId']] : new ZM\Server($monitor['ServerId']); echo $Server->Name(); ?></td>
<?php <?php
} }
echo '<td class="colSource">'. makePopupLink( '?view=monitor&amp;mid='.$monitor['Id'], 'zmMonitor'.$monitor['Id'], 'monitor', '<span class="'.$source_class.'">'.validHtmlStr($Monitor->Source()).'</span>', canEdit('Monitors') ).'</td>'; echo '<td class="colSource">'. makePopupLink( '?view=monitor&amp;mid='.$monitor['Id'], 'zmMonitor'.$monitor['Id'], 'monitor', '<span class="'.$source_class.'">'.validHtmlStr($Monitor->Source()).'</span>', canEdit('Monitors') ).'</td>';

View File

@ -46,7 +46,7 @@ foreach ( dbFetchAll($sql, false, $params) as $row ) {
foreach ( getSkinIncludes('includes/control_functions.php') as $includeFile ) foreach ( getSkinIncludes('includes/control_functions.php') as $includeFile )
require_once $includeFile; require_once $includeFile;
$monitor = new Monitor($mid); $monitor = new ZM\Monitor($mid);
$focusWindow = true; $focusWindow = true;

View File

@ -50,7 +50,7 @@ foreach( $displayMonitors as &$row ) {
$row['PopupScale'] = reScale(SCALE_BASE, $row['DefaultScale'], ZM_WEB_DEFAULT_SCALE); $row['PopupScale'] = reScale(SCALE_BASE, $row['DefaultScale'], ZM_WEB_DEFAULT_SCALE);
$row['connKey'] = generateConnKey(); $row['connKey'] = generateConnKey();
$monitors[] = new Monitor($row); $monitors[] = new ZM\Monitor($row);
} # end foreach Monitor } # end foreach Monitor
if ( $monitors ) { if ( $monitors ) {

View File

@ -26,7 +26,7 @@ if ( !canView('Events') ) {
$eid = validInt( $_REQUEST['eid'] ); $eid = validInt( $_REQUEST['eid'] );
$fid = !empty($_REQUEST['fid'])?validInt($_REQUEST['fid']):1; $fid = !empty($_REQUEST['fid'])?validInt($_REQUEST['fid']):1;
$Event = new Event( $eid ); $Event = new ZM\Event( $eid );
if ( $user['MonitorIds'] ) { if ( $user['MonitorIds'] ) {
$monitor_ids = explode( ',', $user['MonitorIds'] ); $monitor_ids = explode( ',', $user['MonitorIds'] );
if ( count($monitor_ids) and ! in_array( $Event->MonitorId(), $monitor_ids ) ) { if ( count($monitor_ids) and ! in_array( $Event->MonitorId(), $monitor_ids ) ) {

View File

@ -80,12 +80,12 @@ $focusWindow = true;
if ( $_POST ) { if ( $_POST ) {
// I think this is basically so that a refresh doesn't repost // I think this is basically so that a refresh doesn't repost
Logger::Debug("Redirecting to " . $_SERVER['REQUEST_URI']); ZM\Logger::Debug('Redirecting to ' . $_SERVER['REQUEST_URI']);
header('Location: ?view=' . $view.htmlspecialchars_decode($filterQuery).htmlspecialchars_decode($sortQuery).$limitQuery.'&page='.$page); header('Location: ?view=' . $view.htmlspecialchars_decode($filterQuery).htmlspecialchars_decode($sortQuery).$limitQuery.'&page='.$page);
exit(); exit();
} }
$storage_areas = Storage::find(); $storage_areas = ZM\Storage::find();
$StorageById = array(); $StorageById = array();
foreach ( $storage_areas as $S ) { foreach ( $storage_areas as $S ) {
$StorageById[$S->Id()] = $S; $StorageById[$S->Id()] = $S;
@ -146,7 +146,7 @@ $disk_space_total = 0;
$results = dbQuery($eventsSql); $results = dbQuery($eventsSql);
while ( $event_row = dbFetchNext($results) ) { while ( $event_row = dbFetchNext($results) ) {
$event = new Event($event_row); $event = new ZM\Event($event_row);
if ( $event_row['Archived'] ) if ( $event_row['Archived'] )
$archived = true; $archived = true;
else else

View File

@ -40,7 +40,7 @@ if ( isset($_SESSION['export']) ) {
if (isset($_REQUEST['exportFormat'])) { if (isset($_REQUEST['exportFormat'])) {
if (!in_array($_REQUEST['exportFormat'], array('zip', 'tar'))) { if (!in_array($_REQUEST['exportFormat'], array('zip', 'tar'))) {
Error('Invalid exportFormat'); ZM\Error('Invalid exportFormat');
return; return;
} }
} }

View File

@ -36,11 +36,11 @@ foreach ( dbFetchAll('SELECT * FROM Filters ORDER BY Name') as $row ) {
$filterNames[$row['Id']] .= '&'; $filterNames[$row['Id']] .= '&';
if ( isset($_REQUEST['Id']) && $_REQUEST['Id'] == $row['Id'] ) { if ( isset($_REQUEST['Id']) && $_REQUEST['Id'] == $row['Id'] ) {
$filter = new Filter($row); $filter = new ZM\Filter($row);
} }
} }
if ( ! $filter ) { if ( ! $filter ) {
$filter = new Filter(); $filter = new ZM\Filter();
} }
if ( isset($_REQUEST['sort_field']) && isset($_REQUEST['filter']) ) { if ( isset($_REQUEST['sort_field']) && isset($_REQUEST['filter']) ) {

View File

@ -29,7 +29,7 @@ $eid = validInt($_REQUEST['eid']);
if ( !empty($_REQUEST['fid']) ) if ( !empty($_REQUEST['fid']) )
$fid = validInt($_REQUEST['fid']); $fid = validInt($_REQUEST['fid']);
$Event = new Event($eid); $Event = new ZM\Event($eid);
$Monitor = $Event->Monitor(); $Monitor = $Event->Monitor();
if ( !empty($fid) ) { if ( !empty($fid) ) {
@ -39,7 +39,7 @@ if ( !empty($fid) ) {
} else { } else {
$frame = dbFetchOne( 'SELECT * FROM Frames WHERE EventId = ? AND Score = ?', NULL, array( $eid, $Event->MaxScore() ) ); $frame = dbFetchOne( 'SELECT * FROM Frames WHERE EventId = ? AND Score = ?', NULL, array( $eid, $Event->MaxScore() ) );
} }
$Frame = new Frame($frame); $Frame = new ZM\Frame($frame);
$maxFid = $Event->Frames(); $maxFid = $Event->Frames();
@ -63,7 +63,7 @@ $scale = $scale ?: "auto";
$imageData = $Event->getImageSrc( $frame, $scale, 0 ); $imageData = $Event->getImageSrc( $frame, $scale, 0 );
if ( ! $imageData ) { if ( ! $imageData ) {
Error("No data found for Event $eid frame $fid"); ZM\Error("No data found for Event $eid frame $fid");
$imageData = array(); $imageData = array();
} }

View File

@ -23,7 +23,7 @@ if ( !canView('Events') ) {
return; return;
} }
require_once('includes/Frame.php'); require_once('includes/Frame.php');
$Event = new Event( $_REQUEST['eid'] ); $Event = new ZM\Event($_REQUEST['eid']);
$sql = 'SELECT *, unix_timestamp( TimeStamp ) AS UnixTimeStamp FROM Frames WHERE EventID = ? ORDER BY FrameId'; $sql = 'SELECT *, unix_timestamp( TimeStamp ) AS UnixTimeStamp FROM Frames WHERE EventID = ? ORDER BY FrameId';
$frames = dbFetchAll( $sql, NULL, array( $_REQUEST['eid'] ) ); $frames = dbFetchAll( $sql, NULL, array( $_REQUEST['eid'] ) );
@ -62,7 +62,7 @@ xhtmlHeaders(__FILE__, translate('Frames').' - '.$Event->Id() );
<?php <?php
if ( count($frames) ) { if ( count($frames) ) {
foreach ( $frames as $frame ) { foreach ( $frames as $frame ) {
$Frame = new Frame( $frame ); $Frame = new ZM\Frame( $frame );
$class = strtolower($frame['Type']); $class = strtolower($frame['Type']);
?> ?>

View File

@ -24,9 +24,9 @@ if ( !canEdit('Groups') ) {
} }
if ( !empty($_REQUEST['gid']) ) { if ( !empty($_REQUEST['gid']) ) {
$newGroup = new Group($_REQUEST['gid']); $newGroup = new ZM\Group($_REQUEST['gid']);
} else { } else {
$newGroup = new Group(); $newGroup = new ZM\Group();
} }
xhtmlHeaders(__FILE__, translate('Group').' - '.$newGroup->Name()); xhtmlHeaders(__FILE__, translate('Group').' - '.$newGroup->Name());
@ -51,7 +51,7 @@ xhtmlHeaders(__FILE__, translate('Group').' - '.$newGroup->Name());
<td> <td>
<?php <?php
$Groups = array(); $Groups = array();
foreach ( Group::find() as $Group ) { foreach ( ZM\Group::find() as $Group ) {
$Groups[$Group->Id()] = $Group; $Groups[$Group->Id()] = $Group;
} }

View File

@ -28,7 +28,7 @@ $group_id = 0;
$max_depth = 0; $max_depth = 0;
$Groups = array(); $Groups = array();
foreach ( Group::find() as $Group ) { foreach ( ZM\Group::find() as $Group ) {
$Groups[$Group->Id()] = $Group; $Groups[$Group->Id()] = $Group;
} }

View File

@ -120,21 +120,21 @@ echo " };\n";
echo "\nvar Storage = [];\n"; echo "\nvar Storage = [];\n";
$have_storage_zero = 0; $have_storage_zero = 0;
foreach ( Storage::find() as $Storage ) { foreach ( ZM\Storage::find() as $Storage ) {
echo 'Storage[' . $Storage->Id() . '] = ' . $Storage->to_json(). ";\n"; echo 'Storage[' . $Storage->Id() . '] = ' . $Storage->to_json(). ";\n";
if ( $Storage->Id() == 0 ) if ( $Storage->Id() == 0 )
$have_storage_zero = true; $have_storage_zero = true;
} }
if ( !$have_storage_zero ) { if ( !$have_storage_zero ) {
$Storage = new Storage(); $Storage = new ZM\Storage();
echo 'Storage[0] = ' . $Storage->to_json(). ";\n"; echo 'Storage[0] = ' . $Storage->to_json(). ";\n";
} }
echo "\nvar Servers = [];\n"; echo "\nvar Servers = [];\n";
// Fall back to get Server paths, etc when no using multi-server mode // Fall back to get Server paths, etc when no using multi-server mode
$Server = new Server(); $Server = new ZM\Server();
echo 'Servers[0] = new Server(' . $Server->to_json(). ");\n"; echo 'Servers[0] = new Server(' . $Server->to_json(). ");\n";
foreach ( Server::find() as $Server ) { foreach ( ZM\Server::find() as $Server ) {
echo 'Servers[' . $Server->Id() . '] = new Server(' . $Server->to_json(). ");\n"; echo 'Servers[' . $Server->Id() . '] = new Server(' . $Server->to_json(). ");\n";
} }

View File

@ -36,7 +36,7 @@ if ( ! $Server ) {
$monitor = null; $monitor = null;
if ( ! empty($_REQUEST['mid']) ) { if ( ! empty($_REQUEST['mid']) ) {
$monitor = new Monitor( $_REQUEST['mid'] ); $monitor = new ZM\Monitor( $_REQUEST['mid'] );
if ( $monitor and ZM_OPT_X10 ) if ( $monitor and ZM_OPT_X10 )
$x10Monitor = dbFetchOne( 'SELECT * FROM TriggersX10 WHERE MonitorId = ?', NULL, array($_REQUEST['mid']) ); $x10Monitor = dbFetchOne( 'SELECT * FROM TriggersX10 WHERE MonitorId = ?', NULL, array($_REQUEST['mid']) );
} }
@ -44,7 +44,7 @@ if ( ! $monitor ) {
$nextId = getTableAutoInc( 'Monitors' ); $nextId = getTableAutoInc( 'Monitors' );
if ( isset( $_REQUEST['dupId'] ) ) { if ( isset( $_REQUEST['dupId'] ) ) {
$monitor = new Monitor( $_REQUEST['dupId'] ); $monitor = new ZM\Monitor( $_REQUEST['dupId'] );
$monitor->GroupIds(); // have to load before we change the Id $monitor->GroupIds(); // have to load before we change the Id
if ( ZM_OPT_X10 ) if ( ZM_OPT_X10 )
$x10Monitor = dbFetchOne( 'SELECT * FROM TriggersX10 WHERE MonitorId = ?', NULL, array($_REQUEST['dupId']) ); $x10Monitor = dbFetchOne( 'SELECT * FROM TriggersX10 WHERE MonitorId = ?', NULL, array($_REQUEST['dupId']) );
@ -52,7 +52,7 @@ if ( ! $monitor ) {
$monitor->Name( translate('Monitor').'-'.$nextId ); $monitor->Name( translate('Monitor').'-'.$nextId );
$monitor->Id( $nextId ); $monitor->Id( $nextId );
} else { } else {
$monitor = new Monitor(); $monitor = new ZM\Monitor();
$monitor->set( array( $monitor->set( array(
'Id' => 0, 'Id' => 0,
'Name' => translate('Monitor').'-'.$nextId, 'Name' => translate('Monitor').'-'.$nextId,
@ -678,10 +678,8 @@ switch ( $tab ) {
<tr><td><?php echo translate('Server') ?></td><td> <tr><td><?php echo translate('Server') ?></td><td>
<?php <?php
$servers = array(''=>'None','auto'=>'Auto'); $servers = array(''=>'None','auto'=>'Auto');
$result = dbQuery( 'SELECT * FROM Servers ORDER BY Name'); foreach ( ZM\Server::find(NULL, array('order'=>'lower(Name)')) as $Server ) {
$results = $result->fetchALL(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'Server' ); $servers[$Server->Id()] = $Server->Name();
foreach ( $results as $row => $server_obj ) {
$servers[$server_obj->Id()] = $server_obj->Name();
} }
echo htmlSelect( 'newMonitor[ServerId]', $servers, $monitor->ServerId() ); echo htmlSelect( 'newMonitor[ServerId]', $servers, $monitor->ServerId() );
?> ?>
@ -689,10 +687,8 @@ switch ( $tab ) {
<tr><td><?php echo translate('StorageArea') ?></td><td> <tr><td><?php echo translate('StorageArea') ?></td><td>
<?php <?php
$storage_areas = array(0=>'Default'); $storage_areas = array(0=>'Default');
$result = dbQuery( 'SELECT * FROM Storage ORDER BY Name'); foreach ( ZM\Storage::find( NULL, array('order'=>'lower(Name)') ) as $Storage ) {
$results = $result->fetchALL(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'Storage' ); $storage_areas[$Storage->Id()] = $Storage->Name();
foreach ( $results as $row => $storage_obj ) {
$storage_areas[$storage_obj->Id] = $storage_obj->Name();
} }
echo htmlSelect( 'newMonitor[StorageId]', $storage_areas, $monitor->StorageId() ); echo htmlSelect( 'newMonitor[StorageId]', $storage_areas, $monitor->StorageId() );
?> ?>
@ -733,7 +729,7 @@ switch ( $tab ) {
</td> </td>
</tr> </tr>
<tr><td><?php echo translate('Groups'); ?></td><td><select name="newMonitor[GroupIds][]" multiple="multiple" class="chosen"><?php <tr><td><?php echo translate('Groups'); ?></td><td><select name="newMonitor[GroupIds][]" multiple="multiple" class="chosen"><?php
echo htmlOptions(Group::get_dropdown_options( ), $monitor->GroupIds() ); echo htmlOptions(ZM\Group::get_dropdown_options( ), $monitor->GroupIds() );
?></td></tr> ?></td></tr>
<tr><td><?php echo translate('AnalysisFPS') ?></td><td><input type="text" name="newMonitor[AnalysisFPSLimit]" value="<?php echo validHtmlStr($monitor->AnalysisFPSLimit()) ?>" size="6"/></td></tr> <tr><td><?php echo translate('AnalysisFPS') ?></td><td><input type="text" name="newMonitor[AnalysisFPSLimit]" value="<?php echo validHtmlStr($monitor->AnalysisFPSLimit()) ?>" size="6"/></td></tr>
<?php <?php

View File

@ -34,7 +34,7 @@ function probeV4L() {
$result = exec(escapeshellcmd($command), $output, $status); $result = exec(escapeshellcmd($command), $output, $status);
if ( $status ) { if ( $status ) {
Error("Unable to probe local cameras, status is '$status'"); ZM\Error("Unable to probe local cameras using $command, status is '$status' " . implode("\n",$output));
return $cameras; return $cameras;
} }
@ -47,7 +47,7 @@ function probeV4L() {
$preferredFormats = array('BGR3', 'RGB3', 'YUYV', 'UYVY', 'JPEG', 'MJPG', '422P', 'YU12', 'GREY'); $preferredFormats = array('BGR3', 'RGB3', 'YUYV', 'UYVY', 'JPEG', 'MJPG', '422P', 'YU12', 'GREY');
foreach ( $output as $line ) { foreach ( $output as $line ) {
if ( !preg_match('/^d:([^|]+).*S:([^|]*).*F:([^|]+).*I:(\d+)\|(.+)$/', $line, $deviceMatches) ) if ( !preg_match('/^d:([^|]+).*S:([^|]*).*F:([^|]+).*I:(\d+)\|(.+)$/', $line, $deviceMatches) )
Fatal("Can't parse command output '$line'"); ZM\Fatal("Can't parse command output '$line'");
$standards = explode('/',$deviceMatches[2]); $standards = explode('/',$deviceMatches[2]);
$preferredStandard = false; $preferredStandard = false;
foreach ( $preferredStandards as $standard ) { foreach ( $preferredStandards as $standard ) {
@ -74,7 +74,7 @@ function probeV4L() {
$inputs = array(); $inputs = array();
for ( $i = 0; $i < $deviceMatches[4]; $i++ ) { for ( $i = 0; $i < $deviceMatches[4]; $i++ ) {
if ( !preg_match('/i'.$i.':([^|]+)\|i'.$i.'T:([^|]+)\|/', $deviceMatches[5], $inputMatches) ) if ( !preg_match('/i'.$i.':([^|]+)\|i'.$i.'T:([^|]+)\|/', $deviceMatches[5], $inputMatches) )
Fatal("Can't parse input '".$deviceMatches[5]."'"); ZM\Fatal("Can't parse input '".$deviceMatches[5]."'");
if ( $inputMatches[2] == 'Camera' ) { if ( $inputMatches[2] == 'Camera' ) {
$input = array( $input = array(
'index' => $i, 'index' => $i,
@ -247,13 +247,13 @@ function probeNetwork() {
$arp_command = ZM_PATH_ARP; $arp_command = ZM_PATH_ARP;
$result = explode(' ', $arp_command); $result = explode(' ', $arp_command);
if ( !is_executable($result[0]) ) { if ( !is_executable($result[0]) ) {
Error("ARP compatible binary not found or not executable by the web user account. Verify ZM_PATH_ARP points to a valid arp tool."); ZM\Error("ARP compatible binary not found or not executable by the web user account. Verify ZM_PATH_ARP points to a valid arp tool.");
return; return;
} }
$result = exec(escapeshellcmd($arp_command), $output, $status); $result = exec(escapeshellcmd($arp_command), $output, $status);
if ( $status ) { if ( $status ) {
Error("Unable to probe network cameras, status is '$status'"); ZM\Error("Unable to probe network cameras, status is '$status'");
return; return;
} }

View File

@ -23,14 +23,14 @@ if ( !canEdit('Monitors') ) {
return; return;
} }
$monitors = Monitor::find(array('Id' => $_REQUEST['mids'])); $monitors = ZM\Monitor::find(array('Id' => $_REQUEST['mids']));
$monitor = $monitors[0]; $monitor = $monitors[0];
$servers = Server::find(); $servers = ZM\Server::find();
$ServersById = array(); $ServersById = array();
foreach ( $servers as $S ) { foreach ( $servers as $S ) {
$ServersById[$S->Id()] = $S; $ServersById[$S->Id()] = $S;
} }
$storage_areas = Storage::find(); $storage_areas = ZM\Storage::find();
$StorageById = array(); $StorageById = array();
foreach ( $storage_areas as $S ) { foreach ( $storage_areas as $S ) {
$StorageById[$S->Id()] = $S; $StorageById[$S->Id()] = $S;

View File

@ -50,16 +50,16 @@ $scale = '100'; # actual
if ( isset( $_REQUEST['scale'] ) ) { if ( isset( $_REQUEST['scale'] ) ) {
$scale = validInt($_REQUEST['scale']); $scale = validInt($_REQUEST['scale']);
Logger::Debug("Setting scale from request to $scale"); ZM\Logger::Debug("Setting scale from request to $scale");
} else if ( isset($_COOKIE['zmMontageScale']) ) { } else if ( isset($_COOKIE['zmMontageScale']) ) {
$scale = $_COOKIE['zmMontageScale']; $scale = $_COOKIE['zmMontageScale'];
Logger::Debug("Setting scale from cookie to $scale"); ZM\Logger::Debug("Setting scale from cookie to $scale");
} }
if ( ! $scale ) if ( ! $scale )
$scale = 100; $scale = 100;
$layouts = MontageLayout::find(NULL, array('order'=>"lower('Name')")); $layouts = ZM\MontageLayout::find(NULL, array('order'=>"lower('Name')"));
$layoutsById = array(); $layoutsById = array();
foreach ( $layouts as $l ) { foreach ( $layouts as $l ) {
$layoutsById[$l->Id()] = $l; $layoutsById[$l->Id()] = $l;
@ -126,7 +126,7 @@ foreach( $displayMonitors as &$row ) {
if ( ! isset($heights[$row['Height']]) ) { if ( ! isset($heights[$row['Height']]) ) {
$heights[$row['Height']] = $row['Height']; $heights[$row['Height']] = $row['Height'];
} }
$monitors[] = new Monitor($row); $monitors[] = new ZM\Monitor($row);
} # end foreach Monitor } # end foreach Monitor
xhtmlHeaders(__FILE__, translate('Montage')); xhtmlHeaders(__FILE__, translate('Montage'));

View File

@ -223,7 +223,7 @@ $monitors = array();
foreach( $displayMonitors as $row ) { foreach( $displayMonitors as $row ) {
if ( $row['Function'] == 'None' || $row['Type'] == 'WebSite' ) if ( $row['Function'] == 'None' || $row['Type'] == 'WebSite' )
continue; continue;
$Monitor = new Monitor($row); $Monitor = new ZM\Monitor($row);
$monitors[] = $Monitor; $monitors[] = $Monitor;
} }

View File

@ -36,12 +36,12 @@ function execONVIF( $cmd ) {
if ( $status ) { if ( $status ) {
$html_output = implode( '<br/>', $output ); $html_output = implode( '<br/>', $output );
Fatal( "Unable to probe network cameras, status is '$status'. Output was:<br/><br/> ZM\Fatal( "Unable to probe network cameras, status is '$status'. Output was:<br/><br/>
$html_output<br/><br/> $html_output<br/><br/>
Please the following command from a command line for more information:<br/><br/>$shell_command" Please the following command from a command line for more information:<br/><br/>$shell_command"
); );
} else { } else {
Logger::Debug( "Results from probe: " . implode( '<br/>', $output ) ); ZM\Logger::Debug( "Results from probe: " . implode( '<br/>', $output ) );
} }
return $output; return $output;
@ -73,7 +73,7 @@ function probeCameras( $localIp ) {
} elseif ( $tokens[1] == 'location' ) { } elseif ( $tokens[1] == 'location' ) {
// $camera['location'] = $tokens[2]; // $camera['location'] = $tokens[2];
} else { } else {
Logger::Debug('Unknown token ' . $tokens[1]); ZM\Logger::Debug('Unknown token ' . $tokens[1]);
} }
} }
} // end foreach token } // end foreach token
@ -109,7 +109,7 @@ function probeProfiles( $device_ep, $soapversion, $username, $password ) {
); );
$profiles[] = $profile; $profiles[] = $profile;
} else { } else {
Logger::Debug("Line did not match preg: $line"); ZM\Logger::Debug("Line did not match preg: $line");
} }
} // end foreach line } // end foreach line
} // end if results from execONVIF } // end if results from execONVIF
@ -190,7 +190,7 @@ if ( !isset($_REQUEST['step']) || ($_REQUEST['step'] == '1') ) {
</p> </p>
<p> <p>
<label for="password"><?php echo translate('Password') ?></label> <label for="password"><?php echo translate('Password') ?></label>
<input type="password" name="password" value=""onChange="configureButtons(this)"/> <input type="password" name="password" value="" onChange="configureButtons(this)"/>
</p> </p>
<div id="contentButtons"> <div id="contentButtons">
<input type="button" value="<?php echo translate('Cancel') ?>" data-on-click="closeWindow"/> <input type="button" value="<?php echo translate('Cancel') ?>" data-on-click="closeWindow"/>
@ -206,12 +206,12 @@ if ( !isset($_REQUEST['step']) || ($_REQUEST['step'] == '1') ) {
//==== STEP 2 ============================================================ //==== STEP 2 ============================================================
} else if($_REQUEST['step'] == '2') { } else if($_REQUEST['step'] == '2') {
if ( empty($_REQUEST['probe']) ) if ( empty($_REQUEST['probe']) )
Fatal('No probe passed in request. Please go back and try again.'); ZM\Fatal('No probe passed in request. Please go back and try again.');
#|| empty($_REQUEST['username']) || #|| empty($_REQUEST['username']) ||
#empty($_REQUEST['password']) ) #empty($_REQUEST['password']) )
$probe = json_decode(base64_decode($_REQUEST['probe'])); $probe = json_decode(base64_decode($_REQUEST['probe']));
Logger::Debug(print_r($probe,true)); ZM\Logger::Debug(print_r($probe,true));
foreach ( $probe as $name=>$value ) { foreach ( $probe as $name=>$value ) {
if ( isset($value) ) { if ( isset($value) ) {
$monitor[$name] = $value; $monitor[$name] = $value;

View File

@ -230,7 +230,7 @@ foreach ( array_map('basename', glob('skins/'.$current_skin.'/css/*',GLOB_ONLYDI
<tbody> <tbody>
<?php <?php
$monitor_counts = dbFetchAssoc('SELECT Id,(SELECT COUNT(Id) FROM Monitors WHERE ServerId=Servers.Id) AS MonitorCount FROM Servers', 'Id', 'MonitorCount'); $monitor_counts = dbFetchAssoc('SELECT Id,(SELECT COUNT(Id) FROM Monitors WHERE ServerId=Servers.Id) AS MonitorCount FROM Servers', 'Id', 'MonitorCount');
foreach ( Server::find() as $Server ) { foreach ( ZM\Server::find() as $Server ) {
?> ?>
<tr> <tr>
<td class="colName"><?php echo makePopupLink('?view=server&amp;id='.$Server->Id(), 'zmServer', 'server', validHtmlStr($Server->Name()), $canEdit) ?></td> <td class="colName"><?php echo makePopupLink('?view=server&amp;id='.$Server->Id(), 'zmServer', 'server', validHtmlStr($Server->Name()), $canEdit) ?></td>
@ -287,7 +287,7 @@ foreach ( array_map('basename', glob('skins/'.$current_skin.'/css/*',GLOB_ONLYDI
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<?php foreach( Storage::find( null, array('order'=>'lower(Name)') ) as $Storage ) { ?> <?php foreach( ZM\Storage::find( null, array('order'=>'lower(Name)') ) as $Storage ) { ?>
<tr> <tr>
<td class="colId"><?php echo makePopupLink('?view=storage&amp;id='.$Storage->Id(), 'zmStorage', 'storage', validHtmlStr($Storage->Id()), $canEdit ) ?></td> <td class="colId"><?php echo makePopupLink('?view=storage&amp;id='.$Storage->Id(), 'zmStorage', 'storage', validHtmlStr($Storage->Id()), $canEdit ) ?></td>
<td class="colName"><?php echo makePopupLink('?view=storage&amp;id='.$Storage->Id(), 'zmStorage', 'storage', validHtmlStr($Storage->Name()), $canEdit ) ?></td> <td class="colName"><?php echo makePopupLink('?view=storage&amp;id='.$Storage->Id(), 'zmStorage', 'storage', validHtmlStr($Storage->Name()), $canEdit ) ?></td>

View File

@ -62,7 +62,7 @@ if ( count($selected_monitor_ids) ) {
} }
parseFilter($filter); parseFilter($filter);
$filterQuery = $filter['query']; $filterQuery = $filter['query'];
Logger::Debug($filterQuery); ZM\Logger::Debug($filterQuery);
$eventsSql = 'SELECT *, $eventsSql = 'SELECT *,
UNIX_TIMESTAMP(E.StartTime) AS StartTimeSecs, UNIX_TIMESTAMP(E.StartTime) AS StartTimeSecs,
@ -83,12 +83,12 @@ $eventsSql .= ' ORDER BY Id ASC';
$result = dbQuery($eventsSql); $result = dbQuery($eventsSql);
if ( !$result ) { if ( !$result ) {
Fatal('SQL-ERR'); ZM\Fatal('SQL-ERR');
return; return;
} }
$EventsByMonitor = array(); $EventsByMonitor = array();
while( $event = $result->fetch(PDO::FETCH_ASSOC) ) { while( $event = $result->fetch(PDO::FETCH_ASSOC) ) {
$Event = new Event($event); $Event = new ZM\Event($event);
if ( ! isset($EventsByMonitor[$event['MonitorId']]) ) if ( ! isset($EventsByMonitor[$event['MonitorId']]) )
$EventsByMonitor[$event['MonitorId']] = array( 'Events'=>array(), 'MinGap'=>0, 'MaxGap'=>0, 'FileMissing'=>array(), 'ZeroSize'=>array() ); $EventsByMonitor[$event['MonitorId']] = array( 'Events'=>array(), 'MinGap'=>0, 'MaxGap'=>0, 'FileMissing'=>array(), 'ZeroSize'=>array() );
@ -147,7 +147,7 @@ while( $event = $result->fetch(PDO::FETCH_ASSOC) ) {
<?php <?php
for( $monitor_i = 0; $monitor_i < count($displayMonitors); $monitor_i += 1 ) { for( $monitor_i = 0; $monitor_i < count($displayMonitors); $monitor_i += 1 ) {
$monitor = $displayMonitors[$monitor_i]; $monitor = $displayMonitors[$monitor_i];
$Monitor = new Monitor($monitor); $Monitor = new ZM\Monitor($monitor);
$montagereview_link = "?view=montagereview&live=0&MonitorId=". $monitor['Id'] . '&minTime='.$minTime.'&maxTime='.$maxTime; $montagereview_link = "?view=montagereview&live=0&MonitorId=". $monitor['Id'] . '&minTime='.$minTime.'&maxTime='.$maxTime;
$monitor_filter = addFilterTerm( $monitor_filter = addFilterTerm(
@ -202,7 +202,7 @@ for( $monitor_i = 0; $monitor_i < count($displayMonitors); $monitor_i += 1 ) {
<a href="<?php echo $montagereview_link ?>"><?php echo $monitor['Name'] ?></a><br/><div class="small text-nowrap text-muted"> <a href="<?php echo $montagereview_link ?>"><?php echo $monitor['Name'] ?></a><br/><div class="small text-nowrap text-muted">
<?php echo implode('<br/>', <?php echo implode('<br/>',
array_map(function($group_id){ array_map(function($group_id){
$Group = new Group($group_id); $Group = new ZM\Group($group_id);
$Groups = $Group->Parents(); $Groups = $Group->Parents();
array_push($Groups, $Group); array_push($Groups, $Group);
return implode(' &gt; ', array_map(function($Group){ return '<a href="?view=montagereview&GroupId='.$Group->Id().'">'.$Group->Name().'</a>'; }, $Groups )); return implode(' &gt; ', array_map(function($Group){ return '<a href="?view=montagereview&GroupId='.$Group->Id().'">'.$Group->Name().'</a>'; }, $Groups ));

View File

@ -23,7 +23,7 @@ if ( !canEdit('System') ) {
return; return;
} }
$Server = new Server($_REQUEST['id']); $Server = new ZM\Server($_REQUEST['id']);
if ( $_REQUEST['id'] and ! $Server->Id() ) { if ( $_REQUEST['id'] and ! $Server->Id() ) {
$view = 'error'; $view = 'error';
return; return;
@ -97,9 +97,8 @@ xhtmlHeaders(__FILE__, translate('Server').' - '.$Server->Name());
</tbody> </tbody>
</table> </table>
<div id="contentButtons"> <div id="contentButtons">
<input type="hidden" name="action" value="Save"/> <button type="submit" name="action" value="Save" ><?php echo translate('Save') ?></button>
<input type="submit" value="<?php echo translate('Save') ?>"/> <button type="button" data-on-click="closeWindow"><?php echo translate('Cancel') ?></button>
<input type="button" value="<?php echo translate('Cancel') ?>" data-on-click="closeWindow"/>
</div> </div>
</form> </form>
</div> </div>

View File

@ -48,7 +48,7 @@ $scheme_options = array(
'Shallow' => translate('Shallow'), 'Shallow' => translate('Shallow'),
); );
$servers = Server::find( null, array('order'=>'lower(Name)') ); $servers = ZM\Server::find( null, array('order'=>'lower(Name)') );
$ServersById = array(); $ServersById = array();
foreach ( $servers as $S ) { foreach ( $servers as $S ) {
$ServersById[$S->Id()] = $S; $ServersById[$S->Id()] = $S;

View File

@ -757,7 +757,6 @@ if ( $mode == 'overlay' ) {
echo drawYGrid( $chart, $majYScale, 'majLabelY', 'majTickY', 'majGridY graphWidth' ); echo drawYGrid( $chart, $majYScale, 'majLabelY', 'majTickY', 'majGridY graphWidth' );
} }
echo drawXGrid( $chart, $majXScale, 'majLabelX', 'majTickX', 'majGridX graphHeight', 'zoom graphHeight' ); echo drawXGrid( $chart, $majXScale, 'majLabelX', 'majTickX', 'majGridX graphHeight', 'zoom graphHeight' );
Warning("Mode: $mode");
if ( $mode == 'overlay' ) { if ( $mode == 'overlay' ) {
?> ?>
<div id='activity' class='activitySize'> <div id='activity' class='activitySize'>

View File

@ -37,7 +37,7 @@ if ( ! visibleMonitor($mid) ) {
return; return;
} }
$monitor = new Monitor($mid); $monitor = new ZM\Monitor($mid);
#Whether to show the controls button #Whether to show the controls button
$showPtzControls = ( ZM_OPT_CONTROL && $monitor->Controllable() && canView('Control') && $monitor->Type() != 'WebSite' ); $showPtzControls = ( ZM_OPT_CONTROL && $monitor->Controllable() && canView('Control') && $monitor->Type() != 'WebSite' );

View File

@ -54,7 +54,7 @@ foreach ( getEnumValues( 'Zones', 'CheckMethod' ) as $optCheckMethod ) {
$optCheckMethods[$optCheckMethod] = $optCheckMethod; $optCheckMethods[$optCheckMethod] = $optCheckMethod;
} }
$monitor = new Monitor( $mid ); $monitor = new ZM\Monitor( $mid );
$minX = 0; $minX = 0;
$maxX = $monitor->Width()-1; $maxX = $monitor->Width()-1;

View File

@ -43,7 +43,7 @@ if ( $archivetype ) {
if ( $mimetype ) { if ( $mimetype ) {
$filename = "zmExport.$file_ext"; $filename = "zmExport.$file_ext";
$filename_path = ZM_DIR_EXPORTS.'/'.$filename; $filename_path = ZM_DIR_EXPORTS.'/'.$filename;
Logger::Debug("downloading archive from $filename_path"); ZM\Logger::Debug("downloading archive from $filename_path");
if ( is_readable($filename_path) ) { if ( is_readable($filename_path) ) {
ob_clean(); ob_clean();
header("Content-type: application/$mimetype" ); header("Content-type: application/$mimetype" );
@ -51,16 +51,16 @@ if ( $archivetype ) {
header('Content-Length: ' . filesize($filename_path) ); header('Content-Length: ' . filesize($filename_path) );
set_time_limit(0); set_time_limit(0);
if ( ! @readfile( $filename_path ) ) { if ( ! @readfile( $filename_path ) ) {
Error("Error sending $filename_path"); ZM\Error("Error sending $filename_path");
} }
} else { } else {
Error("$filename_path does not exist or is not readable."); ZM\Error("$filename_path does not exist or is not readable.");
} }
} else { } else {
Error("Unsupported archive type specified. Supported archives are tar and zip"); ZM\Error("Unsupported archive type specified. Supported archives are tar and zip");
} }
} else { } else {
Error("No archive type given to archive.php. Please specify a tar or zip archive."); ZM\Error("No archive type given to archive.php. Please specify a tar or zip archive.");
} }
?> ?>

View File

@ -64,16 +64,16 @@ if ( empty($_REQUEST['path']) ) {
if ( empty($_REQUEST['fid']) ) { if ( empty($_REQUEST['fid']) ) {
header('HTTP/1.0 404 Not Found'); header('HTTP/1.0 404 Not Found');
Fatal('No Frame ID specified'); ZM\Fatal('No Frame ID specified');
return; return;
} }
if ( !empty($_REQUEST['eid']) ) { if ( !empty($_REQUEST['eid']) ) {
Logger::Debug("Loading by eid"); ZM\Logger::Debug("Loading by eid");
$Event = Event::find_one(array('Id'=>$_REQUEST['eid'])); $Event = ZM\Event::find_one(array('Id'=>$_REQUEST['eid']));
if ( !$Event ) { if ( !$Event ) {
header('HTTP/1.0 404 Not Found'); header('HTTP/1.0 404 Not Found');
Fatal('Event '.$_REQUEST['eid'].' Not found'); ZM\Fatal('Event '.$_REQUEST['eid'].' Not found');
return; return;
} }
@ -81,19 +81,19 @@ if ( empty($_REQUEST['path']) ) {
$path = $Event->Path().'/objdetect.jpg'; $path = $Event->Path().'/objdetect.jpg';
if ( !file_exists($path) ) { if ( !file_exists($path) ) {
header('HTTP/1.0 404 Not Found'); header('HTTP/1.0 404 Not Found');
Fatal("File $path does not exist. Please make sure store_frame_in_zm is enabled in the object detection config"); ZM\Fatal("File $path does not exist. Please make sure store_frame_in_zm is enabled in the object detection config");
} }
$Frame = new Frame(); $Frame = new ZM\Frame();
$Frame->Id('objdetect'); $Frame->Id('objdetect');
} else if ( $_REQUEST['fid'] == 'alarm' ) { } else if ( $_REQUEST['fid'] == 'alarm' ) {
# look for first alarmed frame # look for first alarmed frame
$Frame = Frame::find_one(array('EventId'=>$_REQUEST['eid'], 'Type'=>'Alarm'), $Frame = ZM\Frame::find_one(array('EventId'=>$_REQUEST['eid'], 'Type'=>'Alarm'),
array('order'=>'FrameId ASC')); array('order'=>'FrameId ASC'));
if ( !$Frame ) { # no alarms, get first one I find if ( !$Frame ) { # no alarms, get first one I find
$Frame = Frame::find_one(array('EventId'=>$_REQUEST['eid'])); $Frame = ZM\Frame::find_one(array('EventId'=>$_REQUEST['eid']));
if ( !$Frame ) { if ( !$Frame ) {
Warning('No frame found for event '.$_REQUEST['eid']); ZM\Warning('No frame found for event '.$_REQUEST['eid']);
$Frame = new Frame(); $Frame = new ZM\Frame();
$Frame->Delta(1); $Frame->Delta(1);
$Frame->FrameId(1); $Frame->FrameId(1);
} }
@ -106,12 +106,12 @@ if ( empty($_REQUEST['path']) ) {
$path = $Event->Path().'/alarm.jpg'; $path = $Event->Path().'/alarm.jpg';
} }
} else if ( $_REQUEST['fid'] == 'snapshot' ) { } else if ( $_REQUEST['fid'] == 'snapshot' ) {
$Frame = Frame::find_one(array('EventId'=>$_REQUEST['eid'], 'Score'=>$Event->MaxScore())); $Frame = ZM\Frame::find_one(array('EventId'=>$_REQUEST['eid'], 'Score'=>$Event->MaxScore()));
if ( !$Frame ) if ( !$Frame )
$Frame = Frame::find_one(array('EventId'=>$_REQUEST['eid'])); $Frame = ZM\Frame::find_one(array('EventId'=>$_REQUEST['eid']));
if ( !$Frame ) { if ( !$Frame ) {
Warning('No frame found for event ' . $_REQUEST['eid']); ZM\Warning('No frame found for event ' . $_REQUEST['eid']);
$Frame = new Frame(); $Frame = new ZM\Frame();
$Frame->Delta(1); $Frame->Delta(1);
$Frame->FrameId('snapshot'); $Frame->FrameId('snapshot');
} }
@ -124,7 +124,7 @@ if ( empty($_REQUEST['path']) ) {
} }
} else { } else {
$Frame = Frame::find_one(array('EventId'=>$_REQUEST['eid'], 'FrameId'=>$_REQUEST['fid'])); $Frame = ZM\Frame::find_one(array('EventId'=>$_REQUEST['eid'], 'FrameId'=>$_REQUEST['fid']));
if ( ! $Frame ) { if ( ! $Frame ) {
$previousBulkFrame = dbFetchOne( $previousBulkFrame = dbFetchOne(
'SELECT * FROM Frames WHERE EventId=? AND FrameId < ? ORDER BY FrameID DESC LIMIT 1', 'SELECT * FROM Frames WHERE EventId=? AND FrameId < ? ORDER BY FrameID DESC LIMIT 1',
@ -135,72 +135,72 @@ if ( empty($_REQUEST['path']) ) {
NULL, array($_REQUEST['eid'], $_REQUEST['fid']) NULL, array($_REQUEST['eid'], $_REQUEST['fid'])
); );
if ( $previousBulkFrame and $nextBulkFrame ) { if ( $previousBulkFrame and $nextBulkFrame ) {
$Frame = new Frame($previousBulkFrame); $Frame = new ZM\Frame($previousBulkFrame);
$Frame->FrameId($_REQUEST['fid']); $Frame->FrameId($_REQUEST['fid']);
$percentage = ($Frame->FrameId() - $previousBulkFrame['FrameId']) / ($nextBulkFrame['FrameId'] - $previousBulkFrame['FrameId']); $percentage = ($Frame->FrameId() - $previousBulkFrame['FrameId']) / ($nextBulkFrame['FrameId'] - $previousBulkFrame['FrameId']);
$Frame->Delta($previousBulkFrame['Delta'] + floor( 100* ( $nextBulkFrame['Delta'] - $previousBulkFrame['Delta'] ) * $percentage )/100); $Frame->Delta($previousBulkFrame['Delta'] + floor( 100* ( $nextBulkFrame['Delta'] - $previousBulkFrame['Delta'] ) * $percentage )/100);
Logger::Debug("Got virtual frame from Bulk Frames previous delta: " . $previousBulkFrame['Delta'] . " + nextdelta:" . $nextBulkFrame['Delta'] . ' - ' . $previousBulkFrame['Delta'] . ' * ' . $percentage ); ZM\Logger::Debug("Got virtual frame from Bulk Frames previous delta: " . $previousBulkFrame['Delta'] . " + nextdelta:" . $nextBulkFrame['Delta'] . ' - ' . $previousBulkFrame['Delta'] . ' * ' . $percentage );
} else { } else {
Fatal('No Frame found for event('.$_REQUEST['eid'].') and frame id('.$_REQUEST['fid'].')'); ZM\Fatal('No Frame found for event('.$_REQUEST['eid'].') and frame id('.$_REQUEST['fid'].')');
} }
} }
// Frame can be non-existent. We have Bulk frames. So now we should try to load the bulk frame // Frame can be non-existent. We have Bulk frames. So now we should try to load the bulk frame
$path = $Event->Path().'/'.sprintf('%0'.ZM_EVENT_IMAGE_DIGITS.'d',$Frame->FrameId()).'-'.$show.'.jpg'; $path = $Event->Path().'/'.sprintf('%0'.ZM_EVENT_IMAGE_DIGITS.'d',$Frame->FrameId()).'-'.$show.'.jpg';
Logger::Debug("Path: $path"); ZM\Logger::Debug("Path: $path");
} }
} else { } else {
# If we are only specifying fid, then the fid must be the primary key into the frames table. But when the event is specified, then it is the frame # # If we are only specifying fid, then the fid must be the primary key into the frames table. But when the event is specified, then it is the frame #
$Frame = Frame::find_one(array('Id'=>$_REQUEST['fid'])); $Frame = ZM\Frame::find_one(array('Id'=>$_REQUEST['fid']));
if ( !$Frame ) { if ( !$Frame ) {
header('HTTP/1.0 404 Not Found'); header('HTTP/1.0 404 Not Found');
Fatal('Frame ' . $_REQUEST['fid'] . ' Not Found'); ZM\Fatal('Frame ' . $_REQUEST['fid'] . ' Not Found');
return; return;
} }
$Event = Event::find_one(array('Id'=>$Frame->EventId())); $Event = ZM\Event::find_one(array('Id'=>$Frame->EventId()));
if ( !$Event ) { if ( !$Event ) {
header('HTTP/1.0 404 Not Found'); header('HTTP/1.0 404 Not Found');
Fatal('Event ' . $Frame->EventId() . ' Not Found'); ZM\Fatal('Event ' . $Frame->EventId() . ' Not Found');
return; return;
} }
$path = $Event->Path().'/'.sprintf('%0'.ZM_EVENT_IMAGE_DIGITS.'d',$Frame->FrameId()).'-'.$show.'.jpg'; $path = $Event->Path().'/'.sprintf('%0'.ZM_EVENT_IMAGE_DIGITS.'d',$Frame->FrameId()).'-'.$show.'.jpg';
} # end if have eid } # end if have eid
if ( !file_exists($path) ) { if ( !file_exists($path) ) {
Logger::Debug("$path does not exist"); ZM\Logger::Debug("$path does not exist");
# Generate the frame JPG # Generate the frame JPG
if ( ($show == 'capture') and $Event->DefaultVideo() ) { if ( ($show == 'capture') and $Event->DefaultVideo() ) {
if ( !file_exists($Event->Path().'/'.$Event->DefaultVideo()) ) { if ( !file_exists($Event->Path().'/'.$Event->DefaultVideo()) ) {
header('HTTP/1.0 404 Not Found'); header('HTTP/1.0 404 Not Found');
Fatal("Can't create frame images from video because there is no video file for this event at (".$Event->Path().'/'.$Event->DefaultVideo() ); ZM\Fatal("Can't create frame images from video because there is no video file for this event at (".$Event->Path().'/'.$Event->DefaultVideo() );
} }
$command ='ffmpeg -ss '. $Frame->Delta() .' -i '.$Event->Path().'/'.$Event->DefaultVideo().' -frames:v 1 '.$path; $command ='ffmpeg -ss '. $Frame->Delta() .' -i '.$Event->Path().'/'.$Event->DefaultVideo().' -frames:v 1 '.$path;
#$command ='ffmpeg -ss '. $Frame->Delta() .' -i '.$Event->Path().'/'.$Event->DefaultVideo().' -vf "select=gte(n\\,'.$Frame->FrameId().'),setpts=PTS-STARTPTS" '.$path; #$command ='ffmpeg -ss '. $Frame->Delta() .' -i '.$Event->Path().'/'.$Event->DefaultVideo().' -vf "select=gte(n\\,'.$Frame->FrameId().'),setpts=PTS-STARTPTS" '.$path;
#$command ='ffmpeg -v 0 -i '.$Storage->Path().'/'.$Event->Path().'/'.$Event->DefaultVideo().' -vf "select=gte(n\\,'.$Frame->FrameId().'),setpts=PTS-STARTPTS" '.$path; #$command ='ffmpeg -v 0 -i '.$Storage->Path().'/'.$Event->Path().'/'.$Event->DefaultVideo().' -vf "select=gte(n\\,'.$Frame->FrameId().'),setpts=PTS-STARTPTS" '.$path;
Logger::Debug("Running $command"); ZM\Logger::Debug("Running $command");
$output = array(); $output = array();
$retval = 0; $retval = 0;
exec( $command, $output, $retval ); exec( $command, $output, $retval );
Logger::Debug("Command: $command, retval: $retval, output: " . implode("\n", $output)); ZM\Logger::Debug("Command: $command, retval: $retval, output: " . implode("\n", $output));
if ( ! file_exists( $path ) ) { if ( ! file_exists( $path ) ) {
header('HTTP/1.0 404 Not Found'); header('HTTP/1.0 404 Not Found');
Fatal("Can't create frame images from video for this event (".$Event->DefaultVideo() ); ZM\Fatal("Can't create frame images from video for this event (".$Event->DefaultVideo() );
} }
# Generating an image file will use up more disk space, so update the Event record. # Generating an image file will use up more disk space, so update the Event record.
$Event->DiskSpace(null); $Event->DiskSpace(null);
$Event->save(); $Event->save();
} else { } else {
header('HTTP/1.0 404 Not Found'); header('HTTP/1.0 404 Not Found');
Fatal("Can't create frame $show images from video because there is no video file for this event at ". ZM\Fatal("Can't create frame $show images from video because there is no video file for this event at ".
$Event->Path().'/'.$Event->DefaultVideo() ); $Event->Path().'/'.$Event->DefaultVideo() );
} }
} # end if ! file_exists($path) } # end if ! file_exists($path)
} else { } else {
Warning('Loading images by path is deprecated'); ZM\Warning('Loading images by path is deprecated');
$dir_events = realpath(ZM_DIR_EVENTS); $dir_events = realpath(ZM_DIR_EVENTS);
$path = realpath($dir_events . '/' . $_REQUEST['path']); $path = realpath($dir_events . '/' . $_REQUEST['path']);
$pos = strpos($path, $dir_events); $pos = strpos($path, $dir_events);
@ -223,7 +223,7 @@ if ( empty($_REQUEST['path']) ) {
} }
if ( !file_exists($path) ) { if ( !file_exists($path) ) {
header('HTTP/1.0 404 Not Found'); header('HTTP/1.0 404 Not Found');
Fatal("Image not found at $path"); ZM\Fatal("Image not found at $path");
} }
} }
@ -239,7 +239,7 @@ if ( !empty($_REQUEST['scale']) ) {
$width = 0; $width = 0;
if ( !empty($_REQUEST['width']) ) { if ( !empty($_REQUEST['width']) ) {
Logger::Debug("Setting width: " . $_REQUEST['width']); ZM\Logger::Debug("Setting width: " . $_REQUEST['width']);
if ( is_numeric($_REQUEST['width']) ) { if ( is_numeric($_REQUEST['width']) ) {
$x = $_REQUEST['width']; $x = $_REQUEST['width'];
if ( $x >= 10 and $x <= 8000 ) if ( $x >= 10 and $x <= 8000 )
@ -257,7 +257,7 @@ if ( !empty($_REQUEST['height']) ) {
} }
if ( $errorText ) { if ( $errorText ) {
Error($errorText); ZM\Error($errorText);
} else { } else {
# Clears the output buffer. Not sure what is there, but have had troubles. # Clears the output buffer. Not sure what is there, but have had troubles.
ob_end_clean(); ob_end_clean();
@ -269,10 +269,10 @@ if ( $errorText ) {
header('Content-Disposition: inline; filename="' . $filename . '"'); header('Content-Disposition: inline; filename="' . $filename . '"');
} }
if ( !readfile($path) ) { if ( !readfile($path) ) {
Error('No bytes read from '. $path); ZM\Error('No bytes read from '. $path);
} }
} else { } else {
Logger::Debug("Doing a scaled image: scale($scale) width($width) height($height)"); ZM\Logger::Debug("Doing a scaled image: scale($scale) width($width) height($height)");
$i = 0; $i = 0;
if ( ! ( $width && $height ) ) { if ( ! ( $width && $height ) ) {
$i = imagecreatefromjpeg($path); $i = imagecreatefromjpeg($path);
@ -285,10 +285,10 @@ if ( $errorText ) {
$width = ($height * $oldWidth) / $oldHeight; $width = ($height * $oldWidth) / $oldHeight;
} elseif ( $width != 0 && $height == 0 ) { } elseif ( $width != 0 && $height == 0 ) {
$height = ($width * $oldHeight) / $oldWidth; $height = ($width * $oldHeight) / $oldWidth;
Logger::Debug("Figuring out height using width: $height = ($width * $oldHeight) / $oldWidth"); ZM\Logger::Debug("Figuring out height using width: $height = ($width * $oldHeight) / $oldWidth");
} }
if ( $width == $oldWidth && $height == $oldHeight ) { if ( $width == $oldWidth && $height == $oldHeight ) {
Warning('No change to width despite scaling.'); ZM\Warning('No change to width despite scaling.');
} }
} }
@ -299,7 +299,7 @@ Logger::Debug("Figuring out height using width: $height = ($width * $oldHeight)
header('Content-Disposition: inline; filename="' . $filename . '"'); header('Content-Disposition: inline; filename="' . $filename . '"');
} }
if ( !( file_exists($scaled_path) and readfile($scaled_path) ) ) { if ( !( file_exists($scaled_path) and readfile($scaled_path) ) ) {
Logger::Debug("Cached scaled image does not exist at $scaled_path or is no good.. Creating it"); ZM\Logger::Debug("Cached scaled image does not exist at $scaled_path or is no good.. Creating it");
ob_start(); ob_start();
if ( !$i ) if ( !$i )
$i = imagecreatefromjpeg($path); $i = imagecreatefromjpeg($path);
@ -312,12 +312,12 @@ Logger::Debug("Figuring out height using width: $height = ($width * $oldHeight)
ob_end_clean(); ob_end_clean();
echo $scaled_jpeg_data; echo $scaled_jpeg_data;
} else { } else {
Logger::Debug("Sending $scaled_path"); ZM\Logger::Debug("Sending $scaled_path");
$bytes = readfile($scaled_path); $bytes = readfile($scaled_path);
if ( !$bytes ) { if ( !$bytes ) {
Error('No bytes read from '. $scaled_path); ZM\Error('No bytes read from '. $scaled_path);
} else { } else {
Logger::Debug("$bytes sent"); ZM\Logger::Debug("$bytes sent");
} }
} }
} }

View File

@ -38,19 +38,19 @@ $path = '';
$Event = null; $Event = null;
if ( ! empty($_REQUEST['eid']) ) { if ( ! empty($_REQUEST['eid']) ) {
$Event = new Event($_REQUEST['eid']); $Event = new ZM\Event($_REQUEST['eid']);
$path = $Event->Path().'/'.$Event->DefaultVideo(); $path = $Event->Path().'/'.$Event->DefaultVideo();
Logger::Debug("Path: $path"); ZM\Logger::Debug("Path: $path");
} else if ( ! empty($_REQUEST['event_id']) ) { } else if ( ! empty($_REQUEST['event_id']) ) {
$Event = new Event($_REQUEST['event_id']); $Event = new ZM\Event($_REQUEST['event_id']);
$path = $Event->Path().'/'.$Event->DefaultVideo(); $path = $Event->Path().'/'.$Event->DefaultVideo();
Logger::Debug("Path: $path"); ZM\Logger::Debug("Path: $path");
} else { } else {
$errorText = 'No video path'; $errorText = 'No video path';
} }
if ( $errorText ) { if ( $errorText ) {
Error($errorText); ZM\Error($errorText);
header('HTTP/1.0 404 Not Found'); header('HTTP/1.0 404 Not Found');
die(); die();
} }
@ -68,14 +68,14 @@ $end = $size-1;
$length = $size; $length = $size;
if ( isset($_SERVER['HTTP_RANGE']) ) { if ( isset($_SERVER['HTTP_RANGE']) ) {
Logger::Debug('Using Range ' . $_SERVER['HTTP_RANGE']); ZM\Logger::Debug('Using Range ' . $_SERVER['HTTP_RANGE']);
if ( preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches) ) { if ( preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches) ) {
$begin = intval($matches[1]); $begin = intval($matches[1]);
if ( ! empty($matches[2]) ) { if ( ! empty($matches[2]) ) {
$end = intval($matches[2]); $end = intval($matches[2]);
} }
$length = $end - $begin + 1; $length = $end - $begin + 1;
Logger::Debug("Using Range $begin $end size: $size, length: $length"); ZM\Logger::Debug("Using Range $begin $end size: $size, length: $length");
} }
} # end if HTTP_RANGE } # end if HTTP_RANGE