Url() ) { $valid = true; header('Access-Control-Allow-Origin: ' . $Server->Url() ); header('Access-Control-Allow-Headers: x-requested-with,x-request'); } } if ( ! $valid ) { Warning( $_SERVER['HTTP_ORIGIN'] . ' is not found in servers list.' ); } } } function getAuthUser( $auth ) { if ( ZM_OPT_USE_AUTH && ZM_AUTH_RELAY == 'hashed' && !empty($auth) ) { $remoteAddr = ''; if ( ZM_AUTH_HASH_IPS ) { $remoteAddr = $_SERVER['REMOTE_ADDR']; if ( !$remoteAddr ) { Error( "Can't determine remote address for authentication, using empty string" ); $remoteAddr = ''; } } if ( isset( $_SESSION['username'] ) ) { # Most of the time we will be logged in already and the session will have our username, so we can significantly speed up our hash testing by only looking at our user. # Only really important if you have a lot of users. $sql = "SELECT * FROM Users WHERE Enabled = 1 AND Username='".$_SESSION['username']."'"; } else { $sql = 'SELECT * FROM Users WHERE Enabled = 1'; } foreach ( dbFetchAll( $sql ) as $user ) { $now = time(); for ( $i = 0; $i < ZM_AUTH_HASH_TTL; $i++, $now -= (3600) ) { // Try for last two hours $time = localtime( $now ); $authKey = ZM_AUTH_HASH_SECRET.$user['Username'].$user['Password'].$remoteAddr.$time[2].$time[3].$time[4].$time[5]; $authHash = md5( $authKey ); if ( $auth == $authHash ) { return $user; } } // end foreach hour } // end foreach user } // end if using auth hash Error( "Unable to authenticate user from auth hash '$auth'" ); return( false ); } // end getAuthUser($auth) function generateAuthHash( $useRemoteAddr ) { if ( ZM_OPT_USE_AUTH and ZM_AUTH_RELAY == 'hashed' and isset($_SESSION['username']) and $_SESSION['passwordHash'] ) { # regenerate a hash at half the liftetime of a hash, an hour is 3600 so half is 1800 $time = time(); if ( ( ! isset($_SESSION['AuthHash']) ) or ( $_SESSION['AuthHashGeneratedAt'] < ( $time - ( ZM_AUTH_HASH_TTL * 1800 ) ) ) ) { # Don't both regenerating Auth Hash if an hour hasn't gone by yet $local_time = localtime(); $authKey = ''; if ( $useRemoteAddr ) { $authKey = ZM_AUTH_HASH_SECRET.$_SESSION['username'].$_SESSION['passwordHash'].$_SESSION['remoteAddr'].$local_time[2].$local_time[3].$local_time[4].$local_time[5]; } else { $authKey = ZM_AUTH_HASH_SECRET.$_SESSION['username'].$_SESSION['passwordHash'].$local_time[2].$local_time[3].$local_time[4].$local_time[5]; } $auth = md5( $authKey ); if ( session_status() == PHP_SESSION_NONE ) { $backTrace = debug_backtrace(); $file = $backTrace[1]['file']; $line = $backTrace[1]['line']; Warning("Session is not active. AuthHash will not be cached. called from $file:$line"); } $_SESSION['AuthHash'] = $auth; $_SESSION['AuthHashGeneratedAt'] = $time; Logger::Debug("Generated new auth $auth at " . $_SESSION['AuthHashGeneratedAt']. " using $authKey" ); } else { Logger::Debug( "Using cached auth " . $_SESSION['AuthHash'] ." beacuse " . $_SESSION['AuthHashGeneratedAt'] . ' < '. $time . ' - ' . ZM_AUTH_HASH_TTL . ' * 1800 = '.( $time - (ZM_AUTH_HASH_TTL * 1800) )); } # end if AuthHash is not cached return $_SESSION['AuthHash']; } else { $auth = ''; } return( $auth ); } function getStreamSrc( $args, $querySep='&' ) { $streamSrc = ZM_BASE_URL.ZM_PATH_ZMS; if ( ZM_OPT_USE_AUTH ) { if ( ZM_AUTH_RELAY == 'hashed' ) { $args[] = 'auth='.generateAuthHash( ZM_AUTH_HASH_IPS ); } elseif ( ZM_AUTH_RELAY == 'plain' ) { $args[] = 'user='.$_SESSION['username']; $args[] = 'pass='.$_SESSION['password']; } elseif ( ZM_AUTH_RELAY == 'none' ) { $args[] = 'user='.$_SESSION['username']; } } if ( !in_array( 'mode=single', $args ) && !empty($GLOBALS['connkey']) ) { $args[] = 'connkey='.$GLOBALS['connkey']; } if ( ZM_RAND_STREAM ) { $args[] = 'rand='.time(); } if ( count($args) ) { $streamSrc .= '?'.join( $querySep, $args ); } return( $streamSrc ); } function getMimeType( $file ) { if ( function_exists('mime_content_type') ) { return( mime_content_type( $file ) ); } elseif ( function_exists('finfo_file') ) { $finfo = finfo_open( FILEINFO_MIME ); $mimeType = finfo_file( $finfo, $file ); finfo_close($finfo); return( $mimeType ); } return( trim( exec( 'file -bi '.escapeshellarg( $file ).' 2>/dev/null' ) ) ); } function outputVideoStream( $id, $src, $width, $height, $format, $title='' ) { echo getVideoStreamHTML( $id, $src, $width, $height, $format, $title ); } function getVideoStreamHTML( $id, $src, $width, $height, $format, $title='' ) { $html = ''; $width = validInt($width); $height = validInt($height); $title = validHtmlStr($title); if ( file_exists( $src ) ) { $mimeType = getMimeType( $src ); } else { switch( $format ) { case 'asf' : $mimeType = 'video/x-ms-asf'; break; case 'avi' : case 'wmv' : $mimeType = 'video/x-msvideo'; break; case 'mov' : $mimeType = 'video/quicktime'; break; case 'mpg' : case 'mpeg' : $mimeType = 'video/mpeg'; break; case 'swf' : $mimeType = 'application/x-shockwave-flash'; break; case '3gp' : $mimeType = 'video/3gpp'; break; default : $mimeType = "video/$format"; break; } } if ( !$mimeType || ($mimeType == 'application/octet-stream') ) $mimeType = 'video/'.$format; if ( ZM_WEB_USE_OBJECT_TAGS ) { switch( $mimeType ) { case 'video/x-ms-asf' : case 'video/x-msvideo' : case 'video/mp4' : { if ( isWindows() ) { return ''; } } case 'video/quicktime' : { return ''; } case 'application/x-shockwave-flash' : { return ''; } } # end switch } # end if use object tags return ''; } function outputImageStream( $id, $src, $width, $height, $title='' ) { echo getImageStreamHTML( $id, $src, $width, $height, $title ); } function getImageStreamHTML( $id, $src, $width, $height, $title='' ) { if ( canStreamIframe() ) { return ''; } else { return ''; } } function outputControlStream( $src, $width, $height, $monitor, $scale, $target ) { ?>
'; } function outputImageStill( $id, $src, $width, $height, $title='' ) { echo getImageStill( $id, $src, $width, $height, $title='' ); } function getImageStill( $id, $src, $width, $height, $title='' ) { return ''; } function outputControlStill( $src, $width, $height, $monitor, $scale, $target ) { ?> getStreamSrc( array( 'mode'=>'mpeg', 'format'=>'h264' ) ); } function deletePath( $path ) { if ( is_dir( $path ) ) { system( escapeshellcmd( 'rm -rf '.$path ) ); } else { unlink( $path ); } } function deleteEvent( $event ) { if ( empty($event) ) { 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 ); } else { Logger::Debug("Event type: " . gettype($event)); } global $user; if ( $user['Events'] == 'Edit' ) { $event->delete(); } # CAN EDIT } function makeLink( $url, $label, $condition=1, $options='' ) { $string = ''; if ( $condition ) { $string .= ''; } $string .= $label; if ( $condition ) { $string .= ''; } return( $string ); } function makePopupLink( $url, $winName, $winSize, $label, $condition=1, $options='' ) { $string = ''; if ( $condition ) { if ( is_array( $winSize ) ) $popupParms = "'".$url."', '".$winName."', '".$winSize[0]."', ".$winSize[1].", ".$winSize[2]; else $popupParms = "'".$url."', '".$winName."', '".$winSize."'"; $string .= ''; } else { $string .= ''; } $string .= $label; $string .= ''; return( $string ); } function makePopupButton( $url, $winName, $winSize, $buttonValue, $condition=1, $options='' ) { if ( is_array( $winSize ) ) $popupParms = "'".$url."', '".$winName."', '".$winSize[0]."', ".$winSize[1].", ".$winSize[2]; else $popupParms = "'".$url."', '".$winName."', '".$winSize."'"; $string = ''; return( $string ); } function htmlSelect( $name, $contents, $values, $behaviours=false ) { $behaviourText = ''; if ( !empty($behaviours) ) { if ( is_array($behaviours) ) { foreach ( $behaviours as $event=>$action ) { $behaviourText .= ' '.$event.'="'.$action.'"'; } } else { $behaviourText = ' onchange="'.$behaviours.'"'; } } $html = "'; return $html; } function truncText( $text, $length, $deslash=1 ) { return( preg_replace( '/^(.{'.$length.',}?)\b.*$/', '\\1…', ($deslash?stripslashes($text):$text) ) ); } function buildSelect( $name, $contents, $behaviours=false ) { $value = ''; if ( preg_match( '/^\s*(\w+)\s*(\[.*\])?\s*$/', $name, $matches ) && count($matches) > 2 ) { $arr = $matches[1]; if ( isset($GLOBALS[$arr]) ) $value = $GLOBALS[$arr]; elseif ( isset($_REQUEST[$arr]) ) $value = $_REQUEST[$arr]; if ( !preg_match_all( '/\[\s*[\'"]?(\w+)["\']?\s*\]/', $matches[2], $matches ) ) { Fatal( "Can't parse selector '$name'" ); } for ( $i = 0; $i < count($matches[1]); $i++ ) { $idx = $matches[1][$i]; $value = isset($value[$idx])?$value[$idx]:false; } } else { if ( isset($GLOBALS[$name]) ) $value = $GLOBALS[$name]; elseif ( isset($_REQUEST[$name]) ) $value = $_REQUEST[$name]; } ob_start(); $behaviourText = ''; if ( !empty($behaviours) ) { if ( is_array($behaviours) ) { foreach ( $behaviours as $event=>$action ) { $behaviourText .= ' '.$event.'="'.$action.'"'; } } else { $behaviourText = ' onchange="'.$behaviours.'"'; } } ?> $value ) { if ( $columns && !$columns[$key] ) continue; if ( !isset($types[$key]) ) $types[$key] = false; switch( $types[$key] ) { case 'set' : { if ( is_array( $newValues[$key] ) ) { if ( join(',',$newValues[$key]) != $values[$key] ) { $changes[$key] = "`$key` = ".dbEscape(join(',',$newValues[$key])); } } elseif ( $values[$key] ) { $changes[$key] = "`$key` = ''"; } break; } case 'image' : { if ( is_array( $newValues[$key] ) ) { $imageData = getimagesize( $newValues[$key]['tmp_name'] ); $changes[$key.'Width'] = $key.'Width = '.$imageData[0]; $changes[$key.'Height'] = $key.'Height = '.$imageData[1]; $changes[$key.'Type'] = $key."Type = '".$newValues[$key]['type']."'"; $changes[$key.'Size'] = $key.'Size = '.$newValues[$key]['size']; ob_start(); readfile( $newValues[$key]['tmp_name'] ); $changes[$key] = $key." = ".dbEscape( ob_get_contents() ); ob_end_clean(); } else { $changes[$key] = "$key = ".dbEscape($value); } break; } case 'document' : { if ( is_array( $newValues[$key] ) ) { $imageData = getimagesize( $newValues[$key]['tmp_name'] ); $changes[$key.'Type'] = $key."Type = '".$newValues[$key]['type']."'"; $changes[$key.'Size'] = $key.'Size = '.$newValues[$key]['size']; ob_start(); readfile( $newValues[$key]['tmp_name'] ); $changes[$key] = $key.' = '.dbEscape( ob_get_contents() ); ob_end_clean(); } else { $changes[$key] = $key . ' = '.dbEscape($value); } break; } case 'file' : { $changes[$key.'Type'] = $key.'Type = '.dbEscape($newValues[$key]['type']); $changes[$key.'Size'] = $key.'Size = '.dbEscape($newValues[$key]['size']); ob_start(); readfile( $newValues[$key]['tmp_name'] ); $changes[$key] = $key." = '".dbEscape( ob_get_contents() )."'"; ob_end_clean(); break; } case 'raw' : { if ( $values[$key] != $value ) { $changes[$key] = $key . ' = '.dbEscape($value); } break; } default : { if ( !isset($values[$key]) || ($values[$key] != $value) ) { if ( ! isset($value) || $value == '' ) { $changes[$key] = "`$key` = NULL"; } else { $changes[$key] = "`$key` = ".dbEscape(trim($value)); } } break; } } // end switch } // end foreach newvalues foreach( $values as $key=>$value ) { if ( !empty($columns[$key]) ) { if ( !empty($types[$key]) ) { if ( $types[$key] == 'toggle' ) { if ( !isset($newValues[$key]) && !empty($value) ) { $changes[$key] = "$key = 0"; } } else if ( $types[$key] == 'set' ) { $changes[$key] = "$key = ''"; } } } } return( $changes ); } function getBrowser( &$browser, &$version ) { if ( isset($_SESSION['browser']) ) { $browser = $_SESSION['browser']; $version = $_SESSION['version']; } else { if (( preg_match( '/MSIE (.*?);/', $_SERVER['HTTP_USER_AGENT'], $logVersion)) || (preg_match( '/.*Trident.*rv:(.*?)(;|\))/', $_SERVER['HTTP_USER_AGENT'], $logVersion))) { $version = $logVersion[1]; $browser = 'ie'; } elseif ( preg_match( '/Chrome\/([0-9.]+)/', $_SERVER['HTTP_USER_AGENT'], $logVersion) ) { $version = $logVersion[1]; // Check for old version of Chrome with bug 5876 if ( $version < 7 ) { $browser = 'oldchrome'; } else { $browser = 'chrome'; } } elseif ( preg_match( '/Safari\/([0-9.]+)/', $_SERVER['HTTP_USER_AGENT'], $logVersion) ) { $version = $logVersion[1]; $browser = 'safari'; } elseif ( preg_match( '/Opera[ \/]([0-9].[0-9]{1,2})/', $_SERVER['HTTP_USER_AGENT'], $logVersion) ) { $version = $logVersion[1]; $browser = 'opera'; } elseif ( preg_match( '/Konqueror\/([0-9.]+)/', $_SERVER['HTTP_USER_AGENT'], $logVersion) ) { $version = $logVersion[1]; $browser = 'konqueror'; } elseif ( preg_match( '/Mozilla\/([0-9].[0-9]{1,2})/', $_SERVER['HTTP_USER_AGENT'], $logVersion) ) { $version = $logVersion[1]; $browser = 'mozilla'; } else { $version = 0; $browser = 'unknown'; } $_SESSION['browser'] = $browser; $_SESSION['version'] = $version; } } function isMozilla() { getBrowser( $browser, $version ); return( $browser == 'mozilla' ); } function isKonqueror() { getBrowser( $browser, $version ); return( $browser == 'konqueror' ); } function isInternetExplorer() { getBrowser( $browser, $version ); return( $browser == 'ie' ); } function isOldChrome() { getBrowser( $browser, $version ); return( $browser == 'oldchrome' ); } function isChrome() { getBrowser( $browser, $version ); return( $browser == 'chrome' ); } function isOpera() { getBrowser( $browser, $version ); return( $browser == 'opera' ); } function isSafari() { getBrowser( $browser, $version ); return( $browser == 'safari' ); } function isWindows() { return ( preg_match( '/Win/', $_SERVER['HTTP_USER_AGENT'] ) ); } function canStreamIframe() { return( isKonqueror() ); } function canStreamNative() { // Old versions of Chrome can display the stream, but then it blocks everything else (Chrome bug 5876) return( ZM_WEB_CAN_STREAM == 'yes' || ( ZM_WEB_CAN_STREAM == 'auto' && (!isInternetExplorer() && !isOldChrome()) ) ); } function canStreamApplet() { if ( (ZM_OPT_CAMBOZOLA && !file_exists( ZM_PATH_WEB.'/'.ZM_PATH_CAMBOZOLA )) ) { Warning ( 'ZM_OPT_CAMBOZOLA is enabled, but the system cannot find '.ZM_PATH_WEB.'/'.ZM_PATH_CAMBOZOLA ); } return( (ZM_OPT_CAMBOZOLA && file_exists( ZM_PATH_WEB.'/'.ZM_PATH_CAMBOZOLA )) ); } function canStream() { return( canStreamNative() | canStreamApplet() ); } function packageControl( $command ) { $string = ZM_PATH_BIN.'/zmpkg.pl '.escapeshellarg( $command ); $string .= ' 2>/dev/null >&- <&- >/dev/null'; exec( $string ); } function daemonControl( $command, $daemon=false, $args=false ) { $string = escapeshellcmd(ZM_PATH_BIN).'/zmdc.pl '.$command; if ( $daemon ) { $string .= ' ' . $daemon; if ( $args ) { $string .= ' ' . $args; } } $string = escapeshellcmd( $string ); #$string .= ' 2>/dev/null >&- <&- >/dev/null'; exec( $string ); } function zmcControl( $monitor, $mode=false ) { $Monitor = new Monitor( $monitor ); return $Monitor->zmcControl($mode); } function zmaControl( $monitor, $mode=false ) { if ( !is_array( $monitor ) ) { $monitor = $monitor = dbFetchOne( 'select C.*, M.* from Monitors as M left join Controls as C on (M.ControlId = C.Id ) where M.Id=?', NULL, array($monitor) ); } $Monitor = new Monitor( $monitor ); $Monitor->zmaControl($mode); } function initDaemonStatus() { global $daemon_status; if ( !isset($daemon_status) ) { if ( daemonCheck() ) { $string = ZM_PATH_BIN."/zmdc.pl status"; $daemon_status = shell_exec( $string ); } else { $daemon_status = ''; } } } function daemonStatus( $daemon, $args=false ) { global $daemon_status; initDaemonStatus(); $string = $daemon; if ( $args ) $string .= ' ' . $args; return( strpos( $daemon_status, "'$string' running" ) !== false ); } function zmcStatus( $monitor ) { if ( $monitor['Type'] == 'Local' ) { $zmcArgs = '-d '.$monitor['Device']; } else { $zmcArgs = '-m '.$monitor['Id']; } return( daemonStatus( 'zmc', $zmcArgs ) ); } function zmaStatus( $monitor ) { if ( is_array( $monitor ) ) { $monitor = $monitor['Id']; } return( daemonStatus( 'zma', "-m $monitor" ) ); } function daemonCheck( $daemon=false, $args=false ) { $string = ZM_PATH_BIN.'/zmdc.pl check'; if ( $daemon ) { $string .= ' ' . $daemon; if ( $args ) $string .= ' '. $args; } $string = escapeshellcmd( $string ); $result = exec( $string ); return( preg_match( '/running/', $result ) ); } function zmcCheck( $monitor ) { if ( $monitor['Type'] == 'Local' ) { $zmcArgs = '-d '.$monitor['Device']; } else { $zmcArgs = '-m '.$monitor['Id']; } return( daemonCheck( 'zmc', $zmcArgs ) ); } function zmaCheck( $monitor ) { if ( is_array( $monitor ) ) { $monitor = $monitor['Id']; } return( daemonCheck( 'zma', "-m $monitor" ) ); } function getImageSrc( $event, $frame, $scale=SCALE_BASE, $captureOnly=false, $overwrite=false ) { $Event = new Event( $event ); return $Event->getImageSrc( $frame, $scale, $captureOnly, $overwrite ); } function viewImagePath( $path, $querySep='&' ) { if ( strncmp( $path, ZM_DIR_IMAGES, strlen(ZM_DIR_IMAGES) ) == 0 ) { // Thumbnails return( $path ); } elseif ( strpos( ZM_DIR_EVENTS, '/' ) === 0 ) { return( '?view=image'.$querySep.'path='.$path ); } return( ZM_DIR_EVENTS.'/'.$path ); } function createListThumbnail( $event, $overwrite=false ) { # Load the frame with the highest score to use as a thumbnail if ( !($frame = dbFetchOne( "SELECT * FROM Frames WHERE EventId=? AND Score=? ORDER BY FrameId LIMIT 1", NULL, array( $event['Id'], $event['MaxScore'] ) )) ) return( false ); $frameId = $frame['FrameId']; if ( ZM_WEB_LIST_THUMB_WIDTH ) { $thumbWidth = ZM_WEB_LIST_THUMB_WIDTH; $scale = (SCALE_BASE*ZM_WEB_LIST_THUMB_WIDTH)/$event['Width']; $thumbHeight = reScale( $event['Height'], $scale ); } elseif ( ZM_WEB_LIST_THUMB_HEIGHT ) { $thumbHeight = ZM_WEB_LIST_THUMB_HEIGHT; $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" ); } $imageData = getImageSrc( $event, $frame, $scale, false, $overwrite ); if ( ! $imageData ) { return ( false ); } $thumbData = $frame; $thumbData['Path'] = $imageData['thumbPath']; $thumbData['Width'] = (int)$thumbWidth; $thumbData['Height'] = (int)$thumbHeight; return( $thumbData ); } function createVideo( $event, $format, $rate, $scale, $overwrite=false ) { $command = ZM_PATH_BIN."/zmvideo.pl -e ".$event['Id']." -f ".$format." -r ".sprintf( "%.2F", ($rate/RATE_BASE) ); if ( preg_match( '/\d+x\d+/', $scale ) ) $command .= " -S ".$scale; else if ( version_compare( phpversion(), "4.3.10", ">=") ) $command .= " -s ".sprintf( "%.2F", ($scale/SCALE_BASE) ); else $command .= " -s ".sprintf( "%.2f", ($scale/SCALE_BASE) ); if ( $overwrite ) $command .= " -o"; $command = escapeshellcmd( $command ); $result = exec( $command, $output, $status ); Logger::Debug("generating Video $command: result($result outptu:(".implode("\n", $output )." status($status"); return( $status?"":rtrim($result) ); } function executeFilter( $filter ) { $command = ZM_PATH_BIN."/zmfilter.pl --filter ".escapeshellarg($filter); $result = exec( $command, $output, $status ); dbQuery( "delete from Filters where Name like '_TempFilter%'" ); return( $status ); } # This takes more than one scale amount, so it runs through each and alters dimension. # I can't imagine why you would want to do that. function reScale( $dimension, $dummy ) { $new_dimension = $dimension; for ( $i = 1; $i < func_num_args(); $i++ ) { $scale = func_get_arg( $i ); if ( !empty($scale) && $scale != SCALE_BASE ) $new_dimension = (int)(($new_dimension*$scale)/SCALE_BASE); } return( $new_dimension ); } function deScale( $dimension, $dummy ) { $new_dimension = $dimension; for ( $i = 1; $i < func_num_args(); $i++ ) { $scale = func_get_arg( $i ); if ( !empty($scale) && $scale != SCALE_BASE ) $new_dimension = (int)(($new_dimension*SCALE_BASE)/$scale); } return( $new_dimension ); } function monitorLimitSql() { global $user; if ( !empty($user['MonitorIds']) ) $midSql = " and MonitorId in (".join( ",", preg_split( '/["\'\s]*,["\'\s]*/', $user['MonitorIds'] ) ).")"; else $midSql = ''; return( $midSql ); } function parseSort( $saveToSession=false, $querySep='&' ) { global $sortQuery, $sortColumn, $sortOrder, $limitQuery; // Outputs if (isset($_REQUEST['filter']['Query']['sort_field'])) { //Handle both new and legacy filter passing $_REQUEST['sort_field'] = $_REQUEST['filter']['Query']['sort_field']; } if (isset($_REQUEST['filter']['Query']['sort_asc'])) { $_REQUEST['sort_asc'] = $_REQUEST['filter']['Query']['sort_asc']; } if (isset($_REQUEST['filter']['Query']['limit'])) { $_REQUEST['limit'] = $_REQUEST['filter']['Query']['limit']; } if ( empty($_REQUEST['sort_field']) ) { $_REQUEST['sort_field'] = ZM_WEB_EVENT_SORT_FIELD; $_REQUEST['sort_asc'] = (ZM_WEB_EVENT_SORT_ORDER == 'asc'); } switch( $_REQUEST['sort_field'] ) { case 'Id' : $sortColumn = 'E.Id'; break; case 'MonitorName' : $sortColumn = 'M.Name'; break; case 'Name' : $sortColumn = 'E.Name'; break; case 'Cause' : $sortColumn = 'E.Cause'; break; case 'DateTime' : $sortColumn = 'E.StartTime'; $_REQUEST['sort_field'] = 'StartTime'; break; case 'DiskSpace' : $sortColumn = 'E.DiskSpace'; break; case 'StartTime' : $sortColumn = 'E.StartTime'; break; case 'EndTime' : $sortColumn = 'E.EndTime'; break; case 'Length' : $sortColumn = 'E.Length'; break; case 'Frames' : $sortColumn = 'E.Frames'; break; case 'AlarmFrames' : $sortColumn = 'E.AlarmFrames'; break; case 'TotScore' : $sortColumn = 'E.TotScore'; break; case 'AvgScore' : $sortColumn = 'E.AvgScore'; break; case 'MaxScore' : $sortColumn = 'E.MaxScore'; break; default: $sortColumn = 'E.StartTime'; break; } $sortOrder = $_REQUEST['sort_asc']?'asc':'desc'; if ( !$_REQUEST['sort_asc'] ) $_REQUEST['sort_asc'] = 0; $sortQuery = $querySep.'sort_field='.validHtmlStr($_REQUEST['sort_field']).$querySep.'sort_asc='.validHtmlStr($_REQUEST['sort_asc']); if ( !isset($_REQUEST['limit']) ) $_REQUEST['limit'] = ''; if ( $saveToSession ) { $_SESSION['sort_field'] = validHtmlStr($_REQUEST['sort_field']); $_SESSION['sort_asc'] = validHtmlStr($_REQUEST['sort_asc']); } if ($_REQUEST['limit'] != '') { $limitQuery = "&limit=".$_REQUEST['limit']; } } function parseFilter( &$filter, $saveToSession=false, $querySep='&' ) { $filter['query'] = ''; $filter['sql'] = ''; $filter['fields'] = ''; $StorageArea = NULL; $terms = isset($filter['Query']) ? $filter['Query']['terms'] : NULL; if ( isset($terms) && count($terms) ) { for ( $i = 0; $i < count($terms); $i++ ) { if ( isset($terms[$i]['cnj']) ) { $filter['query'] .= $querySep.urlencode("filter[Query][terms][$i][cnj]").'='.urlencode($terms[$i]['cnj']); $filter['sql'] .= ' '.$terms[$i]['cnj'].' '; $filter['fields'] .= "\n"; } if ( isset($terms[$i]['obr']) ) { $filter['query'] .= $querySep.urlencode("filter[Query][terms][$i][obr]").'='.urlencode($terms[$i]['obr']); $filter['sql'] .= ' '.str_repeat( '(', $terms[$i]['obr'] ).' '; $filter['fields'] .= "\n"; } if ( isset($terms[$i]['attr']) ) { $filter['query'] .= $querySep.urlencode("filter[Query][terms][$i][attr]").'='.urlencode($terms[$i]['attr']); $filter['fields'] .= "\n"; switch ( $terms[$i]['attr'] ) { case 'MonitorName': $filter['sql'] .= 'M.'.preg_replace( '/^Monitor/', '', $terms[$i]['attr'] ); break; case 'ServerId': $filter['sql'] .= 'M.ServerId'; break; # Unspecified start or end, so assume start, this is to support legacy filters case 'DateTime': $filter['sql'] .= 'E.StartTime'; break; case 'Date': $filter['sql'] .= 'to_days( E.StartTime )'; break; case 'Time': $filter['sql'] .= 'extract( hour_second from E.StartTime )'; break; case 'Weekday': $filter['sql'] .= 'weekday( E.StartTime )'; break; # Starting Time case 'StartDateTime': $filter['sql'] .= 'E.StartTime'; break; case 'StartDate': $filter['sql'] .= 'to_days( E.StartTime )'; break; case 'StartTime': $filter['sql'] .= 'extract( hour_second from E.StartTime )'; break; case 'StartWeekday': $filter['sql'] .= 'weekday( E.StartTime )'; break; # Ending Time case 'EndDateTime': $filter['sql'] .= 'E.EndTime'; break; case 'EndDate': $filter['sql'] .= 'to_days( E.EndTime )'; break; case 'EndTime': $filter['sql'] .= 'extract( hour_second from E.EndTime )'; break; case 'EndWeekday': $filter['sql'] .= 'weekday( E.EndTime )'; break; case 'Id': case 'Name': case 'DiskSpace': case 'MonitorId': case 'StorageId': case 'Length': case 'Frames': case 'AlarmFrames': case 'TotScore': case 'AvgScore': case 'MaxScore': case 'Cause': case 'Notes': case 'StateId': case 'Archived': $filter['sql'] .= 'E.'.$terms[$i]['attr']; break; case 'DiskPercent': // Need to specify a storage area, so need to look through other terms looking for a storage area, else we default to ZM_EVENTS_PATH if ( ! $StorageArea ) { for ( $j = 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']); break; } } // end foreach remaining term if ( ! $StorageArea ) $StorageArea = new Storage(); } // end no StorageArea found yet $filter['sql'] .= getDiskPercent( $StorageArea->Path() ); break; case 'DiskBlocks': // Need to specify a storage area, so need to look through other terms looking for a storage area, else we default to ZM_EVENTS_PATH if ( ! $StorageArea ) { for ( $j = $i; $j < count($terms); $j++ ) { if ( isset($terms[$i]['attr']) and $terms[$i]['attr'] == 'StorageId' and isset($terms[$j]['val']) ) { $StorageArea = new Storage($terms[$i]['val']); } } // end foreach remaining term } // end no StorageArea found yet $filter['sql'] .= getDiskBlocks( $StorageArea ); break; case 'SystemLoad': $filter['sql'] .= getLoad(); break; } $valueList = array(); foreach ( preg_split( '/["\'\s]*?,["\'\s]*?/', preg_replace( '/^["\']+?(.+)["\']+?$/', '$1', $terms[$i]['val'] ) ) as $value ) { switch ( $terms[$i]['attr'] ) { case 'MonitorName': case 'Name': case 'Cause': case 'Notes': $value = dbEscape($value); break; case 'ServerId': if ( $value == 'ZM_SERVER_ID' ) { $value = ZM_SERVER_ID; } else { $value = dbEscape($value); } break; case 'StorageId': $StorageArea = new Storage( $value ); $value = dbEscape($value); break; case 'DateTime': case 'StartDateTime': case 'EndDateTime': $value = "'".strftime( STRF_FMT_DATETIME_DB, strtotime( $value ) )."'"; break; case 'Date': case 'StartDate': case 'EndDate': $value = "to_days( '".strftime( STRF_FMT_DATETIME_DB, strtotime( $value ) )."' )"; break; case 'Time': case 'StartTime': case 'EndTime': $value = "extract( hour_second from '".strftime( STRF_FMT_DATETIME_DB, strtotime( $value ) )."' )"; break; default : $value = dbEscape($value); break; } $valueList[] = $value; } switch ( $terms[$i]['op'] ) { case '=' : case '!=' : case '>=' : case '>' : case '<' : case '<=' : $filter['sql'] .= ' '.$terms[$i]['op'].' '. $value; break; case '=~' : $filter['sql'] .= ' regexp '.$value; break; case '!~' : $filter['sql'] .= ' not regexp '.$value; break; case '=[]' : case 'IN' : $filter['sql'] .= ' in ('.join( ',', $valueList ).')'; break; case '![]' : $filter['sql'] .= ' not in ('.join( ',', $valueList ).')'; break; case 'IS' : $filter['sql'] .= " IS $value"; break; case 'IS NOT' : $filter['sql'] .= " IS NOT $value"; break; default: Warning("Invalid operator in filter: " . $terms[$i]['op'] ); } $filter['query'] .= $querySep.urlencode("filter[Query][terms][$i][op]").'='.urlencode($terms[$i]['op']); $filter['fields'] .= "\n"; if ( isset($terms[$i]['val']) ) { $filter['query'] .= $querySep.urlencode("filter[Query][terms][$i][val]").'='.urlencode($terms[$i]['val']); $filter['fields'] .= "\n"; } } // end foreach term if ( isset($terms[$i]['cbr']) ) { $filter['query'] .= $querySep.urlencode("filter[Query][terms][$i][cbr]").'='.urlencode($terms[$i]['cbr']); $filter['sql'] .= ' '.str_repeat( ')', $terms[$i]['cbr'] ).' '; $filter['fields'] .= "\n"; } } if ( $filter['sql'] ) $filter['sql'] = ' and ( '.$filter['sql'].' )'; if ( $saveToSession ) { $_SESSION['filter'] = $filter; } } } // Please note that the filter is passed in by copy, so you need to use the return value from this function. // function addFilterTerm( $filter, $position, $term=false ) { if ( $position < 0 ) $position = 0; if ( ! isset( $filter['Query']['terms'] ) ) $filter['Query']['terms'] = array(); elseif( $position > count($filter['Query']['terms']) ) $position = count($filter['Query']['terms']); if ( $term && $position == 0 ) unset( $term['cnj'] ); array_splice( $filter['Query']['terms'], $position, 0, array( $term?$term:array() ) ); return( $filter ); } function delFilterTerm( $filter, $position ) { if ( $position < 0 ) $position = 0; elseif( $position >= count($filter['Query']['terms']) ) $position = count($filter['Query']['terms']); array_splice( $filter['Query']['terms'], $position, 1 ); return( $filter ); } function getPagination( $pages, $page, $maxShortcuts, $query, $querySep='&' ) { global $view; $pageText = ''; if ( $pages > 1 ) { if ( $page ) { if ( $page < 0 ) $page = 1; if ( $page > $pages ) $page = $pages; if ( $page > 1 ) { if ( false && $page > 2 ) { $pageText .= '<<'; } $pageText .= '<'; $newPages = array(); $pagesUsed = array(); $lo_exp = max(2,log($page-1)/log($maxShortcuts)); for ( $i = 0; $i < $maxShortcuts; $i++ ) { $newPage = round($page-pow($lo_exp,$i)); if ( isset($pagesUsed[$newPage]) ) continue; if ( $newPage <= 1 ) break; $pagesUsed[$newPage] = true; array_unshift( $newPages, $newPage ); } if ( !isset($pagesUsed[1]) ) array_unshift( $newPages, 1 ); foreach ( $newPages as $newPage ) { $pageText .= ''.$newPage.' '; } } $pageText .= '- '.$page.' -'; if ( $page < $pages ) { $newPages = array(); $pagesUsed = array(); $hi_exp = max(2,log($pages-$page)/log($maxShortcuts)); for ( $i = 0; $i < $maxShortcuts; $i++ ) { $newPage = round($page+pow($hi_exp,$i)); if ( isset($pagesUsed[$newPage]) ) continue; if ( $newPage > $pages ) break; $pagesUsed[$newPage] = true; array_push( $newPages, $newPage ); } if ( !isset($pagesUsed[$pages]) ) array_push( $newPages, $pages ); foreach ( $newPages as $newPage ) { $pageText .= ' '.$newPage.''; } $pageText .= '>'; if ( false && $page < ($pages-1) ) { $pageText .= '>>'; } } } } return( $pageText ); } function sortHeader( $field, $querySep='&' ) { global $view; return( '?view='.$view.$querySep.'page=1'.$_REQUEST['filter']['query'].$querySep.'sort_field='.$field.$querySep.'sort_asc='.($_REQUEST['sort_field'] == $field?!$_REQUEST['sort_asc']:0).$querySep.'limit='.$_REQUEST['limit'] ); } function sortTag( $field ) { if ( $_REQUEST['sort_field'] == $field ) if ( $_REQUEST['sort_asc'] ) return( '(^)' ); else return( '(v)' ); return( false ); } function getLoad() { $load = sys_getloadavg(); return( $load[0] ); } function getDiskPercent($path = ZM_DIR_EVENTS) { $total = disk_total_space($path); if ( $total === false ) { Error('disk_total_space returned false. Verify the web account user has access to ' . $path ); return 0; } elseif ( $total == 0 ) { Error('disk_total_space indicates the following path has a filesystem size of zero bytes ' . $path ); return 100; } $free = disk_free_space($path); if ( $free === false ) { Error('disk_free_space returned false. Verify the web account user has access to ' . $path ); } $space = round((($total - $free) / $total) * 100); return( $space ); } function getDiskBlocks() { if ( ! $StorageArea ) $StorageArea = new Storage(); $df = shell_exec( 'df '.escapeshellarg($StorageArea->Path() )); $space = -1; if ( preg_match( '/\s(\d+)\s+\d+\s+\d+%/ms', $df, $matches ) ) $space = $matches[1]; return( $space ); } function systemStats() { $load = getLoad(); $diskPercent = getDiskPercent(); $pathMapPercent = getDiskPercent(ZM_PATH_MAP); $cpus = getcpus(); $normalized_load = $load / $cpus; # Colorize the system load stat if ( $normalized_load <= 0.75 ) { $htmlLoad=$load; } elseif ( $normalized_load <= 0.9 ) { $htmlLoad="$load"; } elseif ( $normalized_load <= 1.1 ) { $htmlLoad="$load"; } else { $htmlLoad="$load"; } # Colorize the disk space stat if ( $diskPercent < 98 ) { $htmlDiskPercent="$diskPercent%"; } elseif ( $diskPercent <= 99 ) { $htmlDiskPercent="$diskPercent%"; } else { $htmlDiskPercent="$diskPercent%"; } # Colorize the PATH_MAP (usually /dev/shm) stat if ( $pathMapPercent < 90 ) { if ( disk_free_space(ZM_PATH_MAP) > 209715200 ) { # have to always have at least 200MiB free $htmlPathMapPercent="$pathMapPercent%"; } else { $htmlPathMapPercent="$pathMapPercent%"; } } elseif ( $pathMapPercent < 100 ) { $htmlPathMapPercent="$pathMapPercent%"; } else { $htmlPathMapPercent="$pathMapPercent%"; } $htmlString = translate('Load').": $htmlLoad - ".translate('Disk').": $htmlDiskPercent - ".ZM_PATH_MAP.": $htmlPathMapPercent"; return( $htmlString ); } function getcpus() { if (is_readable("/proc/cpuinfo") ) { # Works on Linux preg_match_all('/^processor/m', file_get_contents('/proc/cpuinfo'), $matches); $num_cpus = count($matches[0]); } else { # Works on BSD $matches = explode(":", shell_exec("sysctl hw.ncpu")); $num_cpus = trim($matches[1]); } return( $num_cpus ); } // Function to fix a problem whereby the built in PHP session handling // features want to put the sid as a hidden field after the form or // fieldset tag, neither of which will work with strict XHTML Basic. function sidField() { if ( SID ) { list( $sessname, $sessid ) = explode( "=", SID ); ?> '; return( false ); } $dx1 = $line1[1]['x'] - $line1[0]['x']; $dy1 = $line1[1]['y'] - $line1[0]['y']; $dx2 = $line2[1]['x'] - $line2[0]['x']; $dy2 = $line2[1]['y'] - $line2[0]['y']; if ( $dx1 ) { $m1 = $dy1/$dx1; $b1 = $line1[0]['y'] - ($m1 * $line1[0]['x']); } else { $b1 = $line1[0]['y']; } if ( $dx2 ) { $m2 = $dy2/$dx2; $b2 = $line2[0]['y'] - ($m2 * $line2[0]['x']); } else { $b2 = $line2[0]['y']; } if ( $dx1 && $dx2 ) { // Both not vertical if ( $m1 != $m2 ) { // Not parallel or colinear $x = ( $b2 - $b1 ) / ( $m1 - $m2 ); if ( $x >= $min_x1 && $x <= $max_x1 && $x >= $min_x2 && $x <= $max_x2 ) { if ( $debug ) echo "Intersecting, at x $x