diff --git a/classes/BinAudits.class.php b/classes/BinAudits.class.php index 0ad910fa9..4d3a431d1 100644 --- a/classes/BinAudits.class.php +++ b/classes/BinAudits.class.php @@ -29,7 +29,7 @@ class BinAudits { function MakeSafe(){ $this->BinID=intval($this->BinID); - $this->UserID=sanitize($this->UserID); + $this->UserID=trim($this->UserID); $this->AuditStamp=sanitize($this->AuditStamp); } @@ -48,7 +48,12 @@ function AddAudit(){ $this->MakeSafe(); $sql="INSERT INTO fac_BinAudits SET BinID=$this->BinID, UserID=\"$this->UserID\", AuditStamp=\"$this->AuditStamp\";"; - $this->exec($sql); + if ( $this->exec($sql) === false ) { + $info = $GLOBALS['dbh']->errorInfo(); + error_log("BinAudits::AddAudit PDO Error: {$info[2]} SQL=$sql"); + return false; +} +return true; } public static function RedactUser($UserID) { diff --git a/classes/BinContents.class.php b/classes/BinContents.class.php index 1f615889b..16c9181c0 100644 --- a/classes/BinContents.class.php +++ b/classes/BinContents.class.php @@ -53,6 +53,7 @@ function exec($sql){ } function AddContents(){ + $this->MakeSafe(); $sql="INSERT INTO fac_BinContents SET BinID=$this->BinID, SupplyID=$this->SupplyID, Count=$this->Count;"; return $this->exec($sql); } @@ -92,7 +93,7 @@ function UpdateCount(){ $sql="UPDATE fac_BinContents SET Count=$this->Count WHERE BinID=$this->BinID AND SupplyID=$this->SupplyID;"; - return $this->query($sql); + return $this->exec($sql); } function RemoveContents(){ diff --git a/classes/CDUInfo.class.php b/classes/CDUInfo.class.php index 58ea78bbc..1207910de 100644 --- a/classes/CDUInfo.class.php +++ b/classes/CDUInfo.class.php @@ -43,10 +43,10 @@ static private function BasicTests($DeviceID){ // If the device doesn't have an SNMP community set, // check and see if we have a global one - $dev->SNMPCommunity=($dev->SNMPCommunity=="")?$config->ParameterArray["SNMPCommunity"]:$dev->SNMPCommunity; + $dev->SNMPCommunity=($dev->SNMPCommunity=="")?($config->ParameterArray["SNMPCommunity"] ?? ''):$dev->SNMPCommunity; // Make this false faster - $dev->SNMPCommunity=trim($dev->SNMPCommunity); + $dev->SNMPCommunity=trim((string)$dev->SNMPCommunity); if($dev->SNMPCommunity==""){return false;} // We've passed all the repeatable tests, return the device object for digging @@ -58,8 +58,8 @@ static private function BasicTests($DeviceID){ static private function OSS_SNMP_Lookup($dev,$snmplookup,$portid=null,$baseOID=null){ // This is find out the name of the function that called this to // make the error logging more descriptive - $caller=debug_backtrace(); - $caller=$caller[1]['function']; + $trace=debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2); + $caller=$trace[1]['function'] ?? 'unknown'; // Since we don't really let the user specify the version right now here's a stop gap // Try the default version of 2c first diff --git a/classes/CDUTemplate.class.php b/classes/CDUTemplate.class.php index 82f1aa2d6..8cba10651 100644 --- a/classes/CDUTemplate.class.php +++ b/classes/CDUTemplate.class.php @@ -75,43 +75,43 @@ function MakeSafe(){ } function MakeDisplay(){ - $this->Model=stripslashes($this->Model); - $this->VersionOID=stripslashes($this->VersionOID); - $this->OutletNameOID=stripslashes($this->OutletNameOID); - $this->OutletDescOID=stripslashes($this->OutletDescOID); - $this->OutletCountOID=stripslashes($this->OutletCountOID); - $this->OutletStatusOID=stripslashes($this->OutletStatusOID); - $this->OutletStatusOn=stripslashes($this->OutletStatusOn); - $this->OID1=stripslashes($this->OID1); - $this->OID2=stripslashes($this->OID2); - $this->OID3=stripslashes($this->OID3); - $this->ATSStatusOID=stripslashes($this->ATSStatusOID); - $this->ATSDesiredResult=stripslashes($this->ATSDesiredResult); + $this->Model=stripslashes((string)$this->Model); + $this->VersionOID=stripslashes((string)$this->VersionOID); + $this->OutletNameOID=stripslashes((string)$this->OutletNameOID); + $this->OutletDescOID=stripslashes((string)$this->OutletDescOID); + $this->OutletCountOID=stripslashes((string)$this->OutletCountOID); + $this->OutletStatusOID=stripslashes((string)$this->OutletStatusOID); + $this->OutletStatusOn=stripslashes((string)$this->OutletStatusOn); + $this->OID1=stripslashes((string)$this->OID1); + $this->OID2=stripslashes((string)$this->OID2); + $this->OID3=stripslashes((string)$this->OID3); + $this->ATSStatusOID=stripslashes((string)$this->ATSStatusOID); + $this->ATSDesiredResult=stripslashes((string)$this->ATSDesiredResult); } static function RowToObject($row){ $template=new CDUTemplate(); - $template->TemplateID=$row["TemplateID"]; - $template->ManufacturerID=$row["ManufacturerID"]; - $template->Model=$row["Model"]; - $template->Managed=$row["Managed"]; - $template->ATS=$row["ATS"]; - $template->VersionOID=$row["VersionOID"]; - $template->OutletNameOID=$row["OutletNameOID"]; - $template->OutletDescOID=$row["OutletDescOID"]; - $template->OutletCountOID=$row["OutletCountOID"]; - $template->OutletStatusOID=$row["OutletStatusOID"]; - $template->OutletStatusOn=$row["OutletStatusOn"]; - $template->Multiplier=$row["Multiplier"]; - $template->OID1=$row["OID1"]; - $template->OID2=$row["OID2"]; - $template->OID3=$row["OID3"]; - $template->ATSStatusOID=$row["ATSStatusOID"]; - $template->ATSDesiredResult=$row["ATSDesiredResult"]; - $template->ProcessingProfile=$row["ProcessingProfile"]; - $template->Voltage=$row["Voltage"]; - $template->Amperage=$row["Amperage"]; - $template->NumOutlets=$row["NumOutlets"]; + $template->TemplateID=$row["TemplateID"] ?? null; + $template->ManufacturerID=$row["ManufacturerID"] ?? null; + $template->Model=$row["Model"] ?? null; + $template->Managed=$row["Managed"] ?? null; + $template->ATS=$row["ATS"] ?? null; + $template->VersionOID=$row["VersionOID"] ?? null; + $template->OutletNameOID=$row["OutletNameOID"] ?? null; + $template->OutletDescOID=$row["OutletDescOID"] ?? null; + $template->OutletCountOID=$row["OutletCountOID"] ?? null; + $template->OutletStatusOID=$row["OutletStatusOID"] ?? null; + $template->OutletStatusOn=$row["OutletStatusOn"] ?? null; + $template->Multiplier=$row["Multiplier"] ?? null; + $template->OID1=$row["OID1"] ?? null; + $template->OID2=$row["OID2"] ?? null; + $template->OID3=$row["OID3"] ?? null; + $template->ATSStatusOID=$row["ATSStatusOID"] ?? null; + $template->ATSDesiredResult=$row["ATSDesiredResult"] ?? null; + $template->ProcessingProfile=$row["ProcessingProfile"] ?? null; + $template->Voltage=$row["Voltage"] ?? null; + $template->Amperage=$row["Amperage"] ?? null; + $template->NumOutlets=$row["NumOutlets"] ?? null; $template->MakeDisplay(); @@ -125,8 +125,10 @@ function GetTemplateList(){ a.ManufacturerID=b.ManufacturerID ORDER BY b.Name ASC,a.Model ASC;"; $tmpList=array(); - foreach($dbh->query($sql) as $row){ - $tmpList[]=CDUTemplate::RowToObject($row); + if($stmt=$dbh->query($sql)){ + foreach($stmt as $row){ + $tmpList[]=CDUTemplate::RowToObject($row); + } } return $tmpList; @@ -139,7 +141,8 @@ function GetTemplate(){ $sql="SELECT * FROM fac_CDUTemplate WHERE TemplateID=$this->TemplateID"; - if($row=$dbh->query($sql)->fetch()){ + $stmt=$dbh->query($sql); + if($stmt && ($row=$stmt->fetch())){ foreach(CDUTemplate::RowToObject($row) as $prop => $value){ $this->$prop=$value; } diff --git a/classes/CabRow.class.php b/classes/CabRow.class.php index b0567e6d0..f6ebbb36e 100644 --- a/classes/CabRow.class.php +++ b/classes/CabRow.class.php @@ -36,15 +36,15 @@ function MakeSafe() { } function MakeDisplay(){ - $this->Name=stripslashes($this->Name); + $this->Name=stripslashes((string)$this->Name); } static function RowToObject($row){ $cabrow=new CabRow(); - $cabrow->CabRowID=$row["CabRowID"]; - $cabrow->Name=$row["Name"]; - $cabrow->DataCenterID=$row["DataCenterID"]; - $cabrow->ZoneID=$row["ZoneID"]; + $cabrow->CabRowID=$row["CabRowID"] ?? null; + $cabrow->Name=$row["Name"] ?? null; + $cabrow->DataCenterID=$row["DataCenterID"] ?? null; + $cabrow->ZoneID=$row["ZoneID"] ?? null; $cabrow->MakeDisplay(); return $cabrow; @@ -134,8 +134,10 @@ function GetCabRow(){ $sql="SELECT * FROM fac_CabRow WHERE CabRowID=$this->CabRowID;"; - if($row=$this->query($sql)->fetch()){ - foreach(CabRow::RowToObject($row) as $prop => $value){ + $stmt=$this->query($sql); + if($stmt && ($row=$stmt->fetch())){ + $tmp = CabRow::RowToObject($row); + foreach (get_object_vars($tmp) as $prop => $value) { $this->$prop=$value; } return true; @@ -150,8 +152,10 @@ function GetCabRowsByZones(){ $sql="SELECT * FROM fac_CabRow WHERE ZoneID=$this->ZoneID ORDER BY Name;"; $cabrowList=array(); - foreach($this->query($sql) as $row){ - $cabrowList[]=CabRow::RowToObject($row); + if($stmt=$this->query($sql)){ + foreach($stmt as $row){ + $cabrowList[]=CabRow::RowToObject($row); + } } return $cabrowList; @@ -166,18 +170,23 @@ function GetCabRowsByDC($nozone=false){ $sql="SELECT * FROM fac_CabRow WHERE DataCenterID=$this->DataCenterID AND $sqladdon ORDER BY Name;"; $cabrowList=array(); - foreach($this->query($sql) as $row){ - $cabrowList[]=CabRow::RowToObject($row); + if($stmt=$this->query($sql)){ + foreach($stmt as $row){ + $cabrowList[]=CabRow::RowToObject($row); + } } return $cabrowList; } function GetCabRowList(){ + $this->MakeSafe(); $sql="SELECT * FROM fac_CabRow ORDER BY Name ASC;"; $cabrowList=array(); - foreach($this->query($sql) as $row){ - $cabrowList[]=CabRow::RowToObject($row); + if($stmt=$this->query($sql)){ + foreach($stmt as $row){ + $cabrowList[]=CabRow::RowToObject($row); + } } return $cabrowList; @@ -203,8 +212,9 @@ function GetCabRowFrontEdge($layout=""){ CabRowID=$this->CabRowID$layout GROUP BY FrontEdge ORDER BY CabCount DESC LIMIT 1;"; - if($cabinetRow=$this->query($sql)->fetch()){ - return $cabinetRow["FrontEdge"]; + $stmt=$this->query($sql); + if($stmt && ($cabinetRow=$stmt->fetch())){ + return $cabinetRow["FrontEdge"] ?? ""; } return ""; @@ -213,8 +223,8 @@ function GetCabRowFrontEdge($layout=""){ function Search($indexedbyid=false,$loose=false){ $o=new stdClass(); // Store any values that have been added before we make them safe - foreach($this as $prop => $val){ - if(isset($val)){ + foreach (get_object_vars($this) as $prop => $val) { + if ($val !== null) { $o->$prop=$val; } } @@ -233,11 +243,13 @@ function Search($indexedbyid=false,$loose=false){ $rowList=array(); - foreach($this->query($sql) as $row){ - if($indexedbyid){ - $rowList[$row["CabRowID"]]=CabRow::RowToObject($row); - }else{ - $rowList[]=CabRow::RowToObject($row); + if($stmt=$this->query($sql)){ + foreach($stmt as $row){ + if($indexedbyid){ + $rowList[$row["CabRowID"] ?? null]=CabRow::RowToObject($row); + }else{ + $rowList[]=CabRow::RowToObject($row); + } } } @@ -249,4 +261,4 @@ function LooseSearch($indexedbyid=false){ return $this->Search($indexedbyid,true); } } -?> \ No newline at end of file +?> diff --git a/classes/Cabinet.class.php b/classes/Cabinet.class.php index c34d1878e..2688206dd 100644 --- a/classes/Cabinet.class.php +++ b/classes/Cabinet.class.php @@ -172,9 +172,9 @@ private function FilterRights(){ if($this->Rights=='None'){ // ZoneID and CabRowID are probably both not important but meh $publicfields=array('CabinetID','DataCenterID','Location','LocationSortable','ZoneID','CabRowID','Rights','AssignedTo','U1Position'); - foreach($this as $prop => $value){ - if(!in_array($prop,$publicfields)){ - $this->$prop=null; + foreach (get_object_vars($this) as $prop => $value) { + if (!in_array($prop, $publicfields, true)) { + $this->$prop = null; } } } @@ -254,8 +254,9 @@ function GetCabinet(){ $sql="SELECT * FROM fac_Cabinet WHERE CabinetID=$this->CabinetID;"; if($cabinetRow=$dbh->query($sql)->fetch()){ - foreach(Cabinet::RowToObject($cabinetRow) as $prop => $value){ - $this->$prop=$value; + $tmp = Cabinet::RowToObject($cabinetRow); + foreach (get_object_vars($tmp) as $prop => $value) { + $this->$prop = $value; } return true; }else{ @@ -539,7 +540,8 @@ function Search($indexedbyid=false,$loose=false){ // This will store all our extended sql $sqlextend=""; - foreach($this as $prop => $val){ + $epochDate=date("Y-m-d",0); + foreach (get_object_vars($this) as $prop => $val) { // We force the following values to knowns in makesafe if($prop=="FrontEdge" && $val=="Top" && $ot!="Top"){ continue; @@ -547,7 +549,7 @@ function Search($indexedbyid=false,$loose=false){ if($prop=="U1Position" && $val=="Default" && $op!="Default") { continue; } - if($val && $val!=date("Y-m-d", strtotime(0))){ + if($val && $val !== $epochDate){ extendsql($prop,$val,$sqlextend,$loose); } } @@ -580,9 +582,14 @@ function SearchByCustomTag( $tag=null ) { $cabinetList=array(); - foreach ( $dbh->query( $sql ) as $cabinetRow ) { - $cabID=$cabinetRow["CabinetID"]; - $cabinetList[$cabID]=Cabinet::RowToObject($cabinetRow); + $stmt = $dbh->query($sql); + if ( $stmt === false ) { + return $cabinetList; + } + + foreach ( $stmt as $cabinetRow ) { + $cabID = $cabinetRow['CabinetID']; + $cabinetList[$cabID] = Cabinet::RowToObject($cabinetRow); } return $cabinetList; } @@ -594,9 +601,13 @@ function GetTags() { $tags = array(); - foreach ( $dbh->query( $sql ) as $row ) { - $tags[]=Tags::FindName($row[0]); + $stmt = $dbh->query($sql); + if ( $stmt === false ) { + return $tags; } + foreach ( $stmt as $row ) { + $tags[] = Tags::FindName($row[0]); + } return $tags; } diff --git a/classes/CabinetAudit.class.php b/classes/CabinetAudit.class.php index ef79bebaa..89473b514 100644 --- a/classes/CabinetAudit.class.php +++ b/classes/CabinetAudit.class.php @@ -41,17 +41,18 @@ function CertifyAudit() { (class_exists('LogActions'))?LogActions::LogThis($this):''; } - return; + return true; } - function GetLastAudit( $db = null ) { + function GetLastAudit() { global $dbh; global $config; global $person; $sql = "select * from fac_GenericLog where ObjectID=\"" . intval( $this->CabinetID ) . "\" and Class=\"CabinetAudit\" order by Time DESC Limit 1"; - if($row=$dbh->query($sql)->fetch()){ + $stmt = $dbh->query($sql); + if ($stmt && ($row = $stmt->fetch())) { $this->CabinetID=$row["ObjectID"]; if ( !$person->SiteAdmin && ($config->ParameterArray["GDPRCountryIsolation"] == "enabled" || $config->ParameterArray["GDPRPIIPrivacy"] == "enabled" )) { $p = new People(); @@ -79,9 +80,13 @@ function GetLastAuditByUser() { global $config; global $person; - $sql = "select * from fac_GenericLog where UserID=\"" . addslashes( $this->UserID ) . "\" and Class=\"CabinetAudit\" order by Time DESC Limit 1"; + $sql = "select * from fac_GenericLog where UserID=:userid and Class='CabinetAudit' order by Time DESC limit 1"; + $st = $dbh->prepare($sql); + $st->execute([ ':userid' => $this->UserID ]); + $row = $st->fetch(); - if ( $row = $dbh->query( $sql )->fetch() ) { + $stmt = $dbh->query($sql); + if ($stmt && ($row = $stmt->fetch())) { $this->CabinetID = $row["ObjectID"]; if ( !$person->SiteAdmin && ($config->ParameterArray["GDPRCountryIsolation"] == "enabled" || $config->ParameterArray["GDPRPIIPrivacy"] == "enabled" )) { $p = new People(); @@ -103,7 +108,7 @@ function GetLastAuditByUser() { return false; } - return; + return true; } } ?> \ No newline at end of file diff --git a/classes/CabinetMetrics.class.php b/classes/CabinetMetrics.class.php index 932065597..9ea5e6496 100644 --- a/classes/CabinetMetrics.class.php +++ b/classes/CabinetMetrics.class.php @@ -40,10 +40,19 @@ static function getMetrics( $CabinetID ) { $m = new CabinetMetrics(); $m->CabinetID = $CabinetID; - + $m->IntakeTemperature = 0; + $m->IntakeHumidity = 0; + $m->ExhaustTemperature = 0; + $m->ExhaustHumidity = 0; + $m->CalculatedPower = 0; + $m->CalculatedWeight = 0; + $m->MeasuredPower = 0; + $m->LastRead = null; + $m->SpaceUsed = 0; + $params = array( ":CabinetID"=>$CabinetID ); // Get the intake side - $sql = "select max(Temperature) as Temp, max(Humidity) as Humid, LastRead from fac_SensorReadings where DeviceID in (select DeviceID from fac_Device where DeviceType='Sensor' and BackSide=0 and Cabinet=:CabinetID)"; + $sql = "select max(Temperature) as Temp, max(Humidity) as Humid, max(LastRead) as LastRead from fac_SensorReadings where DeviceID in (select DeviceID from fac_Device where DeviceType='Sensor' and BackSide=0 and Cabinet=:CabinetID)"; $st = $dbh->prepare( $sql ); $st->execute( $params ); if ( $row = $st->fetch() ) { @@ -69,8 +78,8 @@ static function getMetrics( $CabinetID ) { $st = $dbh->prepare( $sql ); $st->execute( $params ); if ( $row = $st->fetch() ) { - $m->CalculatedPower = $row["Power"]; - $m->CalculatedWeight = $row["Weight"]; + $m->CalculatedPower = (int)($row["Power"]??0); + $m->CalculatedWeight = (int)($row["Weight"]??0); } // Space needs to only count devices that are not children of other devices (slots in a chassis) @@ -78,7 +87,7 @@ static function getMetrics( $CabinetID ) { $st = $dbh->prepare( $sql ); $st->execute( $params ); if ( $row = $st->fetch() ) { - $m->SpaceUsed = $row["SpaceUsed"]; + $m->SpaceUsed = (int)($row["SpaceUsed"]??0); } @@ -87,7 +96,7 @@ static function getMetrics( $CabinetID ) { $st = $dbh->prepare( $sql ); $st->execute( $params ); if ( $row = $st->fetch() ) { - $m->MeasuredPower = $row["Power"]; + $m->MeasuredPower = (int)($row["Power"]??0); } return $m; diff --git a/classes/CabinetTemps.class.php b/classes/CabinetTemps.class.php index 3ceebe747..eb7d238ce 100644 --- a/classes/CabinetTemps.class.php +++ b/classes/CabinetTemps.class.php @@ -37,14 +37,20 @@ function GetReading() { $sql = sprintf( "select * from fac_CabinetTemps where CabinetID=%d", $this->CabinetID ); - if ( $row = $dbh->query( $sql )->fetch() ) { - $this->LastRead = date( "m-d-Y H:i:s", strtotime($row["LastRead"]) ); - $Temp = $row["Temp"]; - $Humidity = $row["Humidity"]; + $stmt = $dbh->query( $sql ); + if ( $stmt && ( $row = $stmt->fetch() ) ) { + $lastRead = $row["LastRead"] ?? null; + if ( $lastRead ) { + $this->LastRead = date( "m-d-Y H:i:s", strtotime( $lastRead ) ); + } else { + $this->LastRead = null; + } + $this->Temp = $row["Temp"] ?? null; + $this->Humidity = $row["Humidity"] ?? null; } else { $info = $dbh->errorInfo(); - error_log( "PDO Error: " . $info[2] . " SQL=" . $sql ); + error_log( "PDO Error: " . ( $info[2] ?? 'Unknown error' ) . " SQL=" . $sql ); return false; } diff --git a/classes/ColorCoding.class.php b/classes/ColorCoding.class.php index f61ce8548..1cf0a9058 100644 --- a/classes/ColorCoding.class.php +++ b/classes/ColorCoding.class.php @@ -39,7 +39,7 @@ function CreateCode() { }else{ $info=$dbh->errorInfo(); - error_log("PDO Error::CreateCode {$info[2]}"); + error_log("PDO Error::CreateCode " . ($info[2] ?? 'Unknown error')); return false; } @@ -54,7 +54,7 @@ function UpdateCode() { if(!$dbh->query($sql)){ $info=$dbh->errorInfo(); - error_log("PDO Error: {$info[2]}"); + error_log("PDO Error: " . ($info[2] ?? 'Unknown error')); return false; }else{ return true; @@ -71,7 +71,7 @@ function DeleteCode() { if(!$dbh->exec($sql)){ $info=$dbh->errorInfo(); - error_log("PDO Error: {$info[2]}"); + error_log("PDO Error: " . ($info[2] ?? 'Unknown error')); return false; } @@ -83,9 +83,10 @@ function GetCode() { $sql="SELECT * FROM fac_ColorCoding WHERE ColorID=".intval($this->ColorID); - if($row=$dbh->query($sql)->fetch()){ - $this->Name=$row["Name"]; - $this->DefaultNote=$row["DefaultNote"]; + $stmt=$dbh->query($sql); + if($stmt && ($row=$stmt->fetch())){ + $this->Name=$row["Name"] ?? null; + $this->DefaultNote=$row["DefaultNote"] ?? null; }else{ return false; } @@ -98,9 +99,10 @@ function GetCodeByName() { $sql="SELECT * FROM fac_ColorCoding WHERE ucase(Name)=ucase('".transform($this->Name)."');"; - if($row=$dbh->query($sql)->fetch()){ - $this->ColorID=$row["ColorID"]; - $this->DefaultNote=$row["DefaultNote"]; + $stmt=$dbh->query($sql); + if($stmt && ($row=$stmt->fetch())){ + $this->ColorID=$row["ColorID"] ?? null; + $this->DefaultNote=$row["DefaultNote"] ?? null; }else{ return false; } @@ -115,12 +117,14 @@ static function GetCodeList($indexedby="ColorID") { $sql="SELECT * FROM fac_ColorCoding ORDER BY Name ASC"; $codeList=array(); - foreach($dbh->query($sql) as $row){ - $n=$row[$indexedby]; // index array by id - $codeList[$n]=new ColorCoding(); - $codeList[$n]->ColorID=$row["ColorID"]; - $codeList[$n]->Name=$row["Name"]; - $codeList[$n]->DefaultNote=$row["DefaultNote"]; + if($stmt=$dbh->query($sql)){ + foreach($stmt as $row){ + $n=$row[$indexedby] ?? null; // index array by id + $codeList[$n]=new ColorCoding(); + $codeList[$n]->ColorID=$row["ColorID"] ?? null; + $codeList[$n]->Name=$row["Name"] ?? null; + $codeList[$n]->DefaultNote=$row["DefaultNote"] ?? null; + } } return $codeList; @@ -148,7 +152,7 @@ static function ResetCode($colorid,$tocolorid=0){ if($error){ $info=$dbh->errorInfo(); - error_log("PDO Error: {$info[2]}"); + error_log("PDO Error: " . ($info[2] ?? 'Unknown error')); return false; }else{ return true; diff --git a/classes/ConnectionPath.class.php b/classes/ConnectionPath.class.php index 6beb97e10..0cdf30c30 100644 --- a/classes/ConnectionPath.class.php +++ b/classes/ConnectionPath.class.php @@ -42,6 +42,9 @@ function MakeSafe(){ } private function AddDeviceToPathAux () { + if(!is_array($this->PathAux)){ + $this->PathAux=array(); + } $i=count($this->PathAux); $this->PathAux[$i]["DeviceID"]=$this->DeviceID; $this->PathAux[$i]["PortNumber"]=$this->PortNumber; @@ -54,8 +57,11 @@ private function ClearPathAux(){ private function IsDeviceInPathAux () { $ret=false; $crossovercount=0; - for ($i=0; $iPathAux); $i++){ - if ($this->PathAux[$i]["DeviceID"]==$this->DeviceID && $this->PathAux[$i]["PortNumber"]=$this->PortNumber) { + if(!is_array($this->PathAux)){ + return false; + } + for ($i=0, $cnt=count($this->PathAux); $i<$cnt; $i++){ + if (($this->PathAux[$i]["DeviceID"] ?? null)==$this->DeviceID && ($this->PathAux[$i]["PortNumber"] ?? null)==$this->PortNumber) { ++$crossovercount; if($crossovercount>=200){ $ret=true; diff --git a/classes/Container.class.php b/classes/Container.class.php index 93c02b355..1f3711a0f 100644 --- a/classes/Container.class.php +++ b/classes/Container.class.php @@ -161,7 +161,8 @@ function GetContainer(){ ORDER BY LENGTH(Name), Name ASC;"; if($row=$this->query($sql)->fetch()){ - foreach(Container::RowToObject($row) as $prop => $value){ + $tmp = Container::RowToObject($row); + foreach (get_object_vars($tmp) as $prop => $value) { $this->$prop=$value; } return true; @@ -293,12 +294,22 @@ function MakeContainerImage(){ } if ( file_exists( $mapfile ) ) { - if(mime_content_type($mapfile)=='image/svg+xml'){ - $svgfile = simplexml_load_file($mapfile); + $mime = @mime_content_type($mapfile); + if ($mime === 'image/svg+xml') { + $svgfile = @simplexml_load_file($mapfile); + if ($svgfile !== false) { + $width = intval($svgfile['width'] ?? 0); + $height = intval($svgfile['height'] ?? 0); + } else { + $width = 0; + $height = 0; + } $width = substr($svgfile['width'],0,4); $height = substr($svgfile['height'],0,4); }else{ - list($width, $height, $type, $attr)=getimagesize($mapfile); + $imgSize = @getimagesize($mapfile); + $width = $imgSize[0] ?? 0; + $height = $imgSize[1] ?? 0; } $mapHTML.="
\n"; $mapHTML.="\"Container\n"; @@ -365,11 +376,20 @@ function MakeContainerMiniImage($tipo="",$id=0) { if ( file_exists( $mapfile ) ) { if(mime_content_type($mapfile)=='image/svg+xml'){ - $svgfile = simplexml_load_file($mapfile); + $svgfile = @simplexml_load_file($mapfile); + if ($svgfile !== false) { + $width = intval($svgfile['width'] ?? 0); + $height = intval($svgfile['height'] ?? 0); + } else { + $width = 0; + $height = 0; + } $width = substr($svgfile['width'],0,4); $height = substr($svgfile['height'],0,4); }else{ - list($width, $height, $type, $attr)=getimagesize($mapfile); + $imgSize = @getimagesize($mapfile); + $width = $imgSize[0] ?? 0; + $height = $imgSize[1] ?? 0; } $mapHTML.="
\n"; $mapHTML.="isHTML(true); if ($this->From == ''){ - $this->setFrom( $config->ParameterArray['MailFromAddr'] ); + $this->setFrom( $config->ParameterArray['MailFromAddr'] ?? '' ); } if ($this->Subject == ''){ - $this->setFrom( $config->ParameterArray['MailSubject'] ); + $this->setFrom( $config->ParameterArray['MailSubject'] ?? '' ); } $this->SMTPDebug = SMTP::DEBUG_OFF; $this->isSMTP(); - $this->Host = $config->ParameterArray['SMTPServer']; - $this->Port = $config->ParameterArray['SMTPPort']; + $this->Host = $config->ParameterArray['SMTPServer'] ?? ''; + $this->Port = $config->ParameterArray['SMTPPort'] ?? 25; $this->SMTPAutoTLS = false; // If any port other than 25 is specified, assume encryption and authentication - if($config->ParameterArray['SMTPPort']!= 25){ + if(($config->ParameterArray['SMTPPort'] ?? 25) != 25){ $this->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; $this->SMTPAuth = true; - $this->Username = $config->ParameterArray['SMTPUser']; - $this->Password = $config->ParameterArray['SMTPPassword']; + $this->Username = $config->ParameterArray['SMTPUser'] ?? ''; + $this->Password = $config->ParameterArray['SMTPPassword'] ?? ''; } } @@ -41,7 +41,7 @@ function send() { global $config; if (count($this->all_recipients) == 0){ - $this->addAddress($config->ParameterArray['FacMgrMail']); + $this->addAddress($config->ParameterArray['FacMgrMail'] ?? ''); } parent::send(); diff --git a/classes/DataCenter.class.php b/classes/DataCenter.class.php index 1100bb0ce..b685bc54a 100644 --- a/classes/DataCenter.class.php +++ b/classes/DataCenter.class.php @@ -97,19 +97,22 @@ function exec($sql){ return $dbh->exec($sql); } - function Search($indexedbyid=false,$loose=false){ - global $person; - global $config; + function Search($indexedbyid = false, $loose = false) { + global $person, $config; - if ($config->ParameterArray["GDPRCountryIsolation"] == "enabled" && !$person->SiteAdmin ) { + if ( + $config->ParameterArray["GDPRCountryIsolation"] === "enabled" + && !$person->SiteAdmin + ) { $this->countryCode = $person->countryCode; } - $o=new stdClass(); - // Store any values that have been added before we make them safe - foreach($this as $prop => $val){ - if(isset($val)){ - $o->$prop=$val; + $o = new stdClass(); + + // Store any values that have been added before we make them safe + foreach (get_object_vars($this) as $prop => $val) { + if ($val !== null) { + $o->$prop = $val; } } @@ -117,28 +120,31 @@ function Search($indexedbyid=false,$loose=false){ $this->MakeSafe(); // This will store all our extended sql - $sqlextend=""; - foreach($this as $prop => $val){ - if($val){ - extendsql($prop,$val,$sqlextend,$loose); + $sqlextend = ""; + + foreach (get_object_vars($this) as $prop => $val) { + if ($val !== null && $val !== '') { + extendsql($prop, $val, $sqlextend, $loose); } } - $sql="SELECT * FROM fac_DataCenter $sqlextend ORDER BY Name ASC;"; + $sql = "SELECT * FROM fac_DataCenter $sqlextend ORDER BY Name ASC;"; - $dcList=array(); + $dcList = []; - foreach($this->query($sql) as $row){ - if($indexedbyid){ - $dcList[$row["DataCenterID"]]=DataCenter::RowToObject($row); - }else{ - $dcList[]=DataCenter::RowToObject($row); + foreach ($this->query($sql) as $row) { + $dc = DataCenter::RowToObject($row); + if ($indexedbyid) { + $dcList[$row["DataCenterID"]] = $dc; + } else { + $dcList[] = $dc; } } return $dcList; } + // Make a simple reference to a loose search function LooseSearch($indexedbyid=false){ return $this->Search($indexedbyid,true); @@ -211,9 +217,11 @@ function DeleteDataCenter($junkremoval=true) { $zn->DataCenterID = $this->DataCenterID; $zoneList = $zn->GetZonesByDC(); + if (is_iterable($zoneList) ) { foreach ( $zoneList as $z ) { // This function already deletes any rows within the zone $z->DeleteZone(); + } } // Time to deal with the crap in storage @@ -294,9 +302,11 @@ function GetDataCenter(){ if($row=$this->query($sql)->fetch()){ - foreach(DataCenter::RowToObject($row) as $prop => $value){ - $this->$prop=$value; + $tmp = DataCenter::RowToObject($row); + foreach (get_object_vars($tmp) as $prop => $value) { + $this->$prop = $value; } + return true; }else{ return false; @@ -392,7 +402,8 @@ public function getContainerList($containerID = 0) function GetOverview(){ global $config; $this->MakeSafe(); - $statusarray=array(); + $statusarray=array(); + $airflow=array(); // check to see if map was set if(strlen($this->DrawingFileName)){ $mapfile=$config->ParameterArray['drawingpath'].DIRECTORY_SEPARATOR.$this->DrawingFileName; @@ -452,7 +463,8 @@ function GetOverview(){ $RealPowerYellow=intval($this->dcconfig->ParameterArray["PowerYellow"]); // get image file attributes and type - if(mime_content_type($mapfile)=='image/svg+xml'){ + $mime = mime_content_type($mapfile); + if ($mime === 'image/svg+xml') { $svgfile = simplexml_load_file($mapfile); $width = substr($svgfile['width'],0,4); $height = substr($svgfile['height'],0,4); diff --git a/classes/Department.class.php b/classes/Department.class.php index 5aadd2c2a..6125ebf60 100644 --- a/classes/Department.class.php +++ b/classes/Department.class.php @@ -54,21 +54,21 @@ function MakeSafe(){ } function MakeDisplay(){ - $this->Name=stripslashes($this->Name); - $this->ExecSponsor=stripslashes($this->ExecSponsor); - $this->SDM=stripslashes($this->SDM); - $this->Classification=stripslashes($this->Classification); - $this->DeptColor=stripslashes($this->DeptColor); + $this->Name=stripslashes((string)$this->Name); + $this->ExecSponsor=stripslashes((string)$this->ExecSponsor); + $this->SDM=stripslashes((string)$this->SDM); + $this->Classification=stripslashes((string)$this->Classification); + $this->DeptColor=stripslashes((string)$this->DeptColor); } static function RowToObject($row){ $dept=new Department(); - $dept->DeptID=$row["DeptID"]; - $dept->Name=$row["Name"]; - $dept->ExecSponsor=$row["ExecSponsor"]; - $dept->SDM=$row["SDM"]; - $dept->Classification=$row["Classification"]; - $dept->DeptColor=$row["DeptColor"]; + $dept->DeptID=$row["DeptID"] ?? null; + $dept->Name=$row["Name"] ?? null; + $dept->ExecSponsor=$row["ExecSponsor"] ?? null; + $dept->SDM=$row["SDM"] ?? null; + $dept->Classification=$row["Classification"] ?? null; + $dept->DeptColor=$row["DeptColor"] ?? null; $dept->MakeDisplay(); @@ -195,14 +195,15 @@ function GetDeptByID() { $sql="SELECT * FROM fac_Department WHERE DeptID=$this->DeptID;"; - if($row=$this->query($sql)->fetch()){ + $stmt=$this->query($sql); + if($stmt && ($row=$stmt->fetch())){ foreach(Department::RowToObject($row) as $prop => $value){ $this->$prop=$value; } return true; }else{ // Return an empty object in the case of a failed lookup, preserve the id though - foreach($this as $prop => $value){ + foreach(get_object_vars($this) as $prop => $value){ $this->$prop=($prop=='DeptID')?$value:''; } return false; @@ -213,14 +214,15 @@ function GetDeptByName() { $this->MakeSafe(); $sql="SELECT count(*) as Total, fac_Department.* FROM fac_Department WHERE ucase(Name)=ucase(\"$this->Name\");"; - if($row=$this->query($sql)->fetch()){ + $stmt=$this->query($sql); + if($stmt && ($row=$stmt->fetch())){ foreach(Department::RowToObject($row) as $prop => $value){ if ( $prop != "Total" ) $this->$prop=$value; } } - if ( $row["Total"] == 0 ) { + if ( ($row["Total"] ?? 0) == 0 ) { return false; } else { return true; @@ -229,8 +231,10 @@ function GetDeptByName() { function GetDepartmentList() { $sql="SELECT * FROM fac_Department ORDER BY Name ASC;"; $deptList=array(); - foreach($this->query($sql) as $row){ - $deptList[]=Department::RowToObject($row); + if($stmt=$this->query($sql)){ + foreach($stmt as $row){ + $deptList[]=Department::RowToObject($row); + } } return $deptList; @@ -248,7 +252,7 @@ public static function GetDepartmentListIndexedbyID() { $stmt->execute(); while ($row = $stmt->fetch()) { $dept = Department::RowToObject($row); - $deptList[$dept->DeptID] = $dept; + $deptList[$dept->DeptID ?? null] = $dept; } return $deptList; } @@ -275,8 +279,9 @@ function GetDepartmentByContact($UserID){ c.UserID=\"".sanitize($UserID)."\";"; // If someone is assigned to more than one department, just return the first hit - if($row=$this->query($sql)->fetch()){ - $this->DeptID=$row["DeptID"]; + $stmt=$this->query($sql); + if($stmt && ($row=$stmt->fetch())){ + $this->DeptID=$row["DeptID"] ?? null; $this->GetDeptByID(); } } @@ -314,11 +319,13 @@ function Search($indexedbyid=false,$loose=false){ } $sql="SELECT * FROM fac_Department $sqlextend ORDER BY Name ASC;"; $deptList=array(); - foreach($this->query($sql) as $deptRow){ - if($indexedbyid){ - $deptList[$deptRow["DeptID"]]=Department::RowToObject($deptRow); - }else{ - $deptList[]=Department::RowToObject($deptRow); + if($stmt=$this->query($sql)){ + foreach($stmt as $deptRow){ + if($indexedbyid){ + $deptList[$deptRow["DeptID"] ?? null]=Department::RowToObject($deptRow); + }else{ + $deptList[]=Department::RowToObject($deptRow); + } } } diff --git a/classes/Device.class.php b/classes/Device.class.php index 999d048ec..e2550e27d 100644 --- a/classes/Device.class.php +++ b/classes/Device.class.php @@ -212,9 +212,9 @@ static function RowToObject($dbRow,$filterrights=true,$extendmodel=true,$customv $dev->APIPort=$dbRow["APIPort"]; $dev->ProxMoxRealm=$dbRow["ProxMoxRealm"]; $dev->Owner=$dbRow["Owner"]; - // Suppressing errors on the following two because they can be null and that generates an apache error - @$dev->EscalationTimeID=$dbRow["EscalationTimeID"]; - @$dev->EscalationID=$dbRow["EscalationID"]; + // Suppressing notices in case these fields are null in the database + $dev->EscalationTimeID = isset($dbRow["EscalationTimeID"]) ? $dbRow["EscalationTimeID"] : null; + $dev->EscalationID = isset($dbRow["EscalationID"]) ? $dbRow["EscalationID"] : null; $dev->PrimaryContact=$dbRow["PrimaryContact"]; $dev->Cabinet=$dbRow["Cabinet"]; $dev->Position=$dbRow["Position"]; @@ -231,7 +231,7 @@ static function RowToObject($dbRow,$filterrights=true,$extendmodel=true,$customv $dev->MfgDate=$dbRow["MfgDate"]; $dev->InstallDate=$dbRow["InstallDate"]; $dev->WarrantyCo=$dbRow["WarrantyCo"]; - @$dev->WarrantyExpire=$dbRow["WarrantyExpire"]; + $dev->WarrantyExpire = isset($dbRow["WarrantyExpire"]) ? $dbRow["WarrantyExpire"] : null; $dev->Notes=$dbRow["Notes"]; $dev->Status = $dbRow["Status"]; $dev->HalfDepth=$dbRow["HalfDepth"]; @@ -316,7 +316,7 @@ private function FilterRights(){ if ( !$person->SiteAdmin && $dc->countryCode != $person->countryCode && $config->ParameterArray["GDPRCountryIsolation"] == "enabled" ) { error_log( "-> Isolation section entered" ); $this->Rights = 'None'; - foreach($this as $prop=>$val) { + foreach (get_object_vars($this) as $prop => $val) { $this->$prop=null; } return; @@ -331,7 +331,7 @@ private function FilterRights(){ // Remove information that this user isn't allowed to see if($this->Rights=='None'){ $publicfields=array('DeviceID','Label','Cabinet','Position','Height','Status','DeviceType','Rights'); - foreach($this as $prop => $value){ + foreach (get_object_vars($this) as $prop => $val) { if(!in_array($prop,$publicfields)){ $this->$prop=null; } @@ -385,8 +385,8 @@ static function BasicTests($DeviceID){ */ static function OSS_SNMP_Lookup($dev,$snmplookup,$oid=null,$walk=false){ // This is find out the name of the function that called this to make the error logging more descriptive - $caller=debug_backtrace(); - $caller=$caller[1]['function']; + $trace=debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS,2); + $caller=$trace[1]['function'] ?? 'unknown'; if (preg_match('/(?\{(?[^\}]+)+\})/i', $oid, $oid_matches)) { @@ -405,11 +405,20 @@ static function OSS_SNMP_Lookup($dev,$snmplookup,$oid=null,$walk=false){ $snmpHost=new OSS_SNMP\SNMP($dev->PrimaryIP,$dev->SNMPCommunity,$dev->SNMPVersion,$dev->v3SecurityLevel,$dev->v3AuthProtocol,$dev->v3AuthPassphrase,$dev->v3PrivProtocol,$dev->v3PrivPassphrase); $snmpresult=false; try { - $snmpresult=((is_null($oid))?$snmpHost->useSystem()->$snmplookup(true):($walk))?$snmpHost->realWalk($oid):$snmpHost->get($oid); + //$snmpresult=((is_null($oid))?$snmpHost->useSystem()->$snmplookup(true):($walk))?$snmpHost->realWalk($oid):$snmpHost->get($oid); + //Comptatility fix for PHP 8.x and earlier , ternaires is confusing with method calls + if (is_null($oid)) { + $snmpresult = $snmpHost->useSystem()->{$snmplookup}(true); + } elseif ($walk) { + $snmpresult = $snmpHost->realWalk($oid); + } else { + $snmpresult = $snmpHost->get($oid); + } }catch (Exception $e){ $dev->IncrementFailures(); error_log("Device::$caller($dev->DeviceID) ".$e->getMessage()); + return false; } $dev->ResetFailures(); @@ -458,7 +467,6 @@ function CreateDevice(){ if(!$dbh->exec($sql)){ $info = $dbh->errorInfo(); - error_log( "PDO Error: {$info[2]} SQL=$sql" ); return false; } @@ -655,6 +663,8 @@ function IncrementFailures(){ $sql="UPDATE fac_Device SET SNMPFailureCount=SNMPFailureCount+1 WHERE DeviceID=$this->DeviceID"; if(!$this->query($sql)){ + global $dbh; + $info = $dbh->errorInfo(); error_log( "Device::IncrementFailures::PDO Error: {$info[2]} SQL=$sql"); return false; }else{ @@ -669,6 +679,8 @@ function ResetFailures(){ $sql="UPDATE fac_Device SET SNMPFailureCount=0 WHERE DeviceID=$this->DeviceID"; if(!$this->query($sql)){ + global $dbh; + $info = $dbh->errorInfo(); error_log( "Device::ResetFailures::PDO Error: {$info[2]} SQL=$sql"); return false; }else{ @@ -1038,7 +1050,6 @@ function Audit() { if(!$dbh->exec($sql)){ $info=$dbh->errorInfo(); - error_log("Device:Audit::PDO Error: {$info[2]} SQL=$sql"); return false; } @@ -1061,7 +1072,8 @@ function GetDevice($filterrights=true){ $sql="SELECT * FROM fac_Device WHERE DeviceID=$this->DeviceID;"; if($devRow=$dbh->query($sql)->fetch()){ - foreach(Device::RowToObject($devRow,$filterrights) as $prop => $value){ + $tmp = Device::RowToObject($devRow,$filterrights); + foreach (get_object_vars($tmp) as $prop => $value) { $this->$prop=$value; } @@ -1088,7 +1100,7 @@ function GetDeviceList( $datacenterid=null ) { $sql = "select a.* from fac_Device a, fac_Cabinet b where a.Cabinet=b.CabinetID $dcLimit order by b.DataCenterID ASC, Label ASC"; $deviceList = array(); - foreach ( $this->query( $sql ) as $deviceRow ) { + foreach ($this->query( $sql ) as $deviceRow ) { $deviceList[]=Device::RowToObject( $deviceRow ); } @@ -1372,7 +1384,6 @@ function DeleteDevice(){ if(!$dbh->exec($sql)){ $info=$dbh->errorInfo(); - error_log("PDO Error: {$info[2]} SQL=$sql"); return false; } @@ -1403,7 +1414,7 @@ function SearchDevicebyIP(){ $sql="SELECT * FROM fac_Device WHERE Status<>'Disposed' AND PrimaryIP LIKE \"%$this->PrimaryIP%\" ORDER BY Label;"; $deviceList = array(); - foreach($this->query($sql) as $deviceRow){ + foreach ($this->query($sql) as $deviceRow){ $deviceList[$deviceRow["DeviceID"]]=Device::RowToObject($deviceRow); } @@ -1422,7 +1433,7 @@ function GetDevicesbyOwner(){ $deviceList=array(); - foreach($dbh->query($sql) as $deviceRow){ + foreach ($dbh->query($sql) as $deviceRow){ $deviceList[$deviceRow["DeviceID"]]=Device::RowToObject($deviceRow); } @@ -1436,7 +1447,7 @@ function GetESXDevices() { $deviceList = array(); - foreach($dbh->query($sql) as $deviceRow){ + foreach ($dbh->query($sql) as $deviceRow){ $deviceList[$deviceRow["DeviceID"]]=Device::RowToObject($deviceRow); } @@ -1471,7 +1482,7 @@ function Search($indexedbyid=false,$loose=false,$filterrights=false){ $o=array(); // Store any values that have been added before we make them safe - foreach($this as $prop => $val){ + foreach (get_object_vars($this) as $prop => $val) { if(isset($val)){ $o[$prop]=$val; } @@ -1486,7 +1497,7 @@ function Search($indexedbyid=false,$loose=false,$filterrights=false){ // This will store all our extended sql $sqlextend=""; - foreach($o as $prop => $val){ + foreach ($o as $prop => $val){ if(property_exists("Device",$prop)){ extendsql($prop,$this->$prop,$sqlextend,$loose); }else{ @@ -1874,7 +1885,6 @@ function SetTags($tags=array()) { $sql="INSERT INTO fac_DeviceTags (DeviceID, TagID) VALUES ($this->DeviceID,$t);"; if(!$dbh->exec($sql)){ $info=$dbh->errorInfo(); - error_log("PDO Error: {$info[2]} SQL=$sql"); return false; } @@ -2037,7 +2047,9 @@ function GetChildDevicePicture($parentDetails, $rear=false){ if (!file_exists($path.$picturefile)){ $picturefile=$config->ParameterArray["picturepath"]."P_ERROR.png"; } - @list($width, $height)=getimagesize($path.$picturefile); + $imgSize = @getimagesize($path.$picturefile); + $width = $imgSize[0] ?? 0; + $height = $imgSize[1] ?? 0; // Make sure there is an image! DOH! If either is 0 then use a text box $width=intval($width); $height=intval($height); @@ -2469,7 +2481,7 @@ static function UpdateSensors($CabinetID=null){ if ( ! is_null($CabinetID) ) { $filterType = "Cabinet"; $filterValue = $CabinetID; - $this->UpdateSensorsFilter( $filterType, $filterValue ); + self::UpdateSensorsFilter( $filterType, $filterValue ); } } @@ -2498,7 +2510,7 @@ static function UpdateSensorsFilter( $filterType, $filterValue ) { $filterSQL = "AND b.CabRowID='$filterValue'"; break; case "Cabinet": - $filterSQL=(is_null($CabinetID))?"":" AND a.Cabinet=$cab->CabinetID"; + $filterSQL = "AND a.Cabinet='" . intval($filterValue) . "'"; break; default: $filterSQL = ""; @@ -2561,7 +2573,6 @@ static function UpdateSensorsFilter( $filterType, $filterValue ) { if(!$dbh->query($insertsql)){ $info=$dbh->errorInfo(); - error_log( "UpdateSensors::PDO Error: {$info[2]} SQL=$insertsql" ); return false; } @@ -2687,7 +2698,7 @@ static function resetCounter( $deviceID=false ) { if ( ! $p->SiteAdmin ) { return false; } - + $clause = ""; if ( $deviceID != false ) { $clause = "WHERE DeviceID=" . intval( $deviceID ); } diff --git a/classes/DeviceCustomAttribute.class.php b/classes/DeviceCustomAttribute.class.php index 0a4c5d106..14944a2b1 100644 --- a/classes/DeviceCustomAttribute.class.php +++ b/classes/DeviceCustomAttribute.class.php @@ -97,12 +97,12 @@ function CheckInput() { static function RowToObject($dbRow) { $dca = new DeviceCustomAttribute(); - $dca->AttributeID=$dbRow["AttributeID"]; - $dca->Label=$dbRow["Label"]; - $dca->AttributeType=$dbRow["AttributeType"]; - $dca->Required=$dbRow["Required"]; - $dca->AllDevices=$dbRow["AllDevices"]; - $dca->DefaultValue=$dbRow["DefaultValue"]; + $dca->AttributeID=$dbRow["AttributeID"] ?? null; + $dca->Label=$dbRow["Label"] ?? null; + $dca->AttributeType=$dbRow["AttributeType"] ?? null; + $dca->Required=$dbRow["Required"] ?? null; + $dca->AllDevices=$dbRow["AllDevices"] ?? null; + $dca->DefaultValue=$dbRow["DefaultValue"] ?? null; return $dca; } @@ -123,7 +123,7 @@ function CreateDeviceCustomAttribute() { if(!$dbh->exec($sql)) { $info=$dbh->errorInfo(); - error_log("CreateDeviceCustomAttribute::PDO Error: {$info[2]} SQL=$sql"); + error_log("CreateDeviceCustomAttribute::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql"); return false; } else { $this->AttributeID=$dbh->LastInsertId(); @@ -162,7 +162,7 @@ function UpdateDeviceCustomAttribute() { if(!$dbh->query($sql)) { $info=$dbh->errorInfo(); - error_log("UpdateDeviceCustomAttribute::PDO Error: {$info[2]} SQL=$sql"); + error_log("UpdateDeviceCustomAttribute::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql"); return false; } @@ -178,7 +178,8 @@ function GetDeviceCustomAttribute() { FROM fac_DeviceCustomAttribute WHERE AttributeID=$this->AttributeID;"; - if($dcaRow=$dbh->query($sql)->fetch()) { + $stmt=$dbh->query($sql); + if($stmt && ($dcaRow=$stmt->fetch())) { foreach(DeviceCustomAttribute::RowToObject($dcaRow) as $prop => $value) { $this->$prop=$value; } @@ -195,21 +196,21 @@ function RemoveDeviceCustomAttribute() { $sql="DELETE FROM fac_DeviceTemplateCustomValue WHERE AttributeID=$this->AttributeID;"; if(!$dbh->query($sql)){ $info=$dbh->errorInfo(); - error_log("RemoveDeviceCustomAttribute::PDO Error: {$info[2]} SQL=$sql" ); + error_log("RemoveDeviceCustomAttribute::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql" ); return false; } $sql="DELETE FROM fac_DeviceCustomValue WHERE AttributeID=$this->AttributeID;"; if(!$dbh->query($sql)){ $info=$dbh->errorInfo(); - error_log("RemoveDeviceCustomAttribute::PDO Error: {$info[2]} SQL=$sql" ); + error_log("RemoveDeviceCustomAttribute::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql" ); return false; } $sql="DELETE FROM fac_DeviceCustomAttribute WHERE AttributeID=$this->AttributeID;"; if(!$dbh->query($sql)){ $info=$dbh->errorInfo(); - error_log("RemoveDeviceCustomAttribute::PDO Error: {$info[2]} SQL=$sql" ); + error_log("RemoveDeviceCustomAttribute::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql" ); return false; } @@ -225,14 +226,14 @@ function RemoveFromTemplatesAndDevices() { $sql="DELETE FROM fac_DeviceTemplateCustomValue WHERE AttributeID=$this->AttributeID;"; if(!$dbh->query($sql)){ $info=$dbh->errorInfo(); - error_log("RemoveDeviceCustomAttribute::PDO Error: {$info[2]} SQL=$sql" ); + error_log("RemoveDeviceCustomAttribute::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql" ); return false; } $sql="DELETE FROM fac_DeviceCustomValue WHERE AttributeID=$this->AttributeID;"; if(!$dbh->query($sql)){ $info=$dbh->errorInfo(); - error_log("RemoveDeviceCustomAttribute::PDO Error: {$info[2]} SQL=$sql" ); + error_log("RemoveDeviceCustomAttribute::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql" ); return false; } @@ -248,11 +249,13 @@ static function GetDeviceCustomAttributeList($indexbyname=false) { FROM fac_DeviceCustomAttribute ORDER BY Label, AttributeID;"; - foreach($dbh->query($sql) as $dcaRow) { - if($indexbyname){ - $dcaList[$dcaRow["Label"]]=DeviceCustomAttribute::RowToObject($dcaRow); - }else{ - $dcaList[$dcaRow["AttributeID"]]=DeviceCustomAttribute::RowToObject($dcaRow); + if($stmt=$dbh->query($sql)){ + foreach($stmt as $dcaRow) { + if($indexbyname){ + $dcaList[$dcaRow["Label"] ?? null]=DeviceCustomAttribute::RowToObject($dcaRow); + }else{ + $dcaList[$dcaRow["AttributeID"] ?? null]=DeviceCustomAttribute::RowToObject($dcaRow); + } } } diff --git a/classes/DevicePorts.class.php b/classes/DevicePorts.class.php index c4ebdb3ed..12b3e4b01 100644 --- a/classes/DevicePorts.class.php +++ b/classes/DevicePorts.class.php @@ -56,23 +56,23 @@ function MakeSafe() { } function MakeDisplay(){ - $this->Label=stripslashes(trim($this->Label)); - $this->Notes=stripslashes(trim($this->Notes)); + $this->Label=stripslashes(trim((string)$this->Label)); + $this->Notes=stripslashes(trim((string)$this->Notes)); } static function RowToObject($dbRow){ $dp=new DevicePorts(); - $dp->DeviceID=$dbRow['DeviceID']; - $dp->PortNumber=(int)$dbRow['PortNumber']; - $dp->Label=$dbRow['Label']; - $dp->ConnectorID=$dbRow['ConnectorID']; - $dp->ProtocolID=$dbRow['ProtocolID']; - $dp->RateID=$dbRow['RateID']; - $dp->MediaID=$dbRow['MediaID']; - $dp->ColorID=$dbRow['ColorID']; - $dp->ConnectedDeviceID=(int)$dbRow['ConnectedDeviceID']; - $dp->ConnectedPort=(int)$dbRow['ConnectedPort']; - $dp->Notes=$dbRow['Notes']; + $dp->DeviceID=$dbRow['DeviceID'] ?? null; + $dp->PortNumber=(int)($dbRow['PortNumber'] ?? 0); + $dp->Label=$dbRow['Label'] ?? null; + $dp->ConnectorID=$dbRow['ConnectorID'] ?? null; + $dp->ProtocolID=$dbRow['ProtocolID'] ?? null; + $dp->RateID=$dbRow['RateID'] ?? null; + $dp->MediaID=$dbRow['MediaID'] ?? null; + $dp->ColorID=$dbRow['ColorID'] ?? null; + $dp->ConnectedDeviceID=(int)($dbRow['ConnectedDeviceID'] ?? 0); + $dp->ConnectedPort=(int)($dbRow['ConnectedPort'] ?? 0); + $dp->Notes=$dbRow['Notes'] ?? null; $dp->MakeDisplay(); @@ -84,7 +84,8 @@ function getPort(){ $this->MakeSafe(); $sql="SELECT * FROM fac_Ports WHERE DeviceID=$this->DeviceID AND PortNumber=$this->PortNumber;"; - if(!$row=$dbh->query($sql)->fetch()){ + $stmt=$dbh->query($sql); + if(!$stmt || !($row=$stmt->fetch())){ return false; }else{ foreach(DevicePorts::RowToObject($row) as $prop => $value){ @@ -107,8 +108,10 @@ function getPorts( $empty = false ){ $sql="SELECT * FROM fac_Ports WHERE DeviceID=$this->DeviceID $clause ORDER BY PortNumber ASC;"; $ports=array(); - foreach($dbh->query($sql) as $row){ - $ports[$row['PortNumber']]=DevicePorts::RowToObject($row); + if($stmt=$dbh->query($sql)){ + foreach($stmt as $row){ + $ports[$row['PortNumber'] ?? null]=DevicePorts::RowToObject($row); + } } return $ports; } @@ -119,9 +122,10 @@ function getActivePortCount() { $sql = "select count(*) as ActivePorts from fac_Ports where DeviceID=$this->DeviceID and (ConnectedDeviceID>0 or Notes > '')"; - $row = $dbh->query($sql)->fetch(); + $stmt = $dbh->query($sql); + $row = $stmt ? $stmt->fetch() : null; - return $row["ActivePorts"]; + return $row["ActivePorts"] ?? 0; } function createPort($update_existing=false) { @@ -142,7 +146,7 @@ function createPort($update_existing=false) { if(!$dbh->query($sql)){ $info=$dbh->errorInfo(); - error_log("createPort::PDO Error: {$info[2]} SQL=$sql"); + error_log("createPort::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql"); return false; } @@ -326,7 +330,7 @@ function updatePort($fasttrack=false) { if(!$dbh->query($sql)){ $info=$dbh->errorInfo(); - error_log("updatePort::PDO Error: {$info[2]} SQL=$sql"); + error_log("updatePort::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql"); return false; } @@ -400,7 +404,7 @@ static function makeConnection($port1,$port2){ if(!$dbh->exec($sql)){ $info=$dbh->errorInfo(); - error_log("updatePort::PDO Error: {$info[2]} SQL=$sql"); + error_log("updatePort::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql"); return false; } @@ -510,7 +514,7 @@ static function getPatchCandidates($DeviceID,$PortNum=null,$listports=null,$patc if(!$dev->GetDevice()){return false;} $mediaenforce=""; - if($config->ParameterArray["MediaEnforce"]=='enabled' && !is_null($PortNum)){ + if(($config->ParameterArray["MediaEnforce"] ?? null)=='enabled' && !is_null($PortNum)){ $dp=new DevicePorts(); $dp->DeviceID=$DeviceID; $dp->PortNumber=$PortNum; @@ -520,7 +524,7 @@ static function getPatchCandidates($DeviceID,$PortNum=null,$listports=null,$patc $mt->GetType(); $mediaenforce=" AND MediaID=$mt->MediaID"; - }elseif($config->ParameterArray["MediaEnforce"]=='enabled' && is_null($PortNum)){ + }elseif(($config->ParameterArray["MediaEnforce"] ?? null)=='enabled' && is_null($PortNum)){ // Media Type Enforcing is enabled and you didn't supply a port to match type on return false; } @@ -583,18 +587,22 @@ static function getPatchCandidates($DeviceID,$PortNum=null,$listports=null,$patc Cabinet!=$cabinetID $rights$pp$limiter GROUP BY DeviceID ORDER BY Label ASC;"; foreach(array($sqlSameCabDevice, $sqlDiffCabDevice) as $sql){ - foreach($dbh->query($sql) as $row){ - // false to skip rights check we filtered using sql above - $tmpDev=Device::RowToObject($row,false); - $candidates[]=array("DeviceID"=>$tmpDev->DeviceID,"Label"=>$tmpDev->Label,"CabinetID"=>$tmpDev->Cabinet); + if($stmt=$dbh->query($sql)){ + foreach($stmt as $row){ + // false to skip rights check we filtered using sql above + $tmpDev=Device::RowToObject($row,false); + $candidates[]=array("DeviceID"=>$tmpDev->DeviceID,"Label"=>$tmpDev->Label,"CabinetID"=>$tmpDev->Cabinet); + } } } }else{ $sql="SELECT a.*, b.Cabinet as CabinetID FROM fac_Ports a, fac_Device b WHERE Ports>0 AND Cabinet>-1 AND a.DeviceID=b.DeviceID AND a.DeviceID!=$dev->DeviceID AND ConnectedDeviceID IS NULL$mediaenforce$pp;"; - foreach($dbh->query($sql) as $row){ - $candidates[]=array("DeviceID"=>$row["DeviceID"], "Label"=>$row["Label"], "CabinetID"=>$row["CabinetID"]); + if($stmt=$dbh->query($sql)){ + foreach($stmt as $row){ + $candidates[]=array("DeviceID"=>$row["DeviceID"] ?? null, "Label"=>$row["Label"] ?? null, "CabinetID"=>$row["CabinetID"] ?? null); + } } } @@ -613,8 +621,10 @@ static function getPortList($DeviceID){ $sql="SELECT * FROM fac_Ports WHERE DeviceID=$dev->DeviceID;"; $portList=array(); - foreach($dbh->query($sql) as $row){ - $portList[$row['PortNumber']]=DevicePorts::RowToObject($row); + if($stmt=$dbh->query($sql)){ + foreach($stmt as $row){ + $portList[$row['PortNumber'] ?? null]=DevicePorts::RowToObject($row); + } } if( sizeof($portList)==0 && $dev->DeviceType!="Physical Infrastructure" ){ @@ -629,7 +639,7 @@ function Search($indexedbyid=false,$loose=false){ global $dbh; $o=array(); // Store any values that have been added before we make them safe - foreach($this as $prop => $val){ + foreach(get_object_vars($this) as $prop => $val){ if(isset($val)){ $o[$prop]=$val; } @@ -647,11 +657,13 @@ function Search($indexedbyid=false,$loose=false){ $portList=array(); - foreach($dbh->query($sql) as $portRow){ - if($indexedbyid){ - $portList[$portRow["DeviceID"].$portRow["PortNumber"]]=DevicePorts::RowToObject($portRow); - }else{ - $portList[]=DevicePorts::RowToObject($portRow); + if($stmt=$dbh->query($sql)){ + foreach($stmt as $portRow){ + if($indexedbyid){ + $portList[($portRow["DeviceID"] ?? '').($portRow["PortNumber"] ?? '')]=DevicePorts::RowToObject($portRow); + }else{ + $portList[]=DevicePorts::RowToObject($portRow); + } } } diff --git a/classes/DeviceStatus.inc.php b/classes/DeviceStatus.inc.php index 95ab77280..b301491f8 100644 --- a/classes/DeviceStatus.inc.php +++ b/classes/DeviceStatus.inc.php @@ -43,14 +43,14 @@ function MakeSafe(){ } } - static function RowToObject($row){ - $ds=new DeviceStatus(); - $ds->StatusID=$row["StatusID"]; - $ds->Status=$row["Status"]; - $ds->ColorCode=$row["ColorCode"]; - - return $ds; - } + static function RowToObject($row){ + $ds=new DeviceStatus(); + $ds->StatusID=$row["StatusID"] ?? null; + $ds->Status=$row["Status"] ?? null; + $ds->ColorCode=$row["ColorCode"] ?? null; + + return $ds; + } function exec($sql){ global $dbh; return $dbh->exec($sql); @@ -81,23 +81,24 @@ function createStatus() { $this->Status=trim($this->Status); // See if this Status already exists. - $sql="SELECT 1 FROM fac_DeviceStatus WHERE Status=\"$this->Status\""; - if(is_array($this->query($sql)->fetch())){ - // Do not allow a duplicate to be added. - return false; - } + $sql="SELECT 1 FROM fac_DeviceStatus WHERE Status=\"$this->Status\""; + $stmt=$this->query($sql); + if($stmt && is_array($stmt->fetch())){ + // Do not allow a duplicate to be added. + return false; + } $sql="INSERT INTO fac_DeviceStatus SET Status=\"$this->Status\", ColorCode=\"$this->ColorCode\""; - if($this->exec($sql)){ - $this->StatusID=$dbh->lastInsertId(); - }else{ - $info=$dbh->errorInfo(); - - error_log("PDO Error::createStatus {$info[2]}"); - return false; - } + if($this->exec($sql)){ + $this->StatusID=$dbh->lastInsertId(); + }else{ + $info=$dbh->errorInfo(); + + error_log("PDO Error::createStatus " . ($info[2] ?? 'Unknown error')); + return false; + } return $this->StatusID; } @@ -107,19 +108,20 @@ function getStatus() { $sql="SELECT * FROM fac_DeviceStatus WHERE StatusID=$this->StatusID;"; - if($row=$this->query($sql)->fetch()){ - foreach(DeviceStatus::RowToObject($row) as $prop=>$value){ - $this->$prop=$value; - } - - return true; - }else{ - // Kick back a blank record if the StatusID was not found - foreach($this as $prop=>$value){ - if($prop!='StatusID'){ - $this->$prop = ''; - } - } + $stmt=$this->query($sql); + if($stmt && ($row=$stmt->fetch())){ + foreach(DeviceStatus::RowToObject($row) as $prop=>$value){ + $this->$prop=$value; + } + + return true; + }else{ + // Kick back a blank record if the StatusID was not found + foreach(get_object_vars($this) as $prop=>$value){ + if($prop!='StatusID'){ + $this->$prop = ''; + } + } return false; } @@ -155,11 +157,11 @@ static function getStatusNames() { $st->execute( array() ); $sList = array(); - while ( $row = $st->fetch() ) { - $sList[] = $row["Status"]; - } - - return $sList; + while ( $row = $st->fetch() ) { + $sList[] = $row["Status"]; + } + + return $sList; } function updateStatus() { diff --git a/classes/DeviceTemplate.class.php b/classes/DeviceTemplate.class.php index 23c56f657..ab4d45b24 100644 --- a/classes/DeviceTemplate.class.php +++ b/classes/DeviceTemplate.class.php @@ -68,35 +68,35 @@ function MakeSafe(){ $this->RearPictureFile=sanitize($this->RearPictureFile); $this->ChassisSlots=intval($this->ChassisSlots); $this->RearChassisSlots=intval($this->RearChassisSlots); - $this->SNMPVersion=(in_array($this->SNMPVersion, $validSNMPVersions))?$this->SNMPVersion:$config->ParameterArray["SNMPVersion"]; + $this->SNMPVersion=(in_array($this->SNMPVersion, $validSNMPVersions))?$this->SNMPVersion:($config->ParameterArray["SNMPVersion"] ?? ''); $this->GlobalID=intval($this->GlobalID); } function MakeDisplay(){ - $this->Model=stripslashes($this->Model); - $this->Notes=stripslashes($this->Notes); - $this->FrontPictureFile=stripslashes($this->FrontPictureFile); - $this->RearPictureFile=stripslashes($this->RearPictureFile); + $this->Model=stripslashes((string)$this->Model); + $this->Notes=stripslashes((string)$this->Notes); + $this->FrontPictureFile=stripslashes((string)$this->FrontPictureFile); + $this->RearPictureFile=stripslashes((string)$this->RearPictureFile); } static function RowToObject($row,$extendmodel=true){ $Template=new DeviceTemplate(); - $Template->TemplateID=$row["TemplateID"]; - $Template->ManufacturerID=$row["ManufacturerID"]; - $Template->Model=$row["Model"]; - $Template->Height=$row["Height"]; - $Template->Weight=$row["Weight"]; - $Template->Wattage=$row["Wattage"]; - $Template->DeviceType=$row["DeviceType"]; - $Template->PSCount=$row["PSCount"]; - $Template->NumPorts=$row["NumPorts"]; - $Template->Notes=$row["Notes"]; - $Template->FrontPictureFile=html_entity_decode($row["FrontPictureFile"],ENT_QUOTES); - $Template->RearPictureFile=html_entity_decode($row["RearPictureFile"],ENT_QUOTES); - $Template->ChassisSlots=$row["ChassisSlots"]; - $Template->RearChassisSlots=$row["RearChassisSlots"]; - $Template->SNMPVersion=$row["SNMPVersion"]; - $Template->GlobalID = $row["GlobalID"]; + $Template->TemplateID=$row["TemplateID"] ?? null; + $Template->ManufacturerID=$row["ManufacturerID"] ?? null; + $Template->Model=$row["Model"] ?? null; + $Template->Height=$row["Height"] ?? null; + $Template->Weight=$row["Weight"] ?? null; + $Template->Wattage=$row["Wattage"] ?? null; + $Template->DeviceType=$row["DeviceType"] ?? null; + $Template->PSCount=$row["PSCount"] ?? null; + $Template->NumPorts=$row["NumPorts"] ?? null; + $Template->Notes=$row["Notes"] ?? null; + $Template->FrontPictureFile=html_entity_decode($row["FrontPictureFile"] ?? '',ENT_QUOTES); + $Template->RearPictureFile=html_entity_decode($row["RearPictureFile"] ?? '',ENT_QUOTES); + $Template->ChassisSlots=$row["ChassisSlots"] ?? null; + $Template->RearChassisSlots=$row["RearChassisSlots"] ?? null; + $Template->SNMPVersion=$row["SNMPVersion"] ?? null; + $Template->GlobalID = $row["GlobalID"] ?? null; $Template->MakeDisplay(); $Template->GetCustomValues(); @@ -259,7 +259,7 @@ function DeleteTemplate(){ function Search($indexedbyid=false,$loose=false){ $o=new stdClass(); // Store any values that have been added before we make them safe - foreach($this as $prop => $val){ + foreach(get_object_vars($this) as $prop => $val){ if(isset($val)){ $o->$prop=$val; } @@ -281,11 +281,13 @@ function Search($indexedbyid=false,$loose=false){ $templateList=array(); - foreach($this->query($sql) as $row){ - if($indexedbyid){ - $templateList[$row["TemplateID"]]=DeviceTemplate::RowToObject($row); - }else{ - $templateList[]=DeviceTemplate::RowToObject($row); + if($stmt=$this->query($sql)){ + foreach($stmt as $row){ + if($indexedbyid){ + $templateList[$row["TemplateID"] ?? null]=DeviceTemplate::RowToObject($row); + }else{ + $templateList[]=DeviceTemplate::RowToObject($row); + } } } @@ -328,7 +330,8 @@ function GetTemplateByID(){ // $value=($prop!='TemplateID')?null:$value; //} - if($row=$this->query($sql)->fetch()){ + $stmt=$this->query($sql); + if($stmt && ($row=$stmt->fetch())){ foreach(DeviceTemplate::RowToObject($row) as $prop => $value){ $this->$prop=$value; } @@ -361,11 +364,13 @@ static function GetTemplateList( $indexed=false ){ a.ManufacturerID=b.ManufacturerID ORDER BY Name ASC, Model ASC;"; $templateList=array(); - foreach($dbh->query($sql) as $row){ - if ( $indexed ) { - $templateList[$row["TemplateID"]]=DeviceTemplate::RowToObject($row); - } else { - $templateList[]=DeviceTemplate::RowToObject($row); + if($stmt=$dbh->query($sql)){ + foreach($stmt as $row){ + if ( $indexed ) { + $templateList[$row["TemplateID"] ?? null]=DeviceTemplate::RowToObject($row); + } else { + $templateList[]=DeviceTemplate::RowToObject($row); + } } } @@ -380,8 +385,10 @@ function GetTemplateListByManufacturer(){ ORDER BY Name ASC, Model ASC;"; $templateList=array(); - foreach($this->query($sql) as $row){ - $templateList[]=DeviceTemplate::RowToObject($row); + if($stmt=$this->query($sql)){ + foreach($stmt as $row){ + $templateList[]=DeviceTemplate::RowToObject($row); + } } return $templateList; @@ -399,7 +406,7 @@ public static function getTemplateListIndexedbyID() { $stmt->execute(); while ($row = $stmt->fetch()) { $devTempl = DeviceTemplate::RowToObject($row); - $templateList[$devTempl->TemplateID] = $devTempl; + $templateList[$devTempl->TemplateID ?? null] = $devTempl; } return $templateList; } @@ -412,8 +419,10 @@ function GetMissingMfgDates(){ a.MfgDate<'1970-01-01'"; $devList=array(); - foreach($this->query($sql) as $row){ - $devList[]=Device::RowToObject($row); + if($stmt=$this->query($sql)){ + foreach($stmt as $row){ + $devList[]=Device::RowToObject($row); + } } $this->MakeDisplay(); @@ -689,10 +698,15 @@ function GetCustomValues() { fac_DeviceTemplateCustomValue v, fac_DeviceCustomAttribute a WHERE a.AttributeID=v.AttributeID AND TemplateID=$this->TemplateID ORDER BY Label, AttributeID;"; - foreach($this->query($sql) as $tdcrow) { - $this->{$tdcrow["Label"]}=$tdcrow["Value"]; - $tdca[$tdcrow["AttributeID"]]["value"]=$tdcrow["Value"]; - $tdca[$tdcrow["AttributeID"]]["required"]=$tdcrow["Required"]; + if($stmt=$this->query($sql)){ + foreach($stmt as $tdcrow) { + $label=$tdcrow["Label"] ?? null; + $value=$tdcrow["Value"] ?? null; + $attributeID=$tdcrow["AttributeID"] ?? null; + $this->{$label}=$value; + $tdca[$attributeID]["value"]=$value; + $tdca[$attributeID]["required"]=$tdcrow["Required"] ?? null; + } } $this->CustomValues = $tdca; } diff --git a/classes/ESX.class.php b/classes/ESX.class.php index 47a36cae2..5e6bab4bb 100644 --- a/classes/ESX.class.php +++ b/classes/ESX.class.php @@ -58,8 +58,10 @@ static function EnumerateVMs($d,$debug=false){ $vm->DeviceID=$dev->DeviceID; $vm->LastUpdated=date( 'Y-m-d H:i:s' ); $vm->vmID=count($vmList); - $vm->vmName=trim(str_replace('"','',@end(explode(":",$name)))); - $vm->vmState=trim(str_replace('"','',@end(explode(":",$state)))); + $nameParts = explode(':', $name); + $stateParts = explode(':', $state); + $vm->vmName = trim(str_replace('"', '', $nameParts[count($nameParts) - 1])); + $vm->vmState = trim(str_replace('"', '', $stateParts[count($stateParts) - 1])); $vmList[]=$vm; } } diff --git a/classes/EscalationTimes.class.php b/classes/EscalationTimes.class.php index aee0a6049..7b07e13c2 100644 --- a/classes/EscalationTimes.class.php +++ b/classes/EscalationTimes.class.php @@ -33,7 +33,7 @@ function MakeSafe(){ } function MakeDisplay(){ - $this->TimePeriod=stripslashes($this->TimePeriod); + $this->TimePeriod=stripslashes((string)$this->TimePeriod); } function query($sql){ @@ -77,24 +77,30 @@ function GetEscalationTime(){ //if($row=$this->query($sql)->fetch()){ if($q=$this->query($sql)){ $row=$q->fetch(); - $this->EscalationTimeID=$row["EscalationTimeID"]; - $this->TimePeriod=$row["TimePeriod"]; - $this->MakeDisplay(); - return true; + if($row){ + $this->EscalationTimeID=$row["EscalationTimeID"] ?? null; + $this->TimePeriod=$row["TimePeriod"] ?? null; + $this->MakeDisplay(); + return true; + } }else{ return false; } + return false; } function GetEscalationTimeList(){ $sql="SELECT * FROM fac_EscalationTimes ORDER BY TimePeriod ASC;"; $escList=array(); - foreach($this->query($sql) as $row){ - $escList[$row["EscalationTimeID"]]=new EscalationTimes(); - $escList[$row["EscalationTimeID"]]->EscalationTimeID = $row["EscalationTimeID"]; - $escList[$row["EscalationTimeID"]]->TimePeriod = $row["TimePeriod"]; - $escList[$row["EscalationTimeID"]]->MakeDisplay(); + if($stmt=$this->query($sql)){ + foreach($stmt as $row){ + $escID=$row["EscalationTimeID"] ?? null; + $escList[$escID]=new EscalationTimes(); + $escList[$escID]->EscalationTimeID = $escID; + $escList[$escID]->TimePeriod = $row["TimePeriod"] ?? null; + $escList[$escID]->MakeDisplay(); + } } return $escList; diff --git a/classes/Escalations.class.php b/classes/Escalations.class.php index 0db8b5969..8f4f8eb55 100644 --- a/classes/Escalations.class.php +++ b/classes/Escalations.class.php @@ -32,7 +32,7 @@ function MakeSafe(){ } function MakeDisplay(){ - $this->Details=stripslashes($this->Details); + $this->Details=stripslashes((string)$this->Details); } function query($sql){ @@ -78,24 +78,30 @@ function GetEscalation(){ // if($row=$this->query($sql)->fetch()){ if($q=$this->query($sql)){ $row=$q->fetch(); - $this->EscalationID=$row["EscalationID"] ?? ''; - $this->Details=$row["Details"] ?? ''; - $this->MakeDisplay(); - return true; + if($row){ + $this->EscalationID=$row["EscalationID"] ?? ''; + $this->Details=$row["Details"] ?? ''; + $this->MakeDisplay(); + return true; + } }else{ return false; } + return false; } function GetEscalationList() { $sql="SELECT * FROM fac_Escalations ORDER BY Details ASC;"; $escList=array(); - foreach($this->query($sql) as $row){ - $escList[$row["EscalationID"]]=new Escalations(); - $escList[$row["EscalationID"]]->EscalationID=$row["EscalationID"]; - $escList[$row["EscalationID"]]->Details=$row["Details"]; - $escList[$row["EscalationID"]]->MakeDisplay(); + if($stmt=$this->query($sql)){ + foreach($stmt as $row){ + $escID=$row["EscalationID"] ?? null; + $escList[$escID]=new Escalations(); + $escList[$escID]->EscalationID=$escID; + $escList[$escID]->Details=$row["Details"] ?? null; + $escList[$escID]->MakeDisplay(); + } } return $escList; diff --git a/classes/LogActions.class.php b/classes/LogActions.class.php index 7e40cc8de..6efa4aa43 100644 --- a/classes/LogActions.class.php +++ b/classes/LogActions.class.php @@ -61,20 +61,20 @@ static function RowToObject($dbRow){ * table and convert it to an object for use in array or other */ $log=new LogActions(); - $log->UserID=$dbRow["UserID"]; - $log->Class=$dbRow["Class"]; - $log->ObjectID=$dbRow["ObjectID"]; - $log->ChildID=$dbRow["ChildID"]; - $log->Property=$dbRow["Property"]; - $log->Action=$dbRow["Action"]; + $log->UserID=$dbRow["UserID"] ?? null; + $log->Class=$dbRow["Class"] ?? null; + $log->ObjectID=$dbRow["ObjectID"] ?? null; + $log->ChildID=$dbRow["ChildID"] ?? null; + $log->Property=$dbRow["Property"] ?? null; + $log->Action=$dbRow["Action"] ?? null; if (strpos($log->Property, "assword") || strpos($log->Property, "ommunity")) { - $log->OldVal=str_repeat("*", strlen($dbRow["OldVal"])); - $log->NewVal=str_repeat("*", strlen($dbRow["NewVal"])); + $log->OldVal=str_repeat("*", strlen((string)($dbRow["OldVal"] ?? ''))); + $log->NewVal=str_repeat("*", strlen((string)($dbRow["NewVal"] ?? ''))); }else{ - $log->OldVal=$dbRow["OldVal"]; - $log->NewVal=$dbRow["NewVal"]; + $log->OldVal=$dbRow["OldVal"] ?? null; + $log->NewVal=$dbRow["NewVal"] ?? null; } - $log->Time=$dbRow["Time"]; + $log->Time=$dbRow["Time"] ?? null; return $log; } @@ -86,7 +86,7 @@ static function LogThis($object,$originalobject=null){ $log=new LogActions(); $log->UserID=$person->UserID; - $trace=debug_backtrace(); + $trace=debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2); // we're only concerned with the 2nd record $trace can be read for a full debug if something calls for it $caller=(isset($trace[1]))?$trace[1]:array('function' => 'direct'); $action=$caller['function']; @@ -110,13 +110,13 @@ function val_comp($v1, $v2) { } // The diff function is acting retarded with some values so scrub em - foreach($object as $key => $value){ + foreach(get_object_vars($object) as $key => $value){ if($value=='NULL' || $value=='0'){ $object->$key=''; } } if(!is_null($originalobject)){ - foreach($originalobject as $key => $value){ + foreach(get_object_vars($originalobject) as $key => $value){ if($value=='NULL' || $value=='0'){ $originalobject->$key=''; } @@ -210,7 +210,7 @@ function val_comp($v1, $v2) { $return=true; // If a retention period has been set, trim the logs for this ObjectID prior to making this entry - if ( $config->ParameterArray["logretention"] > 0 ) { + if ( ($config->ParameterArray["logretention"] ?? 0) > 0 ) { LogActions::Prune( $config->ParameterArray["logretention"], $log->ObjectID ); } @@ -232,7 +232,7 @@ function val_comp($v1, $v2) { }else{ // if we're creating a new object make a note of all the values if($log->Action==1){ - foreach($object as $prop => $value){ + foreach(get_object_vars($object) as $prop => $value){ $log->Property=$prop; $log->NewVal=$value; // Log only new object properties that have values @@ -282,7 +282,7 @@ function WriteToDB(){ if(!$stmt->execute()){ $info=$stmt->errorInfo(); - error_log("PDO Error::LogActions:WriteToDB {$info[1]}::{$info[2]}"); + error_log("PDO Error::LogActions:WriteToDB " . ($info[1] ?? 'Unknown') . "::" . ($info[2] ?? 'Unknown error')); return false; } return true; @@ -296,9 +296,11 @@ static function GetLastDeviceAction($DeviceID) { // Return a blank entry if nothing is found $result = new LogActions(); - foreach ( $log->query($sql) as $dbRow ) { - // There can be only one - $result = LogActions::RowToObject($dbRow); + if($stmt=$log->query($sql)){ + foreach ( $stmt as $dbRow ) { + // There can be only one + $result = LogActions::RowToObject($dbRow); + } } return $result; @@ -314,7 +316,7 @@ static function GetLog($object=null,$limitbyclass=true){ $log->Class=get_class($object); // Attempt to autofind the id of the object we've been handed - foreach($object as $prop => $value){ + foreach(get_object_vars($object) as $prop => $value){ if(preg_match("/id/i", $prop)){ $log->ObjectID=$value; break; @@ -336,16 +338,18 @@ function sql($sql,$prop,$var){ $sql.=$add.' ORDER BY Time ASC;'; $events=array(); - foreach($log->query($sql) as $dbRow){ - if ( $config->ParameterArray["GDPRPIIPrivacy"] == "enabled" && !$person->SiteAdmin ) { - $p = new People(); - $p->UserID=$dbRow["UserID"]; - $p->GetPersonByUserID(); - if ( $p->countryCode != $person->countryCode ) { - $dbRow["UserID"] = "PIIProtected"; + if($stmt=$log->query($sql)){ + foreach($stmt as $dbRow){ + if ( ($config->ParameterArray["GDPRPIIPrivacy"] ?? '') == "enabled" && !$person->SiteAdmin ) { + $p = new People(); + $p->UserID=$dbRow["UserID"] ?? null; + $p->GetPersonByUserID(); + if ( $p->countryCode != $person->countryCode ) { + $dbRow["UserID"] = "PIIProtected"; + } } + $events[]=LogActions::RowToObject($dbRow); } - $events[]=LogActions::RowToObject($dbRow); } return $events; @@ -400,7 +404,7 @@ function ListUnique($sqlcolumn){ function findit($prop,$val,&$sql){ $sql.=" AND $prop LIKE \"%$val%\""; } - foreach($this as $prop => $val){ + foreach(get_object_vars($this) as $prop => $val){ if($val && $val!=date("Y-m-d", strtotime(0))){ findit($prop,$val,$sqlextend); } @@ -408,8 +412,10 @@ function findit($prop,$val,&$sql){ $sql="SELECT DISTINCT CAST($sqlcolumn AS CHAR(80)) AS Search FROM fac_GenericLog WHERE $sqlcolumn!=\"\"$sqlextend ORDER BY $sqlcolumn ASC;"; $values=array(); - foreach($this->query($sql) as $row){ - $values[]=$row['Search']; + if($stmt=$this->query($sql)){ + foreach($stmt as $row){ + $values[]=$row['Search'] ?? null; + } } return array_unique($values); @@ -430,7 +436,7 @@ function Search($num_rec_per_page=0,$page=1){ // This will store all our extended sql $sqlextend=""; - foreach($this as $prop => $val){ + foreach(get_object_vars($this) as $prop => $val){ if($val && $val!=date("Y-m-d", strtotime(0))){ // Setting wild card searching to false because we use exact matches // in the report_logging and I don't think we use this function @@ -453,8 +459,10 @@ function Search($num_rec_per_page=0,$page=1){ $sql="SELECT * FROM fac_GenericLog $sqlextend;"; $events=array(); - foreach($this->query($sql) as $dbRow){ - $events[]=LogActions::RowToObject($dbRow); + if($stmt=$this->query($sql)){ + foreach($stmt as $dbRow){ + $events[]=LogActions::RowToObject($dbRow); + } } return $events; diff --git a/classes/Manufacturer.class.php b/classes/Manufacturer.class.php index 9ca1a9784..549272cbf 100644 --- a/classes/Manufacturer.class.php +++ b/classes/Manufacturer.class.php @@ -42,15 +42,15 @@ function MakeSafe(){ } function MakeDisplay(){ - $this->Name=stripslashes($this->Name); + $this->Name=stripslashes((string)$this->Name); } static function RowToObject($row){ $m=new Manufacturer(); - $m->ManufacturerID=$row["ManufacturerID"]; - $m->Name=$row["Name"]; - $m->GlobalID = $row["GlobalID"]; - $m->SubscribeToUpdates = $row["SubscribeToUpdates"]; + $m->ManufacturerID=$row["ManufacturerID"] ?? null; + $m->Name=$row["Name"] ?? null; + $m->GlobalID = $row["GlobalID"] ?? null; + $m->SubscribeToUpdates = $row["SubscribeToUpdates"] ?? null; $m->MakeDisplay(); return $m; @@ -97,7 +97,8 @@ function GetManufacturerByID(){ $sql="SELECT * FROM fac_Manufacturer WHERE ManufacturerID=$this->ManufacturerID;"; - if($row=$this->query($sql)->fetch()){ + $stmt=$this->query($sql); + if($stmt && ($row=$stmt->fetch())){ foreach(Manufacturer::RowToObject($row) as $prop => $value){ $this->$prop=$value; } @@ -112,7 +113,8 @@ function GetManufacturerByName(){ $sql="SELECT * FROM fac_Manufacturer WHERE ucase(Name)=ucase('".$this->Name."');"; - if($row=$this->query($sql)->fetch()){ + $stmt=$this->query($sql); + if($stmt && ($row=$stmt->fetch())){ foreach(Manufacturer::RowToObject($row) as $prop => $value){ $this->$prop=$value; } @@ -128,11 +130,13 @@ static function GetManufacturerList($indexbyid=false){ $sql="SELECT * FROM fac_Manufacturer ORDER BY Name ASC;"; $ManufacturerList=array(); - foreach($dbh->query($sql) as $row){ - if($indexbyid){ - $ManufacturerList[$row['ManufacturerID']]=Manufacturer::RowToObject($row); - }else{ - $ManufacturerList[]=Manufacturer::RowToObject($row); + if($stmt=$dbh->query($sql)){ + foreach($stmt as $row){ + if($indexbyid){ + $ManufacturerList[$row['ManufacturerID'] ?? null]=Manufacturer::RowToObject($row); + }else{ + $ManufacturerList[]=Manufacturer::RowToObject($row); + } } } diff --git a/classes/MediaTypes.class.php b/classes/MediaTypes.class.php index 9d9610ea2..4e08ec53d 100644 --- a/classes/MediaTypes.class.php +++ b/classes/MediaTypes.class.php @@ -39,7 +39,7 @@ function CreateType() { }else{ $info=$dbh->errorInfo(); - error_log("PDO Error: {$info[2]}"); + error_log("PDO Error: " . ($info[2] ?? 'Unknown error')); return false; } @@ -54,7 +54,7 @@ function UpdateType() { if(!$dbh->query($sql)){ $info=$dbh->errorInfo(); - error_log("PDO Error: {$info[2]}"); + error_log("PDO Error: " . ($info[2] ?? 'Unknown error')); return false; }else{ return true; @@ -76,11 +76,12 @@ function GetType() { $sql="SELECT * FROM fac_MediaTypes WHERE MediaID=".intval($this->MediaID); - if(!$row=$dbh->query($sql)->fetch()){ + $stmt=$dbh->query($sql); + if(!$stmt || !($row=$stmt->fetch())){ return false; }else{ - $this->MediaType = $row["MediaType"]; - $this->ColorID = $row["ColorID"]; + $this->MediaType = $row["MediaType"] ?? null; + $this->ColorID = $row["ColorID"] ?? null; return true; } @@ -91,11 +92,12 @@ function GetTypeByName() { $sql="SELECT * FROM fac_MediaTypes WHERE UCASE(MediaType)=UCASE('".sanitize($this->MediaType)."')"; - if(!$row=$dbh->query($sql)->fetch()){ + $stmt=$dbh->query($sql); + if(!$stmt || !($row=$stmt->fetch())){ return false; }else{ - $this->MediaID = $row["MediaID"]; - $this->ColorID = $row["ColorID"]; + $this->MediaID = $row["MediaID"] ?? null; + $this->ColorID = $row["ColorID"] ?? null; return true; } @@ -108,12 +110,14 @@ static function GetMediaTypeList($indexedby="MediaID") { $mediaList = array(); - foreach ( $dbh->query( $sql ) as $row ) { - $n=$row[$indexedby]; - $mediaList[$n] = new MediaTypes(); - $mediaList[$n]->MediaID = $row["MediaID"]; - $mediaList[$n]->MediaType = $row["MediaType"]; - $mediaList[$n]->ColorID = $row["ColorID"]; + if($stmt=$dbh->query($sql)){ + foreach ( $stmt as $row ) { + $n=$row[$indexedby] ?? null; + $mediaList[$n] = new MediaTypes(); + $mediaList[$n]->MediaID = $row["MediaID"] ?? null; + $mediaList[$n]->MediaType = $row["MediaType"] ?? null; + $mediaList[$n]->ColorID = $row["ColorID"] ?? null; + } } return $mediaList; @@ -134,7 +138,7 @@ static function ResetType($mediaid,$tomediaid=0){ if(!$dbh->query($sql)){ $info=$dbh->errorInfo(); - error_log("PDO Error: {$info[2]}"); + error_log("PDO Error: " . ($info[2] ?? 'Unknown error')); return false; }else{ return true; diff --git a/classes/PDUStats.class.php b/classes/PDUStats.class.php index 156dfe6ad..382965714 100644 --- a/classes/PDUStats.class.php +++ b/classes/PDUStats.class.php @@ -38,9 +38,9 @@ function MakeSafe(){ static function RowToObject($row){ $m=new PDUStats(); - $m->PDUID=$row["PDUID"]; - $m->Wattage=$row["Wattage"]; - $m->LastRead=$row["LastRead"]; + $m->PDUID=$row["PDUID"] ?? null; + $m->Wattage=$row["Wattage"] ?? null; + $m->LastRead=$row["LastRead"] ?? null; return $m; } @@ -57,11 +57,12 @@ function GetPDUStatsByID(){ $sql="SELECT * FROM fac_PDUStats WHERE PDUID=$this->PDUID"; - if ( !$person->SiteAdmin && $config->ParameterArray["GDPRCountryIsolation"] == "enabled" ) { + if ( !$person->SiteAdmin && ($config->ParameterArray["GDPRCountryIsolation"] ?? '') == "enabled" ) { $sql = "SELECT a.* FROM fac_PDUStats a, fac_Device b, fac_Cabinet c, fac_DataCenter d WHERE PDUID=$this->PDUID and a.PDUID=b.DeviceID and b.Cabinet=c.CabinetID and c.DataCenterID=d.DataCenterID and d.countryCode='".$person->countryCode."'"; } - if($row=$this->query($sql)->fetch()){ + $stmt=$this->query($sql); + if($stmt && ($row=$stmt->fetch())){ foreach(PDUStats::RowToObject($row) as $prop => $value){ $this->$prop=$value; } @@ -76,14 +77,17 @@ function UpdatePDUStats() { $this->MakeSafe(); + $lastRead=strtotime((string)$this->LastRead); + $lastRead=($lastRead !== false) ? date("Y-m-d H:i:s", $lastRead) : null; + $lastReadSql=($lastRead !== null) ? "\"$lastRead\"" : "NULL"; $sql="INSERT INTO fac_PDUStats (PDUID,Wattage,LastRead) VALUES - ($this->PDUID,$this->Wattage,\"".date("Y-m-d H:i:s", strtotime($this->LastRead))."\") ON DUPLICATE KEY - UPDATE Wattage=$this->Wattage,LastRead=\"".date("Y-m-d H:i:s", strtotime($this->LastRead))."\";"; + ($this->PDUID,$this->Wattage,$lastReadSql) ON DUPLICATE KEY + UPDATE Wattage=$this->Wattage,LastRead=$lastReadSql;"; if(!$dbh->query($sql)){ $info=$dbh->errorInfo(); - error_log("UpdatePDUStats::PDO Error: {$info[2]} SQL=$sql" ); + error_log("UpdatePDUStats::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql" ); return false; } return true; @@ -99,7 +103,7 @@ function DeletePDUStats() { if(!$dbh->query($sql)){ $info=$dbh->errorInfo(); - error_log("DeletePDUStats::PDO Error: {$info[2]} SQL=$sql" ); + error_log("DeletePDUStats::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql" ); return false; } return true; @@ -112,24 +116,26 @@ function Search( $indexedbyid=false,$loose=false ) { $this->MakeSafe(); $sqlextend=""; - foreach($this as $prop => $val){ + foreach(get_object_vars($this) as $prop => $val){ if($val){ extendsql($prop,$val,$sqlextend,$loose); } } - if ( $config->ParameterArray["GDPRCountryIsolation"] == "enabled" && !$person->SiteAdmin ) { + if ( ($config->ParameterArray["GDPRCountryIsolation"] ?? '') == "enabled" && !$person->SiteAdmin ) { $sql = "SELECT * FROM fac_PDUStats where PDUID in (select a.PDUID from fac_PDUStats a, fac_Device b, fac_Cabinet c, fac_DataCenter d WHERE a.PDUID=b.DeviceID and b.Cabinet=c.CabinetID and c.DataCenterID=d.DataCenterID and d.countryCode='".$person->countryCode."') $sqlextend"; } else { $sql="SELECT * FROM fac_PDUStats $sqlextend;"; } $pdustatsList=array(); - foreach($this->query($sql) as $pdustatsRow){ - if($indexedbyid){ - $pdustatsList[$pdustatsRow["PDUID"]]=PDUStats::RowToObject($pdustatsRow); - }else{ - $pdustatsList[]=PDUStats::RowToObject($pdustatsRow); + if($stmt=$this->query($sql)){ + foreach($stmt as $pdustatsRow){ + if($indexedbyid){ + $pdustatsList[$pdustatsRow["PDUID"] ?? null]=PDUStats::RowToObject($pdustatsRow); + }else{ + $pdustatsList[]=PDUStats::RowToObject($pdustatsRow); + } } } diff --git a/classes/PMox.class.php b/classes/PMox.class.php index f746570fa..ed2a313cb 100644 --- a/classes/PMox.class.php +++ b/classes/PMox.class.php @@ -56,15 +56,15 @@ static function EnumerateVMs($d,$debug=false){ exit; } - if ( sizeof( $pveList ) > 0 ) { + if ( isset($pveList["data"]) && is_array($pveList["data"]) && sizeof( $pveList["data"] ) > 0 ) { foreach( $pveList["data"] as $pve ) { $tmpVM = new VM; $tmpVM->DeviceID = $d->DeviceID; $tmpVM->LastUpdated = date( "Y-m-d H:i:s" ); - $tmpVM->vmID = $pve["vmid"]; - $tmpVM->vmName = $pve["name"]; - $tmpVM->vmState = $pve["status"]; + $tmpVM->vmID = $pve["vmid"] ?? null; + $tmpVM->vmName = $pve["name"] ?? null; + $tmpVM->vmState = $pve["status"] ?? null; if ( $debug ) { error_log( "VM: " . $tmpVM->vmName . " added to device " . $d->DeviceID ); @@ -135,7 +135,7 @@ static function RefreshInventory( $pveDevice, $debug = false ) { } } - $expire = "delete from fac_VMInventory where to_days(now())-to_days(LastUpdated)>" . intval( $config->ParameterArray['VMExpirationTime']); + $expire = "delete from fac_VMInventory where to_days(now())-to_days(LastUpdated)>" . intval( $config->ParameterArray['VMExpirationTime'] ?? 0); $dbh->query( $expire ); return $vmList; diff --git a/classes/PUEView.class.php b/classes/PUEView.class.php index 5775074ee..fb88a0c55 100644 --- a/classes/PUEView.class.php +++ b/classes/PUEView.class.php @@ -50,7 +50,7 @@ function makeSafe() { // Instead of letting them pick ANY number of days, limit selection to 30, 90, 180, or 365 $validTimes = array( "30", "90", "180", "365" ); - $this->ViewID = int($this->ViewID); + $this->ViewID = intval($this->ViewID); $this->Description = sanitize($this->Description); $this->Category = (in_array( $this->Category, $validCategories ))?$this->Category:"1"; $this->TimePeriod = (in_array( $this->TimePeriod, $validTimes ))?$this->TimePeriod:"180"; @@ -59,7 +59,7 @@ function makeSafe() { public function getView( $ViewID = false ) { global $dbh; - if ( $viewID == false ) { + if ( $ViewID == false ) { $sql = "select * from fac_PUEView order by Description ASC"; $args = array(); } else { @@ -68,7 +68,7 @@ public function getView( $ViewID = false ) { } $st = $dbh->prepare( $sql ); $st->setFetchMode( PDO::FETCH_CLASS, "PUEView" ); - $st->exececute( $args ); + $st->execute( $args ); $vList = array(); while ( $row = $st->fetch() ) { @@ -112,4 +112,4 @@ function deleteView() { return; } } -?> \ No newline at end of file +?> diff --git a/classes/PanelSchedule.class.php b/classes/PanelSchedule.class.php index f8d71d0c9..77db1abab 100644 --- a/classes/PanelSchedule.class.php +++ b/classes/PanelSchedule.class.php @@ -41,7 +41,7 @@ function MakeSafe(){ } function MakeDisplay(){ - $this->Label=stripslashes($this->Label); + $this->Label=stripslashes((string)$this->Label); } function MakeConnection(){ @@ -71,19 +71,24 @@ function DisplayPanel(){ $sql="SELECT * FROM fac_PanelSchedule WHERE PanelID=$this->PanelID ORDER BY PolePosition ASC;"; - foreach($dbh->query($sql) as $row){ - $sched[$row["PolePosition"]]="{$row["Label"]}"; + if($stmt=$dbh->query($sql)){ + foreach($stmt as $row){ + $polePosition=$row["PolePosition"] ?? null; + $numPoles=$row["NumPoles"] ?? 0; + $label=$row["Label"] ?? ''; + $sched[$polePosition]="{$label}"; - if($row["NumPoles"] >1){ - $sched[$row["PolePosition"] + 2] = ""; - } + if($numPoles >1){ + $sched[$polePosition + 2] = ""; + } - if($row["NumPoles"] >2){ - $sched[$row["PolePosition"] + 4] = ""; - } + if($numPoles >2){ + $sched[$polePosition + 4] = ""; + } - for($i=1; $i< $pan->NumberOfPoles + 1; $i++){ - $html .= "$i{$sched[$i]}".($i+1)."{$sched[++$i]}\n"; + for($i=1; $i< $pan->NumberOfPoles + 1; $i++){ + $html .= "$i{$sched[$i]}".($i+1)."{$sched[++$i]}\n"; + } } } @@ -92,4 +97,4 @@ function DisplayPanel(){ return $html; } } -?> \ No newline at end of file +?> diff --git a/classes/People.class.php b/classes/People.class.php index e78930594..e2db19e37 100644 --- a/classes/People.class.php +++ b/classes/People.class.php @@ -80,12 +80,12 @@ function MakeDisplay(){ $this->PersonID=intval($this->PersonID); $this->UserID=sanitize($this->UserID); - $this->LastName=stripslashes($this->LastName); - $this->FirstName=stripslashes($this->FirstName); - $this->Phone1=stripslashes($this->Phone1); - $this->Phone2=stripslashes($this->Phone2); - $this->countryCode=stripslashes($this->countryCode); - $this->Email=stripslashes($this->Email); + $this->LastName=stripslashes((string)$this->LastName); + $this->FirstName=stripslashes((string)$this->FirstName); + $this->Phone1=stripslashes((string)$this->Phone1); + $this->Phone2=stripslashes((string)$this->Phone2); + $this->countryCode=stripslashes((string)$this->countryCode); + $this->Email=stripslashes((string)$this->Email); $this->AdminOwnDevices=intval($this->AdminOwnDevices); $this->ReadAccess=intval($this->ReadAccess); $this->WriteAccess=intval($this->WriteAccess); @@ -100,27 +100,27 @@ function MakeDisplay(){ static function RowToObject($row){ $person=new People(); - $person->PersonID=$row["PersonID"]; - $person->UserID=$row["UserID"]; - $person->LastName=$row["LastName"]; - $person->FirstName=$row["FirstName"]; - $person->Phone1=$row["Phone1"]; - $person->Phone2=$row["Phone2"]; - $person->countryCode=@$row["countryCode"]; - $person->Email=$row["Email"]; - $person->AdminOwnDevices=$row["AdminOwnDevices"]; - $person->ReadAccess=$row["ReadAccess"]; - $person->WriteAccess=$row["WriteAccess"]; - $person->DeleteAccess=$row["DeleteAccess"]; - $person->ContactAdmin=$row["ContactAdmin"]; - $person->RackRequest=$row["RackRequest"]; - $person->RackAdmin=$row["RackAdmin"]; - $person->BulkOperations=$row["BulkOperations"]; - $person->SiteAdmin=$row["SiteAdmin"]; - $person->APIKey=$row["APIKey"]; - $person->Disabled=$row["Disabled"]; - $person->LastActivity=$row["LastActivity"]; - $person->ExpirationDate=$row["ExpirationDate"]; + $person->PersonID=$row["PersonID"] ?? null; + $person->UserID=$row["UserID"] ?? null; + $person->LastName=$row["LastName"] ?? null; + $person->FirstName=$row["FirstName"] ?? null; + $person->Phone1=$row["Phone1"] ?? null; + $person->Phone2=$row["Phone2"] ?? null; + $person->countryCode=$row["countryCode"] ?? null; + $person->Email=$row["Email"] ?? null; + $person->AdminOwnDevices=$row["AdminOwnDevices"] ?? null; + $person->ReadAccess=$row["ReadAccess"] ?? null; + $person->WriteAccess=$row["WriteAccess"] ?? null; + $person->DeleteAccess=$row["DeleteAccess"] ?? null; + $person->ContactAdmin=$row["ContactAdmin"] ?? null; + $person->RackRequest=$row["RackRequest"] ?? null; + $person->RackAdmin=$row["RackAdmin"] ?? null; + $person->BulkOperations=$row["BulkOperations"] ?? null; + $person->SiteAdmin=$row["SiteAdmin"] ?? null; + $person->APIKey=$row["APIKey"] ?? null; + $person->Disabled=$row["Disabled"] ?? null; + $person->LastActivity=$row["LastActivity"] ?? null; + $person->ExpirationDate=$row["ExpirationDate"] ?? null; $person->MakeDisplay(); @@ -199,8 +199,8 @@ function CreatePerson() { $this->MakeSafe(); - if ( $config->ParameterArray["GDPRCountryIsolation"] && $this->countryCode == "" ) { - $this->countryCode = $config->ParameterArray["DefaultCountry"]; + if ( ($config->ParameterArray["GDPRCountryIsolation"] ?? false) && $this->countryCode == "" ) { + $this->countryCode = $config->ParameterArray["DefaultCountry"] ?? ''; } $sql="INSERT INTO fac_People SET UserID=\"$this->UserID\", LastName=\"$this->LastName\", @@ -214,7 +214,7 @@ function CreatePerson() { if(!$this->query($sql)){ $info=$dbh->errorInfo(); - error_log("CreatePerson::PDO Error: {$info[2]} SQL=$sql"); + error_log("CreatePerson::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql"); return false; }else{ $this->PersonID = $dbh->lastInsertId(); @@ -309,7 +309,8 @@ function GetPerson() { $sql = "select * from fac_People where PersonID=\"". $this->PersonID . "\""; - if ( $row = $this->query( $sql )->fetch() ) { + $stmt = $this->query( $sql ); + if ( $stmt && ( $row = $stmt->fetch() ) ) { foreach( People::RowToObject( $row ) as $prop=>$value ) { $this->$prop=$value; } @@ -317,7 +318,7 @@ function GetPerson() { return true; } else { // Kick back a blank record if the PersonID was not found - foreach ( $this as $prop => $value ) { + foreach ( get_object_vars($this) as $prop => $value ) { if ( $prop!='PersonID' ) { $this->$prop = ''; } @@ -331,8 +332,10 @@ function GetPeopleByDepartment( $DeptID ) { $sql = "select * from fac_People where PersonID in (select ContactID from fac_DeptContacts where DeptID=$DeptID) order by LastName ASC, FirstName ASC"; $personList=array(); - foreach($this->query($sql) as $row){ - $personList[]=People::RowToObject($row); + if($stmt=$this->query($sql)){ + foreach($stmt as $row){ + $personList[]=People::RowToObject($row); + } } return $personList; @@ -343,7 +346,8 @@ function GetPersonByUserID() { $sql = "select * from fac_People where ucase(UserID)=ucase(\"" . $this->UserID . "\")"; - if ( $row = $this->query( $sql )->fetch() ) { + $stmt = $this->query( $sql ); + if ( $stmt && ( $row = $stmt->fetch() ) ) { foreach( People::RowToObject( $row ) as $prop=>$value ) { $this->$prop=$value; } @@ -351,7 +355,7 @@ function GetPersonByUserID() { return true; } else { // Kick back a blank record if the UserID was not found - foreach ( $this as $prop => $value ) { + foreach ( get_object_vars($this) as $prop => $value ) { if ( $prop!='UserID' ) { $this->$prop = ''; } @@ -365,11 +369,13 @@ function GetUserList($indexed=false){ $sql="SELECT * FROM fac_People ORDER BY LastName ASC, FirstName ASC"; $userList=array(); - foreach($this->query($sql) as $row){ - if($indexed){ - $userList[$row['PersonID']]=People::RowToObject($row); - }else{ - $userList[]=People::RowToObject($row); + if($stmt=$this->query($sql)){ + foreach($stmt as $row){ + if($indexed){ + $userList[$row['PersonID'] ?? null]=People::RowToObject($row); + }else{ + $userList[]=People::RowToObject($row); + } } } @@ -380,7 +386,7 @@ function GetUserRights( $templateNewUsers = false ) { $this->MakeSafe(); /* Set all rights to false just in case the object being called is reused */ - foreach($this as $prop => $value){ + foreach(get_object_vars($this) as $prop => $value){ if($prop!='LastName' && $prop!='UserID'){ $this->$prop=false; } @@ -391,7 +397,8 @@ function GetUserRights( $templateNewUsers = false ) { $sql="SELECT * FROM fac_People WHERE UserID=\"$this->UserID\";"; - if($row=$this->query($sql)->fetch()){ + $stmt=$this->query($sql); + if($stmt && ($row=$stmt->fetch())){ foreach(People::RowToObject($row) as $prop => $value){ $this->$prop=$value; } @@ -411,7 +418,7 @@ function GetUserRights( $templateNewUsers = false ) { /* Just in case someone disabled a user, but didn't remove all of their individual rights */ if($this->Disabled){ - foreach($this as $prop => $value){ + foreach(get_object_vars($this) as $prop => $value){ if($prop!='Name' && $prop!='UserID'){ $this->$prop=false; } @@ -440,8 +447,10 @@ function isMemberOf(){ function UpdatePerson() { $this->MakeSafe(); - if ( $this->ExpirationDate != "" ) { - $formattedDate = date("Y-m-d", strtotime($this->ExpirationDate)); + $expirationDate = (string)$this->ExpirationDate; + if ( $expirationDate !== "" ) { + $expirationTime = strtotime($expirationDate); + $formattedDate = ($expirationTime !== false) ? date("Y-m-d", $expirationTime) : null; } else { $formattedDate = null; } @@ -468,7 +477,7 @@ function UpdatePerson() { function Search($indexedbyid=false,$loose=false){ $o=array(); // Store any values that have been added before we make them safe - foreach($this as $prop => $val){ + foreach(get_object_vars($this) as $prop => $val){ if(isset($val)){ $o[$prop]=$val; } @@ -484,11 +493,13 @@ function Search($indexedbyid=false,$loose=false){ } $sql="SELECT * FROM fac_People $sqlextend ORDER BY LastName ASC, FirstName ASC;"; $peopleList=array(); - foreach($this->query($sql) as $peopleRow){ - if($indexedbyid){ - $peopleList[$peopleRow["PersonID"]]=People::RowToObject($peopleRow); - }else{ - $peopleList[]=People::RowToObject($peopleRow); + if($stmt=$this->query($sql)){ + foreach($stmt as $peopleRow){ + if($indexedbyid){ + $peopleList[$peopleRow["PersonID"] ?? null]=People::RowToObject($peopleRow); + }else{ + $peopleList[]=People::RowToObject($peopleRow); + } } } diff --git a/classes/PlannedPath.class.php b/classes/PlannedPath.class.php index 5345c3041..b7e363a2c 100644 --- a/classes/PlannedPath.class.php +++ b/classes/PlannedPath.class.php @@ -140,9 +140,10 @@ private function SelectNode () { $this->DeviceID=0; $this->escribe_log("CANDIDATES:"); foreach($this->candidates as $dev => $port) { - $this->escribe_log(" [D=".$dev.", P=".$port.", W=".$this->nodes[$dev][$port]["weight"]."]"); - if($this->nodes[$dev][$port]["weight"]<$minweight){ - $minweight=$this->nodes[$dev][$port]["weight"]; + $weight=$this->nodes[$dev][$port]["weight"] ?? null; + $this->escribe_log(" [D=".$dev.", P=".$port.", W=".$weight."]"); + if($weight !== null && $weight<$minweight){ + $minweight=$weight; $this->DeviceID=$dev; $this->PortNumber=$port; } @@ -159,17 +160,17 @@ private function UpdateList () { //Destination device is $this->devID2 //weights - $weight_cabinet=$config->ParameterArray["path_weight_cabinet"]; //weight for patches on actual cabinet - $weight_rear=$config->ParameterArray["path_weight_rear"]; //weight fot rear connetcion between panels - $weight_row=$config->ParameterArray["path_weight_row"]; //weigth for patches on same row of cabinets (except actual cabinet) + $weight_cabinet=$config->ParameterArray["path_weight_cabinet"] ?? 0; //weight for patches on actual cabinet + $weight_rear=$config->ParameterArray["path_weight_rear"] ?? 0; //weight fot rear connetcion between panels + $weight_row=$config->ParameterArray["path_weight_row"] ?? 0; //weigth for patches on same row of cabinets (except actual cabinet) //It is possible to assign a weight proportional to the distance between the actual cabinet and each cabinet of actual row, //so you can prioritize closest cabinets in the actual row. In the future... $this->escribe_log("\nSelected node: D=".$this->DeviceID. "; P=".$this->PortNumber. - "; W=".$this->nodes[$this->DeviceID][$this->PortNumber]["weight"]. - "; PD=".$this->nodes[$this->DeviceID][$this->PortNumber]["prev_dev"]. - "; PP=".$this->nodes[$this->DeviceID][$this->PortNumber]["prev_port"]);; + "; W=".($this->nodes[$this->DeviceID][$this->PortNumber]["weight"] ?? null). + "; PD=".($this->nodes[$this->DeviceID][$this->PortNumber]["prev_dev"] ?? null). + "; PP=".($this->nodes[$this->DeviceID][$this->PortNumber]["prev_port"] ?? null));; //Compruebo si el puerto del dispositivo actual esta conectado a la conexion trasera de un panel //I check if the port of this device is connected to a rear-panel connection @@ -226,7 +227,7 @@ private function UpdateList () { global $config; $mediaenforce=""; - if($config->ParameterArray["MediaEnforce"]=='enabled'){ + if(($config->ParameterArray["MediaEnforce"] ?? null)=='enabled'){ $mediaenforce=" AND af.MediaID=".$port->MediaID; } $sql="SELECT af.DeviceID AS DeviceID1, @@ -245,15 +246,20 @@ private function UpdateList () { bf.ConnectedDeviceID IS NULL ORDER BY DeviceID1,PortNumber1,DeviceID2,PortNumber2;"; foreach($dbh->query($sql) as $row){ + $deviceID2=$row["DeviceID2"] ?? null; + $deviceID1=$row["DeviceID1"] ?? null; + $portNumber1=$row["PortNumber1"] ?? null; + $portNumber2=$row["PortNumber2"] ?? null; + $nodeWeight=$this->nodes[$this->DeviceID][$this->PortNumber]["weight"] ?? 0; //Compruebo si tengo que anadir esta pareja //I check if I have to add this pair of nodes - if (isset($this->candidates[$row["DeviceID2"]]) - && $this->nodes[$row["DeviceID2"]][$this->candidates[$row["DeviceID2"]]]["weight"]>$this->nodes[$this->DeviceID][$this->PortNumber]["weight"]+$weight_cabinet+$weight_rear - || !isset($this->candidates[$row["DeviceID2"]]) && !isset($this->used_candidates[$row["DeviceID2"]])){ - $this->AddNodeToList($row["DeviceID1"],-$row["PortNumber1"],$this->nodes[$this->DeviceID][$this->PortNumber]["weight"]+$weight_cabinet, $this->DeviceID, $this->PortNumber); + if (isset($this->candidates[$deviceID2]) + && ($this->nodes[$deviceID2][$this->candidates[$deviceID2]]["weight"] ?? 0)>$nodeWeight+$weight_cabinet+$weight_rear + || !isset($this->candidates[$deviceID2]) && !isset($this->used_candidates[$deviceID2])){ + $this->AddNodeToList($deviceID1,-$portNumber1,$nodeWeight+$weight_cabinet, $this->DeviceID, $this->PortNumber); //Anado directamente el espejo de este puerto //I add directly the mirror port of this port - $this->AddNodeToList($row["DeviceID2"],$row["PortNumber2"],$this->nodes[$this->DeviceID][$this->PortNumber]["weight"]+$weight_cabinet+$weight_rear, $row["DeviceID1"],-$row["PortNumber1"]); + $this->AddNodeToList($deviceID2,$portNumber2,$nodeWeight+$weight_cabinet+$weight_rear, $deviceID1,-$portNumber1); } } @@ -278,15 +284,20 @@ private function UpdateList () { bf.ConnectedDeviceID IS NULL ORDER BY DeviceID1,PortNumber1,DeviceID2,PortNumber2;"; foreach($dbh->query($sql) as $row){ + $deviceID2=$row["DeviceID2"] ?? null; + $deviceID1=$row["DeviceID1"] ?? null; + $portNumber1=$row["PortNumber1"] ?? null; + $portNumber2=$row["PortNumber2"] ?? null; + $nodeWeight=$this->nodes[$this->DeviceID][$this->PortNumber]["weight"] ?? 0; //Compruebo si tengo que anadir esta pareja //I check if I have to add this pair of nodes - if (isset($this->candidates[$row["DeviceID2"]]) - && $this->nodes[$row["DeviceID2"]][$this->candidates[$row["DeviceID2"]]]["weight"]>$this->nodes[$this->DeviceID][$this->PortNumber]["weight"]+$weight_row+$weight_rear - || !isset($this->candidates[$row["DeviceID2"]]) && !isset($this->used_candidates[$row["DeviceID2"]])){ - $this->AddNodeToList($row["DeviceID1"],-$row["PortNumber1"],$this->nodes[$this->DeviceID][$this->PortNumber]["weight"]+$weight_row,$this->DeviceID, $this->PortNumber); + if (isset($this->candidates[$deviceID2]) + && ($this->nodes[$deviceID2][$this->candidates[$deviceID2]]["weight"] ?? 0)>$nodeWeight+$weight_row+$weight_rear + || !isset($this->candidates[$deviceID2]) && !isset($this->used_candidates[$deviceID2])){ + $this->AddNodeToList($deviceID1,-$portNumber1,$nodeWeight+$weight_row,$this->DeviceID, $this->PortNumber); //Anado directamente el espejo de este puerto //I add directly the mirror port of this port - $this->AddNodeToList($row["DeviceID2"],$row["PortNumber2"],$this->nodes[$this->DeviceID][$this->PortNumber]["weight"]+$weight_row+$weight_rear, $row["DeviceID1"],-$row["PortNumber1"]); + $this->AddNodeToList($deviceID2,$portNumber2,$nodeWeight+$weight_row+$weight_rear, $deviceID1,-$portNumber1); } } } @@ -400,7 +411,7 @@ function MakePath () { function GotoHeadDevice () { //Pone el objeto en el primer dispositivo del Path, si no lo es ya //Places the object in the first device of Path, if not already - If (isset($this->Path[1]["DeviceID"]) && $this->Path[1]["DeviceID"]==$this->devID1){ + if (isset($this->Path[1]["DeviceID"]) && $this->Path[1]["DeviceID"]==$this->devID1){ $this->DeviceID=$this->Path[1]["DeviceID"]; $this->PortNumber=$this->Path[1]["PortNumber"]; $this->acti=1; @@ -416,7 +427,7 @@ function GotoNextDevice () { // Places the object with the DeviceID, PortNumber and Front of the next device in the path. // If the object's current device is not connected returns "false" and the object doesn't change. $this->acti++; - If (isset($this->Path[$this->acti]["DeviceID"])){ + if (isset($this->Path[$this->acti]["DeviceID"])){ $this->DeviceID=$this->Path[$this->acti]["DeviceID"]; $this->PortNumber=$this->Path[$this->acti]["PortNumber"]; return true; diff --git a/classes/PowerConnection.class.php b/classes/PowerConnection.class.php index c30241bab..dabd0e5a9 100644 --- a/classes/PowerConnection.class.php +++ b/classes/PowerConnection.class.php @@ -43,15 +43,15 @@ private function MakeSafe(){ } private function MakeDisplay(){ - $this->PDUPosition=stripslashes($this->PDUPosition); + $this->PDUPosition=stripslashes((string)$this->PDUPosition); } static function RowToObject($row){ $conn=new PowerConnection; - $conn->PDUID=$row["PDUID"]; - $conn->PDUPosition=$row["PDUPosition"]; - $conn->DeviceID=$row["DeviceID"]; - $conn->DeviceConnNumber=$row["DeviceConnNumber"]; + $conn->PDUID=$row["PDUID"] ?? null; + $conn->PDUPosition=$row["PDUPosition"] ?? null; + $conn->DeviceID=$row["DeviceID"] ?? null; + $conn->DeviceConnNumber=$row["DeviceConnNumber"] ?? null; $conn->MakeDisplay(); return $conn; @@ -64,7 +64,7 @@ function CanWrite(){ // check for an existing device $tmpconn=new PowerConnection(); - foreach($this as $prop => $value){ + foreach(get_object_vars($this) as $prop => $value){ $tmpconn->$prop=$value; } $tmpconn->GetPDUConnectionByPosition(); @@ -155,7 +155,8 @@ function GetPDUConnectionByPosition(){ $sql="SELECT * FROM fac_PowerConnection WHERE PDUID=$this->PDUID AND PDUPosition=\"$this->PDUPosition\";"; - if($row=$dbh->query($sql)->fetch()){ + $stmt=$dbh->query($sql); + if($stmt && ($row=$stmt->fetch())){ foreach(PowerConnection::RowToObject($row) as $prop => $value){ $this->$prop=$value; } @@ -172,8 +173,10 @@ function GetConnectionsByPDU(){ PDUPosition;"; $connList=array(); - foreach($dbh->query($sql) as $row){ - $connList[$row["PDUPosition"]]=PowerConnection::RowToObject($row); + if($stmt=$dbh->query($sql)){ + foreach($stmt as $row){ + $connList[$row["PDUPosition"] ?? null]=PowerConnection::RowToObject($row); + } } return $connList; } @@ -185,8 +188,10 @@ function GetConnectionsByDevice(){ $sql="SELECT * FROM fac_PowerConnection WHERE DeviceID=$this->DeviceID ORDER BY DeviceConnnumber ASC, PDUID, PDUPosition"; $connList=array(); - foreach($dbh->query($sql) as $row){ - $connList[]=PowerConnection::RowToObject($row); + if($stmt=$dbh->query($sql)){ + foreach($stmt as $row){ + $connList[]=PowerConnection::RowToObject($row); + } } return $connList; } diff --git a/classes/PowerDistribution.class.php b/classes/PowerDistribution.class.php index 2ee3ac682..bc7391d0e 100644 --- a/classes/PowerDistribution.class.php +++ b/classes/PowerDistribution.class.php @@ -67,28 +67,28 @@ function MakeSafe(){ } function MakeDisplay(){ - $this->Label=stripslashes($this->Label); - $this->IPAddress=stripslashes($this->IPAddress); - $this->SNMPCommunity=stripslashes($this->SNMPCommunity); - $this->FirmwareVersion=stripslashes($this->FirmwareVersion); + $this->Label=stripslashes((string)$this->Label); + $this->IPAddress=stripslashes((string)$this->IPAddress); + $this->SNMPCommunity=stripslashes((string)$this->SNMPCommunity); + $this->FirmwareVersion=stripslashes((string)$this->FirmwareVersion); } static function RowToObject($row){ $PDU=new PowerDistribution(); - $PDU->PDUID=$row["PDUID"]; - $PDU->Label=$row["Label"]; - $PDU->CabinetID=$row["CabinetID"]; - $PDU->TemplateID=$row["TemplateID"]; - $PDU->IPAddress=$row["IPAddress"]; - $PDU->SNMPCommunity=$row["SNMPCommunity"]; - $PDU->FirmwareVersion=$row["FirmwareVersion"]; - $PDU->PanelID=$row["PanelID"]; - $PDU->BreakerSize=$row["BreakerSize"]; - $PDU->PanelPole=$row["PanelPole"]; - $PDU->InputAmperage=$row["InputAmperage"]; - $PDU->FailSafe=$row["FailSafe"]; - $PDU->PanelID2=$row["PanelID2"]; - $PDU->PanelPole2=$row["PanelPole2"]; + $PDU->PDUID=$row["PDUID"] ?? null; + $PDU->Label=$row["Label"] ?? null; + $PDU->CabinetID=$row["CabinetID"] ?? null; + $PDU->TemplateID=$row["TemplateID"] ?? null; + $PDU->IPAddress=$row["IPAddress"] ?? null; + $PDU->SNMPCommunity=$row["SNMPCommunity"] ?? null; + $PDU->FirmwareVersion=$row["FirmwareVersion"] ?? null; + $PDU->PanelID=$row["PanelID"] ?? null; + $PDU->BreakerSize=$row["BreakerSize"] ?? null; + $PDU->PanelPole=$row["PanelPole"] ?? null; + $PDU->InputAmperage=$row["InputAmperage"] ?? null; + $PDU->FailSafe=$row["FailSafe"] ?? null; + $PDU->PanelID2=$row["PanelID2"] ?? null; + $PDU->PanelPole2=$row["PanelPole2"] ?? null; $PDU->MakeDisplay(); @@ -122,7 +122,7 @@ static private function BasicTests($DeviceID){ if($dev->PrimaryIP==""){return false;} // If the device doesn't have an SNMP community set, check and see if we have a global one - $dev->SNMPCommunity=($dev->SNMPCommunity=="")?$config->ParameterArray["SNMPCommunity"]:$dev->SNMPCommunity; + $dev->SNMPCommunity=($dev->SNMPCommunity=="")?($config->ParameterArray["SNMPCommunity"] ?? ''):$dev->SNMPCommunity; // We've passed all the repeatable tests, return the device object for digging return $dev; @@ -140,8 +140,8 @@ static private function BasicTests($DeviceID){ */ static private function OSS_SNMP_Lookup($dev,$snmplookup,$oid=null){ // This is find out the name of the function that called this to make the error logging more descriptive - $caller=debug_backtrace(); - $caller=$caller[1]['function']; + $trace=debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2); + $caller=$trace[1]['function'] ?? 'unknown'; /***************************************************************************************************** @@ -216,7 +216,7 @@ function CreatePDU($pduid=null){ }else{ $info=$dbh->errorInfo(); - error_log("CreatePDU::PDO Error: {$info[2]} SQL=$sql"); + error_log("CreatePDU::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql"); return false; } @@ -257,12 +257,13 @@ function GetPDU(){ $sql="SELECT * FROM fac_PowerDistribution WHERE PDUID=$this->PDUID;"; - if($PDURow=$this->query($sql)->fetch()){ + $stmt=$this->query($sql); + if($stmt && ($PDURow=$stmt->fetch())){ foreach(PowerDistribution::RowToObject($PDURow) as $prop => $value){ $this->$prop=$value; } }else{ - foreach($this as $prop => $value){ + foreach(get_object_vars($this) as $prop => $value){ if($prop!='PDUID'){ $this->$prop=null; } @@ -279,8 +280,10 @@ function GetPDUbyPanel(){ OR PanelID2=$this->PanelID ORDER BY PanelPole ASC, CabinetID, Label"; $PDUList=array(); - foreach($this->query($sql) as $PDURow){ - $PDUList[]=PowerDistribution::RowToObject($PDURow); + if($stmt=$this->query($sql)){ + foreach($stmt as $PDURow){ + $PDUList[]=PowerDistribution::RowToObject($PDURow); + } } return $PDUList; @@ -292,8 +295,10 @@ function GetPDUbyCabinet(){ $sql="SELECT * FROM fac_PowerDistribution WHERE CabinetID=$this->CabinetID ORDER BY Label ASC;"; $PDUList=array(); - foreach($this->query($sql) as $PDURow){ - $PDUList[$PDURow["PDUID"]]=PowerDistribution::RowToObject($PDURow); + if($stmt=$this->query($sql)){ + foreach($stmt as $PDURow){ + $PDUList[$PDURow["PDUID"] ?? null]=PowerDistribution::RowToObject($PDURow); + } } return $PDUList; @@ -305,8 +310,10 @@ function SearchByPDUName(){ $sql="SELECT * FROM fac_PowerDistribution WHERE Label LIKE \"%$this->Label%\";"; $PDUList=array(); - foreach($this->query($sql) as $PDURow){ - $PDUList[$PDURow["PDUID"]]=PowerDistribution::RowToObject($PDURow); + if($stmt=$this->query($sql)){ + foreach($stmt as $PDURow){ + $PDUList[$PDURow["PDUID"] ?? null]=PowerDistribution::RowToObject($PDURow); + } } return $PDUList; @@ -320,10 +327,12 @@ function GetLastReading(){ $stats=new stdClass(); $stats->Wattage=0; $stats->LastRead=date('Y-m-d G:i:s',0); - foreach($this->query($sql) as $row){ - foreach($row as $prop => $value){ - if(!is_int($prop)){ - $stats->$prop=$value; + if($stmt=$this->query($sql)){ + foreach($stmt as $row){ + foreach($row as $prop => $value){ + if(!is_int($prop)){ + $stats->$prop=$value; + } } } } @@ -415,7 +424,8 @@ function UpdateStats( $filterType="None", $filterValue="" ) { ORDER BY f.Name ASC, e.Location ASC"; // The result set should have no PDU's with blank IP Addresses or SNMP Community, so we can forge ahead with processing them all - foreach($this->query($sql) as $row){ + if($stmt=$this->query($sql)){ + foreach($stmt as $row){ if(!$dev=PowerDistribution::BasicTests($row['PDUID'])){ // if we fail the basic test on a single device we don't want to skip all the rest so continue instead of return false; continue; @@ -475,7 +485,7 @@ function UpdateStats( $filterType="None", $filterValue="" ) { if(!$dbh->query($sql)){ $info=$dbh->errorInfo(); - error_log("PowerDistribution::UpdateStats::PDO Error: {$info[2]} SQL=$sql"); + error_log("PowerDistribution::UpdateStats::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql"); } $maxWatts = $row["Voltage"] * $row["Amperage"]; @@ -486,10 +496,10 @@ function UpdateStats( $filterType="None", $filterValue="" ) { // Derate everything 80% per standard $maxWatts *= 0.8; - if ( $config->ParameterArray["PowerAlertsEmail"] == "enabled" ) { - if ( $watts >= $config->ParameterArray["PowerRed"] / 100 * $maxWatts ) { + if ( ($config->ParameterArray["PowerAlertsEmail"] ?? '') == "enabled" ) { + if ( $watts >= ($config->ParameterArray["PowerRed"] ?? 0) / 100 * $maxWatts ) { $AlertList .= sprintf( "%s%s%s%s%s\n", $row["Name"], $row["Location"], $row["Label"], $watts, __("Critical")); - } elseif ( $watts >= $config->ParameterArray["PowerYellow"] / 100 * $maxWatts ) { + } elseif ( $watts >= ($config->ParameterArray["PowerYellow"] ?? 0) / 100 * $maxWatts ) { $AlertList .= sprintf( "%s%s%s%s%s\n", $row["Name"], $row["Location"], $row["Label"], $watts, __("Warning")); } } @@ -499,25 +509,26 @@ function UpdateStats( $filterType="None", $filterValue="" ) { $sql="UPDATE fac_PowerDistribution SET FirmwareVersion=\"$ver\" WHERE PDUID=$this->PDUID;"; if(!$dbh->query($sql)){ $info=$dbh->errorInfo(); - error_log("PowerDistribution::UpdateStats::PDO Error: {$info[2]} SQL=$sql"); + error_log("PowerDistribution::UpdateStats::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql"); } } + } } - if ( $config->ParameterArray["PowerAlertsEmail"] == "enabled" && $AlertList != "" ) { + if ( ($config->ParameterArray["PowerAlertsEmail"] ?? '') == "enabled" && $AlertList != "" ) { // If any port other than 25 is specified, assume encryption and authentication - if($config->ParameterArray['SMTPPort']!= 25){ + if(($config->ParameterArray['SMTPPort'] ?? 25)!= 25){ $transport=Swift_SmtpTransport::newInstance() - ->setHost($config->ParameterArray['SMTPServer']) - ->setPort($config->ParameterArray['SMTPPort']) + ->setHost($config->ParameterArray['SMTPServer'] ?? '') + ->setPort($config->ParameterArray['SMTPPort'] ?? 25) ->setEncryption('ssl') - ->setUsername($config->ParameterArray['SMTPUser']) - ->setPassword($config->ParameterArray['SMTPPassword']); + ->setUsername($config->ParameterArray['SMTPUser'] ?? '') + ->setPassword($config->ParameterArray['SMTPPassword'] ?? ''); }else{ $transport=Swift_SmtpTransport::newInstance() - ->setHost($config->ParameterArray['SMTPServer']) - ->setPort($config->ParameterArray['SMTPPort']); + ->setHost($config->ParameterArray['SMTPServer'] ?? '') + ->setPort($config->ParameterArray['SMTPPort'] ?? 25); } $mailer = Swift_Mailer::newInstance($transport); @@ -525,19 +536,19 @@ function UpdateStats( $filterType="None", $filterValue="" ) { // Set from address try{ - $message->setFrom($config->ParameterArray['MailFromAddr']); + $message->setFrom($config->ParameterArray['MailFromAddr'] ?? ''); }catch(Swift_RfcComplianceException $e){ $error.=__("MailFrom").": ".$e->getMessage()."
\n"; } // Add data center team to the list of recipients try{ - $message->addTo($config->ParameterArray['FacMgrMail']); + $message->addTo($config->ParameterArray['FacMgrMail'] ?? ''); }catch(Swift_RfcComplianceException $e){ $error.=__("Facility Manager email address").": ".$e->getMessage()."
\n"; } - $logofile=getcwd().'/'.$config->ParameterArray["PDFLogoFile"]; + $logofile=getcwd().'/'.($config->ParameterArray["PDFLogoFile"] ?? ''); $logo=$message->embed(Swift_Image::fromPath($logofile)->setFilename($logofile)); $style = " @@ -550,7 +561,7 @@ function UpdateStats( $filterType="None", $filterValue="" ) { "; - $htmlMessage = sprintf( "%s%s

\n", __("Data Center Power Alerts"), $style, $config->ParameterArray["HeaderColor"], $logo ); + $htmlMessage = sprintf( "%s%s

\n", __("Data Center Power Alerts"), $style, $config->ParameterArray["HeaderColor"] ?? '', $logo ); $htmlMessage .= sprintf( "\n\n", __("Data Center"), __("Cabinet"), __("CDU"), __("Value"), __("Alert Level") ); diff --git a/classes/PowerPanel.class.php b/classes/PowerPanel.class.php index db5fae8fd..8745f1bce 100644 --- a/classes/PowerPanel.class.php +++ b/classes/PowerPanel.class.php @@ -93,28 +93,28 @@ function MakeSafe() { } function MakeDisplay(){ - $this->PanelLabel=stripslashes($this->PanelLabel); - $this->ParentBreakerName=stripslashes($this->ParentBreakerName); - $this->PanelIPAddress=stripslashes($this->PanelIPAddress); + $this->PanelLabel=stripslashes((string)$this->PanelLabel); + $this->ParentBreakerName=stripslashes((string)$this->ParentBreakerName); + $this->PanelIPAddress=stripslashes((string)$this->PanelIPAddress); } static function RowToObject($row){ $panel=new PowerPanel(); - $panel->PanelID=$row["PanelID"]; - $panel->PanelLabel=$row["PanelLabel"]; - $panel->NumberOfPoles=$row["NumberOfPoles"]; - $panel->MainBreakerSize=$row["MainBreakerSize"]; - $panel->PanelVoltage=$row["PanelVoltage"]; - $panel->NumberScheme=$row["NumberScheme"]; - $panel->ParentPanelID=$row["ParentPanelID"]; - $panel->ParentBreakerName=$row["ParentBreakerName"]; - $panel->TemplateID=$row["TemplateID"]; - $panel->PanelIPAddress=$row["PanelIPAddress"]; - $panel->MapDataCenterID=$row["MapDataCenterID"]; - $panel->MapX1=$row["MapX1"]; - $panel->MapX2=$row["MapX2"]; - $panel->MapY1=$row["MapY1"]; - $panel->MapY2=$row["MapY2"]; + $panel->PanelID=$row["PanelID"] ?? null; + $panel->PanelLabel=$row["PanelLabel"] ?? null; + $panel->NumberOfPoles=$row["NumberOfPoles"] ?? null; + $panel->MainBreakerSize=$row["MainBreakerSize"] ?? null; + $panel->PanelVoltage=$row["PanelVoltage"] ?? null; + $panel->NumberScheme=$row["NumberScheme"] ?? null; + $panel->ParentPanelID=$row["ParentPanelID"] ?? null; + $panel->ParentBreakerName=$row["ParentBreakerName"] ?? null; + $panel->TemplateID=$row["TemplateID"] ?? null; + $panel->PanelIPAddress=$row["PanelIPAddress"] ?? null; + $panel->MapDataCenterID=$row["MapDataCenterID"] ?? null; + $panel->MapX1=$row["MapX1"] ?? null; + $panel->MapX2=$row["MapX2"] ?? null; + $panel->MapY1=$row["MapY1"] ?? null; + $panel->MapY2=$row["MapY2"] ?? null; $panel->MakeDisplay(); @@ -147,8 +147,10 @@ static function getInheritedLoad( $PanelID ) { // Ok, now repeat for the subpanels $sql = "select PanelID from fac_PowerPanel where ParentPanelID=" . intval( $PanelID); - foreach ( $dbh->query( $sql ) as $pnl) { - $watts += PowerPanel::getInheritedLoad( $pnl["PanelID"] ); + if($stmt=$dbh->query( $sql )){ + foreach ( $stmt as $pnl) { + $watts += PowerPanel::getInheritedLoad( $pnl["PanelID"] ?? null ); + } } return $watts; @@ -160,14 +162,18 @@ static function getEstimatedLoad( $PanelID ) { // Same as with the InheritedLoad - get all the power strips off of the requested panel, then all of the subpanels $sql = "select PDUID from fac_PowerDistribution where PanelID=" . intval( $PanelID ); - foreach( $dbh->query( $sql ) as $pdu ) { - $watts += PowerDistribution::calculateEstimatedLoad( $pdu["PDUID"] ); + if($stmt=$dbh->query( $sql )){ + foreach( $stmt as $pdu ) { + $watts += PowerDistribution::calculateEstimatedLoad( $pdu["PDUID"] ?? null ); + } } // Now get the subpanels $sql = "select PanelID from fac_PowerPanel where ParentPanelID=" . intval( $PanelID ); - foreach( $dbh->query( $sql ) as $pnl ) { - $watts += PowerPanel::getEstimatedLoad( $pnl["PanelID"] ); + if($stmt=$dbh->query( $sql )){ + foreach( $stmt as $pnl ) { + $watts += PowerPanel::getEstimatedLoad( $pnl["PanelID"] ?? null ); + } } return $watts; @@ -189,13 +195,13 @@ function getPowerSource() { while ( $currParent != 0 ) { $st->execute( array( ":PanelID"=>$currParent ) ); $row = $st->fetch(); - $currParent = $row->ParentPanelID; + $currParent = $row->ParentPanelID ?? 0; } if ( ! @is_object( $row ) ) { // Someone called this on a PowerSource $row = new PowerPanel(); - foreach ( $this as $prop=>$val ) { + foreach ( get_object_vars($this) as $prop=>$val ) { $row->$prop = $val; } } @@ -294,7 +300,8 @@ function getPanel() { $this->MakeSafe(); $sql="SELECT * FROM fac_PowerPanel WHERE PanelID=$this->PanelID;"; - if($row=$this->query($sql)->fetch()){ + $stmt=$this->query($sql); + if($stmt && ($row=$stmt->fetch())){ foreach(PowerPanel::RowToObject($row) as $prop => $value){ $this->$prop=$value; } @@ -317,7 +324,7 @@ function createPanel() { if(!$this->exec($sql)){ $info=$this->errorInfo(); - error_log("createPanel::PDO Error: {$info[2]} $sql"); + error_log("createPanel::PDO Error: " . ($info[2] ?? 'Unknown error') . " $sql"); return false; }else{ $this->PanelID=$this->lastInsertId(); @@ -583,7 +590,7 @@ function updatePanel(){ if(!$this->query($sql)){ $info=$this->errorInfo(); - error_log("updatePanel::PDO Error: {$info[2]} SQL=$sql"); + error_log("updatePanel::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql"); return false; } @@ -600,7 +607,7 @@ function Search($indexedbyid=false,$loose=false){ // This will store all our extended sql $sqlextend=""; - foreach($this as $prop => $val){ + foreach(get_object_vars($this) as $prop => $val){ // We force NumberScheme to a known value so this is to check if they wanted to search for the default if($prop=="NumberScheme" && $val=="Sequential" && $os!="Sequential"){ continue; @@ -614,11 +621,13 @@ function Search($indexedbyid=false,$loose=false){ $panelList=array(); - foreach($this->query($sql) as $row){ - if($indexedbyid){ - $panelList[$deviceRow["DeviceID"]]=PowerPanel::RowToObject($row); - }else{ - $panelList[]=PowerPanel::RowToObject($row); + if($stmt=$this->query($sql)){ + foreach($stmt as $row){ + if($indexedbyid){ + $panelList[$deviceRow["DeviceID"] ?? null]=PowerPanel::RowToObject($row); + }else{ + $panelList[]=PowerPanel::RowToObject($row); + } } } diff --git a/classes/PowerPorts.class.php b/classes/PowerPorts.class.php index 08fa3067d..625047e72 100644 --- a/classes/PowerPorts.class.php +++ b/classes/PowerPorts.class.php @@ -52,21 +52,21 @@ function MakeSafe() { } function MakeDisplay(){ - $this->Label=stripslashes(trim($this->Label)); - $this->Notes=stripslashes(trim($this->Notes)); + $this->Label=stripslashes(trim((string)$this->Label)); + $this->Notes=stripslashes(trim((string)$this->Notes)); } static function RowToObject($dbRow){ $pp=new PowerPorts(); - $pp->DeviceID=$dbRow['DeviceID']; - $pp->PortNumber=$dbRow['PortNumber']; - $pp->Label=$dbRow['Label']; - $pp->ConnectorID=$dbRow['ConnectorID']; - $pp->PhaseID=$dbRow['PhaseID']; - $pp->VoltageID=$dbRow['VoltageID']; - $pp->ConnectedDeviceID=$dbRow['ConnectedDeviceID']; - $pp->ConnectedPort=$dbRow['ConnectedPort']; - $pp->Notes=$dbRow['Notes']; + $pp->DeviceID=$dbRow['DeviceID'] ?? null; + $pp->PortNumber=$dbRow['PortNumber'] ?? null; + $pp->Label=$dbRow['Label'] ?? null; + $pp->ConnectorID=$dbRow['ConnectorID'] ?? null; + $pp->PhaseID=$dbRow['PhaseID'] ?? null; + $pp->VoltageID=$dbRow['VoltageID'] ?? null; + $pp->ConnectedDeviceID=$dbRow['ConnectedDeviceID'] ?? null; + $pp->ConnectedPort=$dbRow['ConnectedPort'] ?? null; + $pp->Notes=$dbRow['Notes'] ?? null; $pp->MakeDisplay(); @@ -79,7 +79,8 @@ function getPort(){ $sql="SELECT * FROM fac_PowerPorts WHERE DeviceID=$this->DeviceID AND PortNumber=$this->PortNumber;"; - if(!$row=$dbh->query($sql)->fetch()){ + $stmt=$dbh->query($sql); + if(!$stmt || !($row=$stmt->fetch())){ return false; }else{ foreach(PowerPorts::RowToObject($row) as $prop => $value){ @@ -96,8 +97,10 @@ function getPorts(){ $sql="SELECT * FROM fac_PowerPorts WHERE DeviceID=$this->DeviceID ORDER BY PortNumber ASC;"; $ports=array(); - foreach($dbh->query($sql) as $row){ - $ports[$row['PortNumber']]=PowerPorts::RowToObject($row); + if($stmt=$dbh->query($sql)){ + foreach($stmt as $row){ + $ports[$row['PortNumber'] ?? null]=PowerPorts::RowToObject($row); + } } return $ports; } @@ -422,7 +425,7 @@ static function getConnectedPortList($DeviceID){ function Search($indexedbyid=false,$loose=false){ global $dbh; // Store any values that have been added before we make them safe - foreach($this as $prop => $val){ + foreach(get_object_vars($this) as $prop => $val){ if(isset($val)){ $o[$prop]=$val; } @@ -440,11 +443,13 @@ function Search($indexedbyid=false,$loose=false){ $portList=array(); - foreach($dbh->query($sql) as $portRow){ - if($indexedbyid){ - $portList[$portRow["DeviceID"].$portRow["PortNumber"]]=PowerPorts::RowToObject($portRow); - }else{ - $portList[]=PowerPorts::RowToObject($portRow); + if($stmt=$dbh->query($sql)){ + foreach($stmt as $portRow){ + if($indexedbyid){ + $portList[($portRow["DeviceID"] ?? '').($portRow["PortNumber"] ?? '')]=PowerPorts::RowToObject($portRow); + }else{ + $portList[]=PowerPorts::RowToObject($portRow); + } } } diff --git a/classes/Projects.class.php b/classes/Projects.class.php index b1d23df61..29daf9bc1 100644 --- a/classes/Projects.class.php +++ b/classes/Projects.class.php @@ -129,7 +129,7 @@ function Search($indexedbyid=false,$loose=false){ // This will store all our extended sql $sqlextend=""; $args = array(); - foreach($this as $prop => $val){ + foreach(get_object_vars($this) as $prop => $val){ if ( isset( $val ) ) { $method=($loose)?" LIKE \":" . $prop . "%\"":"=:" . $prop; if ($sqlextend) { @@ -146,7 +146,7 @@ function Search($indexedbyid=false,$loose=false){ $projectList=array(); while( $row = $st->fetch() ) { if($indexedbyid){ - $projectList[$row["ProjectID"]]=$row; + $projectList[$row->ProjectID]=$row; }else{ $projectList[]=$row; } diff --git a/classes/RCI.class.php b/classes/RCI.class.php index 8d77efd1c..3775aa8a5 100644 --- a/classes/RCI.class.php +++ b/classes/RCI.class.php @@ -47,9 +47,9 @@ static function GetStatistics( $limit = "global", $id = "" ) { $st = $dbh->prepare( $countSQL ); $st->execute(); $row = $st->fetch(); - $result["TotalCabinets"] = $row["TotalCabinets"]; + $result["TotalCabinets"] = $row["TotalCabinets"] ?? 0; - $lowSQL = "select c.Location, a.Temperature from fac_SensorReadings a, fac_Device b, fac_Cabinet c where a.DeviceID=b.DeviceID and b.BackSide=0 and b.Cabinet=c.CabinetID and a.Temperature<>0 and a.Temperature<'" . $config->ParameterArray["RCILow"] . "' $limitSQL order by Location ASC"; + $lowSQL = "select c.Location, a.Temperature from fac_SensorReadings a, fac_Device b, fac_Cabinet c where a.DeviceID=b.DeviceID and b.BackSide=0 and b.Cabinet=c.CabinetID and a.Temperature<>0 and a.Temperature<'" . ($config->ParameterArray["RCILow"] ?? '') . "' $limitSQL order by Location ASC"; $RCILow = array(); $st = $dbh->prepare( $lowSQL ); $st->execute(); @@ -60,7 +60,7 @@ static function GetStatistics( $limit = "global", $id = "" ) { $result["RCILowCount"] = sizeof( $RCILow ); $result["RCILowList"] = $RCILow; - $highSQL = "select c.Location, a.Temperature from fac_SensorReadings a, fac_Device b, fac_Cabinet c where a.DeviceID=b.DeviceID and b.BackSide=0 and b.Cabinet=c.CabinetID and a.Temperature<>0 and a.Temperature>'" . $config->ParameterArray["RCIHigh"] . "' $limitSQL order by Location ASC"; + $highSQL = "select c.Location, a.Temperature from fac_SensorReadings a, fac_Device b, fac_Cabinet c where a.DeviceID=b.DeviceID and b.BackSide=0 and b.Cabinet=c.CabinetID and a.Temperature<>0 and a.Temperature>'" . ($config->ParameterArray["RCIHigh"] ?? '') . "' $limitSQL order by Location ASC"; $RCIHigh = array(); $st = $dbh->prepare( $highSQL ); $st->execute(); diff --git a/classes/RackRequest.class.php b/classes/RackRequest.class.php index e1717cda2..88f8d219d 100644 --- a/classes/RackRequest.class.php +++ b/classes/RackRequest.class.php @@ -80,19 +80,20 @@ function MakeSafe(){ $this->CurrentLocation=sanitize(transform($this->CurrentLocation)); $this->SpecialInstructions=sanitize($this->SpecialInstructions); $this->RequestedAction=(in_array($this->RequestedAction,$validrequestactions))?$this->RequestedAction:''; - $this->MfgDate=date("Y-m-d", strtotime($this->MfgDate)); //date + $mfgDate=strtotime((string)$this->MfgDate); + $this->MfgDate=($mfgDate !== false) ? date("Y-m-d", $mfgDate) : ''; } function MakeDisplay(){ - $this->Label=stripslashes($this->Label); - $this->SerialNo=stripslashes($this->SerialNo); - $this->AssetTag=stripslashes($this->AssetTag); - $this->VLANList=stripslashes($this->VLANList); - $this->SANList=stripslashes($this->SANList); - $this->DeviceClass=stripslashes($this->DeviceClass); - $this->LabelColor=stripslashes($this->LabelColor); - $this->CurrentLocation=stripslashes($this->CurrentLocation); - $this->SpecialInstructions=stripslashes($this->SpecialInstructions); + $this->Label=stripslashes((string)$this->Label); + $this->SerialNo=stripslashes((string)$this->SerialNo); + $this->AssetTag=stripslashes((string)$this->AssetTag); + $this->VLANList=stripslashes((string)$this->VLANList); + $this->SANList=stripslashes((string)$this->SANList); + $this->DeviceClass=stripslashes((string)$this->DeviceClass); + $this->LabelColor=stripslashes((string)$this->LabelColor); + $this->CurrentLocation=stripslashes((string)$this->CurrentLocation); + $this->SpecialInstructions=stripslashes((string)$this->SpecialInstructions); } function CreateRequest(){ @@ -111,7 +112,7 @@ function CreateRequest(){ if(!$dbh->exec($sql)){ $info=$dbh->errorInfo(); - error_log("PDO Error: {$info[2]}"); + error_log("PDO Error: " . ($info[2] ?? 'Unknown error')); return false; }else{ $this->RequestID=$dbh->lastInsertId(); @@ -126,31 +127,34 @@ function GetOpenRequests() { $sql="SELECT * FROM fac_RackRequest WHERE CompleteTime='0000-00-00 00:00:00'"; $requestList=array(); - foreach($dbh->query($sql) as $row){ - $requestNum=sizeof($requestList); - - $requestList[$requestNum]=new RackRequest(); - $requestList[$requestNum]->RequestID=$row["RequestID"]; - $requestList[$requestNum]->RequestorID=$row["RequestorID"]; - $requestList[$requestNum]->RequestTime=$row["RequestTime"]; - $requestList[$requestNum]->CompleteTime=$row["CompleteTime"]; - $requestList[$requestNum]->Label=$row["Label"]; - $requestList[$requestNum]->SerialNo=$row["SerialNo"]; - $requestList[$requestNum]->AssetTag=$row["AssetTag"]; - $requestList[$requestNum]->Hypervisor=$row["Hypervisor"]; - $requestList[$requestNum]->Owner=$row["Owner"]; - $requestList[$requestNum]->DeviceHeight=$row["DeviceHeight"]; - $requestList[$requestNum]->EthernetCount=$row["EthernetCount"]; - $requestList[$requestNum]->VLANList=$row["VLANList"]; - $requestList[$requestNum]->SANCount=$row["SANCount"]; - $requestList[$requestNum]->SANList=$row["SANList"]; - $requestList[$requestNum]->DeviceClass=$row["DeviceClass"]; - $requestList[$requestNum]->DeviceType=$row["DeviceType"]; - $requestList[$requestNum]->LabelColor=$row["LabelColor"]; - $requestList[$requestNum]->CurrentLocation=$row["CurrentLocation"]; - $requestList[$requestNum]->SpecialInstructions=$row["SpecialInstructions"]; - $requestList[$requestNum]->RequestedAction=$row["RequestedAction"]; - $requestList[$requestNum]->MakeDisplay(); + $stmt=$dbh->query($sql); + if($stmt){ + foreach($stmt as $row){ + $requestNum=sizeof($requestList); + + $requestList[$requestNum]=new RackRequest(); + $requestList[$requestNum]->RequestID=$row["RequestID"] ?? null; + $requestList[$requestNum]->RequestorID=$row["RequestorID"] ?? null; + $requestList[$requestNum]->RequestTime=$row["RequestTime"] ?? null; + $requestList[$requestNum]->CompleteTime=$row["CompleteTime"] ?? null; + $requestList[$requestNum]->Label=$row["Label"] ?? null; + $requestList[$requestNum]->SerialNo=$row["SerialNo"] ?? null; + $requestList[$requestNum]->AssetTag=$row["AssetTag"] ?? null; + $requestList[$requestNum]->Hypervisor=$row["Hypervisor"] ?? null; + $requestList[$requestNum]->Owner=$row["Owner"] ?? null; + $requestList[$requestNum]->DeviceHeight=$row["DeviceHeight"] ?? null; + $requestList[$requestNum]->EthernetCount=$row["EthernetCount"] ?? null; + $requestList[$requestNum]->VLANList=$row["VLANList"] ?? null; + $requestList[$requestNum]->SANCount=$row["SANCount"] ?? null; + $requestList[$requestNum]->SANList=$row["SANList"] ?? null; + $requestList[$requestNum]->DeviceClass=$row["DeviceClass"] ?? null; + $requestList[$requestNum]->DeviceType=$row["DeviceType"] ?? null; + $requestList[$requestNum]->LabelColor=$row["LabelColor"] ?? null; + $requestList[$requestNum]->CurrentLocation=$row["CurrentLocation"] ?? null; + $requestList[$requestNum]->SpecialInstructions=$row["SpecialInstructions"] ?? null; + $requestList[$requestNum]->RequestedAction=$row["RequestedAction"] ?? null; + $requestList[$requestNum]->MakeDisplay(); + } } return $requestList; @@ -160,27 +164,28 @@ function GetRequest(){ global $dbh; $sql="SELECT * FROM fac_RackRequest WHERE RequestID=\"".intval($this->RequestID)."\";"; - if($row=$dbh->query($sql)->fetch()){ - $this->RequestorID=$row["RequestorID"]; - $this->RequestTime=$row["RequestTime"]; - $this->CompleteTime=$row["CompleteTime"]; - $this->Label=$row["Label"]; - $this->SerialNo=$row["SerialNo"]; - $this->MfgDate=$row["MfgDate"]; - $this->AssetTag=$row["AssetTag"]; - $this->Hypervisor=$row["Hypervisor"]; - $this->Owner=$row["Owner"]; - $this->DeviceHeight=$row["DeviceHeight"]; - $this->EthernetCount=$row["EthernetCount"]; - $this->VLANList=$row["VLANList"]; - $this->SANCount=$row["SANCount"]; - $this->SANList=$row["SANList"]; - $this->DeviceClass=$row["DeviceClass"]; - $this->DeviceType=$row["DeviceType"]; - $this->LabelColor=$row["LabelColor"]; - $this->CurrentLocation=$row["CurrentLocation"]; - $this->SpecialInstructions=$row["SpecialInstructions"]; - $this->RequestedAction=$row["RequestedAction"]; + $stmt=$dbh->query($sql); + if($stmt && ($row=$stmt->fetch())){ + $this->RequestorID=$row["RequestorID"] ?? null; + $this->RequestTime=$row["RequestTime"] ?? null; + $this->CompleteTime=$row["CompleteTime"] ?? null; + $this->Label=$row["Label"] ?? null; + $this->SerialNo=$row["SerialNo"] ?? null; + $this->MfgDate=$row["MfgDate"] ?? null; + $this->AssetTag=$row["AssetTag"] ?? null; + $this->Hypervisor=$row["Hypervisor"] ?? null; + $this->Owner=$row["Owner"] ?? null; + $this->DeviceHeight=$row["DeviceHeight"] ?? null; + $this->EthernetCount=$row["EthernetCount"] ?? null; + $this->VLANList=$row["VLANList"] ?? null; + $this->SANCount=$row["SANCount"] ?? null; + $this->SANList=$row["SANList"] ?? null; + $this->DeviceClass=$row["DeviceClass"] ?? null; + $this->DeviceType=$row["DeviceType"] ?? null; + $this->LabelColor=$row["LabelColor"] ?? null; + $this->CurrentLocation=$row["CurrentLocation"] ?? null; + $this->SpecialInstructions=$row["SpecialInstructions"] ?? null; + $this->RequestedAction=$row["RequestedAction"] ?? null; $this->MakeDisplay(); }else{ //something bad happened maybe tell someone diff --git a/classes/SensorReadings.class.php b/classes/SensorReadings.class.php index 1f4c3c49a..823f5027f 100644 --- a/classes/SensorReadings.class.php +++ b/classes/SensorReadings.class.php @@ -40,10 +40,10 @@ function MakeSafe(){ static function RowToObject($row){ $m=new SensorReadings(); - $m->SensorID=$row["DeviceID"]; - $m->Temperature=$row["Temperature"]; - $m->Humidity= $row["Humidity"]; - $m->LastRead=$row["LastRead"]; + $m->SensorID=$row["DeviceID"] ?? null; + $m->Temperature=$row["Temperature"] ?? null; + $m->Humidity= $row["Humidity"] ?? null; + $m->LastRead=$row["LastRead"] ?? null; return $m; } @@ -57,8 +57,9 @@ function GetSensorReadingsByID(){ $sql="SELECT * FROM fac_SensorReadings WHERE DeviceID=$this->SensorID;"; - if($row=$this->query($sql)->fetch()){ - foreach(SensorReadings::RowToObject($row) as $prop => $value){ + $stmt=$this->query($sql); + if($stmt && ($row=$stmt->fetch())){ + foreach(get_object_vars(SensorReadings::RowToObject($row)) as $prop => $value){ $this->$prop=$value; } return true; @@ -72,14 +73,17 @@ function UpdateSensorReadings() { $this->MakeSafe(); + $lastRead=strtotime((string)$this->LastRead); + $lastRead=($lastRead === false) ? 0 : $lastRead; + $lastReadSQL=date("Y-m-d H:i:s", $lastRead); $sql="INSERT INTO fac_SensorReadings (DeviceID,Temperature,Humidity,LastRead) VALUES - ($this->SensorID,$this->Temperature,$this->Humidity,\"".date("Y-m-d H:i:s", strtotime($this->LastRead))."\") ON DUPLICATE KEY - UPDATE Temperature=$this->Temperature,Humidity=$this->Humidity,LastRead=\"".date("Y-m-d H:i:s", strtotime($this->LastRead))."\";"; + ($this->SensorID,$this->Temperature,$this->Humidity,\"$lastReadSQL\") ON DUPLICATE KEY + UPDATE Temperature=$this->Temperature,Humidity=$this->Humidity,LastRead=\"$lastReadSQL\";"; if(!$dbh->query($sql)){ $info=$dbh->errorInfo(); - error_log("UpdateSensorReadings::PDO Error: {$info[2]} SQL=$sql" ); + error_log("UpdateSensorReadings::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql" ); return false; } return true; @@ -95,7 +99,7 @@ function DeleteSensorReadings(){ if(!$dbh->query($sql)){ $info=$dbh->errorInfo(); - error_log("DeleteSensorReadings::PDO Error: {$info[2]} SQL=$sql" ); + error_log("DeleteSensorReadings::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql" ); return false; } return true; @@ -105,7 +109,7 @@ function Search($indexedbyid=false,$loose=false){ $this->MakeSafe(); $sqlextend=""; - foreach($this as $prop => $val){ + foreach(get_object_vars($this) as $prop => $val){ if($val){ extendsql($prop,$val,$sqlextend,$loose); } @@ -114,11 +118,14 @@ function Search($indexedbyid=false,$loose=false){ $sql="SELECT * FROM fac_SensorReadings $sqlextend;"; $sensorreadingsList=array(); - foreach($this->query($sql) as $sensorreadingsRow){ - if($indexedbyid){ - $sensorreadingsList[$sensorreadingsRow["DeviceID"]]=SensorReadings::RowToObject($sensorreadingsRow); - }else{ - $sensorreadingsList[]=SensorReadings::RowToObject($sensorreadingsRow); + $stmt=$this->query($sql); + if($stmt){ + foreach($stmt as $sensorreadingsRow){ + if($indexedbyid){ + $sensorreadingsList[$sensorreadingsRow["DeviceID"] ?? null]=SensorReadings::RowToObject($sensorreadingsRow); + }else{ + $sensorreadingsList[]=SensorReadings::RowToObject($sensorreadingsRow); + } } } diff --git a/classes/SensorTemplate.class.php b/classes/SensorTemplate.class.php index 1d79d5292..7ea0aec24 100644 --- a/classes/SensorTemplate.class.php +++ b/classes/SensorTemplate.class.php @@ -59,20 +59,20 @@ function MakeSafe(){ } function MakeDisplay() { - $this->TemperatureOID=stripslashes($this->TemperatureOID); - $this->HumidityOID=stripslashes($this->HumidityOID); + $this->TemperatureOID=stripslashes((string)$this->TemperatureOID); + $this->HumidityOID=stripslashes((string)$this->HumidityOID); } static function RowToObject($dbRow){ $st=new SensorTemplate(); - $st->TemplateID=$dbRow["TemplateID"]; - $st->ManufacturerID=$dbRow["ManufacturerID"]; - $st->Model=$dbRow["Model"]; - $st->TemperatureOID=$dbRow["TemperatureOID"]; - $st->HumidityOID=$dbRow["HumidityOID"]; - $st->TempMultiplier=$dbRow["TempMultiplier"]; - $st->HumidityMultiplier=$dbRow["HumidityMultiplier"]; - $st->mUnits=$dbRow["mUnits"]; + $st->TemplateID=$dbRow["TemplateID"] ?? null; + $st->ManufacturerID=$dbRow["ManufacturerID"] ?? null; + $st->Model=$dbRow["Model"] ?? null; + $st->TemperatureOID=$dbRow["TemperatureOID"] ?? null; + $st->HumidityOID=$dbRow["HumidityOID"] ?? null; + $st->TempMultiplier=$dbRow["TempMultiplier"] ?? null; + $st->HumidityMultiplier=$dbRow["HumidityMultiplier"] ?? null; + $st->mUnits=$dbRow["mUnits"] ?? null; return $st; } @@ -84,8 +84,9 @@ function GetTemplate(){ $sql="SELECT * FROM fac_SensorTemplate WHERE TemplateID=$this->TemplateID;"; - if($sensorRow=$dbh->query($sql)->fetch()){ - foreach(SensorTemplate::RowToObject($sensorRow) as $prop => $value){ + $stmt=$dbh->query($sql); + if($stmt && ($sensorRow=$stmt->fetch())){ + foreach(get_object_vars(SensorTemplate::RowToObject($sensorRow)) as $prop => $value){ $this->$prop=$value; } return true; @@ -100,8 +101,11 @@ static function getTemplates(){ $sql="SELECT * FROM fac_SensorTemplate ORDER BY ManufacturerID, Model ASC;"; $tempList = array(); - foreach($dbh->query($sql) as $row){ - $tempList[]=SensorTemplate::RowToObject($row); + $stmt=$dbh->query($sql); + if($stmt){ + foreach($stmt as $row){ + $tempList[]=SensorTemplate::RowToObject($row); + } } return $tempList; @@ -121,7 +125,7 @@ function CreateTemplate($templateid){ if(!$dbh->exec($sql)){ $info=$dbh->errorInfo(); - error_log("CreateTemplate::PDO Error: {$info[2]} $sql"); + error_log("CreateTemplate::PDO Error: " . ($info[2] ?? 'Unknown error') . " $sql"); return false; } @@ -146,7 +150,7 @@ function UpdateTemplate() { if(!$dbh->query($sql)){ $info=$dbh->errorInfo(); - error_log("UpdateTemplate::PDO Error: {$info[2]} SQL=$sql"); + error_log("UpdateTemplate::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql"); return false; } (class_exists('LogActions'))?LogActions::LogThis($this,$old):''; diff --git a/classes/Slot.class.php b/classes/Slot.class.php index 63ca87b40..c4580c54a 100644 --- a/classes/Slot.class.php +++ b/classes/Slot.class.php @@ -43,13 +43,13 @@ function MakeSafe(){ static function RowToObject($row){ $slot=New Slot(); - $slot->TemplateID=$row["TemplateID"]; - $slot->Position=$row["Position"]; - $slot->BackSide=$row["BackSide"]; - $slot->X=$row["X"]; - $slot->Y=$row["Y"]; - $slot->W=$row["W"]; - $slot->H=$row["H"]; + $slot->TemplateID=$row["TemplateID"] ?? null; + $slot->Position=$row["Position"] ?? null; + $slot->BackSide=$row["BackSide"] ?? null; + $slot->X=$row["X"] ?? null; + $slot->Y=$row["Y"] ?? null; + $slot->W=$row["W"] ?? null; + $slot->H=$row["H"] ?? null; return $slot; } @@ -79,7 +79,7 @@ function CreateSlot(){ ;"; if(!$dbh->exec($sql)){ $info=$dbh->errorInfo(); - error_log("PDO Error: {$info[2]} SQL=$sql"); + error_log("PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql"); return false; }else{ (class_exists('LogActions'))?LogActions::LogThis($this):''; @@ -125,8 +125,9 @@ function GetSlot(){ $this->MakeSafe(); $sql="SELECT * FROM fac_Slots WHERE TemplateID=$this->TemplateID AND Position=$this->Position AND BackSide=$this->BackSide;"; - if($row=$this->query($sql)->fetch()){ - foreach(Slot::RowToObject($row) as $prop => $value){ + $stmt=$this->query($sql); + if($stmt && ($row=$stmt->fetch())){ + foreach(get_object_vars(Slot::RowToObject($row)) as $prop => $value){ $this->$prop=$value; } return true; @@ -156,8 +157,11 @@ static function GetAll($templateid){ $sql="SELECT * FROM fac_Slots WHERE TemplateID=".intval($templateid)." ORDER BY BackSide ASC, Position ASC;"; $slots=array(); - foreach($dbh->query($sql) as $row){ - $slots[$row['BackSide']][$row['Position']]=Slot::RowToObject($row); + $stmt=$dbh->query($sql); + if($stmt){ + foreach($stmt as $row){ + $slots[$row['BackSide'] ?? null][$row['Position'] ?? null]=Slot::RowToObject($row); + } } return $slots; } @@ -166,8 +170,9 @@ function GetFirstSlot(){ $this->MakeSafe(); $sql="SELECT * FROM fac_Slots WHERE TemplateID=$this->TemplateID ORDER BY BackSide,Position;"; - if($row=$this->query($sql)->fetch()){ - foreach(Slot::RowToObject($row) as $prop => $value){ + $stmt=$this->query($sql); + if($stmt && ($row=$stmt->fetch())){ + foreach(get_object_vars(Slot::RowToObject($row)) as $prop => $value){ $this->$prop=$value; } return true; @@ -176,4 +181,4 @@ function GetFirstSlot(){ } } } -?> \ No newline at end of file +?> diff --git a/classes/Supplies.class.php b/classes/Supplies.class.php index b58bb59d3..a010931f2 100644 --- a/classes/Supplies.class.php +++ b/classes/Supplies.class.php @@ -38,17 +38,17 @@ function MakeSafe(){ } function MakeDisplay(){ - $this->PartNum=stripslashes($this->PartNum); - $this->PartName=stripslashes($this->PartName); + $this->PartNum=stripslashes((string)$this->PartNum); + $this->PartName=stripslashes((string)$this->PartName); } static function RowToObject($row){ $supply=new Supplies(); - $supply->SupplyID=$row['SupplyID']; - $supply->PartNum=$row['PartNum']; - $supply->PartName=$row['PartName']; - $supply->MinQty=$row['MinQty']; - $supply->MaxQty=$row['MaxQty']; + $supply->SupplyID=$row['SupplyID'] ?? null; + $supply->PartNum=$row['PartNum'] ?? null; + $supply->PartName=$row['PartName'] ?? null; + $supply->MinQty=$row['MinQty'] ?? null; + $supply->MaxQty=$row['MaxQty'] ?? null; $supply->MakeDisplay(); return $supply; @@ -83,8 +83,9 @@ function GetSupplies(){ $this->MakeSafe(); $sql="SELECT * FROM fac_Supplies WHERE SupplyID=$this->SupplyID;"; - if($row=$this->query($sql)->fetch()){ - foreach(Supplies::RowToObject($row) as $prop => $value){ + $stmt=$this->query($sql); + if($stmt && ($row=$stmt->fetch())){ + foreach(get_object_vars(Supplies::RowToObject($row)) as $prop => $value){ $this->$prop=$value; } return true; @@ -98,8 +99,9 @@ static function GetSupplyCount( $SupplyID ) { $sql = "select sum(Count) as TotalQty from fac_BinContents where SupplyID=" . intval( $SupplyID ); - if ( $row=$dbh->query($sql)->fetch()) { - return $row["TotalQty"]; + $stmt=$dbh->query($sql); + if ($stmt && ($row=$stmt->fetch())) { + return $row["TotalQty"] ?? 0; } else { return 0; } @@ -109,9 +111,12 @@ function GetSuppliesList($indexbyid=false){ $sql="SELECT * FROM fac_Supplies ORDER BY PartNum ASC;"; $supplyList=array(); - foreach($this->query($sql) as $row){ - $index=($indexbyid)?$row['SupplyID']:$row['PartNum']; - $supplyList[$index]=Supplies::RowToObject($row); + $stmt=$this->query($sql); + if($stmt){ + foreach($stmt as $row){ + $index=($indexbyid)?($row['SupplyID'] ?? null):($row['PartNum'] ?? null); + $supplyList[$index]=Supplies::RowToObject($row); + } } return $supplyList; diff --git a/classes/SupplyBin.class.php b/classes/SupplyBin.class.php index 5d4887d6e..8829d2f04 100644 --- a/classes/SupplyBin.class.php +++ b/classes/SupplyBin.class.php @@ -32,13 +32,13 @@ function MakeSafe(){ } function MakeDisplay(){ - $this->Location=stripslashes($this->Location); + $this->Location=stripslashes((string)$this->Location); } static function RowToObject($row){ $bin=New SupplyBin(); - $bin->BinID=$row['BinID']; - $bin->Location=$row['Location']; + $bin->BinID=$row['BinID'] ?? null; + $bin->Location=$row['Location'] ?? null; $bin->MakeDisplay(); return $bin; @@ -59,8 +59,9 @@ function GetBin(){ $sql="SELECT * FROM fac_SupplyBin WHERE BinID=$this->BinID;"; - if($row=$this->query($sql)->fetch()){ - foreach(SupplyBin::RowToObject($row) as $prop => $value){ + $stmt=$this->query($sql); + if($stmt && ($row=$stmt->fetch())){ + foreach(get_object_vars(SupplyBin::RowToObject($row)) as $prop => $value){ $this->$prop=$value; } return true; @@ -108,8 +109,11 @@ function GetBinList(){ $sql="SELECT * FROM fac_SupplyBin ORDER BY Location ASC;"; $binList=array(); - foreach($this->query($sql) as $row){ - $binList[]=SupplyBin::RowToObject($row); + $stmt=$this->query($sql); + if($stmt){ + foreach($stmt as $row){ + $binList[]=SupplyBin::RowToObject($row); + } } return $binList; diff --git a/classes/SwitchInfo.class.php b/classes/SwitchInfo.class.php index 55808348d..bd610b9d5 100644 --- a/classes/SwitchInfo.class.php +++ b/classes/SwitchInfo.class.php @@ -41,10 +41,10 @@ static private function BasicTests($DeviceID){ if($dev->PrimaryIP==""){return false;} // If the device doesn't have an SNMP community set, check and see if we have a global one - $dev->SNMPCommunity=($dev->SNMPCommunity=="")?$config->ParameterArray["SNMPCommunity"]:$dev->SNMPCommunity; + $dev->SNMPCommunity=($dev->SNMPCommunity=="")?($config->ParameterArray["SNMPCommunity"] ?? ''):$dev->SNMPCommunity; // Make this false faster - $dev->SNMPCommunity=trim($dev->SNMPCommunity); + $dev->SNMPCommunity=trim((string)$dev->SNMPCommunity); if($dev->SNMPCommunity==""){return false;} // We've passed all the repeatable tests, return the device object for digging @@ -54,8 +54,8 @@ static private function BasicTests($DeviceID){ // Making an attempt at reducing the lines that I was constantly repeating at a cost of making this a little more convoluted. static private function OSS_SNMP_Lookup($dev,$snmplookup,$portid=null,$baseoid=null){ // This is find out the name of the function that called this to make the error logging more descriptive - $caller=debug_backtrace(); - $caller=$caller[1]['function']; + $caller=debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2); + $caller=$caller[1]['function'] ?? ''; // Since we don't really let the user specify the version right now here's a stop gap // Try the default version of 2c first @@ -69,7 +69,7 @@ static private function OSS_SNMP_Lookup($dev,$snmplookup,$portid=null,$baseoid=n $snmpresult=false; try { - $snmpresult=(is_null($portid))?$snmpHost->useIface()->$snmplookup(true):$snmpHost->get($baseOID.".$portid"); + $snmpresult=(is_null($portid))?$snmpHost->useIface()->$snmplookup(true):$snmpHost->get($baseoid.".$portid"); }catch (Exception $e){ error_log("SwitchInfo::$caller($dev->DeviceID) ".$e->getMessage()); } @@ -92,6 +92,9 @@ static function findFirstPort( $DeviceID ) { $x=array(); $portlist=self::OSS_SNMP_Lookup($dev,"names"); + if(!is_array($portlist)){ + return $portlist; + } foreach($portlist as $index => $portdesc ) { if ( preg_match( "/([0-9]\:|bond|\"[A-Z]|swp|eth|ix|em|e|Ethernet|g|Port-Channel|X|\/)[0]{0,}?[01]$|[01]$/", $portdesc )) { $x[$index] = $portdesc; diff --git a/classes/Tags.class.php b/classes/Tags.class.php index de166b271..3fc743ce2 100644 --- a/classes/Tags.class.php +++ b/classes/Tags.class.php @@ -57,7 +57,7 @@ static function FindID($TagName=null){ } }else{ //No tagname was supplied so kick back an array of all available TagIDs and Names - return $this->FindAll(); + return self::FindAll(); } //everything failed give them nothing return 0; @@ -74,7 +74,7 @@ static function FindName($TagID=null){ } }else{ //No tagname was supplied so kick back an array of all available TagIDs and Names - return $this->FindAll(); + return self::FindAll(); } //everything failed give them nothing return 0; @@ -86,8 +86,11 @@ static function FindAll(){ $sql="SELECT * FROM fac_Tags order by Name ASC"; $tagarray=array(); - foreach($dbh->query($sql) as $row){ - $tagarray[$row['TagID']]=$row['Name']; + $stmt=$dbh->query($sql); + if($stmt){ + foreach($stmt as $row){ + $tagarray[$row['TagID'] ?? null]=$row['Name'] ?? null; + } } return $tagarray; } diff --git a/classes/TemplatePorts.class.php b/classes/TemplatePorts.class.php index 0de638019..c62db38d1 100644 --- a/classes/TemplatePorts.class.php +++ b/classes/TemplatePorts.class.php @@ -52,21 +52,21 @@ function MakeSafe() { } function MakeDisplay(){ - $this->Label=stripslashes(trim($this->Label)); - $this->Notes=stripslashes(trim($this->Notes)); + $this->Label=stripslashes(trim((string)$this->Label)); + $this->Notes=stripslashes(trim((string)$this->Notes)); } static function RowToObject($dbRow){ $tp=new TemplatePorts(); - $tp->TemplateID=$dbRow['TemplateID']; - $tp->PortNumber=$dbRow['PortNumber']; - $tp->Label=$dbRow['Label']; - $tp->MediaID=$dbRow['MediaID']; - $tp->ColorID=$dbRow['ColorID']; - $tp->ConnectorID=$dbRow['ConnectorID']; - $tp->ProtocolID=$dbRow['ProtocolID']; - $tp->RateID=$dbRow['RateID']; - $tp->Notes=$dbRow['Notes']; + $tp->TemplateID=$dbRow['TemplateID'] ?? null; + $tp->PortNumber=$dbRow['PortNumber'] ?? null; + $tp->Label=$dbRow['Label'] ?? null; + $tp->MediaID=$dbRow['MediaID'] ?? null; + $tp->ColorID=$dbRow['ColorID'] ?? null; + $tp->ConnectorID=$dbRow['ConnectorID'] ?? null; + $tp->ProtocolID=$dbRow['ProtocolID'] ?? null; + $tp->RateID=$dbRow['RateID'] ?? null; + $tp->Notes=$dbRow['Notes'] ?? null; $tp->MakeDisplay(); @@ -89,10 +89,11 @@ function getPort(){ $sql="SELECT * FROM fac_TemplatePorts WHERE TemplateID=$this->TemplateID AND PortNumber=$this->PortNumber;"; - if(!$row=$dbh->query($sql)->fetch()){ + $stmt=$dbh->query($sql); + if(!$stmt || !($row=$stmt->fetch())){ return false; }else{ - foreach(TemplatePorts::RowToObject($row) as $prop => $value){ + foreach(get_object_vars(TemplatePorts::RowToObject($row)) as $prop => $value){ $this->$prop=$value; } return true; @@ -106,8 +107,11 @@ function getPorts(){ $sql="SELECT * FROM fac_TemplatePorts WHERE TemplateID=$this->TemplateID ORDER BY PortNumber ASC;"; $ports=array(); - foreach($dbh->query($sql) as $row){ - $ports[$row['PortNumber']]=TemplatePorts::RowToObject($row); + $stmt=$dbh->query($sql); + if($stmt){ + foreach($stmt as $row){ + $ports[$row['PortNumber'] ?? null]=TemplatePorts::RowToObject($row); + } } return $ports; } @@ -124,7 +128,7 @@ function createPort() { if(!$dbh->query($sql)){ $info=$dbh->errorInfo(); - error_log("createPort::PDO Error: {$info[2]} SQL=$sql"); + error_log("createPort::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql"); return false; } @@ -151,7 +155,7 @@ function updatePort() { if(!$dbh->query($sql)){ $info=$dbh->errorInfo(); - error_log("updatePort::PDO Error: {$info[2]} SQL=$sql"); + error_log("updatePort::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql"); return false; } diff --git a/classes/TemplatePowerPorts.class.php b/classes/TemplatePowerPorts.class.php index 46c890680..1116c49dd 100644 --- a/classes/TemplatePowerPorts.class.php +++ b/classes/TemplatePowerPorts.class.php @@ -48,19 +48,19 @@ function MakeSafe() { } function MakeDisplay(){ - $this->Label=stripslashes(trim($this->Label)); - $this->PortNotes=stripslashes(trim($this->PortNotes)); + $this->Label=stripslashes(trim((string)$this->Label)); + $this->PortNotes=stripslashes(trim((string)$this->PortNotes)); } static function RowToObject($dbRow){ - $tp=new TemplatePorts(); - $tp->TemplateID=$dbRow['TemplateID']; - $tp->PortNumber=$dbRow['PortNumber']; - $tp->ConnectorID=$dbRow['ConnectorID']; - $tp->VoltageID=$dbRow['VoltageID']; - $tp->PhaseID=$dbRow['PhaseID']; - $tp->Label=$dbRow['Label']; - $tp->PortNotes=$dbRow['PortNotes']; + $tp=new TemplatePowerPorts(); + $tp->TemplateID=$dbRow['TemplateID'] ?? null; + $tp->PortNumber=$dbRow['PortNumber'] ?? null; + $tp->ConnectorID=$dbRow['ConnectorID'] ?? null; + $tp->VoltageID=$dbRow['VoltageID'] ?? null; + $tp->PhaseID=$dbRow['PhaseID'] ?? null; + $tp->Label=$dbRow['Label'] ?? null; + $tp->PortNotes=$dbRow['PortNotes'] ?? null; $tp->MakeDisplay(); @@ -83,10 +83,11 @@ function getPort(){ $sql="SELECT * FROM fac_TemplatePowerPorts WHERE TemplateID=$this->TemplateID AND PortNumber=$this->PortNumber;"; - if(!$row=$dbh->query($sql)->fetch()){ + $stmt=$dbh->query($sql); + if(!$stmt || !($row=$stmt->fetch())){ return false; }else{ - foreach(TemplatePowerPorts::RowToObject($row) as $prop => $value){ + foreach(get_object_vars(TemplatePowerPorts::RowToObject($row)) as $prop => $value){ $this->$prop=$value; } return true; @@ -100,8 +101,11 @@ function getPorts(){ $sql="SELECT * FROM fac_TemplatePowerPorts WHERE TemplateID=$this->TemplateID ORDER BY PortNumber ASC;"; $ports=array(); - foreach($dbh->query($sql) as $row){ - $ports[$row['PortNumber']]=TemplatePowerPorts::RowToObject($row); + $stmt=$dbh->query($sql); + if($stmt){ + foreach($stmt as $row){ + $ports[$row['PortNumber'] ?? null]=TemplatePowerPorts::RowToObject($row); + } } return $ports; } @@ -119,7 +123,7 @@ function createPort() { if(!$dbh->query($sql)){ $info=$dbh->errorInfo(); - error_log("createPort::PDO Error: {$info[2]} SQL=$sql"); + error_log("createPort::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql"); return false; } @@ -146,7 +150,7 @@ function updatePort() { if(!$dbh->query($sql)){ $info=$dbh->errorInfo(); - error_log("updatePort::PDO Error: {$info[2]} SQL=$sql"); + error_log("updatePort::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql"); return false; } diff --git a/classes/VM.class.php b/classes/VM.class.php index f4784b9e9..e6063d58d 100644 --- a/classes/VM.class.php +++ b/classes/VM.class.php @@ -59,14 +59,14 @@ static function RowToObject($dbRow){ */ $vm=new VM(); - $vm->VMIndex=$dbRow["VMIndex"]; - $vm->DeviceID=$dbRow["DeviceID"]; - $vm->LastUpdated=$dbRow["LastUpdated"]; - $vm->vmID=$dbRow["vmID"]; - $vm->vmName=$dbRow["vmName"]; - $vm->vmState=$dbRow["vmState"]; - $vm->Owner=$dbRow["Owner"]; - $vm->PrimaryContact=$dbRow["PrimaryContact"]; + $vm->VMIndex=$dbRow["VMIndex"] ?? null; + $vm->DeviceID=$dbRow["DeviceID"] ?? null; + $vm->LastUpdated=$dbRow["LastUpdated"] ?? null; + $vm->vmID=$dbRow["vmID"] ?? null; + $vm->vmName=$dbRow["vmName"] ?? null; + $vm->vmState=$dbRow["vmState"] ?? null; + $vm->Owner=$dbRow["Owner"] ?? null; + $vm->PrimaryContact=$dbRow["PrimaryContact"] ?? null; return $vm; } @@ -77,9 +77,12 @@ function search($sql){ $vmList=array(); $vmCount=0; - foreach($dbh->query($sql) as $row){ - $vmList[$vmCount]=VM::RowToObject($row); - $vmCount++; + $stmt=$dbh->query($sql); + if($stmt){ + foreach($stmt as $row){ + $vmList[$vmCount]=VM::RowToObject($row); + $vmCount++; + } } return $vmList; @@ -99,10 +102,11 @@ function GetVMbyIndex() { $sql="SELECT * FROM fac_VMInventory WHERE VMIndex=$this->VMIndex;"; - if(!$vmRow=$dbh->query($sql)->fetch()){ + $stmt=$dbh->query($sql); + if(!$stmt || !($vmRow=$stmt->fetch())){ return false; }else{ - foreach(VM::RowToObject($vmRow) as $param => $value){ + foreach(get_object_vars(VM::RowToObject($vmRow)) as $param => $value){ $this->$param=$value; } return true; @@ -114,7 +118,7 @@ function SearchVM($indexedbyid=false,$loose=false){ $this->MakeSafe(); $sqlextend=""; - foreach($this as $prop => $val){ + foreach(get_object_vars($this) as $prop => $val){ if($val){ extendsql($prop,$val,$sqlextend,$loose); } @@ -123,11 +127,14 @@ function SearchVM($indexedbyid=false,$loose=false){ $sql="SELECT * FROM fac_VMInventory $sqlextend;"; $VMList=array(); - foreach($this->query($sql) as $VMRow){ - if($indexedbyid){ - $VMList[$VMRow["VMIndex"]]=VM::RowToObject($VMRow); - }else{ - $VMList[]=VM::RowToObject($VMRow); + $stmt=$this->query($sql); + if($stmt){ + foreach($stmt as $VMRow){ + if($indexedbyid){ + $VMList[$VMRow["VMIndex"] ?? null]=VM::RowToObject($VMRow); + }else{ + $VMList[]=VM::RowToObject($VMRow); + } } } return $VMList; @@ -138,14 +145,17 @@ function CreateVM() { $this->MakeSafe(); + $lastUpdated=strtotime((string)$this->LastUpdated); + $lastUpdated=($lastUpdated === false) ? 0 : $lastUpdated; + $lastUpdatedSQL=date("Y-m-d H:i:s", $lastUpdated); $sql="INSERT INTO fac_VMInventory (DeviceID,LastUpdated,vmID,vmName,vmState,Owner,PrimaryContact) VALUES - ($this->DeviceID,\"".date("Y-m-d H:i:s", strtotime($this->LastUpdated))."\",$this->vmID, + ($this->DeviceID,\"$lastUpdatedSQL\",$this->vmID, \"".$this->vmName."\",\"".$this->vmState."\",$this->Owner,$this->PrimaryContact);"; if(!$dbh->query($sql)){ $info=$dbh->errorInfo(); - error_log("CreateVM::PDO Error: {$info[2]} SQL=$sql" ); + error_log("CreateVM::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql" ); return false; } return true; @@ -156,14 +166,17 @@ function UpdateVM() { $this->MakeSafe(); - $sql="UPDATE fac_VMInventory SET DeviceID=$this->DeviceID,LastUpdated=\"".date("Y-m-d H:i:s", strtotime($this->LastUpdated))."\",vmID=$this->vmID, + $lastUpdated=strtotime((string)$this->LastUpdated); + $lastUpdated=($lastUpdated === false) ? 0 : $lastUpdated; + $lastUpdatedSQL=date("Y-m-d H:i:s", $lastUpdated); + $sql="UPDATE fac_VMInventory SET DeviceID=$this->DeviceID,LastUpdated=\"$lastUpdatedSQL\",vmID=$this->vmID, vmName=\"".$this->vmName."\",vmState=\"".$this->vmState."\",Owner=$this->Owner,PrimaryContact=$this->PrimaryContact WHERE VMIndex=$this->VMIndex;"; if(!$dbh->query($sql)){ $info=$dbh->errorInfo(); - error_log("UpdateVM::PDO Error: {$info[2]} SQL=$sql" ); + error_log("UpdateVM::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql" ); return false; } return true; @@ -179,7 +192,7 @@ function DeleteVM() { if(!$dbh->query($sql)){ $info=$dbh->errorInfo(); - error_log("DeleteVM::PDO Error: {$info[2]} SQL=$sql" ); + error_log("DeleteVM::PDO Error: " . ($info[2] ?? 'Unknown error') . " SQL=$sql" ); return false; } return true; diff --git a/classes/Zone.class.php b/classes/Zone.class.php index d9022369e..c0d237413 100644 --- a/classes/Zone.class.php +++ b/classes/Zone.class.php @@ -48,7 +48,7 @@ function MakeDisplay(){ } static function RowToObject($row){ - $zone=New Zone(); + $zone=new Zone(); $zone->ZoneID=$row["ZoneID"]; $zone->DataCenterID=$row["DataCenterID"]; $zone->Description=$row["Description"]; @@ -192,7 +192,8 @@ function GetZone(){ $sql="SELECT * FROM fac_Zone WHERE ZoneID=$this->ZoneID;"; if($row=$this->query($sql)->fetch()){ - foreach(Zone::RowToObject($row) as $prop => $value){ + $tmp = Zone::RowToObject($row); + foreach (get_object_vars($tmp) as $prop => $value) { $this->$prop=$value; } return true; @@ -296,8 +297,8 @@ function GetZoneStatistics(){ function Search($indexedbyid=false,$loose=false){ $o=new stdClass(); // Store any values that have been added before we make them safe - foreach($this as $prop => $val){ - if(isset($val)){ + foreach (get_object_vars($this) as $prop => $val) { + if ($val !== null) { $o->$prop=$val; } } diff --git a/refresh_idp_metadata.php b/refresh_idp_metadata.php index d2951002f..cc2c4fbac 100644 --- a/refresh_idp_metadata.php +++ b/refresh_idp_metadata.php @@ -21,7 +21,7 @@ error_log( "SAMLidpx509cert updated to " . $IdPSettings['idp']['x509cert']); } // Only set the SLS URL if it exists in the metadata - if ( array_key_exists( "singleLogoutService", $IdPSettings["idp"] && $config->ParameterArray["SAMLidpslsURL"] != $IdPSettings['idp']['singleLogoutService']['url'] ) { + if ( array_key_exists( "singleLogoutService", $IdPSettings["idp"]) && $config->ParameterArray["SAMLidpslsURL"] != $IdPSettings['idp']['singleLogoutService']['url'] ) { $config->ParameterArray["SAMLidpslsURL"] = $IdPSettings['idp']['singleLogoutService']['url']; error_log( "SAMLidpslsURL updated to " . $IdPSettings['idp']['singleLogoutService']['url']); }
%s%s%s%s%s