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

View File

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

View File

@ -1,6 +1,5 @@
<?php
if ( canEdit( 'Monitors' ) ) {
if ( canEdit('Monitors') ) {
switch ( $_REQUEST['action'] ) {
case 'sort' :
{
@ -8,15 +7,15 @@ if ( canEdit( 'Monitors' ) ) {
# Two concurrent sorts could generate odd sortings... so lock the table.
global $dbConn;
$dbConn->beginTransaction();
$dbConn->exec( 'LOCK TABLES Monitors WRITE' );
$dbConn->exec('LOCK TABLES Monitors WRITE');
for ( $i = 0; $i < count($monitor_ids); $i += 1 ) {
$monitor_id = $monitor_ids[$i];
$monitor_id = preg_replace( '/^monitor_id-/', '', $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;
}
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
$dbConn->commit();
$dbConn->exec('UNLOCK TABLES');
@ -25,13 +24,12 @@ if ( canEdit( 'Monitors' ) ) {
} // end case sort
default:
{
Warning("unknown action " . $_REQUEST['action'] );
ZM\Warning('unknown action ' . $_REQUEST['action']);
} // end ddcase default
}
} 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'] ) )
{
$monitor = new Monitor( $_REQUEST['id'] );
$monitor = new ZM\Monitor( $_REQUEST['id'] );
$ctrlCommand = buildControlCommand( $monitor );

View File

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

View File

@ -9,7 +9,7 @@ switch ( $_REQUEST['task'] ) {
{
// Silently ignore bogus requests
if ( !empty($_POST['level']) && !empty($_POST['message']) ) {
logInit(array('id'=>'web_js'));
ZM\logInit(array('id'=>'web_js'));
$string = $_POST['message'];
@ -21,9 +21,9 @@ switch ( $_REQUEST['task'] ) {
$levels = array_flip(Logger::$codes);
if ( !isset($levels[$_POST['level']]) )
Panic("Unexpected logger level '".$_POST['level']."'");
ZM\Panic("Unexpected logger level '".$_POST['level']."'");
$level = $levels[$_POST['level']];
Logger::fetch()->logPrint($level, $string, $file, $line);
ZM\Logger::fetch()->logPrint($level, $string, $file, $line);
}
ajaxResponse();
break;
@ -33,7 +33,7 @@ switch ( $_REQUEST['task'] ) {
if ( !canView('System') )
ajaxError('Insufficient permissions to view log entries');
$servers = Server::find();
$servers = ZM\Server::find();
$servers_by_Id = array();
# There is probably a better way to do this.
foreach ( $servers as $server ) {
@ -46,7 +46,7 @@ switch ( $_REQUEST['task'] ) {
$limit = 100;
if ( isset($_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 {
$limit = $_REQUEST['limit'];
}
@ -54,7 +54,7 @@ switch ( $_REQUEST['task'] ) {
$sortField = 'TimeKey';
if ( isset($_REQUEST['sortField']) ) {
if ( !in_array($_REQUEST['sortField'], $filterFields) and ( $_REQUEST['sortField'] != 'TimeKey' ) ) {
Error("Invalid sort field " . $_REQUEST['sortField']);
ZM\Error("Invalid sort field " . $_REQUEST['sortField']);
} else {
$sortField = $_REQUEST['sortField'];
}
@ -76,7 +76,7 @@ switch ( $_REQUEST['task'] ) {
foreach ( $filter as $field=>$value ) {
if ( ! in_array($field, $filterFields) ) {
Error("$field is not in valid filter fields");
ZM\Error("$field is not in valid filter fields");
continue;
}
if ( $field == 'Level' ){
@ -105,8 +105,8 @@ switch ( $_REQUEST['task'] ) {
$value = $log[$field];
if ( $field == 'Level' ) {
if ( $value <= Logger::INFO )
$options[$field][$value] = Logger::$codes[$value];
if ( $value <= ZM\Logger::INFO )
$options[$field][$value] = ZM\Logger::$codes[$value];
else
$options[$field][$value] = 'DB'.$value;
} else if ( $field == 'ServerId' ) {
@ -146,14 +146,14 @@ switch ( $_REQUEST['task'] ) {
$sortField = 'TimeKey';
if ( isset($_POST['sortField']) ) {
if ( ! in_array( $_POST['sortField'], $filterFields ) and ( $_POST['sortField'] != 'TimeKey' ) ) {
Error("Invalid sort field " . $_POST['sortField'] );
ZM\Error("Invalid sort field " . $_POST['sortField'] );
} else {
$sortField = $_POST['sortField'];
}
}
$sortOrder = (isset($_POST['sortOrder']) and $_POST['sortOrder']) == 'asc' ? 'asc':'desc';
$servers = Server::find();
$servers = ZM\Server::find();
$servers_by_Id = array();
# There is probably a better way to do this.
foreach ( $servers as $server ) {
@ -164,11 +164,11 @@ switch ( $_REQUEST['task'] ) {
$where = array();
$values = array();
if ( $minTime ) {
Logger::Debug("MinTime: $minTime");
ZM\Logger::Debug("MinTime: $minTime");
if ( preg_match('/(.+)(\.\d+)/', $minTime, $matches) ) {
# This handles sub second precision
$minTime = strtotime($matches[1]).$matches[2];
Logger::Debug("MinTime: $minTime");
ZM\Logger::Debug("MinTime: $minTime");
} else {
$minTime = strtotime($minTime);
}
@ -214,27 +214,27 @@ switch ( $_REQUEST['task'] ) {
$exportExt = 'xml';
break;
default :
Fatal("Unrecognised log export format '$format'");
ZM\Fatal("Unrecognised log export format '$format'");
}
$exportKey = substr(md5(rand()),0,8);
$exportFile = "zm-log.$exportExt";
if ( ! file_exists(ZM_DIR_EXPORTS) ) {
Logger::Debug('Creating ' . ZM_DIR_EXPORTS);
ZM\Logger::Debug('Creating ' . 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";
Logger::Debug("Exporting to $exportPath");
ZM\Logger::Debug("Exporting to $exportPath");
if ( !($exportFP = fopen($exportPath, 'w')) )
Fatal("Unable to open log export file $exportPath");
ZM\Fatal("Unable to open log export file $exportPath");
$logs = array();
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['Server'] = ( $log['ServerId'] and isset($servers_by_Id[$log['ServerId']]) ) ? $servers_by_Id[$log['ServerId']]->Name() : '';
$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 ) {
case 'text' :
@ -318,10 +318,10 @@ switch ( $_REQUEST['task'] ) {
' );
foreach ( $logs as $log ) {
$classLevel = $log['Level'];
if ( $classLevel < Logger::FATAL )
$classLevel = Logger::FATAL;
elseif ( $classLevel > Logger::DEBUG )
$classLevel = Logger::DEBUG;
if ( $classLevel < ZM\Logger::FATAL )
$classLevel = ZM\Logger::FATAL;
elseif ( $classLevel > ZM\Logger::DEBUG )
$classLevel = ZM\Logger::DEBUG;
$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'] );
}
@ -384,10 +384,10 @@ switch ( $_REQUEST['task'] ) {
ajaxError('Insufficient permissions to download logs');
if ( empty($_REQUEST['key']) )
Fatal('No log export key given');
ZM\Fatal('No log export key given');
$exportKey = $_REQUEST['key'];
if ( empty($_REQUEST['format']) )
Fatal('No log export format given');
ZM\Fatal('No log export format given');
$format = $_REQUEST['format'];
switch( $format ) {
@ -404,7 +404,7 @@ switch ( $_REQUEST['task'] ) {
$exportExt = 'xml';
break;
default :
Fatal("Unrecognised log export format '$format'");
ZM\Fatal("Unrecognised log export format '$format'");
}
$exportFile = "zm-log.$exportExt";

View File

@ -284,7 +284,7 @@ function collectData() {
if ( in_array($matches[1], $fieldSql) ) {
$sql .= $matches[1];
} else {
Error('Sort field ' . $matches[1] . ' not in SQL Fields');
ZM\Error('Sort field ' . $matches[1] . ' not in SQL Fields');
}
if ( count($matches) > 2 ) {
$sql .= ' '.strtoupper($matches[2]);
@ -292,7 +292,7 @@ function collectData() {
$sql .= ' '.strtoupper($matches[3]);
}
} 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 if has sort
@ -323,7 +323,7 @@ function collectData() {
}
}
}
#Logger::Debug(print_r($data, true));
#ZM\Logger::Debug(print_r($data, true));
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';
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.
}
if ( ! socket_bind( $socket, $localSocketFile ) ) {
@ -29,23 +29,23 @@ if ( sem_acquire($semaphore,1) !== false ) {
switch ( $_REQUEST['command'] ) {
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 );
break;
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'] );
break;
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'] );
break;
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'] );
break;
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'] );
break;
default :
@ -81,18 +81,18 @@ if ( sem_acquire($semaphore,1) !== false ) {
$numSockets = socket_select( $rSockets, $wSockets, $eSockets, intval($timeout/1000), ($timeout%1000)*1000 );
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()) );
} else if ( $numSockets < 0 ) {
Error( "Socket closed $remSockFile" );
ZM\Error( "Socket closed $remSockFile" );
ajaxError( "Socket closed $remSockFile" );
} else if ( $numSockets == 0 ) {
Error( "Timed out waiting for msg $remSockFile" );
ZM\Error( "Timed out waiting for msg $remSockFile" );
socket_Set_nonblock($socket);
#ajaxError( "Timed out waiting for msg $remSockFile" );
} else if ( $numSockets > 0 ) {
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' );
}
}
@ -122,9 +122,9 @@ if ( sem_acquire($semaphore,1) !== false ) {
case MSG_DATA_WATCH :
{
$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 );
Logger::Debug("FPS: " . $data['fps'] );
ZM\Logger::Debug("FPS: " . $data['fps'] );
$data['rate'] /= RATE_BASE;
$data['delay'] = round( $data['delay'], 2 );
$data['zoom'] = round( $data['zoom']/SCALE_BASE, 1 );
@ -161,7 +161,7 @@ if ( sem_acquire($semaphore,1) !== false ) {
}
sem_release($semaphore);
} else {
Logger::Debug("Couldn't get semaphore");
ZM\Logger::Debug("Couldn't get semaphore");
ajaxResponse( array() );
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -20,7 +20,7 @@
if ( $action == 'delete' ) {
if ( ! canEdit('Monitors') ) {
Warning("No permission to delete monitors");
ZM\Warning('No permission to delete monitors');
return;
}
@ -30,7 +30,7 @@ if ( $action == 'delete' ) {
if ( canEdit('Monitors', $markMid) ) {
// This could be faster as a select all
if ( $monitor = dbFetchOne('SELECT * FROM Monitors WHERE Id = ?', NULL, array($markMid)) ) {
$Monitor = new Monitor($monitor);
$Monitor = new ZM\Monitor($monitor);
$Monitor->delete();
} // end if monitor found in db
} // 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
if ( empty($_REQUEST['mid']) ) {
Warning("Settings requires a monitor id");
ZM\Warning('Settings requires a monitor id');
return;
}
if ( ! canView('Control', $_REQUEST['mid']) ) {
Warning("Settings requires the Control permission");
ZM\Warning('Settings requires the Control permission');
return;
}
@ -32,7 +32,7 @@ require_once('control_functions.php');
require_once('Monitor.php');
$mid = validInt($_REQUEST['mid']);
if ( $action == 'control' ) {
$monitor = new Monitor($mid);
$monitor = new ZM\Monitor($mid);
$ctrlCommand = buildControlCommand($monitor);
sendControlCommand($monitor->Id(), $ctrlCommand);

View File

@ -20,13 +20,13 @@
if ( !canEdit('Control') ) {
Warning("Need Control permissions to edit control capabilities");
ZM\Warning('Need Control permissions to edit control capabilities');
return;
} // end if !canEdit Controls
if ( $action == 'controlcap' ) {
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 );
$Control->save($_REQUEST['newControl']);

View File

@ -20,16 +20,15 @@
if ( !canEdit('Control') ) {
Warning("Need Control permissions to edit control capabilities");
ZM\Warning('Need Control permissions to edit control capabilities');
return;
} // end if !canEdit Controls
}
if ( $action == 'delete' ) {
if ( isset($_REQUEST['markCids']) ) {
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('DELETE FROM Controls WHERE Id = ?', array($markCid));
$refreshParent = true;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -22,7 +22,7 @@
# 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
if ( ! canEdit('Groups') ) {
Warning("Need group edit permissions to edit groups");
ZM\Warning('Need group edit permissions to edit groups');
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.
# However at the moment, you have to have System permissions to do this
if ( ! canEdit('Groups') ) {
Warning("Need group edit permissions to edit groups");
ZM\Warning('Need group edit permissions to edit groups');
return;
}
if ( $action == 'delete' ) {
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();
}
}

View File

@ -25,10 +25,10 @@ if ( isset($_REQUEST['object']) and $_REQUEST['object'] == 'Monitor' ) {
foreach ( $_REQUEST['mids'] as $mid ) {
$mid = ValidInt($mid);
if ( ! canEdit('Monitors', $mid) ) {
Warning("Cannot edit monitor $mid");
ZM\Warning("Cannot edit monitor $mid");
continue;
}
$Monitor = new Monitor($mid);
$Monitor = new ZM\Monitor($mid);
if ( $Monitor->Type() != 'WebSite' ) {
$Monitor->zmaControl('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
if ( ! canEdit('Monitors') ) {
Warning("Monitor actions require Monitors Permissions");
ZM\Warning("Monitor actions require Monitors Permissions");
return;
}
@ -68,7 +68,7 @@ if ( $action == 'monitor' ) {
$x10Monitor = array();
}
}
$Monitor = new Monitor($monitor);
$Monitor = new ZM\Monitor($monitor);
// Define a field type for anything that's not simple text equivalent
$types = array(
@ -86,10 +86,10 @@ if ( $action == 'monitor' ) {
if ( $_REQUEST['newMonitor']['ServerId'] == 'auto' ) {
$_REQUEST['newMonitor']['ServerId'] = dbFetchOne(
'SELECT Id FROM Servers WHERE Status=\'Running\' ORDER BY FreeMem DESC, CpuLoad ASC LIMIT 1', 'Id');
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') ) {
$_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));
// Groups will be added below
if ( isset($changes['Name']) or isset($changes['StorageId']) ) {
$OldStorage = new Storage($monitor['StorageId']);
$OldStorage = new ZM\Storage($monitor['StorageId']);
$saferOldName = basename($monitor['Name']);
if ( file_exists($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) )
mkdir($NewStorage->Path().'/'.$mid, 0755);
$saferNewName = basename($_REQUEST['newMonitor']['Name']);
@ -164,24 +164,24 @@ if ( $action == 'monitor' ) {
$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) ) );
//$view = 'none';
$Storage = new Storage($_REQUEST['newMonitor']['StorageId']);
$Storage = new ZM\Storage($_REQUEST['newMonitor']['StorageId']);
mkdir($Storage->Path().'/'.$mid, 0755);
$saferName = basename($_REQUEST['newMonitor']['Name']);
symlink($mid, $Storage->Path().'/'.$saferName);
} else {
Error('Error saving new Monitor.');
ZM\Error('Error saving new Monitor.');
$error_message = dbError($sql);
return;
}
} else {
Error('Users with Monitors restrictions cannot create new monitors.');
ZM\Error('Users with Monitors restrictions cannot create new monitors.');
return;
}
$restart = true;
} 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)
if (
@ -220,7 +220,7 @@ if ( $action == 'monitor' ) {
if ( $restart ) {
$new_monitor = new Monitor($mid);
$new_monitor = new ZM\Monitor($mid);
//fixDevices();
if ( $new_monitor->Type() != 'WebSite' ) {
@ -238,6 +238,6 @@ if ( $action == 'monitor' ) {
} // end if restart
$view = 'none';
} else {
Warning("Unknown action $action in Monitor");
ZM\Warning("Unknown action $action in Monitor");
} // end if action == Delete
?>

View File

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

View File

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

View File

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

View File

@ -20,7 +20,7 @@
// System edit actions
if ( ! canEdit('System') ) {
Warning("Need System permissions to add servers");
ZM\Warning('Need System permissions to add servers');
return;
}
@ -48,6 +48,6 @@ if ( $action == 'Save' ) {
}
$view = 'none';
} 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
if ( empty($_REQUEST['mid']) ) {
Warning("Settings requires a monitor id");
ZM\Warning('Settings requires a monitor id');
return;
}
if ( ! canView('Control', $_REQUEST['mid']) ) {
Warning("Settings requires the Control permission");
ZM\Warning('Settings requires the Control permission');
return;
}

View File

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

View File

@ -20,7 +20,7 @@
// System edit actions
if ( ! canEdit('System') ) {
Warning("Need System permission to edit Storage");
ZM\Warning('Need System permission to edit Storage');
return;
}
@ -43,7 +43,7 @@ if ( $action == 'Save' ) {
}
$view = 'none';
} 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
if ( !canEdit('System') ) {
Warning("Need System permissions to update version");
ZM\Warning('Need System permissions to update version');
return;
}
if ( $action == 'version' && isset($_REQUEST['option']) ) {

View File

@ -20,7 +20,7 @@
if ( !empty($_REQUEST['mid']) && canEdit('Monitors', $_REQUEST['mid']) ) {
$mid = validInt($_REQUEST['mid']);
$monitor = new Monitor($mid);
$monitor = new ZM\Monitor($mid);
if ( $action == 'delete' ) {
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
if ( $dbUser = dbFetchOne($sql, NULL, $sql_values) ) {
Info("Login successful for user \"$username\"");
ZM\Info("Login successful for user \"$username\"");
$_SESSION['user'] = $user = $dbUser;
unset($_SESSION['loginFailed']);
if ( ZM_AUTH_TYPE == 'builtin' ) {
@ -95,7 +95,7 @@ function userLogin($username='', $password='', $passwordHashed=false) {
}
session_regenerate_id();
} else {
Warning("Login denied for user \"$username\"");
ZM\Warning("Login denied for user \"$username\"");
$_SESSION['loginFailed'] = true;
unset($user);
}
@ -106,7 +106,7 @@ function userLogin($username='', $password='', $passwordHashed=false) {
function userLogout() {
global $user;
Info('User "'.$user['Username'].'" logged out');
ZM\Info('User "'.$user['Username'].'" logged out');
session_start();
unset($_SESSION['user']);
unset($user);
@ -119,7 +119,7 @@ function getAuthUser($auth) {
if ( ZM_AUTH_HASH_IPS ) {
$remoteAddr = $_SERVER['REMOTE_ADDR'];
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 = '';
}
}
@ -145,7 +145,7 @@ function getAuthUser($auth) {
} // end foreach hour
} // end foreach user
} // 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;
} // end getAuthUser($auth)
@ -213,7 +213,7 @@ function is_session_started() {
return session_id() === '' ? FALSE : TRUE;
}
} else {
Warning("php_sapi_name === 'cli'");
ZM\Warning("php_sapi_name === 'cli'");
}
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( 'logger.php' );
loadConfig();
Logger::fetch()->initialise();
ZM\Logger::fetch()->initialise();
$GLOBALS['defaultUser'] = array(
'Username' => 'admin',

View File

@ -93,7 +93,7 @@ function dbLog( $sql, $update=false ) {
global $dbLogLevel;
$noExecute = $update && ($dbLogLevel >= DB_LOG_DEBUG);
if ( $dbLogLevel > DB_LOG_OFF )
Logger::Debug( "SQL-LOG: $sql".($noExecute?" (not executed)":"") );
ZM\Logger::Debug( "SQL-LOG: $sql".($noExecute?" (not executed)":"") );
return( $noExecute );
}
@ -104,7 +104,7 @@ function dbError( $sql ) {
return '';
$message = "SQL-ERR '".implode("\n",$dbConn->errorInfo())."', statement was '".$sql."'";
Error($message);
ZM\Error($message);
return $message;
}
@ -130,32 +130,32 @@ function dbQuery( $sql, $params=NULL ) {
try {
if ( isset($params) ) {
if ( ! $result = $dbConn->prepare( $sql ) ) {
Error("SQL: Error preparing $sql: " . $pdo->errorInfo);
ZM\Error("SQL: Error preparing $sql: " . $pdo->errorInfo);
return NULL;
}
if ( ! $result->execute( $params ) ) {
Error("SQL: Error executing $sql: " . implode(',', $result->errorInfo() ) );
ZM\Error("SQL: Error executing $sql: " . implode(',', $result->errorInfo() ) );
return NULL;
}
} else {
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);
if ( ! $result ) {
Error("SQL: Error preparing $sql: " . $pdo->errorInfo);
ZM\Error("SQL: Error preparing $sql: " . $pdo->errorInfo);
return NULL;
}
}
if ( defined('ZM_DB_DEBUG') ) {
if ( $params )
Logger::Debug("SQL: $sql" . implode(',',$params) . ' rows: '.$result->rowCount() );
ZM\Logger::Debug("SQL: $sql" . implode(',',$params) . ' rows: '.$result->rowCount() );
else
Logger::Debug("SQL: $sql: rows:" . $result->rowCount() );
ZM\Logger::Debug("SQL: $sql: rows:" . $result->rowCount() );
}
} 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 $result;
@ -164,7 +164,7 @@ function dbQuery( $sql, $params=NULL ) {
function dbFetchOne( $sql, $col=false, $params=NULL ) {
$result = dbQuery( $sql, $params );
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;
}
if ( ! $result->rowCount() ) {
@ -175,7 +175,7 @@ function dbFetchOne( $sql, $col=false, $params=NULL ) {
if ( $result && $dbRow = $result->fetch(PDO::FETCH_ASSOC) ) {
if ( $col ) {
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];
}
@ -187,7 +187,7 @@ function dbFetchOne( $sql, $col=false, $params=NULL ) {
function dbFetchAll( $sql, $col=false, $params=NULL ) {
$result = dbQuery( $sql, $params );
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;
}
@ -294,7 +294,7 @@ function getTableDescription( $table, $asString=1 ) {
//$desc['minLength'] = -128;
break;
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;
}
} elseif ( preg_match( "/^(enum|set)\((.*)\)$/", $row['Type'], $matches ) ) {
@ -326,7 +326,7 @@ function getTableDescription( $table, $asString=1 ) {
//$desc['maxValue'] = 127;
break;
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;
}
if ( !empty($matches[1]) )
@ -361,7 +361,7 @@ function getTableDescription( $table, $asString=1 ) {
break;
}
} 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 )

View File

@ -90,12 +90,12 @@ function CORSHeaders() {
# The following is left for future reference/use.
$valid = false;
$Servers = Server::find();
$Servers = ZM\Server::find();
if ( sizeof($Servers) < 1 ) {
# Only need CORSHeaders in the event that there are multiple servers in use.
# ICON: Might not be true. multi-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-Headers: x-requested-with,x-request');
}
@ -108,14 +108,14 @@ function CORSHeaders() {
preg_match('/^(https?:\/\/)?'.preg_quote($Server->Name(),'/').'/i', $_SERVER['HTTP_ORIGIN'])
) {
$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-Headers: x-requested-with,x-request');
break;
}
}
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 ) {
$Event = new Event( $event );
$Event = new ZM\Event( $event );
return $Event->getStreamSrc( array( 'mode'=>'mpeg', 'format'=>'h264' ) );
}
@ -424,15 +424,15 @@ function deletePath( $path ) {
function deleteEvent( $event ) {
if ( empty($event) ) {
Error( 'Empty event passed to deleteEvent.');
ZM\Error('Empty event passed to deleteEvent.');
return;
}
if ( gettype($event) != 'array' ) {
# $event could be an eid, so turn it into an event hash
$event = new Event( $event );
$event = new ZM\Event( $event );
} else {
Logger::Debug("Event type: " . gettype($event));
ZM\Logger::Debug("Event type: " . gettype($event));
}
global $user;
@ -527,7 +527,7 @@ function htmlOptions($contents, $values) {
if ( isset($option['disabled']) ) {
$disabled = $option['disabled'];
Error("Setting to disabled");
ZM\Error("Setting to disabled");
}
} else if ( is_object($option) ) {
$text = $option->Name();
@ -556,7 +556,7 @@ function buildSelect( $name, $contents, $behaviours=false ) {
elseif ( isset($_REQUEST[$arr]) )
$value = $_REQUEST[$arr];
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++ ) {
$idx = $matches[1][$i];
@ -833,17 +833,17 @@ function daemonControl( $command, $daemon=false, $args=false ) {
}
$string = escapeshellcmd( $string );
#$string .= ' 2>/dev/null >&- <&- >/dev/null';
Logger::Debug("daemonControl $string");
ZM\Logger::Debug("daemonControl $string");
exec( $string );
}
function zmcControl($monitor, $mode=false) {
$Monitor = new Monitor( $monitor );
$Monitor = new ZM\Monitor( $monitor );
return $Monitor->zmcControl($mode);
}
function zmaControl($monitor, $mode=false) {
$Monitor = new Monitor($monitor);
$Monitor = new ZM\Monitor($monitor);
return $Monitor->zmaControl($mode);
}
@ -916,7 +916,7 @@ function zmaCheck( $monitor ) {
}
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 );
}
@ -940,7 +940,7 @@ function createListThumbnail( $event, $overwrite=false ) {
$scale = (SCALE_BASE*ZM_WEB_LIST_THUMB_HEIGHT)/$event['Height'];
$thumbWidth = reScale( $event['Width'], $scale );
} 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 );
@ -1196,11 +1196,11 @@ function parseFilter(&$filter, $saveToSession=false, $querySep='&amp;') {
if ( ! $StorageArea ) {
for ( $j = 0; $j < count($terms); $j++ ) {
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;
}
} // end foreach remaining term
if ( ! $StorageArea ) $StorageArea = new Storage();
if ( ! $StorageArea ) $StorageArea = new ZM\Storage();
} // end no StorageArea found yet
$filter['sql'] .= getDiskPercent( $StorageArea->Path() );
@ -1210,7 +1210,7 @@ function parseFilter(&$filter, $saveToSession=false, $querySep='&amp;') {
if ( ! $StorageArea ) {
for ( $j = $i; $j < count($terms); $j++ ) {
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 no StorageArea found yet
@ -1242,7 +1242,7 @@ function parseFilter(&$filter, $saveToSession=false, $querySep='&amp;') {
}
break;
case 'StorageId':
$StorageArea = new Storage( $value );
$StorageArea = new ZM\Storage( $value );
if ( $value != 'NULL' )
$value = dbEscape($value);
break;
@ -1462,7 +1462,7 @@ function getDiskPercent($path = ZM_DIR_EVENTS) {
}
function getDiskBlocks() {
if ( ! $StorageArea ) $StorageArea = new Storage();
if ( ! $StorageArea ) $StorageArea = new ZM\Storage();
$df = shell_exec( 'df '.escapeshellarg($StorageArea->Path() ));
$space = -1;
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 ) {
foreach ( $points as &$point ) {
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;
} 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;
}
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;
} 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;
}
} // end foreach point
@ -1912,13 +1912,13 @@ function initX10Status() {
if ( !isset($x10_status) ) {
$socket = socket_create( AF_UNIX, SOCK_STREAM, 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';
if ( @socket_connect( $socket, $sock_file ) ) {
$command = 'status';
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 );
$x10Output = '';
@ -1954,13 +1954,13 @@ function getDeviceStatusX10( $key ) {
function setDeviceStatusX10( $key, $status ) {
$socket = socket_create( AF_UNIX, SOCK_STREAM, 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';
if ( @socket_connect( $socket, $sock_file ) ) {
$command = "$status;$key";
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 );
$x10Response = socket_read( $socket, 256 );
@ -1983,18 +1983,18 @@ function logState() {
$state = 'ok';
$levelCounts = array(
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 ),
Logger::WARNING => array( ZM_LOG_ALERT_WAR_COUNT, ZM_LOG_ALARM_WAR_COUNT ),
ZM\Logger::FATAL => array( ZM_LOG_ALERT_FAT_COUNT, ZM_LOG_ALARM_FAT_COUNT ),
ZM\Logger::ERROR => array( ZM_LOG_ALERT_ERR_COUNT, ZM_LOG_ALARM_ERR_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
$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);
if ( $counts ) {
foreach ( $counts as $count ) {
if ( $count['Level'] <= Logger::PANIC )
$count['Level'] = Logger::FATAL;
if ( $count['Level'] <= ZM\Logger::PANIC )
$count['Level'] = ZM\Logger::FATAL;
if ( !($levelCount = $levelCounts[$count['Level']]) ) {
Error('Unexpected Log level '.$count['Level']);
next;
@ -2026,15 +2026,15 @@ function checkJsonError($value) {
$value = var_export($value,true);
switch( json_last_error() ) {
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 :
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 :
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 :
Fatal( "Unable to decode JSON string '$value', syntax error" );
ZM\Fatal( "Unable to decode JSON string '$value', syntax error" );
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:
break;
}
@ -2122,7 +2122,7 @@ define( 'HTTP_STATUS_BAD_REQUEST', 400 );
define( 'HTTP_STATUS_FORBIDDEN', 403 );
function ajaxError( $message, $code=HTTP_STATUS_OK ) {
Error( $message );
ZM\Error( $message );
if ( function_exists( 'ajaxCleanup' ) )
ajaxCleanup();
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) ) {
return 'cache/'.$cacheFile;
} else {
Warning("Failed linking $file to $cacheFile");
ZM\Warning("Failed linking $file to $cacheFile");
}
return $file;
}
@ -2292,7 +2292,7 @@ function getStreamHTML( $monitor, $options = array() ) {
$monitor->Name());
} else {
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';
$streamSrc = $monitor->getStreamSrc( $options );
@ -2308,7 +2308,7 @@ function getStreamMode( ) {
$streamMode = 'jpeg';
} else {
$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;
} // end function getStreamMode
@ -2349,13 +2349,13 @@ function check_timezone() {
#");
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 )
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')))
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
namespace ZM;
require_once( 'config.php' );
class Logger {

View File

@ -17,6 +17,7 @@
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
namespace ZM;
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>
<?php
if ( logToDatabase() > Logger::NOLOG ) {
if ( ZM\logToDatabase() > ZM\Logger::NOLOG ) {
if ( ! ZM_RUN_AUDIT ) {
# 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');
@ -355,13 +355,13 @@ if ($reload == 'reload') ob_start();
?>
<li><?php echo translate('Storage') ?>:
<?php
$storage_areas = Storage::find();
$storage_areas = ZM\Storage::find();
$storage_paths = null;
foreach ( $storage_areas as $area ) {
$storage_paths[$area->Path()] = $area;
}
if ( ! isset($storage_paths[ZM_DIR_EVENTS]) ) {
array_push( $storage_areas, new Storage() );
array_push( $storage_areas, new ZM\Storage() );
}
$func = function($S){
$class = '';

View File

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

View File

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

View File

@ -230,7 +230,7 @@ ob_end_clean();
echo $table_head;
for( $monitor_i = 0; $monitor_i < count($displayMonitors); $monitor_i += 1 ) {
$monitor = $displayMonitors[$monitor_i];
$Monitor = new Monitor($monitor);
$Monitor = new ZM\Monitor($monitor);
if ( $monitor_i and ( $monitor_i % 100 == 0 ) ) {
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">
<?php echo implode('<br/>',
array_map(function($group_id){
$Group = Group::find_one(array('Id'=>$group_id));
$Group = ZM\Group::find_one(array('Id'=>$group_id));
if ( $Group ) {
$Groups = $Group->Parents();
array_push( $Groups, $Group );
@ -305,7 +305,7 @@ for( $monitor_i = 0; $monitor_i < count($displayMonitors); $monitor_i += 1 ) {
</div></td>
<?php
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
}
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 )
require_once $includeFile;
$monitor = new Monitor($mid);
$monitor = new ZM\Monitor($mid);
$focusWindow = true;

View File

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

View File

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

View File

@ -80,12 +80,12 @@ $focusWindow = true;
if ( $_POST ) {
// 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);
exit();
}
$storage_areas = Storage::find();
$storage_areas = ZM\Storage::find();
$StorageById = array();
foreach ( $storage_areas as $S ) {
$StorageById[$S->Id()] = $S;
@ -146,7 +146,7 @@ $disk_space_total = 0;
$results = dbQuery($eventsSql);
while ( $event_row = dbFetchNext($results) ) {
$event = new Event($event_row);
$event = new ZM\Event($event_row);
if ( $event_row['Archived'] )
$archived = true;
else

View File

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

View File

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

View File

@ -29,7 +29,7 @@ $eid = validInt($_REQUEST['eid']);
if ( !empty($_REQUEST['fid']) )
$fid = validInt($_REQUEST['fid']);
$Event = new Event($eid);
$Event = new ZM\Event($eid);
$Monitor = $Event->Monitor();
if ( !empty($fid) ) {
@ -39,7 +39,7 @@ if ( !empty($fid) ) {
} else {
$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();
@ -63,7 +63,7 @@ $scale = $scale ?: "auto";
$imageData = $Event->getImageSrc( $frame, $scale, 0 );
if ( ! $imageData ) {
Error("No data found for Event $eid frame $fid");
ZM\Error("No data found for Event $eid frame $fid");
$imageData = array();
}

View File

@ -23,7 +23,7 @@ if ( !canView('Events') ) {
return;
}
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';
$frames = dbFetchAll( $sql, NULL, array( $_REQUEST['eid'] ) );
@ -62,7 +62,7 @@ xhtmlHeaders(__FILE__, translate('Frames').' - '.$Event->Id() );
<?php
if ( count($frames) ) {
foreach ( $frames as $frame ) {
$Frame = new Frame( $frame );
$Frame = new ZM\Frame( $frame );
$class = strtolower($frame['Type']);
?>

View File

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

View File

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

View File

@ -120,21 +120,21 @@ echo " };\n";
echo "\nvar Storage = [];\n";
$have_storage_zero = 0;
foreach ( Storage::find() as $Storage ) {
foreach ( ZM\Storage::find() as $Storage ) {
echo 'Storage[' . $Storage->Id() . '] = ' . $Storage->to_json(). ";\n";
if ( $Storage->Id() == 0 )
$have_storage_zero = true;
}
if ( !$have_storage_zero ) {
$Storage = new Storage();
$Storage = new ZM\Storage();
echo 'Storage[0] = ' . $Storage->to_json(). ";\n";
}
echo "\nvar Servers = [];\n";
// 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";
foreach ( Server::find() as $Server ) {
foreach ( ZM\Server::find() as $Server ) {
echo 'Servers[' . $Server->Id() . '] = new Server(' . $Server->to_json(). ");\n";
}

View File

@ -36,7 +36,7 @@ if ( ! $Server ) {
$monitor = null;
if ( ! empty($_REQUEST['mid']) ) {
$monitor = new Monitor( $_REQUEST['mid'] );
$monitor = new ZM\Monitor( $_REQUEST['mid'] );
if ( $monitor and ZM_OPT_X10 )
$x10Monitor = dbFetchOne( 'SELECT * FROM TriggersX10 WHERE MonitorId = ?', NULL, array($_REQUEST['mid']) );
}
@ -44,7 +44,7 @@ if ( ! $monitor ) {
$nextId = getTableAutoInc( 'Monitors' );
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
if ( ZM_OPT_X10 )
$x10Monitor = dbFetchOne( 'SELECT * FROM TriggersX10 WHERE MonitorId = ?', NULL, array($_REQUEST['dupId']) );
@ -52,7 +52,7 @@ if ( ! $monitor ) {
$monitor->Name( translate('Monitor').'-'.$nextId );
$monitor->Id( $nextId );
} else {
$monitor = new Monitor();
$monitor = new ZM\Monitor();
$monitor->set( array(
'Id' => 0,
'Name' => translate('Monitor').'-'.$nextId,
@ -678,10 +678,8 @@ switch ( $tab ) {
<tr><td><?php echo translate('Server') ?></td><td>
<?php
$servers = array(''=>'None','auto'=>'Auto');
$result = dbQuery( 'SELECT * FROM Servers ORDER BY Name');
$results = $result->fetchALL(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'Server' );
foreach ( $results as $row => $server_obj ) {
$servers[$server_obj->Id()] = $server_obj->Name();
foreach ( ZM\Server::find(NULL, array('order'=>'lower(Name)')) as $Server ) {
$servers[$Server->Id()] = $Server->Name();
}
echo htmlSelect( 'newMonitor[ServerId]', $servers, $monitor->ServerId() );
?>
@ -689,10 +687,8 @@ switch ( $tab ) {
<tr><td><?php echo translate('StorageArea') ?></td><td>
<?php
$storage_areas = array(0=>'Default');
$result = dbQuery( 'SELECT * FROM Storage ORDER BY Name');
$results = $result->fetchALL(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'Storage' );
foreach ( $results as $row => $storage_obj ) {
$storage_areas[$storage_obj->Id] = $storage_obj->Name();
foreach ( ZM\Storage::find( NULL, array('order'=>'lower(Name)') ) as $Storage ) {
$storage_areas[$Storage->Id()] = $Storage->Name();
}
echo htmlSelect( 'newMonitor[StorageId]', $storage_areas, $monitor->StorageId() );
?>
@ -733,7 +729,7 @@ switch ( $tab ) {
</td>
</tr>
<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>
<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

View File

@ -34,7 +34,7 @@ function probeV4L() {
$result = exec(escapeshellcmd($command), $output, $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;
}
@ -47,7 +47,7 @@ function probeV4L() {
$preferredFormats = array('BGR3', 'RGB3', 'YUYV', 'UYVY', 'JPEG', 'MJPG', '422P', 'YU12', 'GREY');
foreach ( $output as $line ) {
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]);
$preferredStandard = false;
foreach ( $preferredStandards as $standard ) {
@ -74,7 +74,7 @@ function probeV4L() {
$inputs = array();
for ( $i = 0; $i < $deviceMatches[4]; $i++ ) {
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' ) {
$input = array(
'index' => $i,
@ -247,13 +247,13 @@ function probeNetwork() {
$arp_command = ZM_PATH_ARP;
$result = explode(' ', $arp_command);
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;
}
$result = exec(escapeshellcmd($arp_command), $output, $status);
if ( $status ) {
Error("Unable to probe network cameras, status is '$status'");
ZM\Error("Unable to probe network cameras, status is '$status'");
return;
}

View File

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

View File

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

View File

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

View File

@ -36,12 +36,12 @@ function execONVIF( $cmd ) {
if ( $status ) {
$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/>
Please the following command from a command line for more information:<br/><br/>$shell_command"
);
} else {
Logger::Debug( "Results from probe: " . implode( '<br/>', $output ) );
ZM\Logger::Debug( "Results from probe: " . implode( '<br/>', $output ) );
}
return $output;
@ -73,7 +73,7 @@ function probeCameras( $localIp ) {
} elseif ( $tokens[1] == 'location' ) {
// $camera['location'] = $tokens[2];
} else {
Logger::Debug('Unknown token ' . $tokens[1]);
ZM\Logger::Debug('Unknown token ' . $tokens[1]);
}
}
} // end foreach token
@ -109,7 +109,7 @@ function probeProfiles( $device_ep, $soapversion, $username, $password ) {
);
$profiles[] = $profile;
} else {
Logger::Debug("Line did not match preg: $line");
ZM\Logger::Debug("Line did not match preg: $line");
}
} // end foreach line
} // end if results from execONVIF
@ -190,7 +190,7 @@ if ( !isset($_REQUEST['step']) || ($_REQUEST['step'] == '1') ) {
</p>
<p>
<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>
<div id="contentButtons">
<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 ============================================================
} else if($_REQUEST['step'] == '2') {
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['password']) )
$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 ) {
if ( isset($value) ) {
$monitor[$name] = $value;

View File

@ -230,7 +230,7 @@ foreach ( array_map('basename', glob('skins/'.$current_skin.'/css/*',GLOB_ONLYDI
<tbody>
<?php
$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>
<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>
</thead>
<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>
<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>

View File

@ -62,7 +62,7 @@ if ( count($selected_monitor_ids) ) {
}
parseFilter($filter);
$filterQuery = $filter['query'];
Logger::Debug($filterQuery);
ZM\Logger::Debug($filterQuery);
$eventsSql = 'SELECT *,
UNIX_TIMESTAMP(E.StartTime) AS StartTimeSecs,
@ -83,12 +83,12 @@ $eventsSql .= ' ORDER BY Id ASC';
$result = dbQuery($eventsSql);
if ( !$result ) {
Fatal('SQL-ERR');
ZM\Fatal('SQL-ERR');
return;
}
$EventsByMonitor = array();
while( $event = $result->fetch(PDO::FETCH_ASSOC) ) {
$Event = new Event($event);
$Event = new ZM\Event($event);
if ( ! isset($EventsByMonitor[$event['MonitorId']]) )
$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
for( $monitor_i = 0; $monitor_i < count($displayMonitors); $monitor_i += 1 ) {
$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;
$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">
<?php echo implode('<br/>',
array_map(function($group_id){
$Group = new Group($group_id);
$Group = new ZM\Group($group_id);
$Groups = $Group->Parents();
array_push($Groups, $Group);
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;
}
$Server = new Server($_REQUEST['id']);
$Server = new ZM\Server($_REQUEST['id']);
if ( $_REQUEST['id'] and ! $Server->Id() ) {
$view = 'error';
return;
@ -97,9 +97,8 @@ xhtmlHeaders(__FILE__, translate('Server').' - '.$Server->Name());
</tbody>
</table>
<div id="contentButtons">
<input type="hidden" name="action" value="Save"/>
<input type="submit" value="<?php echo translate('Save') ?>"/>
<input type="button" value="<?php echo translate('Cancel') ?>" data-on-click="closeWindow"/>
<button type="submit" name="action" value="Save" ><?php echo translate('Save') ?></button>
<button type="button" data-on-click="closeWindow"><?php echo translate('Cancel') ?></button>
</div>
</form>
</div>

View File

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

View File

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

View File

@ -37,7 +37,7 @@ if ( ! visibleMonitor($mid) ) {
return;
}
$monitor = new Monitor($mid);
$monitor = new ZM\Monitor($mid);
#Whether to show the controls button
$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;
}
$monitor = new Monitor( $mid );
$monitor = new ZM\Monitor( $mid );
$minX = 0;
$maxX = $monitor->Width()-1;

View File

@ -43,7 +43,7 @@ if ( $archivetype ) {
if ( $mimetype ) {
$filename = "zmExport.$file_ext";
$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) ) {
ob_clean();
header("Content-type: application/$mimetype" );
@ -51,16 +51,16 @@ if ( $archivetype ) {
header('Content-Length: ' . filesize($filename_path) );
set_time_limit(0);
if ( ! @readfile( $filename_path ) ) {
Error("Error sending $filename_path");
ZM\Error("Error sending $filename_path");
}
} else {
Error("$filename_path does not exist or is not readable.");
ZM\Error("$filename_path does not exist or is not readable.");
}
} 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 {
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']) ) {
header('HTTP/1.0 404 Not Found');
Fatal('No Frame ID specified');
ZM\Fatal('No Frame ID specified');
return;
}
if ( !empty($_REQUEST['eid']) ) {
Logger::Debug("Loading by eid");
$Event = Event::find_one(array('Id'=>$_REQUEST['eid']));
ZM\Logger::Debug("Loading by eid");
$Event = ZM\Event::find_one(array('Id'=>$_REQUEST['eid']));
if ( !$Event ) {
header('HTTP/1.0 404 Not Found');
Fatal('Event '.$_REQUEST['eid'].' Not found');
ZM\Fatal('Event '.$_REQUEST['eid'].' Not found');
return;
}
@ -81,19 +81,19 @@ if ( empty($_REQUEST['path']) ) {
$path = $Event->Path().'/objdetect.jpg';
if ( !file_exists($path) ) {
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');
} else if ( $_REQUEST['fid'] == 'alarm' ) {
# 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'));
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 ) {
Warning('No frame found for event '.$_REQUEST['eid']);
$Frame = new Frame();
ZM\Warning('No frame found for event '.$_REQUEST['eid']);
$Frame = new ZM\Frame();
$Frame->Delta(1);
$Frame->FrameId(1);
}
@ -106,12 +106,12 @@ if ( empty($_REQUEST['path']) ) {
$path = $Event->Path().'/alarm.jpg';
}
} 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 )
$Frame = Frame::find_one(array('EventId'=>$_REQUEST['eid']));
$Frame = ZM\Frame::find_one(array('EventId'=>$_REQUEST['eid']));
if ( !$Frame ) {
Warning('No frame found for event ' . $_REQUEST['eid']);
$Frame = new Frame();
ZM\Warning('No frame found for event ' . $_REQUEST['eid']);
$Frame = new ZM\Frame();
$Frame->Delta(1);
$Frame->FrameId('snapshot');
}
@ -124,7 +124,7 @@ if ( empty($_REQUEST['path']) ) {
}
} 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 ) {
$previousBulkFrame = dbFetchOne(
'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'])
);
if ( $previousBulkFrame and $nextBulkFrame ) {
$Frame = new Frame($previousBulkFrame);
$Frame = new ZM\Frame($previousBulkFrame);
$Frame->FrameId($_REQUEST['fid']);
$percentage = ($Frame->FrameId() - $previousBulkFrame['FrameId']) / ($nextBulkFrame['FrameId'] - $previousBulkFrame['FrameId']);
$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 {
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
$path = $Event->Path().'/'.sprintf('%0'.ZM_EVENT_IMAGE_DIGITS.'d',$Frame->FrameId()).'-'.$show.'.jpg';
Logger::Debug("Path: $path");
ZM\Logger::Debug("Path: $path");
}
} 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 #
$Frame = Frame::find_one(array('Id'=>$_REQUEST['fid']));
$Frame = ZM\Frame::find_one(array('Id'=>$_REQUEST['fid']));
if ( !$Frame ) {
header('HTTP/1.0 404 Not Found');
Fatal('Frame ' . $_REQUEST['fid'] . ' Not Found');
ZM\Fatal('Frame ' . $_REQUEST['fid'] . ' Not Found');
return;
}
$Event = Event::find_one(array('Id'=>$Frame->EventId()));
$Event = ZM\Event::find_one(array('Id'=>$Frame->EventId()));
if ( !$Event ) {
header('HTTP/1.0 404 Not Found');
Fatal('Event ' . $Frame->EventId() . ' Not Found');
ZM\Fatal('Event ' . $Frame->EventId() . ' Not Found');
return;
}
$path = $Event->Path().'/'.sprintf('%0'.ZM_EVENT_IMAGE_DIGITS.'d',$Frame->FrameId()).'-'.$show.'.jpg';
} # end if have eid
if ( !file_exists($path) ) {
Logger::Debug("$path does not exist");
ZM\Logger::Debug("$path does not exist");
# Generate the frame JPG
if ( ($show == 'capture') and $Event->DefaultVideo() ) {
if ( !file_exists($Event->Path().'/'.$Event->DefaultVideo()) ) {
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().' -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();
$retval = 0;
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 ) ) {
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.
$Event->DiskSpace(null);
$Event->save();
} else {
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() );
}
} # end if ! file_exists($path)
} else {
Warning('Loading images by path is deprecated');
ZM\Warning('Loading images by path is deprecated');
$dir_events = realpath(ZM_DIR_EVENTS);
$path = realpath($dir_events . '/' . $_REQUEST['path']);
$pos = strpos($path, $dir_events);
@ -223,7 +223,7 @@ if ( empty($_REQUEST['path']) ) {
}
if ( !file_exists($path) ) {
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;
if ( !empty($_REQUEST['width']) ) {
Logger::Debug("Setting width: " . $_REQUEST['width']);
ZM\Logger::Debug("Setting width: " . $_REQUEST['width']);
if ( is_numeric($_REQUEST['width']) ) {
$x = $_REQUEST['width'];
if ( $x >= 10 and $x <= 8000 )
@ -257,7 +257,7 @@ if ( !empty($_REQUEST['height']) ) {
}
if ( $errorText ) {
Error($errorText);
ZM\Error($errorText);
} else {
# Clears the output buffer. Not sure what is there, but have had troubles.
ob_end_clean();
@ -269,10 +269,10 @@ if ( $errorText ) {
header('Content-Disposition: inline; filename="' . $filename . '"');
}
if ( !readfile($path) ) {
Error('No bytes read from '. $path);
ZM\Error('No bytes read from '. $path);
}
} 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;
if ( ! ( $width && $height ) ) {
$i = imagecreatefromjpeg($path);
@ -285,10 +285,10 @@ if ( $errorText ) {
$width = ($height * $oldWidth) / $oldHeight;
} elseif ( $width != 0 && $height == 0 ) {
$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 ) {
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 . '"');
}
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();
if ( !$i )
$i = imagecreatefromjpeg($path);
@ -312,12 +312,12 @@ Logger::Debug("Figuring out height using width: $height = ($width * $oldHeight)
ob_end_clean();
echo $scaled_jpeg_data;
} else {
Logger::Debug("Sending $scaled_path");
ZM\Logger::Debug("Sending $scaled_path");
$bytes = readfile($scaled_path);
if ( !$bytes ) {
Error('No bytes read from '. $scaled_path);
ZM\Error('No bytes read from '. $scaled_path);
} else {
Logger::Debug("$bytes sent");
ZM\Logger::Debug("$bytes sent");
}
}
}

View File

@ -38,19 +38,19 @@ $path = '';
$Event = null;
if ( ! empty($_REQUEST['eid']) ) {
$Event = new Event($_REQUEST['eid']);
$Event = new ZM\Event($_REQUEST['eid']);
$path = $Event->Path().'/'.$Event->DefaultVideo();
Logger::Debug("Path: $path");
ZM\Logger::Debug("Path: $path");
} else if ( ! empty($_REQUEST['event_id']) ) {
$Event = new Event($_REQUEST['event_id']);
$Event = new ZM\Event($_REQUEST['event_id']);
$path = $Event->Path().'/'.$Event->DefaultVideo();
Logger::Debug("Path: $path");
ZM\Logger::Debug("Path: $path");
} else {
$errorText = 'No video path';
}
if ( $errorText ) {
Error($errorText);
ZM\Error($errorText);
header('HTTP/1.0 404 Not Found');
die();
}
@ -68,14 +68,14 @@ $end = $size-1;
$length = $size;
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) ) {
$begin = intval($matches[1]);
if ( ! empty($matches[2]) ) {
$end = intval($matches[2]);
}
$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