<?php
// DbDatabase.php
// Copyright P.Kassel, M.Seliger, G.Trietsch, all Rights Reserved
namespace Docuform\Database;use Docuform\Lib\ApiUuid;use PDO;use Exception;class DbDatabase{public const CMT_NONE=0x00000000;public const CMT_SYSTEM=0x00000001;public const CMT_USERS=0x00000002;public const CMT_DEVICES=0x00000010;public const CMT_JOBS=0x00000800;public const CMT_USERDELETE=0x00020000;public static function generateUDBID($database):int{$result=0;$driver_options=$database->GetLocking()?[PDO::ATTR_CURSOR=>PDO::CURSOR_SCROLL]:[];$sql="SELECT sValue FROM ACCSYSTEM WHERE sSection='System' AND sKey='NextId'";if($database->GetLocking()){$sql.=' FOR UPDATE';}$cursor=$database->prepare($sql,$driver_options);if($cursor!==false){$inTransaction=$database->inTransaction();if($inTransaction||$database->beginTransaction()){try{$success=$cursor->execute()!==false;if($success){$result=$cursor->fetchColumn();if($result!==false){$nextId=$result+1;$sql="UPDATE ACCSYSTEM SET sValue='$nextId' WHERE sSection='System' AND sKey='NextId'";if(!$database->GetLocking()){$sql.=" AND sValue='$result'";}$cursor->closeCursor();$success=($database->exec($sql)!==false);if($success&&$inTransaction===false){$success=$database->commit();}}else{$success=false;}}}catch(Exception $e){$success=false;}if($success===false){if($inTransaction===false){$database->rollBack();}$result=0;}}}return $result;}public static function generateDeviceUUID($macAddress,$serialNo,$hostAddress):string{if(empty($macAddress)||empty($hostAddress)||$hostAddress==='0.0.0.0'){return '';}$data=substr(hash('sha256',$macAddress.$serialNo.$hostAddress),0,32);$uuid=ApiUuid::uuid4($data);return ApiUuid::toHex($uuid);}public static function setModifiedFlag(DbPDO $database,int $NewFlags,$sKey='ObjectModified',bool $bClear=false):bool{$Result=false;$Query="SELECT sValue FROM ACCSYSTEM WHERE sSection='System' AND sKey='".$sKey."'";$bLocking=$database->GetLocking();$Retry=0;if($bLocking){$Query.=' FOR UPDATE';$driver_options=array(PDO::ATTR_CURSOR=>PDO::CURSOR_SCROLL);}else $driver_options=array();$Cursor=$database->prepare($Query,$driver_options);if($Cursor!==false){while($Retry<2){$InTransaction=$database->inTransaction();if($InTransaction||$database->beginTransaction()){try{$Success=$Cursor->execute()!==false;if($Success){$OldFlags=$Cursor->fetchColumn();if($OldFlags!==false){if(!$bClear)$Flags=(int)$OldFlags|$NewFlags;else $Flags=(int)$OldFlags &~$NewFlags;$Update='UPDATE ACCSYSTEM SET sValue='.$Flags." WHERE sSection='System' AND sKey='".$sKey."'";if(!$bLocking)$Update.=" AND sValue='".$OldFlags."'";$Cursor->closeCursor();$Success=($database->exec($Update)!==false);if($InTransaction===false&&$Success)$Success=$database->commit();}else $Success=false;}}catch(Exception $e){$Success=false;}if($Success===false){if($InTransaction===false)$database->rollBack();}else{$Result=true;break;}}++$Retry;}}return $Result;}}