From 1e3eb8a8923f9b84f29d6fa9a1bc98ef8b1d247e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 08:43:06 +0000 Subject: [PATCH 1/6] Cameras: keep a custom ONVIF port (e.g. 8080) when credentials change The camera address is ip + port + onvif_ctrl (la_mojo builds http://ip[:port]onvif_ctrl). The web UI broke it for cameras whose ONVIF interface isn't on port 80. doCameraOperation.php, CMD 4 (change IP / credentials) - An address without ":port" set port=NULL. The camera editor showed the IP without the port, so changing only the credentials moved a camera on 8080 back to port 80. Now "ip:port" sets the port and "ip" keeps the stored one. - A port kept inside onvif_ctrl (":8080/onvif/device_service", cameras added by discovery) is moved to `port`. Once port was set too, la_mojo built http://ip:8080:8080/onvif/device_service. doCameraOperation.php, CMD 3 (add camera / check credentials) - Camera from the DB: the port may also come from onvif_ctrl (it was read from `port` only, so the check went to port 80 and failed). - Direct address: "ip:port" or the dialog's Port field (PO) is the ONVIF port. Discovery stores ip, port and the device service path separately. Without discovery, onvif_ctrl was the full MEDIA service URL and ip was "ip:port"; now it is /onvif/device_service, ip and port. - count() of a string (PHP 8 TypeError, not caught) killed the request when the snapshot URI was read. getCameraEditor.php - The address field shows "ip:port" when the camera has a port. Tested with PHP 8.3, a SQLite cameras table and a fake ONVIF camera on a custom port. The old code dropped the port, built ip:8080:8080, stored "ip:port" + the media URL, and crashed. Now the record and the credential check are correct. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16 --- lib/controller/doCameraOperation.php | 92 ++++++++++++++++++++++------ lib/controller/getCameraEditor.php | 6 +- 2 files changed, 78 insertions(+), 20 deletions(-) diff --git a/lib/controller/doCameraOperation.php b/lib/controller/doCameraOperation.php index cea3e26..02ce1db 100644 --- a/lib/controller/doCameraOperation.php +++ b/lib/controller/doCameraOperation.php @@ -1,5 +1,36 @@ array( host, port ) - port 0 when not given + function camSplitHostPort( $S ){ + $S = trim( $S ); + $P = 0; + if( preg_match( '/^(.*):(\d{1,5})$/', $S, $M ) ){ + $S = $M[1]; + $P = intval( $M[2] ); + if( $P > 65535 ) $P = 0; + }; + return array( $S, $P ); + }; + // ONVIF service URL or stored onvif_ctrl -> array( path, port ): + // "http://1.2.3.4:8080/onvif/device_service" and ":8080/onvif/device_service" -> ( "/onvif/device_service", 8080 ) + function camOnvifPath( $U ){ + $U = trim( $U ); + $P = 0; + if( preg_match( '#^[a-z]+://#i', $U ) ){ + $H = parse_url( $U ); + $P = isset( $H['port'] ) ? intval( $H['port'] ) : 0; + $U = isset( $H['path'] ) ? $H['path'] : '/'; + } elseif( preg_match( '#^:(\d{1,5})(/.*)?$#', $U, $M ) ){ + $P = intval( $M[1] ); + $U = isset( $M[2] ) ? $M[2] : '/'; + }; + return array( $U, $P ); + }; if( $CUser->Data['id'] > 1 ){ $Data = array(); $Data['status'] = 'na'; @@ -69,12 +100,17 @@ $AUTH = intval( $_POST['AU'] ); $onvif = new Ponvif(); $IP = ''; + $PORT = 0; if( $CameraID ){ // Cam From DB - $QS ="SELECT `ip`,`port` FROM `cameras` WHERE `id`={$CameraID}"; + $QS ="SELECT `ip`,`port`,`onvif_ctrl` FROM `cameras` WHERE `id`={$CameraID}"; $JJ = $DATABASE->Query( $QS ); if( count( $JJ ) ){ $IP = $JJ[0]['ip']; $PORT = intval($JJ[0]['port']); + if( !$PORT ){ + // Older records keep the port in onvif_ctrl (":8080/onvif/device_service") + list( $CTRL, $PORT ) = camOnvifPath( $JJ[0]['onvif_ctrl'] ); + }; if( $PORT ){ $onvif->setIPAddress( $IP.':'.$PORT ); } else { @@ -83,8 +119,14 @@ } else $CameraID = 0; } else { // Direct IP $Data['ss']='DirectIP'; - $IP = $DATABASE->escape( $_POST['IP'] ); - $onvif->setIPAddress( $IP ); + // "1.2.3.4:8080" or the Port field of the dialog (PO): a camera whose ONVIF interface is not on port 80 + list( $IP, $PORT ) = camSplitHostPort( $_POST['IP'] ); + $IP = $DATABASE->escape( $IP ); + if( !$PORT && isset( $_POST['PO'] ) ){ + $PORT = intval( $_POST['PO'] ); + if( $PORT < 1 || $PORT > 65535 ) $PORT = 0; + }; + $onvif->setIPAddress( $IP ); // WS-Discovery probe goes to the host $RR = $onvif->discover(); if( count( $RR ) ){ $Data['ss']='Discover Have'; @@ -97,8 +139,11 @@ $CM = ''; $CI = $DATABASE->escape($R['IPAddr']); $Frr = explode( ' ', $R['XAddrs']); - $Crr = explode( $CI, $Frr[0] ); - $CP = $DATABASE->escape($Crr[1]); + // Path and port of the device service: the port was left inside onvif_ctrl (":8080/onvif/...") + list( $CTRL, $XPORT ) = camOnvifPath( $Frr[0] ); + $CP = $DATABASE->escape( $CTRL ); + if( !$PORT ) $PORT = $XPORT; // a port typed by the user wins (NAT / port forwarding) + $SPORT = $PORT ? $PORT : 'NULL'; $CN = ''; $CH = ''; $CC = 0; @@ -114,7 +159,7 @@ if( stripos($TBrr[0],'hardware') !== false ) $CH = $DATABASE->escape(urldecode($TBrr[1])); if( stripos($TBrr[0],'mac') !== false ) $CM = $DATABASE->escape(urldecode($TBrr[1])); }; - $QS = "INSERT INTO `cameras`(hardware,type,name,uuid,mac,ip,status,onvif_ctrl,online,manual) VALUES('{$CH}',13,'{$CN}','{$CA}','{$CM}','{$CI}',0,'{$CP}',1,1) ON CONFLICT( uuid ) DO UPDATE SET ip='{$CI}', online=1"; + $QS = "INSERT INTO `cameras`(hardware,type,name,uuid,mac,ip,port,status,onvif_ctrl,online,manual) VALUES('{$CH}',13,'{$CN}','{$CA}','{$CM}','{$CI}',{$SPORT},0,'{$CP}',1,1) ON CONFLICT( uuid ) DO UPDATE SET ip='{$CI}', port={$SPORT}, onvif_ctrl='{$CP}', online=1"; $DATABASE->Query($QS,false); $CameraID = $DATABASE->getLastInsertID(); if( $CameraID == 0 ){ @@ -126,10 +171,12 @@ }; } else { $Data['ss'] .='No Discover'; + $onvif->setIPAddress( $PORT ? $IP.':'.$PORT : $IP ); $onvif->setUsername( $EUser ); $onvif->setPassword( $EPass ); $onvif->setAuthMethod( $AUTH ); $CI = $IP; + $SPORT = $PORT ? $PORT : 'NULL'; $CameraID = 0; try { $onvif->initialize(); @@ -139,8 +186,9 @@ $CN = $info['Manufacturer'].'_CAM'.$info['HardwareId']; $CA = $info['SerialNumber']; $CM = $info['SerialNumber']; - $CP = $onvif->getDeviceUri(); - $QS = "INSERT INTO `cameras`(hardware,type,name,uuid,mac,ip,status,onvif_ctrl,online,manual) VALUES('{$CH}',13,'{$CN}','{$CA}','{$CM}','{$CI}',0,'{$CP}',1,1) ON CONFLICT( uuid ) DO UPDATE SET ip='{$CI}', online=1"; + // getDeviceUri() returns the MEDIA service URL (full URL): la_mojo needs the device service path + $CP = '/onvif/device_service'; + $QS = "INSERT INTO `cameras`(hardware,type,name,uuid,mac,ip,port,status,onvif_ctrl,online,manual) VALUES('{$CH}',13,'{$CN}','{$CA}','{$CM}','{$CI}',{$SPORT},0,'{$CP}',1,1) ON CONFLICT( uuid ) DO UPDATE SET ip='{$CI}', port={$SPORT}, onvif_ctrl='{$CP}', online=1"; $DATABASE->Query($QS,false); $CameraID = $DATABASE->getLastInsertID(); }; @@ -178,7 +226,7 @@ $Emrl = str_replace( $mrl_proto . '://' . $IP, '', $Emrl ); $TPArr = explode(':',$pic ); $pic_proto = $TPArr[0]; - if( count( $TPArr[0] ) > 2 ){ + if( count( $TPArr ) > 2 ){ $pic_port = intval( $TPArr[2] ); if($pic_port == 0 ) $pic_port = 80; } else $pic_port = 80; @@ -209,6 +257,7 @@ if( $CameraID ){ $Data['status'] = 'ok'; if( $EUser!= '' ){ + if( $PORT ) $onvif->setIPAddress( $IP.':'.$PORT ); // not port 80 $onvif->setUsername( $EUser ); $onvif->setPassword( $EPass ); $onvif->setAuthMethod( $AUTH ); @@ -300,16 +349,21 @@ //$PA[2] = $EIP; //$OVC = implode('/',$PA); $AUTH = intval( $_POST['AU'] ); - $TAr = explode( ':', $EIP ); - if( count( $TAr ) > 1 ){ - $EIP = $TAr[0]; - $POR = intval($TAr[1]); - //$QS = "UPDATE cameras SET access_login='$EUser', access_pass='$EPass', auth_mode={$AUTH},`ip`='{$EIP}',port={$POR}, onvif_ctrl='{$OVC}' WHERE id={$CameraID}"; - $QS = "UPDATE cameras SET access_login='$EUser', access_pass='$EPass', auth_mode={$AUTH},`ip`='{$EIP}',port={$POR} WHERE id={$CameraID}"; - } else { - //$QS = "UPDATE cameras SET access_login='$EUser', access_pass='$EPass', auth_mode={$AUTH},`ip`='{$EIP}', port=NULL, onvif_ctrl='{$OVC}' WHERE id={$CameraID}"; - $QS = "UPDATE cameras SET access_login='$EUser', access_pass='$EPass', auth_mode={$AUTH},`ip`='{$EIP}', port=NULL WHERE id={$CameraID}"; - }; + /* + Before: an address without ":port" set port=NULL. The editor showed the IP without the + port, so changing only the credentials moved a camera on 8080 back to port 80. + Now: "ip:port" sets the port, "ip" keeps the stored one. A port kept inside onvif_ctrl + (":8080/onvif/...", cameras added by discovery) is moved to `port`: with both, la_mojo + built http://ip:8080:8080/onvif/... + */ + list( $EIP, $POR ) = camSplitHostPort( $_POST['UI'] ); + $EIP = $DATABASE->escape( $EIP ); + list( $CTRL, $CTRL_PORT ) = camOnvifPath( $CC['onvif_ctrl'] ); + if( !$POR ) $POR = intval( $CC['port'] ); + if( !$POR ) $POR = $CTRL_PORT; + $SPOR = $POR ? $POR : 'NULL'; + $ECTRL = $DATABASE->escape( $CTRL ); + $QS = "UPDATE cameras SET access_login='$EUser', access_pass='$EPass', auth_mode={$AUTH},`ip`='{$EIP}', port={$SPOR}, onvif_ctrl='{$ECTRL}' WHERE id={$CameraID}"; $DATABASE->Query( $QS, false ); $Data['status'] = 'ok'; } else { diff --git a/lib/controller/getCameraEditor.php b/lib/controller/getCameraEditor.php index f807c69..caa8ea5 100644 --- a/lib/controller/getCameraEditor.php +++ b/lib/controller/getCameraEditor.php @@ -19,6 +19,10 @@ }; $Cam['node_name'] = $Node['name']; $Cam['name']=urldecode( $Cam['name'] ); + // Address field "ip:port" for a camera not on port 80 (port also kept inside onvif_ctrl by older records) + $CamPort = intval( $Cam['port'] ); + if( !$CamPort && preg_match( '#^:(\d{1,5})/#', trim( $Cam['onvif_ctrl'] ), $CamM ) ) $CamPort = intval( $CamM[1] ); + $Cam['ip_port'] = $Cam['ip'] . ( $CamPort ? ':' . $CamPort : '' ); $TB = explode( ' ', $Cam['name'] ); $Cam['name'] = $TB[0]; if( stripos($Cam['ip'],'/dev/video') !==false ){ @@ -110,7 +114,7 @@ id: 'am_ip_addr', fieldLabel: '{$Labels->GetLabel('_CAM_IP_ADDRESS_')}', width: '100%', - value: '{$Cam['ip']}' + value: '{$Cam['ip_port']}' },{ xtype: 'textfield', id: 'am_login', -- 2.39.5 From 1f0b0812ff0a0549235eeced8a112ea28d5c78b6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 08:44:52 +0000 Subject: [PATCH 2/6] toto.php: XML-escape the values put into ONVIF requests Every request (19 builders) put the user name, profile / preset / node tokens, preset name, stream and protocol into the SOAP XML unescaped. A user name such as "a&b" or a token containing "&" or "<" made the request malformed. The camera rejected it, and the UI reported "Provided Credentials are Wrong!". - _xesc() / _xescAll(): htmlspecialchars(ENT_XML1 | ENT_QUOTES, UTF-8) on string values. Numbers and booleans are replaced as before. - The password itself is not affected: only its digest is sent. Tested against a fake ONVIF camera with user "us&er<1>", password 'p&ss"word' and profile token "main&0", adding the camera on a custom port. Before, the camera got malformed XML after GetSystemDateAndTime. Now the camera, its login and its stream are stored. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16 --- lib/php/onvif/toto.php | 90 ++++++++++++++++++++++++------------------ 1 file changed, 52 insertions(+), 38 deletions(-) diff --git a/lib/php/onvif/toto.php b/lib/php/onvif/toto.php index ad7b9b6..1ccb217 100644 --- a/lib/php/onvif/toto.php +++ b/lib/php/onvif/toto.php @@ -173,10 +173,10 @@ class Ponvif { "%%PASSWORD%%", "%%NONCE%%", "%%CREATED%%"), - array($REQ['USERNAME'], + $this->_xescAll(array($REQ['USERNAME'], $REQ['PASSDIGEST'], $REQ['NONCE'], - $REQ['TIMESTAMP']), + $REQ['TIMESTAMP'])), $post_string); if ($this->isFault($response=$this->_send_request($this->mediauri,$post_string))) { if ($this->intransingent) throw new Exception('GetCapabilities: Communication error'); @@ -192,10 +192,10 @@ class Ponvif { "%%PASSWORD%%", "%%NONCE%%", "%%CREATED%%"), - array($REQ['USERNAME'], + $this->_xescAll(array($REQ['USERNAME'], $REQ['PASSDIGEST'], $REQ['NONCE'], - $REQ['TIMESTAMP']), + $REQ['TIMESTAMP'])), $post_string); //echo "POST STRING:" . $post_string . "\n\n"; if ($this->isFault($response=$this->_send_request($this->mediauri,$post_string))) { @@ -213,10 +213,10 @@ class Ponvif { "%%PASSWORD%%", "%%NONCE%%", "%%CREATED%%"), - array($REQ['USERNAME'], + $this->_xescAll(array($REQ['USERNAME'], $REQ['PASSDIGEST'], $REQ['NONCE'], - $REQ['TIMESTAMP']), + $REQ['TIMESTAMP'])), $post_string); if ($this->isFault($response=$this->_send_request($this->mediauri,$post_string))) { if ($this->intransingent) throw new Exception('GetProfiles: Communication error'); @@ -232,10 +232,10 @@ class Ponvif { "%%PASSWORD%%", "%%NONCE%%", "%%CREATED%%"), - array($REQ['USERNAME'], + $this->_xescAll(array($REQ['USERNAME'], $REQ['PASSDIGEST'], $REQ['NONCE'], - $REQ['TIMESTAMP']), + $REQ['TIMESTAMP'])), $post_string); if ($this->isFault($this->_send_request($this->mediauri,$post_string))) { if ($this->intransingent) throw new Exception('GetServices: Communication error'); @@ -249,10 +249,10 @@ class Ponvif { "%%PASSWORD%%", "%%NONCE%%", "%%CREATED%%"), - array($REQ['USERNAME'], + $this->_xescAll(array($REQ['USERNAME'], $REQ['PASSDIGEST'], $REQ['NONCE'], - $REQ['TIMESTAMP']), + $REQ['TIMESTAMP'])), $post_string); if ($this->isFault($response=$this->_send_request($this->mediauri,$post_string))) { if ($this->intransingent) throw new Exception('GetDeviceInformation: Communication error'); @@ -272,13 +272,13 @@ class Ponvif { "%%PROFILETOKEN%%", "%%STREAM%%", "%%PROTOCOL%%"), - array($REQ['USERNAME'], + $this->_xescAll(array($REQ['USERNAME'], $REQ['PASSDIGEST'], $REQ['NONCE'], $REQ['TIMESTAMP'], $profileToken, $stream, - $protocol), + $protocol)), $post_string ); if ($this->isFault($response=$this->_send_request($this->mediauri,$post_string))) { @@ -296,11 +296,11 @@ class Ponvif { "%%NONCE%%", "%%CREATED%%", "%%PROFILETOKEN%%"), - array($REQ['USERNAME'], + $this->_xescAll(array($REQ['USERNAME'], $REQ['PASSDIGEST'], $REQ['NONCE'], $REQ['TIMESTAMP'], - $profileToken), + $profileToken)), $post_string); if ($this->isFault($response=$this->_send_request($this->mediauri,$post_string))) { if ($this->intransingent) throw new Exception('GetSnapshotUri: Communication error'); @@ -319,11 +319,11 @@ class Ponvif { "%%NONCE%%", "%%CREATED%%", "%%PROFILETOKEN%%"), - array($REQ['USERNAME'], + $this->_xescAll(array($REQ['USERNAME'], $REQ['PASSDIGEST'], $REQ['NONCE'], $REQ['TIMESTAMP'], - $profileToken), + $profileToken)), $post_string); if ($this->isFault($response=$this->_send_request($this->ptzuri,$post_string))) { if ($this->intransingent) throw new Exception('GetPresets: Communication error'); @@ -349,11 +349,11 @@ class Ponvif { "%%NONCE%%", "%%CREATED%%", "%%NODETOKEN%%"), - array($REQ['USERNAME'], + $this->_xescAll(array($REQ['USERNAME'], $REQ['PASSDIGEST'], $REQ['NONCE'], $REQ['TIMESTAMP'], - $ptzNodeToken), + $ptzNodeToken)), $post_string); if ($this->isFault($response=$this->_send_request($this->ptzuri,$post_string))) { if ($this->intransingent) throw new Exception('GetNode: Communication error'); @@ -375,7 +375,7 @@ class Ponvif { "%%SPEEDPANTILTX%%", "%%SPEEDPANTILTY%%", "%%SPEEDZOOMX%%"), - array($REQ['USERNAME'], + $this->_xescAll(array($REQ['USERNAME'], $REQ['PASSDIGEST'], $REQ['NONCE'], $REQ['TIMESTAMP'], @@ -383,7 +383,7 @@ class Ponvif { $presetToken, $speed_pantilt_x, $speed_pantilt_y, - $speed_zoom_x), + $speed_zoom_x)), $post_string); if ($this->isFault($this->_send_request($this->ptzuri,$post_string))) { if ($this->intransingent) throw new Exception('GotoPreset: Communication error'); @@ -400,12 +400,12 @@ class Ponvif { "%%CREATED%%", "%%PROFILETOKEN%%", "%%PRESETTOKEN%%"), - array($REQ['USERNAME'], + $this->_xescAll(array($REQ['USERNAME'], $REQ['PASSDIGEST'], $REQ['NONCE'], $REQ['TIMESTAMP'], $profileToken, - $presetToken), + $presetToken)), $post_string); if ($this->isFault($this->_send_request($this->ptzuri,$post_string))) { if ($this->intransingent) throw new Exception('RemovePreset: Communication error'); @@ -422,12 +422,12 @@ class Ponvif { "%%CREATED%%", "%%PROFILETOKEN%%", "%%PRESETNAME%%"), - array($REQ['USERNAME'], + $this->_xescAll(array($REQ['USERNAME'], $REQ['PASSDIGEST'], $REQ['NONCE'], $REQ['TIMESTAMP'], $profileToken, - $presetName), + $presetName)), $post_string); if ($this->isFault($this->_send_request($this->ptzuri,$post_string))) { if ($this->intransingent) throw new Exception('SetPreset: Communication error'); @@ -447,7 +447,7 @@ class Ponvif { "%%TRANSLATIONPANTILTY%%", "%%SPEEDPANTILTX%%", "%%SPEEDPANTILTY%%"), - array($REQ['USERNAME'], + $this->_xescAll(array($REQ['USERNAME'], $REQ['PASSDIGEST'], $REQ['NONCE'], $REQ['TIMESTAMP'], @@ -455,7 +455,7 @@ class Ponvif { $translation_pantilt_x, $translation_pantilt_y, $speed_pantilt_x, - $speed_pantilt_y), + $speed_pantilt_y)), $post_string); if ($this->isFault($this->_send_request($this->ptzuri,$post_string))) { if ($this->intransingent) throw new Exception('RelativeMove: Communication error'); @@ -473,13 +473,13 @@ class Ponvif { "%%PROFILETOKEN%%", "%%SPEEDZOOM%%", "%%ZOOM%%"), - array($REQ['USERNAME'], + $this->_xescAll(array($REQ['USERNAME'], $REQ['PASSDIGEST'], $REQ['NONCE'], $REQ['TIMESTAMP'], $profileToken, $speedZoom, - $zoom), + $zoom)), $post_string); if ($this->isFault($this->_send_request($this->ptzuri,$post_string))) { if ($this->intransingent) throw new Exception('RelativeMoveZoom: Communication error'); @@ -494,11 +494,11 @@ class Ponvif { "%%NONCE%%", "%%CREATED%%", "%%PROFILETOKEN%%"), - array($REQ['USERNAME'], + $this->_xescAll(array($REQ['USERNAME'], $REQ['PASSDIGEST'], $REQ['NONCE'], $REQ['TIMESTAMP'], - $profileToken), + $profileToken)), $post_string); if ($this->isFault($response = $this->_send_request($this->ptzuri,$post_string))) { if ($this->intransingent) throw new Exception('ptz Get Status: Communication error'); @@ -524,7 +524,7 @@ class Ponvif { "%%SPEEDPANTILTX%%", "%%SPEEDPANTILTY%%", "%%SPEEDZOOMX%%"), - array($REQ['USERNAME'], + $this->_xescAll(array($REQ['USERNAME'], $REQ['PASSDIGEST'], $REQ['NONCE'], $REQ['TIMESTAMP'], @@ -534,7 +534,7 @@ class Ponvif { $zoom, $PSpeed, $TSpeed, - $ZSpeed), + $ZSpeed)), $post_string); if ($this->isFault($this->_send_request($this->ptzuri,$post_string))) { if ($this->intransingent) throw new Exception('AbsoluteMove: Communication error'); @@ -552,13 +552,13 @@ class Ponvif { "%%PROFILETOKEN%%", "%%VELOCITYPANTILTX%%", "%%VELOCITYPANTILTY%%"), - array($REQ['USERNAME'], + $this->_xescAll(array($REQ['USERNAME'], $REQ['PASSDIGEST'], $REQ['NONCE'], $REQ['TIMESTAMP'], $profileToken, $velocity_pantilt_x, - $velocity_pantilt_y), + $velocity_pantilt_y)), $post_string); if ( $this->isFault($this->_send_request($this->ptzuri,$post_string))) { if( $this->intransingent ) throw new Exception('ContinuousMove: Communication error'); @@ -575,12 +575,12 @@ class Ponvif { "%%CREATED%%", "%%PROFILETOKEN%%", "%%ZOOM%%"), - array($REQ['USERNAME'], + $this->_xescAll(array($REQ['USERNAME'], $REQ['PASSDIGEST'], $REQ['NONCE'], $REQ['TIMESTAMP'], $profileToken, - $zoom), + $zoom)), $post_string); if ($this->isFault($this->_send_request($this->ptzuri,$post_string))) { if ($this->intransingent) throw new Exception('ContinuousMoveZoom: Communication error'); @@ -598,13 +598,13 @@ class Ponvif { "%%PROFILETOKEN%%", "%%PANTILT%%", "%%ZOOM%%"), - array($REQ['USERNAME'], + $this->_xescAll(array($REQ['USERNAME'], $REQ['PASSDIGEST'], $REQ['NONCE'], $REQ['TIMESTAMP'], $profileToken, $pantilt, - $zoom), + $zoom)), $post_string); if ($this->isFault($this->_send_request($this->ptzuri,$post_string))) { if ($this->intransingent) throw new Exception('Stop: Communication error'); @@ -707,6 +707,20 @@ class Ponvif { return $data; } + /* + Values put into the XML of a request (user name, profile / preset / node tokens, preset name ...) + must be XML-escaped: a user name like "a&b" or a token with "&" or "<" made the request + malformed - the camera rejected it and the UI reported "Credentials are Wrong!". + Only strings are escaped: numbers and booleans are replaced as before. + */ + protected function _xesc($v) { + return is_string($v) ? htmlspecialchars($v, ENT_XML1 | ENT_QUOTES, 'UTF-8') : $v; + } + + protected function _xescAll($values) { + return array_map(array($this, '_xesc'), $values); + } + protected function _passwordDigest( $username, $password, $timestamp = "default", $nonce = "default" ) { if ($timestamp=='default') $timestamp=date('Y-m-d\TH:i:s.000\Z'); if ($nonce=='default') $nonce=mt_rand(); -- 2.39.5 From d66bde56dd9511ce167d3a01eb269af064939f53 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 18:22:42 +0000 Subject: [PATCH 3/6] toto.php: no PHP Error past try/catch in initialize() Ponvif::initialize() -> media_GetVideoSources() ended the whole request on PHP 8, past the callers' try { } catch (Exception $e): - a camera answering with an HTML page (e.g. HTTP 401): _xml2array() found no , simplexml_load_string() returned false, and $xml->getName() threw an Error; - a reply without : _getActiveSources() called count(null), which throws a TypeError. toto.php - _xml2array() never throws: an empty, HTML or non-SOAP reply becomes a Fault ("reply is not a SOAP envelope", "empty reply", ...). The HTTP status is added in _send_request() ("HTTP 401: ..."). - initialize() throws an Exception when there is no media service, no video source or no profile. Any other PHP Error inside is re-thrown as an Exception. The time query catches Throwable. - The "Communication error" exceptions (19) give the reason: the HTTP fault above, or the SOAP Fault text of the camera. - A camera with ONE profile or video source works: a single XML element decodes to an associative array, so count() counted its fields and no source was found. - _getOnvifVersion(), GetVideoSources and the profile fields (RateControl is optional in ONVIF) are read with isset(). Warnings displayed by PHP would otherwise end up in the AJAX JSON reply. doCameraOperation.php - The 7 try blocks catch Throwable, and "Provided Credentials are Wrong!" now shows the reason, e.g. "GetVideoSources: Communication error (HTTP 401: reply is not a SOAP envelope)". Tested with PHP 8.3 and a fake ONVIF camera. HTML 401 page and empty : before, a fatal Error/TypeError ended the script; now an Exception with the reason, and a JSON reply from doCameraOperation. An empty 401 body and a good camera behave as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16 --- lib/controller/doCameraOperation.php | 28 ++-- lib/php/onvif/toto.php | 213 +++++++++++++++++---------- 2 files changed, 149 insertions(+), 92 deletions(-) diff --git a/lib/controller/doCameraOperation.php b/lib/controller/doCameraOperation.php index 02ce1db..252ca26 100644 --- a/lib/controller/doCameraOperation.php +++ b/lib/controller/doCameraOperation.php @@ -248,8 +248,8 @@ } else { $Data['msg'] = 'No Camera was added.
'; }; - } catch( Exception $e ){ - $Data['msg'] = 'Provided Credentials are Wrong! ['.$EUser.']:['.$EPass.']'; + } catch( Throwable $e ){ // PHP 8 Errors too: an uncaught Error ended the request without an answer + $Data['msg'] = 'Provided Credentials are Wrong! ['.$EUser.']:['.$EPass.']
'.htmlspecialchars( $e->getMessage() ); }; break; }; @@ -308,8 +308,8 @@ } else { $Data['msg'] = 'Camera was added.
However provided Credentials are Wrong! ['.$EUser.']:['.$EPass.']'; }; - } catch( Exception $e ){ - $Data['msg'] = 'Provided Credentials are Wrong! ['.$EUser.']:['.$EPass.']'; + } catch( Throwable $e ){ // PHP 8 Errors too: an uncaught Error ended the request without an answer + $Data['msg'] = 'Provided Credentials are Wrong! ['.$EUser.']:['.$EPass.']
'.htmlspecialchars( $e->getMessage() ); }; } else { $Data['msg'] = 'Camera Sucessfully Added
Please Provide Access Credentials and Other Camera Settings'; @@ -491,8 +491,8 @@ } else { $Data['msg'] = 'OnVif Query Device Fault!'; } - } catch( Exception $e ){ - $Data['msg'] = 'Provided Credentials are Wrong! ['.$EUser.']:['.$EPass.']'; + } catch( Throwable $e ){ // PHP 8 Errors too: an uncaught Error ended the request without an answer + $Data['msg'] = 'Provided Credentials are Wrong! ['.$EUser.']:['.$EPass.']
'.htmlspecialchars( $e->getMessage() ); }; } else { $Data['status'] = 'nocam'; @@ -882,8 +882,8 @@ } else { $Data['msg'] = 'OnVif Query Device Fault!'; } - } catch( Exception $e ){ - $Data['msg'] = 'Provided Credentials are Wrong! ['.$EUser.']:['.$EPass.']'; + } catch( Throwable $e ){ // PHP 8 Errors too: an uncaught Error ended the request without an answer + $Data['msg'] = 'Provided Credentials are Wrong! ['.$EUser.']:['.$EPass.']
'.htmlspecialchars( $e->getMessage() ); }; } else $Data['status'] = 'nocam'; } else $Data['status'] = 'nopresetspace'; @@ -934,8 +934,8 @@ } else { $Data['msg'] = 'OnVif Query Device Fault!'; } - } catch( Exception $e ){ - $Data['msg'] = 'Provided Credentials are Wrong! ['.$EUser.']:['.$EPass.']'; + } catch( Throwable $e ){ // PHP 8 Errors too: an uncaught Error ended the request without an answer + $Data['msg'] = 'Provided Credentials are Wrong! ['.$EUser.']:['.$EPass.']
'.htmlspecialchars( $e->getMessage() ); }; } else $Data['status'] = 'nocam'; } else $Data['status'] = 'nopreset'; @@ -986,8 +986,8 @@ } else { $Data['msg'] = 'OnVif Query Device Fault!'; } - } catch( Exception $e ){ - $Data['msg'] = 'Provided Credentials are Wrong! ['.$EUser.']:['.$EPass.']'; + } catch( Throwable $e ){ // PHP 8 Errors too: an uncaught Error ended the request without an answer + $Data['msg'] = 'Provided Credentials are Wrong! ['.$EUser.']:['.$EPass.']
'.htmlspecialchars( $e->getMessage() ); }; } else $Data['status'] = 'nocam'; } else $Data['status'] = 'nopreset'; @@ -1073,8 +1073,8 @@ } else { $Data['msg'] = 'OnVif Query Device Fault!'; } - } catch( Exception $e ){ - $Data['msg'] = 'Provided Credentials are Wrong! ['.$EUser.']:['.$EPass.']'; + } catch( Throwable $e ){ // PHP 8 Errors too: an uncaught Error ended the request without an answer + $Data['msg'] = 'Provided Credentials are Wrong! ['.$EUser.']:['.$EPass.']
'.htmlspecialchars( $e->getMessage() ); }; } else $Data['status'] = 'nocam'; break; diff --git a/lib/php/onvif/toto.php b/lib/php/onvif/toto.php index 1ccb217..1d95aca 100644 --- a/lib/php/onvif/toto.php +++ b/lib/php/onvif/toto.php @@ -119,27 +119,47 @@ class Ponvif { /* Public functions (basic initialization method and other collaterals) */ + /* + Errors here must be Exceptions: the callers use try { initialize() } catch (Exception $e). + Before, a camera answering GetVideoSources with an HTML page (e.g. HTTP 401) or with no + made PHP 8 throw an Error / TypeError ($xml->getName() on false, count(null)) + that went past catch (Exception) and ended the whole request. + */ public function initialize() { $this->mediauri='http://'.$this->ipaddress.'/onvif/device_service'; try { $datetime=$this->core_GetSystemDateAndTime(); - $timestamp=mktime($datetime['Time']['Hour'], $datetime['Time']['Minute'], $datetime['Time']['Second'], - $datetime['Date']['Month'], $datetime['Date']['Day'], $datetime['Date']['Year']); - $this->deltatime=time()-$timestamp-5; - } catch (Exception $e) {} + if (is_array($datetime) && isset($datetime['Time']) && isset($datetime['Date'])) { + $timestamp=mktime($datetime['Time']['Hour'], $datetime['Time']['Minute'], $datetime['Time']['Second'], + $datetime['Date']['Month'], $datetime['Date']['Day'], $datetime['Date']['Year']); + $this->deltatime=time()-$timestamp-5; + } + } catch (Throwable $e) {} - $this->capabilities=$this->core_GetCapabilities(); - $onvifVersion=$this->_getOnvifVersion($this->capabilities); - $this->mediauri=$onvifVersion['media']; - $this->deviceuri=$onvifVersion['device']; - $this->ptzuri=$onvifVersion['ptz']; - preg_match("/^http(.*)onvif\//",$this->mediauri,$matches); - $this->baseuri=$matches[0]; - $this->onvifversion=array('major'=>$onvifVersion['major'],'minor'=>$onvifVersion['minor']); - $this->videosources=$this->media_GetVideoSources(); - $this->profiles=$this->media_GetProfiles(); - $this->sources=$this->_getActiveSources($this->videosources,$this->profiles); + try { + $this->capabilities=$this->core_GetCapabilities(); + if (!is_array($this->capabilities) || !isset($this->capabilities['Media']['XAddr'])) + throw new Exception('GetCapabilities: no media service in the reply'); + $onvifVersion=$this->_getOnvifVersion($this->capabilities); + $this->mediauri=$onvifVersion['media']; + $this->deviceuri=$onvifVersion['device']; + $this->ptzuri=$onvifVersion['ptz']; + preg_match("/^http(.*)onvif\//",$this->mediauri,$matches); + $this->baseuri=isset($matches[0]) ? $matches[0] : ''; + $this->onvifversion=array('major'=>$onvifVersion['major'],'minor'=>$onvifVersion['minor']); + $this->videosources=$this->media_GetVideoSources(); + if (!is_array($this->videosources) || count($this->videosources)==0) + throw new Exception('GetVideoSources: no video source in the reply'); + $this->profiles=$this->media_GetProfiles(); + if (!is_array($this->profiles) || count($this->profiles)==0) + throw new Exception('GetProfiles: no media profile in the reply'); + $this->sources=$this->_getActiveSources($this->videosources,$this->profiles); + } catch (Exception $e) { + throw $e; + } catch (Throwable $e) { + throw new Exception('ONVIF initialize: '.$e->getMessage(), 0, $e); + } } public function isFault($response) { // Useful to check if response contains a fault @@ -160,7 +180,7 @@ class Ponvif { public function core_GetSystemDateAndTime() { $post_string=''; if ($this->isFault($response=$this->_send_request($this->mediauri,$post_string))) { - if ($this->intransingent) throw new Exception('GetSystemDateAndTime: Communication error'); + if ($this->intransingent) throw new Exception('GetSystemDateAndTime: Communication error'.$this->_faultText()); } else { return $response['Envelope']['Body']['GetSystemDateAndTimeResponse']['SystemDateAndTime']['UTCDateTime']; } @@ -179,7 +199,7 @@ class Ponvif { $REQ['TIMESTAMP'])), $post_string); if ($this->isFault($response=$this->_send_request($this->mediauri,$post_string))) { - if ($this->intransingent) throw new Exception('GetCapabilities: Communication error'); + if ($this->intransingent) throw new Exception('GetCapabilities: Communication error'.$this->_faultText()); } else return $response['Envelope']['Body']['GetCapabilitiesResponse']['Capabilities']; @@ -199,11 +219,11 @@ class Ponvif { $post_string); //echo "POST STRING:" . $post_string . "\n\n"; if ($this->isFault($response=$this->_send_request($this->mediauri,$post_string))) { - if ($this->intransingent) throw new Exception('GetVideoSources: Communication error'); + if ($this->intransingent) throw new Exception('GetVideoSources: Communication error'.$this->_faultText()); } else // var_dump( $response ); - return $response['Envelope']['Body']['GetVideoSourcesResponse']['VideoSources']; + return isset($response['Envelope']['Body']['GetVideoSourcesResponse']['VideoSources']) ? $response['Envelope']['Body']['GetVideoSourcesResponse']['VideoSources'] : null; } public function media_GetProfiles() { @@ -219,7 +239,7 @@ class Ponvif { $REQ['TIMESTAMP'])), $post_string); if ($this->isFault($response=$this->_send_request($this->mediauri,$post_string))) { - if ($this->intransingent) throw new Exception('GetProfiles: Communication error'); + if ($this->intransingent) throw new Exception('GetProfiles: Communication error'.$this->_faultText()); } else return $response['Envelope']['Body']['GetProfilesResponse']['Profiles']; @@ -238,7 +258,7 @@ class Ponvif { $REQ['TIMESTAMP'])), $post_string); if ($this->isFault($this->_send_request($this->mediauri,$post_string))) { - if ($this->intransingent) throw new Exception('GetServices: Communication error'); + if ($this->intransingent) throw new Exception('GetServices: Communication error'.$this->_faultText()); } } @@ -255,7 +275,7 @@ class Ponvif { $REQ['TIMESTAMP'])), $post_string); if ($this->isFault($response=$this->_send_request($this->mediauri,$post_string))) { - if ($this->intransingent) throw new Exception('GetDeviceInformation: Communication error'); + if ($this->intransingent) throw new Exception('GetDeviceInformation: Communication error'.$this->_faultText()); } else return $response['Envelope']['Body']['GetDeviceInformationResponse']; @@ -282,7 +302,7 @@ class Ponvif { $post_string ); if ($this->isFault($response=$this->_send_request($this->mediauri,$post_string))) { - if ($this->intransingent) throw new Exception('GetStreamUri: Communication error'); + if ($this->intransingent) throw new Exception('GetStreamUri: Communication error'.$this->_faultText()); } else return $response['Envelope']['Body']['GetStreamUriResponse']['MediaUri']['Uri']; @@ -303,7 +323,7 @@ class Ponvif { $profileToken)), $post_string); if ($this->isFault($response=$this->_send_request($this->mediauri,$post_string))) { - if ($this->intransingent) throw new Exception('GetSnapshotUri: Communication error'); + if ($this->intransingent) throw new Exception('GetSnapshotUri: Communication error'.$this->_faultText()); var_dump($response); } else @@ -326,7 +346,7 @@ class Ponvif { $profileToken)), $post_string); if ($this->isFault($response=$this->_send_request($this->ptzuri,$post_string))) { - if ($this->intransingent) throw new Exception('GetPresets: Communication error'); + if ($this->intransingent) throw new Exception('GetPresets: Communication error'.$this->_faultText()); } else { $getpresetsresponse=$response['Envelope']['Body']['GetPresetsResponse']['Preset']; @@ -356,7 +376,7 @@ class Ponvif { $ptzNodeToken)), $post_string); if ($this->isFault($response=$this->_send_request($this->ptzuri,$post_string))) { - if ($this->intransingent) throw new Exception('GetNode: Communication error'); + if ($this->intransingent) throw new Exception('GetNode: Communication error'.$this->_faultText()); } else return $response['Envelope']['Body']['GetNodeResponse']; @@ -386,7 +406,7 @@ class Ponvif { $speed_zoom_x)), $post_string); if ($this->isFault($this->_send_request($this->ptzuri,$post_string))) { - if ($this->intransingent) throw new Exception('GotoPreset: Communication error'); + if ($this->intransingent) throw new Exception('GotoPreset: Communication error'.$this->_faultText()); } } @@ -408,7 +428,7 @@ class Ponvif { $presetToken)), $post_string); if ($this->isFault($this->_send_request($this->ptzuri,$post_string))) { - if ($this->intransingent) throw new Exception('RemovePreset: Communication error'); + if ($this->intransingent) throw new Exception('RemovePreset: Communication error'.$this->_faultText()); } } @@ -430,7 +450,7 @@ class Ponvif { $presetName)), $post_string); if ($this->isFault($this->_send_request($this->ptzuri,$post_string))) { - if ($this->intransingent) throw new Exception('SetPreset: Communication error'); + if ($this->intransingent) throw new Exception('SetPreset: Communication error'.$this->_faultText()); } } @@ -458,7 +478,7 @@ class Ponvif { $speed_pantilt_y)), $post_string); if ($this->isFault($this->_send_request($this->ptzuri,$post_string))) { - if ($this->intransingent) throw new Exception('RelativeMove: Communication error'); + if ($this->intransingent) throw new Exception('RelativeMove: Communication error'.$this->_faultText()); } } @@ -482,7 +502,7 @@ class Ponvif { $zoom)), $post_string); if ($this->isFault($this->_send_request($this->ptzuri,$post_string))) { - if ($this->intransingent) throw new Exception('RelativeMoveZoom: Communication error'); + if ($this->intransingent) throw new Exception('RelativeMoveZoom: Communication error'.$this->_faultText()); } } @@ -537,7 +557,7 @@ class Ponvif { $ZSpeed)), $post_string); if ($this->isFault($this->_send_request($this->ptzuri,$post_string))) { - if ($this->intransingent) throw new Exception('AbsoluteMove: Communication error'); + if ($this->intransingent) throw new Exception('AbsoluteMove: Communication error'.$this->_faultText()); } } @@ -561,7 +581,7 @@ class Ponvif { $velocity_pantilt_y)), $post_string); if ( $this->isFault($this->_send_request($this->ptzuri,$post_string))) { - if( $this->intransingent ) throw new Exception('ContinuousMove: Communication error'); + if( $this->intransingent ) throw new Exception('ContinuousMove: Communication error'.$this->_faultText()); } } @@ -583,7 +603,7 @@ class Ponvif { $zoom)), $post_string); if ($this->isFault($this->_send_request($this->ptzuri,$post_string))) { - if ($this->intransingent) throw new Exception('ContinuousMoveZoom: Communication error'); + if ($this->intransingent) throw new Exception('ContinuousMoveZoom: Communication error'.$this->_faultText()); } } @@ -607,7 +627,7 @@ class Ponvif { $zoom)), $post_string); if ($this->isFault($this->_send_request($this->ptzuri,$post_string))) { - if ($this->intransingent) throw new Exception('Stop: Communication error'); + if ($this->intransingent) throw new Exception('Stop: Communication error'.$this->_faultText()); } } @@ -620,30 +640,49 @@ class Ponvif { } protected function _getOnvifVersion($capabilities) { - $version=array(); - if (isset($capabilities['Device']['System']['SupportedVersions']['Major'])) { - // NVT supports a specific onvif version - $version['major']=$capabilities['Device']['System']['SupportedVersions']['Major']; - $version['minor']=$capabilities['Device']['System']['SupportedVersions']['Minor']; - } else { - // NVT supports more onvif versions - $currentma=0; - $currentmi=0; - foreach ($capabilities['Device']['System']['SupportedVersions'] as $cver) { - if ($cver['Major']>$currentma) { $currentma=$cver['Major'];$currentmi=$cver['Minor']; } - } - $version['major']=$currentma; - $version['minor']=$currentmi; + $version=array('major'=>0,'minor'=>0); + $sv=isset($capabilities['Device']['System']['SupportedVersions']) ? $capabilities['Device']['System']['SupportedVersions'] : null; + if (is_array($sv) && isset($sv['Major'])) { + // NVT supports a specific onvif version + $version['major']=$sv['Major']; + $version['minor']=isset($sv['Minor']) ? $sv['Minor'] : 0; + } elseif (is_array($sv)) { + // NVT supports more onvif versions + foreach ($sv as $cver) { + if (is_array($cver) && isset($cver['Major']) && $cver['Major']>$version['major']) { + $version['major']=$cver['Major']; + $version['minor']=isset($cver['Minor']) ? $cver['Minor'] : 0; + } + } } - $version['media']=$capabilities['Media']['XAddr']; - $version['device']=$capabilities['Device']['XAddr']; - $version['event']=$capabilities['Events']['XAddr']; - if (isset($capabilities['PTZ']['XAddr'])) $version['ptz']=$capabilities['PTZ']['XAddr']; else $version['ptz']=''; + $version['media']=isset($capabilities['Media']['XAddr']) ? $capabilities['Media']['XAddr'] : ''; + $version['device']=isset($capabilities['Device']['XAddr']) ? $capabilities['Device']['XAddr'] : ''; + $version['event']=isset($capabilities['Events']['XAddr']) ? $capabilities['Events']['XAddr'] : ''; + $version['ptz']=isset($capabilities['PTZ']['XAddr']) ? $capabilities['PTZ']['XAddr'] : ''; return $version; } + // Why the last request failed: " (HTTP 401: reply is not a SOAP envelope)" or the SOAP Fault reason + protected function _faultText() { + $r=$this->lastresponse; + if (is_array($r) && isset($r['Fault']) && is_string($r['Fault'])) return ' ('.$r['Fault'].')'; + if (is_array($r) && isset($r['Envelope']['Body']['Fault']['Reason']['Text'])) { + $t=$r['Envelope']['Body']['Fault']['Reason']['Text']; + if (is_string($t)) return ' ('.$t.')'; + } + return ''; + } + + // One XML element decodes to an associative array, several to a list: always return a list + protected function _asList($v) { + if (!is_array($v)) return array(); + if (isset($v['@attributes']) || !array_key_exists(0, $v)) return array($v); + return $v; + } + protected function _getActiveSources($videoSources,$profiles) { $sources=array(); + if (!is_array($videoSources)) return $sources; if (isset($videoSources['@attributes'])) { // NVT is a camera @@ -652,8 +691,9 @@ class Ponvif { } else { // NVT is an encoder + $videoSources=$this->_asList($videoSources); for ($i=0;$i_getProfileData($sources,$i,$profiles); } @@ -665,16 +705,20 @@ class Ponvif { protected function _getProfileData(&$sources,$i,$profiles) { $inprofile=0; + // A camera with ONE profile: count() counted the fields of that profile, no source was found + $profiles=$this->_asList($profiles); for ($y=0; $y < count($profiles); $y++) { - if ($profiles[$y]['VideoSourceConfiguration']['SourceToken']==$sources[$i]['sourcetoken']) { + if (isset($profiles[$y]['VideoSourceConfiguration']['SourceToken']) && $profiles[$y]['VideoSourceConfiguration']['SourceToken']==$sources[$i]['sourcetoken']) { $sources[$i][$inprofile]['profilename']=$profiles[$y]['Name']; $sources[$i][$inprofile]['profiletoken']=$profiles[$y]['@attributes']['token']; if ( isset($profiles[$y]['VideoEncoderConfiguration'])) { - $sources[$i][$inprofile]['encoding']=$profiles[$y]['VideoEncoderConfiguration']['Encoding']; - $sources[$i][$inprofile]['width']=$profiles[$y]['VideoEncoderConfiguration']['Resolution']['Width']; - $sources[$i][$inprofile]['height']=$profiles[$y]['VideoEncoderConfiguration']['Resolution']['Height']; - $sources[$i][$inprofile]['fps']=$profiles[$y]['VideoEncoderConfiguration']['RateControl']['FrameRateLimit']; - $sources[$i][$inprofile]['bitrate']=$profiles[$y]['VideoEncoderConfiguration']['RateControl']['BitrateLimit']; + // RateControl (and in theory Resolution) are optional in ONVIF + $vec=$profiles[$y]['VideoEncoderConfiguration']; + $sources[$i][$inprofile]['encoding']=isset($vec['Encoding']) ? $vec['Encoding'] : ''; + $sources[$i][$inprofile]['width']=isset($vec['Resolution']['Width']) ? $vec['Resolution']['Width'] : 0; + $sources[$i][$inprofile]['height']=isset($vec['Resolution']['Height']) ? $vec['Resolution']['Height'] : 0; + $sources[$i][$inprofile]['fps']=isset($vec['RateControl']['FrameRateLimit']) ? $vec['RateControl']['FrameRateLimit'] : 0; + $sources[$i][$inprofile]['bitrate']=isset($vec['RateControl']['BitrateLimit']) ? $vec['RateControl']['BitrateLimit'] : 0; } if ( isset($profiles[$y]['PTZConfiguration'])) { $sources[$i][$inprofile]['ptz']['name']=$profiles[$y]['PTZConfiguration']['Name']; @@ -685,26 +729,35 @@ class Ponvif { } } + // Not SOAP XML (empty, HTML error page ...): a Fault instead of a PHP Error / Exception protected function _xml2array($response) { - //$FD = fopen( "TEST.xml", "a+" ); - //fprintf( $FD, $response ); - //fclose( $FD ); - $sxe = new SimpleXMLElement($response); - $dom_sxe = dom_import_simplexml($sxe); - $dom = new DOMDocument('1.0'); - $dom_sxe = $dom->importNode($dom_sxe, true); - $dom_sxe = $dom->appendChild($dom_sxe); - $element = $dom->childNodes->item(0); - foreach ($sxe->getDocNamespaces() as $name => $uri) { - $element->removeAttributeNS($uri, $name); + try { + if (!is_string($response) || trim($response)=='') return array('Fault'=>'empty reply'); + $prev=libxml_use_internal_errors(true); + $sxe = new SimpleXMLElement($response); + $dom_sxe = dom_import_simplexml($sxe); + $dom = new DOMDocument('1.0'); + $dom_sxe = $dom->importNode($dom_sxe, true); + $dom_sxe = $dom->appendChild($dom_sxe); + $element = $dom->childNodes->item(0); + foreach ($sxe->getDocNamespaces() as $name => $uri) { + $element->removeAttributeNS($uri, $name); + } + $xmldata=$dom->saveXML(); + $b=strpos($xmldata,""); + $e=strpos($xmldata,""); + if ($b===false || $e===false) { libxml_use_internal_errors($prev); return array('Fault'=>'reply is not a SOAP envelope'); } + $xmldata=substr($xmldata,$b,$e+strlen("
")-$b); + $xml=simplexml_load_string($xmldata); + libxml_use_internal_errors($prev); + if ($xml===false) return array('Fault'=>'reply is not valid XML'); + $data=json_decode(json_encode((array)$xml),1); + $data=array($xml->getName()=>$data); + return $data; + } catch (Throwable $e) { + if (isset($prev)) libxml_use_internal_errors($prev); + return array('Fault'=>'reply is not XML: '.$e->getMessage()); } - $xmldata=$dom->saveXML(); - $xmldata=substr($xmldata,strpos($xmldata,"")); - $xmldata=substr($xmldata,0,strpos($xmldata,"")+strlen("")); - $xml=simplexml_load_string($xmldata); - $data=json_decode(json_encode((array)$xml),1); - $data=array($xml->getName()=>$data); - return $data; } /* @@ -778,6 +831,10 @@ class Ponvif { //echo "\n~~~~~~~~~~~~~~~~~~\n"; //var_dump( $result ); $this->lastresponse=$this->_xml2array($result); + if (isset($this->lastresponse['Fault']) && is_string($this->lastresponse['Fault'])) { + $code=curl_getinfo($soap_do, CURLINFO_HTTP_CODE); + $this->lastresponse['Fault']='HTTP '.$code.': '.$this->lastresponse['Fault']; // e.g. "HTTP 401: reply is not a SOAP envelope" + } } return $this->lastresponse; } -- 2.39.5 From 8b061ae862a7dfbec49c7119cf45f1d199a7ce43 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 18:28:35 +0000 Subject: [PATCH 4/6] doCameraOperation: CMD 3 without PR parameter = ONVIF, no undefined key warning A displayed PHP warning ends up in front of the JSON reply. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16 --- lib/controller/doCameraOperation.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/controller/doCameraOperation.php b/lib/controller/doCameraOperation.php index 252ca26..a52ae50 100644 --- a/lib/controller/doCameraOperation.php +++ b/lib/controller/doCameraOperation.php @@ -92,7 +92,7 @@ break; }; case 3:{ - if( intval( $_POST['PR'] ) == 0 ){ + if( intval( isset( $_POST['PR'] ) ? $_POST['PR'] : 0 ) == 0 ){ // PR missing = ONVIF (an undefined key warning broke the JSON) // Checkup Onvif Camera Credentials require_once('../php/onvif/toto.php'); $EUser = $DATABASE->escape( $_POST['UU'] ); -- 2.39.5 From b43f159cc74babbb907a9143124e0cd5d4c5b23b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 18:34:03 +0000 Subject: [PATCH 5/6] doCameraOperation: a failed credential check returns status "error" CMD 3 for a camera (the editor's "Set credentials" button) set status "ok" before the ONVIF check. When the check failed (wrong credentials, unreachable camera, unusable reply), the page saw "ok", reloaded the list and never showed the message. The two failure branches now set status "error", so the reason is shown. Tested through the real ajax_asm.php / web.php login (users table and session id) with the editor's request (UID, SID, CID=5, UU, PP, AU, CMD=3): - camera unreachable: error, "GetCapabilities: Communication error (Failed to connect to ... port 8080 ...)" - fake camera, good: ok, credentials and stream stored - fake camera, HTML 401 page: error, "GetVideoSources: Communication error (HTTP 401: reply is not a SOAP envelope)" - wrong SID: redirected (302) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16 --- lib/controller/doCameraOperation.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/controller/doCameraOperation.php b/lib/controller/doCameraOperation.php index a52ae50..23d061d 100644 --- a/lib/controller/doCameraOperation.php +++ b/lib/controller/doCameraOperation.php @@ -306,9 +306,11 @@ $QS = "UPDATE cameras SET access_login='$EUser', access_pass='$EPass', auth_mode={$AUTH}, ptz_token='{$Eptz}', `status`=1 WHERE id={$CameraID}"; $DATABASE->Query( $QS, false ); } else { + $Data['status'] = 'error'; // the page shows msg only when status is not 'ok' (a failed check was silent) $Data['msg'] = 'Camera was added.
However provided Credentials are Wrong! ['.$EUser.']:['.$EPass.']'; }; } catch( Throwable $e ){ // PHP 8 Errors too: an uncaught Error ended the request without an answer + $Data['status'] = 'error'; $Data['msg'] = 'Provided Credentials are Wrong! ['.$EUser.']:['.$EPass.']
'.htmlspecialchars( $e->getMessage() ); }; } else { -- 2.39.5 From 536e0ddefbaf495ae3c0db527377215431c29d2b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 18:38:02 +0000 Subject: [PATCH 6/6] ONVIF behind NAT: use the reachable address for the camera's services and URIs Tested with the real camera reached as 2.54.237.28:8080 (port forward). It reports its services and URIs at its LAN address 192.168.200.118: GetCapabilities XAddrs http://192.168.200.118:8080/onvif/..., stream URIs rtsp://192.168.200.118:554/... toto.php - initialize(): a service URL (media, device, ptz) on another host than the one the device service was reached at is moved to that address, keeping its path (_reachableUri). GetVideoSources went to 192.168.200.118 and failed with "Couldn't connect", and the UI said "Credentials are Wrong!". A service on the same host is unchanged. doCameraOperation.php - Stream / snapshot URIs are split with parse_url (camMediaUri): protocol, port (scheme default if none) and path + query, whatever the host is. Before, only "proto://" was removed, so with the LAN host the whole URL was stored as the path. The two copies of that code are replaced by the helper. Real camera, request of the camera editor (CID=5, AU=7, CMD=3) through the real login (users table / session): before, status "error" (LAN address unreachable). Now status "ok", credentials, auth mode and PTZ token stored, 3 profiles: mainStream 1920x1080 /Streaming/Channels/101?..., subStream, thirdStream; snapshot http:8080 /onvif-http/snapshot?Profile_n. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16 --- lib/controller/doCameraOperation.php | 69 +++++++++++----------------- lib/php/onvif/toto.php | 22 +++++++-- 2 files changed, 46 insertions(+), 45 deletions(-) diff --git a/lib/controller/doCameraOperation.php b/lib/controller/doCameraOperation.php index 23d061d..c008a5e 100644 --- a/lib/controller/doCameraOperation.php +++ b/lib/controller/doCameraOperation.php @@ -31,6 +31,25 @@ }; return array( $U, $P ); }; + // Stream / snapshot URI of the camera -> array( proto, port, path ): the camera may report its LAN address + // (192.168.x.y behind NAT / port forwarding) - the path is taken whatever the host is. Before, only + // "proto://" was cut off, so with another host the whole URL was stored as the path. + function camMediaUri( $U ){ + if( !is_string( $U ) || $U == '' ) return array( '', 0, '' ); + $H = parse_url( $U ); + if( $H === false || !isset( $H['scheme'] ) ) return array( '', 0, $U ); + $Proto = strtolower( $H['scheme'] ); + $Port = isset( $H['port'] ) ? intval( $H['port'] ) : 0; + if( $Port == 0 ){ + switch( $Proto ){ + case 'rtsp': $Port = 554; break; + case 'http': $Port = 80; break; + case 'https': $Port = 443; break; + }; + }; + $Path = ( isset( $H['path'] ) ? $H['path'] : '/' ) . ( isset( $H['query'] ) ? '?' . $H['query'] : '' ); + return array( $Proto, $Port, $Path ); + }; if( $CUser->Data['id'] > 1 ){ $Data = array(); $Data['status'] = 'na'; @@ -211,28 +230,10 @@ }; $mrl = $onvif->media_GetStreamUri($source['profiletoken']); $pic = $onvif->media_GetSnapshotUri($source['profiletoken']); - $TPArr = explode(':',$mrl); - $mrl_proto = $TPArr[0]; - $mrl_port = intval( $TPArr[2] ); - if( $mrl_port == 0 ) { - switch( $mrl_proto ){ - case 'rtsp': $mrl_port = 554; break; - case 'http': $mrl_port = 80; break; - case 'https': $mrl_port = 443; break; - }; - }; - $Emrl = $DATABASE->escape( $mrl ); - $Emrl = str_replace( $mrl_proto . '://' . $IP . ':' . $mrl_port, '', $Emrl ); - $Emrl = str_replace( $mrl_proto . '://' . $IP, '', $Emrl ); - $TPArr = explode(':',$pic ); - $pic_proto = $TPArr[0]; - if( count( $TPArr ) > 2 ){ - $pic_port = intval( $TPArr[2] ); - if($pic_port == 0 ) $pic_port = 80; - } else $pic_port = 80; - $Epic = $DATABASE->escape( $pic ); - $Epic = str_replace( $pic_proto . '://' . $IP . ':' . $pic_port, '', $Epic ); - $Epic = str_replace( $pic_proto . '://' . $IP , '', $Epic ); + list( $mrl_proto, $mrl_port, $Emrl ) = camMediaUri( $mrl ); + $Emrl = $DATABASE->escape( $Emrl ); + list( $pic_proto, $pic_port, $Epic ) = camMediaUri( $pic ); + $Epic = $DATABASE->escape( $Epic ); $QS = "INSERT INTO `media_streams`(`source_id`,`source_type`,`valid`,`name`,`token`,`img_width`,`img_height`,`compression_type`,`bitrate`,`fps`,`mrl`,`mrl_proto`,`mrl_port`,`picture_proto`,`picture_port`,`picture`) VALUES({$CameraID},'D',1,'{$Ename}','{$Etoken}',{$Ewidth},{$Eheight},'{$Eencode}',{$Ebitrate},{$Efps},'{$Emrl}','{$mrl_proto}','{$mrl_port}','{$pic_proto}','{$pic_port}','{$Epic}') ON CONFLICT(`source_id`,`token`) DO UPDATE SET `source_type`='D', `valid`=1, `mrl`='{$Emrl}', `mrl_proto`='{$mrl_proto}', `mrl_port`='{$mrl_port}', `picture_proto`='{$pic_proto}', `picture_port`='{$pic_port}', `picture`='{$Epic}'"; $Data['ss'] .='Added'; $Data['QS'] = $QS; @@ -280,26 +281,10 @@ }; $mrl = $onvif->media_GetStreamUri($source['profiletoken']); $pic = $onvif->media_GetSnapshotUri($source['profiletoken']); - $TPArr = explode(':',$mrl); - $mrl_proto = $TPArr[0]; - $mrl_port = intval( $TPArr[2] ); - if( $mrl_port == 0 ) { - switch( $mrl_proto ){ - case 'rtsp': $mrl_port = 554; break; - case 'http': $mrl_port = 80; break; - case 'https': $mrl_port = 443; break; - }; - }; - $Emrl = $DATABASE->escape( $mrl ); - $Emrl = str_replace( $mrl_proto . '://' . $IP . ':' . $mrl_port, '', $Emrl ); - $Emrl = str_replace( $mrl_proto . '://' . $IP, '', $Emrl ); - $TPArr = explode(':',$pic ); - $pic_proto = $TPArr[0]; - $pic_port = intval( $TPArr[2] ); - if($pic_port == 0 ) $pic_port = 80; - $Epic = $DATABASE->escape( $pic ); - $Epic = str_replace( $pic_proto . '://' . $IP . ':' . $pic_port, '', $Epic ); - $Epic = str_replace( $pic_proto . '://' . $IP , '', $Epic ); + list( $mrl_proto, $mrl_port, $Emrl ) = camMediaUri( $mrl ); + $Emrl = $DATABASE->escape( $Emrl ); + list( $pic_proto, $pic_port, $Epic ) = camMediaUri( $pic ); + $Epic = $DATABASE->escape( $Epic ); $QS = "INSERT INTO `media_streams`(`source_id`,`source_type`,`valid`,`name`,`token`,`img_width`,`img_height`,`compression_type`,`bitrate`,`fps`,`mrl`,`mrl_proto`,`mrl_port`,`picture_proto`,`picture_port`,`picture`) VALUES({$CameraID},'D',1,'{$Ename}','{$Etoken}',{$Ewidth},{$Eheight},'{$Eencode}',{$Ebitrate},{$Efps},'{$Emrl}','{$mrl_proto}','{$mrl_port}','{$pic_proto}','{$pic_port}','{$Epic}') ON CONFLICT(`source_id`,`token`) DO UPDATE SET `source_type`='D', `valid`=1, `mrl`='{$Emrl}', `mrl_proto`='{$mrl_proto}', `mrl_port`='{$mrl_port}', `picture_proto`='{$pic_proto}', `picture_port`='{$pic_port}', `picture`='{$Epic}'"; $DATABASE->Query( $QS, false ); }; diff --git a/lib/php/onvif/toto.php b/lib/php/onvif/toto.php index 1d95aca..18224ea 100644 --- a/lib/php/onvif/toto.php +++ b/lib/php/onvif/toto.php @@ -142,9 +142,9 @@ class Ponvif { if (!is_array($this->capabilities) || !isset($this->capabilities['Media']['XAddr'])) throw new Exception('GetCapabilities: no media service in the reply'); $onvifVersion=$this->_getOnvifVersion($this->capabilities); - $this->mediauri=$onvifVersion['media']; - $this->deviceuri=$onvifVersion['device']; - $this->ptzuri=$onvifVersion['ptz']; + $this->mediauri=$this->_reachableUri($onvifVersion['media']); + $this->deviceuri=$this->_reachableUri($onvifVersion['device']); + $this->ptzuri=$this->_reachableUri($onvifVersion['ptz']); preg_match("/^http(.*)onvif\//",$this->mediauri,$matches); $this->baseuri=isset($matches[0]) ? $matches[0] : ''; $this->onvifversion=array('major'=>$onvifVersion['major'],'minor'=>$onvifVersion['minor']); @@ -662,6 +662,22 @@ class Ponvif { return $version; } + /* + A camera behind NAT / port forwarding reports its services at its LAN address (e.g. + http://192.168.200.118:8080/onvif/media while it is reached as 2.54.237.28:8080): the next + request went to an address that cannot be reached and the UI said "Credentials are Wrong". + A service URL on another host is moved to the address the device service was reached at + (same scheme, host and port), keeping its path. A service on the same host is kept as is. + */ + protected function _reachableUri($url) { + if (!is_string($url) || $url=='') return $url; + $u=parse_url($url); + $r=parse_url('http://'.$this->ipaddress); + if ($u===false || $r===false || !isset($u['host']) || !isset($r['host'])) return $url; + if (strcasecmp($u['host'], $r['host'])==0) return $url; + return 'http://'.$this->ipaddress.(isset($u['path']) ? $u['path'] : '/').(isset($u['query']) ? '?'.$u['query'] : ''); + } + // Why the last request failed: " (HTTP 401: reply is not a SOAP envelope)" or the SOAP Fault reason protected function _faultText() { $r=$this->lastresponse; -- 2.39.5