Set('trigger_id', $oTrigger->GetKey());
$oLog->Set('action_id', $this->GetKey());
$oLog->Set('object_id', $aContextArgs['this->object()']->GetKey());
- $oLog->Set('object_class', get_class($aContextArgs['this->object()']));
+ $oLog->Set('object_class', get_class($aContextArgs['this->object()']));
// Must be inserted now so that it gets a valid id that will make the link
// between an eventual asynchronous task (queued) and the log
$oLog->DBInsertNoReload();
diff --git a/core/attributedef.class.inc.php b/core/attributedef.class.inc.php
index fcc2c3cb1..808ad1ffa 100644
--- a/core/attributedef.class.inc.php
+++ b/core/attributedef.class.inc.php
@@ -1,4 +1,5 @@
m_proposedValue)) {
+ if (is_object($this->m_proposedValue)) {
if ($this->m_proposedValue instanceof ReportValue) {
return $this->m_proposedValue->GetAsCSV($bLocalizedValues, ',', '"');
}
- throw new Exception('Unexpected class : '. get_class($this->m_proposedValue));
+ throw new Exception('Unexpected class : '.get_class($this->m_proposedValue));
}
return $this->m_proposedValue;
}
@@ -60,12 +60,11 @@ abstract class CellChangeSpec
if ($this->m_proposedValue instanceof ReportValue) {
return $this->m_proposedValue->GetAsHTML($bLocalizedValues);
}
- throw new Exception('Unexpected class : '. get_class($this->m_proposedValue));
+ throw new Exception('Unexpected class : '.get_class($this->m_proposedValue));
}
return utils::EscapeHtml($this->m_proposedValue);
}
-
/**
* @since 3.1.0 N°5305
*/
@@ -84,7 +83,8 @@ abstract class CellChangeSpec
*/
public function GetCLIValueAndDescription(): string
{
- return sprintf("%s%s",
+ return sprintf(
+ "%s%s",
$this->GetCLIValue(),
$this->GetDescription()
);
@@ -93,7 +93,6 @@ abstract class CellChangeSpec
abstract public function GetDescription();
}
-
class CellStatus_Void extends CellChangeSpec
{
public function GetDescription()
@@ -139,20 +138,18 @@ class CellStatus_Issue extends CellStatus_Modify
if (is_null($this->m_proposedValue)) {
return Dict::Format('UI:CSVReport-Value-SetIssue');
}
- return Dict::Format('UI:CSVReport-Value-ChangeIssue',$this->m_proposedValue);
+ return Dict::Format('UI:CSVReport-Value-ChangeIssue', $this->m_proposedValue);
}
public function GetHTMLValue(bool $bLocalizedValues = false): string
{
- if (is_null($this->m_proposedValue))
- {
+ if (is_null($this->m_proposedValue)) {
return Dict::Format('UI:CSVReport-Value-SetIssue');
}
- if ($this->m_proposedValue instanceof ReportValue)
- {
+ if ($this->m_proposedValue instanceof ReportValue) {
return Dict::Format('UI:CSVReport-Value-ChangeIssue', $this->m_proposedValue->GetAsHTML($bLocalizedValues));
}
- return Dict::Format('UI:CSVReport-Value-ChangeIssue',utils::EscapeHtml($this->m_proposedValue));
+ return Dict::Format('UI:CSVReport-Value-ChangeIssue', utils::EscapeHtml($this->m_proposedValue));
}
public function GetDescription()
@@ -164,7 +161,8 @@ class CellStatus_Issue extends CellStatus_Modify
*/
public function GetCLIValueAndDescription(): string
{
- return sprintf("%s. %s",
+ return sprintf(
+ "%s. %s",
$this->GetCLIValue(),
$this->GetDescription()
);
@@ -244,7 +242,8 @@ class CellStatus_SearchIssue extends CellStatus_Issue
*/
public function GetSearchLinkUrl()
{
- return sprintf("UI.php?operation=search&filter=%s",
+ return sprintf(
+ "UI.php?operation=search&filter=%s",
rawurlencode($this->sSerializedSearch ?? "")
);
}
@@ -255,7 +254,8 @@ class CellStatus_SearchIssue extends CellStatus_Issue
*/
public function GetAllowedValuesLinkUrl(): ?string
{
- return sprintf("UI.php?operation=search&filter=%s",
+ return sprintf(
+ "UI.php?operation=search&filter=%s",
rawurlencode($this->sAllowedValuesSearch ?? "")
);
}
@@ -284,7 +284,9 @@ class ReportValue
* @param string $sAttCode
* @param bool $bOriginal
*/
- public function __construct(protected DBObject $oObject, protected string $sAttCode, protected bool $bOriginal){}
+ public function __construct(protected DBObject $oObject, protected string $sAttCode, protected bool $bOriginal)
+ {
+ }
public function GetAsHTML(bool $bLocalizedValues)
{
@@ -293,7 +295,8 @@ class ReportValue
}
return $this->oObject->GetAsHTML($this->sAttCode, $bLocalizedValues);
}
- public function GetAsCSV (bool $bLocalizedValues, string $sCsvSep, string $sCsvDelimiter) {
+ public function GetAsCSV(bool $bLocalizedValues, string $sCsvSep, string $sCsvDelimiter)
+ {
if ($this->bOriginal) {
return $this->oObject->GetOriginalAsCSV($this->sAttCode, $sCsvSep, $sCsvDelimiter, $bLocalizedValues);
}
@@ -301,7 +304,6 @@ class ReportValue
}
}
-
class CellStatus_Ambiguous extends CellStatus_Issue
{
protected $m_iCount;
@@ -338,13 +340,13 @@ class CellStatus_Ambiguous extends CellStatus_Issue
*/
public function GetSearchLinkUrl()
{
- return sprintf("UI.php?operation=search&filter=%s",
+ return sprintf(
+ "UI.php?operation=search&filter=%s",
rawurlencode($this->sSerializedSearch ?? "")
);
}
}
-
/**
* RowStatus
* A series of classes, keeping the information about a given row: could it be changed or not (and why)?
@@ -486,22 +488,18 @@ class BulkChange
$this->m_aOnDisappear = $aOnDisappear;
$this->m_sDateFormat = $sDateFormat;
$this->m_bLocalizedValues = $bLocalize;
- $this->m_aExtKeysMappingCache = array();
- $this->m_iNbCol =$iNbCol;
+ $this->m_aExtKeysMappingCache = [];
+ $this->m_iNbCol = $iNbCol;
}
protected function ResolveExternalKey($aRowData, $sAttCode, &$aResults)
{
$oExtKey = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
$oReconFilter = new DBObjectSearch($oExtKey->GetTargetClass());
- foreach ($this->m_aExtKeys[$sAttCode] as $sReconKeyAttCode => $iCol)
- {
- if ($sReconKeyAttCode == 'id')
- {
+ foreach ($this->m_aExtKeys[$sAttCode] as $sReconKeyAttCode => $iCol) {
+ if ($sReconKeyAttCode == 'id') {
$value = (int) $aRowData[$iCol];
- }
- else
- {
+ } else {
// The foreign attribute is one of our reconciliation key
$oForeignAtt = MetaModel::GetAttributeDef($oExtKey->GetTargetClass(), $sReconKeyAttCode);
$value = $oForeignAtt->MakeValueFromString($aRowData[$iCol], $this->m_bLocalizedValues);
@@ -512,18 +510,16 @@ class BulkChange
$oExtObjects = new CMDBObjectSet($oReconFilter);
$aKeys = $oExtObjects->ToArray();
- return array($oReconFilter, $aKeys);
+ return [$oReconFilter, $aKeys];
}
// Returns true if the CSV data specifies that the external key must be left undefined
protected function IsNullExternalKeySpec($aRowData, $sAttCode)
{
//$oExtKey = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
- foreach ($this->m_aExtKeys[$sAttCode] as $sForeignAttCode => $iCol)
- {
+ foreach ($this->m_aExtKeys[$sAttCode] as $sForeignAttCode => $iCol) {
// The foreign attribute is one of our reconciliation key
- if (isset($aRowData[$iCol]) && strlen($aRowData[$iCol]) > 0)
- {
+ if (isset($aRowData[$iCol]) && strlen($aRowData[$iCol]) > 0) {
return false;
}
}
@@ -544,51 +540,39 @@ class BulkChange
*/
protected function PrepareObject(&$oTargetObj, $aRowData, &$aErrors)
{
- $aResults = array();
- $aErrors = array();
+ $aResults = [];
+ $aErrors = [];
// External keys reconciliation
//
- foreach($this->m_aExtKeys as $sAttCode => $aReconKeys)
- {
+ foreach ($this->m_aExtKeys as $sAttCode => $aReconKeys) {
// Skip external keys used for the reconciliation process
// if (!array_key_exists($sAttCode, $this->m_aAttList)) continue;
$oExtKey = MetaModel::GetAttributeDef(get_class($oTargetObj), $sAttCode);
- if ($this->IsNullExternalKeySpec($aRowData, $sAttCode))
- {
- foreach ($aReconKeys as $sReconKeyAttCode => $iCol)
- {
+ if ($this->IsNullExternalKeySpec($aRowData, $sAttCode)) {
+ foreach ($aReconKeys as $sReconKeyAttCode => $iCol) {
// Default reporting
// $aRowData[$iCol] is always null
$aResults[$iCol] = new CellStatus_Void($aRowData[$iCol]);
}
- if ($oExtKey->IsNullAllowed())
- {
+ if ($oExtKey->IsNullAllowed()) {
$oTargetObj->Set($sAttCode, $oExtKey->GetNullValue());
- $aResults[$sAttCode]= new CellStatus_Void($oExtKey->GetNullValue());
- }
- else
- {
+ $aResults[$sAttCode] = new CellStatus_Void($oExtKey->GetNullValue());
+ } else {
$aErrors[$sAttCode] = Dict::S('UI:CSVReport-Value-Issue-Null');
- $aResults[$sAttCode]= new CellStatus_Issue(null, $oTargetObj->Get($sAttCode), Dict::S('UI:CSVReport-Value-Issue-Null'));
+ $aResults[$sAttCode] = new CellStatus_Issue(null, $oTargetObj->Get($sAttCode), Dict::S('UI:CSVReport-Value-Issue-Null'));
}
- }
- else
- {
+ } else {
$oReconFilter = new DBObjectSearch($oExtKey->GetTargetClass());
- $aCacheKeys = array();
- foreach ($aReconKeys as $sReconKeyAttCode => $iCol)
- {
+ $aCacheKeys = [];
+ foreach ($aReconKeys as $sReconKeyAttCode => $iCol) {
// The foreign attribute is one of our reconciliation key
- if ($sReconKeyAttCode == 'id')
- {
+ if ($sReconKeyAttCode == 'id') {
$value = $aRowData[$iCol];
- }
- else
- {
+ } else {
$oForeignAtt = MetaModel::GetAttributeDef($oExtKey->GetTargetClass(), $sReconKeyAttCode);
$value = $oForeignAtt->MakeValueFromString($aRowData[$iCol], $this->m_bLocalizedValues);
}
@@ -599,37 +583,31 @@ class BulkChange
$sCacheKey = implode('_|_', $aCacheKeys); // Unique key for this query...
$iForeignKey = null;
// TODO: check if *too long* keys can lead to collisions... and skip the cache in such a case...
- if (!array_key_exists($sAttCode, $this->m_aExtKeysMappingCache))
- {
- $this->m_aExtKeysMappingCache[$sAttCode] = array();
+ if (!array_key_exists($sAttCode, $this->m_aExtKeysMappingCache)) {
+ $this->m_aExtKeysMappingCache[$sAttCode] = [];
}
- if (array_key_exists($sCacheKey, $this->m_aExtKeysMappingCache[$sAttCode]))
- {
+ if (array_key_exists($sCacheKey, $this->m_aExtKeysMappingCache[$sAttCode])) {
// Cache hit
$iObjectFoundCount = $this->m_aExtKeysMappingCache[$sAttCode][$sCacheKey]['c'];
$iForeignKey = $this->m_aExtKeysMappingCache[$sAttCode][$sCacheKey]['k'];
// Record the hit
$this->m_aExtKeysMappingCache[$sAttCode][$sCacheKey]['h']++;
- }
- else
- {
+ } else {
// Cache miss, let's initialize it
$oExtObjects = new CMDBObjectSet($oReconFilter);
$iObjectFoundCount = $oExtObjects->Count();
- if ($iObjectFoundCount == 1)
- {
+ if ($iObjectFoundCount == 1) {
$oForeignObj = $oExtObjects->Fetch();
$iForeignKey = $oForeignObj->GetKey();
}
- $this->m_aExtKeysMappingCache[$sAttCode][$sCacheKey] = array(
+ $this->m_aExtKeysMappingCache[$sAttCode][$sCacheKey] = [
'c' => $iObjectFoundCount,
'k' => $iForeignKey,
'oql' => $oReconFilter->ToOql(),
'h' => 0, // number of hits on this cache entry
- );
+ ];
}
- switch($iObjectFoundCount)
- {
+ switch ($iObjectFoundCount) {
case 0:
$oCellStatus_SearchIssue = $this->GetCellSearchIssue($oReconFilter);
$aResults[$sAttCode] = $oCellStatus_SearchIssue;
@@ -643,41 +621,32 @@ class BulkChange
default:
$aErrors[$sAttCode] = Dict::Format('UI:CSVReport-Value-Issue-FoundMany', $iObjectFoundCount);
- $aResults[$sAttCode]= new CellStatus_Ambiguous($oTargetObj->Get($sAttCode), $iObjectFoundCount, $oReconFilter->serialize());
+ $aResults[$sAttCode] = new CellStatus_Ambiguous($oTargetObj->Get($sAttCode), $iObjectFoundCount, $oReconFilter->serialize());
}
}
// Report
- if (!array_key_exists($sAttCode, $aResults))
- {
+ if (!array_key_exists($sAttCode, $aResults)) {
$iForeignObj = $oTargetObj->Get($sAttCode);
- if (array_key_exists($sAttCode, $oTargetObj->ListChanges()))
- {
- if ($oTargetObj->IsNew())
- {
- $aResults[$sAttCode]= new CellStatus_Void($iForeignObj);
- }
- else
- {
- $aResults[$sAttCode]= new CellStatus_Modify($iForeignObj, $oTargetObj->GetOriginal($sAttCode));
- foreach ($aReconKeys as $sReconKeyAttCode => $iCol)
- {
+ if (array_key_exists($sAttCode, $oTargetObj->ListChanges())) {
+ if ($oTargetObj->IsNew()) {
+ $aResults[$sAttCode] = new CellStatus_Void($iForeignObj);
+ } else {
+ $aResults[$sAttCode] = new CellStatus_Modify($iForeignObj, $oTargetObj->GetOriginal($sAttCode));
+ foreach ($aReconKeys as $sReconKeyAttCode => $iCol) {
// Report the change on reconciliation values as well
$aResults[$iCol] = new CellStatus_Modify($aRowData[$iCol]);
}
}
- }
- else
- {
- $aResults[$sAttCode]= new CellStatus_Void($iForeignObj);
+ } else {
+ $aResults[$sAttCode] = new CellStatus_Void($iForeignObj);
}
}
}
// Set the object attributes
//
- foreach ($this->m_aAttList as $sAttCode => $iCol)
- {
+ foreach ($this->m_aAttList as $sAttCode => $iCol) {
// skip the private key, if any
if (($sAttCode == 'id') || ($sAttCode == 'friendlyname')) {
continue;
@@ -690,47 +659,34 @@ class BulkChange
continue;
}
- $aReasons = array();
+ $aReasons = [];
$iFlags = ($oTargetObj->IsNew())
? $oTargetObj->GetInitialStateAttributeFlags($sAttCode, $aReasons)
: $oTargetObj->GetAttributeFlags($sAttCode, $aReasons);
if ((($iFlags & OPT_ATT_READONLY) == OPT_ATT_READONLY) && ($oTargetObj->Get($sAttCode) != $oAttDef->MakeValueFromString($aRowData[$iCol], $this->m_bLocalizedValues))) {
$aErrors[$sAttCode] = Dict::Format('UI:CSVReport-Value-Issue-Readonly', $sAttCode, $oTargetObj->Get($sAttCode), $aRowData[$iCol]);
- }
- else if ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect())
- {
- try
- {
+ } elseif ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect()) {
+ try {
$oSet = $oAttDef->MakeValueFromString($aRowData[$iCol], $this->m_bLocalizedValues);
$oTargetObj->Set($sAttCode, $oSet);
- }
- catch(CoreException $e)
- {
+ } catch (CoreException $e) {
$aErrors[$sAttCode] = Dict::Format('UI:CSVReport-Value-Issue-Format', $e->getMessage());
}
- }
- else
- {
+ } else {
$value = $oAttDef->MakeValueFromString($aRowData[$iCol], $this->m_bLocalizedValues);
- if (is_null($value) && (strlen($aRowData[$iCol]) > 0))
- {
- if ($oAttDef instanceof AttributeEnum || $oAttDef instanceof AttributeTagSet){
+ if (is_null($value) && (strlen($aRowData[$iCol]) > 0)) {
+ if ($oAttDef instanceof AttributeEnum || $oAttDef instanceof AttributeTagSet) {
/** @var AttributeDefinition $oAttributeDefinition */
$oAttributeDefinition = $oAttDef;
$aErrors[$sAttCode] = Dict::Format('UI:CSVReport-Value-Issue-AllowedValues', $sAttCode, implode(',', $oAttributeDefinition->GetAllowedValues()));
} else {
$aErrors[$sAttCode] = Dict::Format('UI:CSVReport-Value-Issue-NoMatch', $sAttCode);
}
- }
- else
- {
+ } else {
$res = $oTargetObj->CheckValue($sAttCode, $value);
- if ($res === true)
- {
+ if ($res === true) {
$oTargetObj->Set($sAttCode, $value);
- }
- else
- {
+ } else {
// $res is a string with the error description
$aErrors[$sAttCode] = Dict::Format('UI:CSVReport-Value-Issue-Unknown', $sAttCode, $res);
}
@@ -743,30 +699,25 @@ class BulkChange
$aChangedFields = $oTargetObj->ListChanges();
foreach ($this->m_aAttList as $sAttCode => $iCol) {
if ($sAttCode == 'id') {
- $aResults[$iCol]= new CellStatus_Void($aRowData[$iCol]);
- }
- else {
+ $aResults[$iCol] = new CellStatus_Void($aRowData[$iCol]);
+ } else {
$sCurValue = new ReportValue($oTargetObj, $sAttCode, false);
$sOrigValue = new ReportValue($oTargetObj, $sAttCode, true);
if (isset($aErrors[$sAttCode])) {
- $aResults[$iCol]= new CellStatus_Issue($aRowData[$iCol], $sOrigValue, $aErrors[$sAttCode]);
- }
- elseif (array_key_exists($sAttCode, $aChangedFields)){
- if ($oTargetObj->IsNew()) {
- $aResults[$iCol]= new CellStatus_Void($sCurValue);
+ $aResults[$iCol] = new CellStatus_Issue($aRowData[$iCol], $sOrigValue, $aErrors[$sAttCode]);
+ } elseif (array_key_exists($sAttCode, $aChangedFields)) {
+ if ($oTargetObj->IsNew()) {
+ $aResults[$iCol] = new CellStatus_Void($sCurValue);
+ } else {
+ $aResults[$iCol] = new CellStatus_Modify($sCurValue, $sOrigValue);
}
- else {
- $aResults[$iCol]= new CellStatus_Modify($sCurValue, $sOrigValue);
- }
- }
- else {
+ } else {
// By default... nothing happens
$oAttDef = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
if ($oAttDef instanceof AttributeDateTime) {
- $aResults[$iCol]= new CellStatus_Void($oAttDef->GetFormat()->Format($aRowData[$iCol]));
- }
- else {
- $aResults[$iCol]= new CellStatus_Void($aRowData[$iCol]);
+ $aResults[$iCol] = new CellStatus_Void($oAttDef->GetFormat()->Format($aRowData[$iCol]));
+ } else {
+ $aResults[$iCol] = new CellStatus_Void($aRowData[$iCol]);
}
}
}
@@ -775,8 +726,7 @@ class BulkChange
// Checks
//
$res = $oTargetObj->CheckConsistency();
- if ($res !== true)
- {
+ if ($res !== true) {
// $res contains the error description
$aErrors["GLOBAL"] = Dict::Format('UI:CSVReport-Row-Issue-Inconsistent', $res);
}
@@ -797,7 +747,8 @@ class BulkChange
*
* @since 3.1.0 N°5305
*/
- protected function GetCellSearchIssue($oDbSearchWithConditions) : CellStatus_SearchIssue {
+ protected function GetCellSearchIssue($oDbSearchWithConditions): CellStatus_SearchIssue
+ {
//current search with current permissions did not match
//let's search why and give some more feedback to the user
@@ -820,36 +771,38 @@ class BulkChange
$iCurrentUserRightsObjectCount = $oExtObjectSetWithCurrentUserPermissions->Count();
$sAllowedValuesOql = $oDbSearchWithoutAnyCondition->serialize();
- if ($iCurrentUserRightsObjectCount === 0){
+ if ($iCurrentUserRightsObjectCount === 0) {
// No objects visible by current user
$sReason = Dict::Format('UI:CSVReport-Value-NoMatch-NoObject-ForCurrentUser', $oDbSearchWithConditions->GetClass());
return new CellStatus_SearchIssue($sSerializedSearch, $sReason);
}
- try{
+ try {
$aDisplayedAllowedValues = [];
// Possibles values are displayed to UI user. we have to limit the amount of displayed values
$oExtObjectSetWithCurrentUserPermissions->SetLimit(4);
- for($i = 0; $i < 3; $i++){
+ for ($i = 0; $i < 3; $i++) {
/** @var DBObject $oVisibleObject */
$oVisibleObject = $oExtObjectSetWithCurrentUserPermissions->Fetch();
- if (is_null($oVisibleObject)){
+ if (is_null($oVisibleObject)) {
break;
}
$aCurrentAllowedValueFields = [];
- foreach ($oDbSearchWithConditions->GetInternalParams() as $sForeignAttCode => $sValue){
+ foreach ($oDbSearchWithConditions->GetInternalParams() as $sForeignAttCode => $sValue) {
$aCurrentAllowedValueFields[] = $oVisibleObject->Get($sForeignAttCode);
}
$aDisplayedAllowedValues[] = implode(" ", $aCurrentAllowedValueFields);
}
$allowedValues = implode(", ", $aDisplayedAllowedValues);
- if ($oExtObjectSetWithCurrentUserPermissions->Count() > 3){
+ if ($oExtObjectSetWithCurrentUserPermissions->Count() > 3) {
$allowedValues .= "...";
}
- } catch(Exception $e) {
- IssueLog::Error("failure during CSV import when fetching few visible objects: ", null,
+ } catch (Exception $e) {
+ IssueLog::Error(
+ "failure during CSV import when fetching few visible objects: ",
+ null,
[ 'target_class' => $oDbSearchWithConditions->GetClass(), 'criteria' => $oDbSearchWithConditions->GetCriteria(), 'message' => $e->getMessage()]
);
$sReason = Dict::Format('UI:CSVReport-Value-NoMatch-NoObject-ForCurrentUser', $oDbSearchWithConditions->GetClass());
@@ -865,39 +818,35 @@ class BulkChange
// No match. This is not linked to any right issue
// Possible values: DD,DD
$aCurrentValueFields = [];
- foreach ($oDbSearchWithConditions->GetInternalParams() as $sValue){
+ foreach ($oDbSearchWithConditions->GetInternalParams() as $sValue) {
$aCurrentValueFields[] = $sValue;
}
- $value =implode(" ", $aCurrentValueFields);
+ $value = implode(" ", $aCurrentValueFields);
$sReason = Dict::Format('UI:CSVReport-Value-NoMatch', $value);
return new CellStatus_SearchIssue($sSerializedSearch, $sReason, $oDbSearchWithConditions->GetClass(), $allowedValues, $sAllowedValuesOql);
}
protected function PrepareMissingObject(&$oTargetObj, &$aErrors)
{
- $aResults = array();
- $aErrors = array();
+ $aResults = [];
+ $aErrors = [];
// External keys
//
- foreach($this->m_aExtKeys as $sAttCode => $aKeyConfig)
- {
+ foreach ($this->m_aExtKeys as $sAttCode => $aKeyConfig) {
//$oExtKey = MetaModel::GetAttributeDef(get_class($oTargetObj), $sAttCode);
- $aResults[$sAttCode]= new CellStatus_Void($oTargetObj->Get($sAttCode));
+ $aResults[$sAttCode] = new CellStatus_Void($oTargetObj->Get($sAttCode));
- foreach ($aKeyConfig as $sForeignAttCode => $iCol)
- {
+ foreach ($aKeyConfig as $sForeignAttCode => $iCol) {
$aResults[$iCol] = new CellStatus_Void('?');
}
}
// Update attributes
//
- foreach($this->m_aOnDisappear as $sAttCode => $value)
- {
- if (!MetaModel::IsValidAttCode(get_class($oTargetObj), $sAttCode))
- {
- throw new BulkChangeException('Invalid attribute code', array('class' => get_class($oTargetObj), 'attcode' => $sAttCode));
+ foreach ($this->m_aOnDisappear as $sAttCode => $value) {
+ if (!MetaModel::IsValidAttCode(get_class($oTargetObj), $sAttCode)) {
+ throw new BulkChangeException('Invalid attribute code', ['class' => get_class($oTargetObj), 'attcode' => $sAttCode]);
}
$oTargetObj->Set($sAttCode, $value);
}
@@ -905,61 +854,46 @@ class BulkChange
// Reporting on fields
//
$aChangedFields = $oTargetObj->ListChanges();
- foreach ($this->m_aAttList as $sAttCode => $iCol)
- {
- if ($sAttCode == 'id')
- {
- $aResults[$iCol]= new CellStatus_Void($oTargetObj->GetKey());
+ foreach ($this->m_aAttList as $sAttCode => $iCol) {
+ if ($sAttCode == 'id') {
+ $aResults[$iCol] = new CellStatus_Void($oTargetObj->GetKey());
}
- if (array_key_exists($sAttCode, $aChangedFields))
- {
- $aResults[$iCol]= new CellStatus_Modify($oTargetObj->Get($sAttCode), $oTargetObj->GetOriginal($sAttCode));
- }
- else
- {
+ if (array_key_exists($sAttCode, $aChangedFields)) {
+ $aResults[$iCol] = new CellStatus_Modify($oTargetObj->Get($sAttCode), $oTargetObj->GetOriginal($sAttCode));
+ } else {
// By default... nothing happens
- $aResults[$iCol]= new CellStatus_Void($oTargetObj->Get($sAttCode));
+ $aResults[$iCol] = new CellStatus_Void($oTargetObj->Get($sAttCode));
}
}
// Checks
//
$res = $oTargetObj->CheckConsistency();
- if ($res !== true)
- {
+ if ($res !== true) {
// $res contains the error description
$aErrors["GLOBAL"] = Dict::Format('UI:CSVReport-Row-Issue-Inconsistent', $res);
}
return $aResults;
}
-
protected function CreateObject(&$aResult, $iRow, $aRowData, CMDBChange $oChange = null)
{
$oTargetObj = MetaModel::NewObject($this->m_sClass);
// Populate the cache for hierarchical keys (only if in verify mode)
- if (is_null($oChange))
- {
+ if (is_null($oChange)) {
// 1. determine if a hierarchical key exists
- foreach($this->m_aExtKeys as $sAttCode => $aKeyConfig)
- {
+ foreach ($this->m_aExtKeys as $sAttCode => $aKeyConfig) {
$oExtKey = MetaModel::GetAttributeDef(get_class($oTargetObj), $sAttCode);
- if (!$this->IsNullExternalKeySpec($aRowData, $sAttCode) && MetaModel::IsParentClass(get_class($oTargetObj), $this->m_sClass))
- {
+ if (!$this->IsNullExternalKeySpec($aRowData, $sAttCode) && MetaModel::IsParentClass(get_class($oTargetObj), $this->m_sClass)) {
// 2. Populate the cache for further checks
- $aCacheKeys = array();
- foreach ($aKeyConfig as $sForeignAttCode => $iCol)
- {
+ $aCacheKeys = [];
+ foreach ($aKeyConfig as $sForeignAttCode => $iCol) {
// The foreign attribute is one of our reconciliation key
- if ($sForeignAttCode == 'id')
- {
+ if ($sForeignAttCode == 'id') {
$value = $aRowData[$iCol];
- }
- else
- {
- if (!isset($this->m_aAttList[$sForeignAttCode]) || !isset($aRowData[$this->m_aAttList[$sForeignAttCode]]))
- {
+ } else {
+ if (!isset($this->m_aAttList[$sForeignAttCode]) || !isset($aRowData[$this->m_aAttList[$sForeignAttCode]])) {
// the key is not in the import
break 2;
}
@@ -968,20 +902,19 @@ class BulkChange
$aCacheKeys[] = $value;
}
$sCacheKey = implode('_|_', $aCacheKeys); // Unique key for this query...
- $this->m_aExtKeysMappingCache[$sAttCode][$sCacheKey] = array(
+ $this->m_aExtKeysMappingCache[$sAttCode][$sCacheKey] = [
'c' => 1,
'k' => -1,
'oql' => '',
'h' => 0, // number of hits on this cache entry
- );
+ ];
}
}
}
$aResult[$iRow] = $this->PrepareObject($oTargetObj, $aRowData, $aErrors);
- if (count($aErrors) > 0)
- {
+ if (count($aErrors) > 0) {
$sErrors = implode(', ', $aErrors);
$aResult[$iRow]["__STATUS__"] = new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-Attribute'));
//__ERRORS__ used by tests only
@@ -990,19 +923,15 @@ class BulkChange
}
// Check that any external key will have a value proposed
- $aMissingKeys = array();
- foreach (MetaModel::GetExternalKeys($this->m_sClass) as $sExtKeyAttCode => $oExtKey)
- {
- if (!$oExtKey->IsNullAllowed())
- {
- if (!array_key_exists($sExtKeyAttCode, $this->m_aExtKeys) && !array_key_exists($sExtKeyAttCode, $this->m_aAttList))
- {
+ $aMissingKeys = [];
+ foreach (MetaModel::GetExternalKeys($this->m_sClass) as $sExtKeyAttCode => $oExtKey) {
+ if (!$oExtKey->IsNullAllowed()) {
+ if (!array_key_exists($sExtKeyAttCode, $this->m_aExtKeys) && !array_key_exists($sExtKeyAttCode, $this->m_aAttList)) {
$aMissingKeys[] = $oExtKey->GetLabel();
}
}
}
- if (count($aMissingKeys) > 0)
- {
+ if (count($aMissingKeys) > 0) {
$sMissingKeys = implode(', ', $aMissingKeys);
$aResult[$iRow]["__STATUS__"] = new RowStatus_Issue(Dict::Format('UI:CSVReport-Row-Issue-MissingExtKey', $sMissingKeys));
return $oTargetObj;
@@ -1010,12 +939,9 @@ class BulkChange
// Optionally record the results
//
- if ($oChange)
- {
+ if ($oChange) {
$newID = $oTargetObj->DBInsert();
- }
- else
- {
+ } else {
$newID = 0;
}
@@ -1048,8 +974,7 @@ class BulkChange
$aResult[$iRow]["finalclass"] = get_class($oTargetObj);
$aResult[$iRow]["id"] = new CellStatus_Void($oTargetObj->GetKey());
- if (count($aErrors) > 0)
- {
+ if (count($aErrors) > 0) {
$sErrors = implode(', ', $aErrors);
$aResult[$iRow]["__STATUS__"] = new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-Attribute'));
//__ERRORS__ used by tests only
@@ -1058,26 +983,19 @@ class BulkChange
}
$aChangedFields = $oTargetObj->ListChanges();
- if (count($aChangedFields) > 0)
- {
+ if (count($aChangedFields) > 0) {
$aResult[$iRow]["__STATUS__"] = new RowStatus_Modify(count($aChangedFields));
// Optionaly record the results
//
- if ($oChange)
- {
- try
- {
+ if ($oChange) {
+ try {
$oTargetObj->DBUpdate();
- }
- catch(CoreException $e)
- {
+ } catch (CoreException $e) {
$aResult[$iRow]["__STATUS__"] = new RowStatus_Issue($e->getMessage());
}
}
- }
- else
- {
+ } else {
$aResult[$iRow]["__STATUS__"] = new RowStatus_NoChange();
}
}
@@ -1099,8 +1017,7 @@ class BulkChange
$aResult[$iRow]["finalclass"] = get_class($oTargetObj);
$aResult[$iRow]["id"] = new CellStatus_Void($oTargetObj->GetKey());
- if (count($aErrors) > 0)
- {
+ if (count($aErrors) > 0) {
$sErrors = implode(', ', $aErrors);
$aResult[$iRow]["__STATUS__"] = new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-Attribute'));
//__ERRORS__ used by tests only
@@ -1109,34 +1026,26 @@ class BulkChange
}
$aChangedFields = $oTargetObj->ListChanges();
- if (count($aChangedFields) > 0)
- {
+ if (count($aChangedFields) > 0) {
$aResult[$iRow]["__STATUS__"] = new RowStatus_Disappeared(count($aChangedFields));
// Optionaly record the results
//
- if ($oChange)
- {
- try
- {
+ if ($oChange) {
+ try {
$oTargetObj->DBUpdate();
- }
- catch(CoreException $e)
- {
+ } catch (CoreException $e) {
$aResult[$iRow]["__STATUS__"] = new RowStatus_Issue($e->getMessage());
}
}
- }
- else
- {
+ } else {
$aResult[$iRow]["__STATUS__"] = new RowStatus_Disappeared(0);
}
}
public function Process(CMDBChange $oChange = null)
{
- if ($oChange)
- {
+ if ($oChange) {
CMDBObject::SetCurrentChange($oChange);
}
@@ -1144,8 +1053,7 @@ class BulkChange
// Debug...
//
- if (false)
- {
+ if (false) {
echo "\n";
echo "Attributes:\n";
print_r($this->m_aAttList);
@@ -1163,10 +1071,9 @@ class BulkChange
exit;
}
- $aResult = array();
+ $aResult = [];
- if (!is_null($this->m_sDateFormat) && (strlen($this->m_sDateFormat) > 0))
- {
+ if (!is_null($this->m_sDateFormat) && (strlen($this->m_sDateFormat) > 0)) {
$sDateTimeFormat = $this->m_sDateFormat; // the specified format is actually the date AND time format
$oDateTimeFormat = new DateTimeFormat($sDateTimeFormat);
$sDateFormat = $oDateTimeFormat->ToDateFormat();
@@ -1174,55 +1081,44 @@ class BulkChange
AttributeDate::SetFormat(new DateTimeFormat($sDateFormat));
// Translate dates from the source data
//
- foreach ($this->m_aAttList as $sAttCode => $iCol)
- {
- if ($sAttCode == 'id') continue;
+ foreach ($this->m_aAttList as $sAttCode => $iCol) {
+ if ($sAttCode == 'id') {
+ continue;
+ }
$oAttDef = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
- if ($oAttDef instanceof AttributeDateTime) // AttributeDate is derived from AttributeDateTime
- {
- foreach($this->m_aData as $iRow => $aRowData)
- {
+ if ($oAttDef instanceof AttributeDateTime) { // AttributeDate is derived from AttributeDateTime
+ foreach ($this->m_aData as $iRow => $aRowData) {
$sFormat = $sDateTimeFormat;
- if(!isset($this->m_aData[$iRow][$iCol])){
+ if (!isset($this->m_aData[$iRow][$iCol])) {
continue;
}
$sValue = $this->m_aData[$iRow][$iCol];
- if (!empty($sValue))
- {
- if ($oAttDef instanceof AttributeDate)
- {
+ if (!empty($sValue)) {
+ if ($oAttDef instanceof AttributeDate) {
$sFormat = $sDateFormat;
}
$oFormat = new DateTimeFormat($sFormat);
$sDateExample = $oFormat->Format(new DateTime('2022-10-23 16:25:33'));
$sRegExp = $oFormat->ToRegExpr('/');
$sErrorMsg = Dict::Format('UI:CSVReport-Row-Issue-ExpectedDateFormat', $sDateExample);
- if (!preg_match($sRegExp, $sValue))
- {
- $aResult[$iRow]["__STATUS__"]= new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-DateFormat'));
+ if (!preg_match($sRegExp, $sValue)) {
+ $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-DateFormat'));
$aResult[$iRow][$iCol] = new CellStatus_Issue($sValue, null, $sErrorMsg);
- }
- else
- {
+ } else {
$oDate = DateTime::createFromFormat($sFormat, $sValue);
- if ($oDate !== false)
- {
+ if ($oDate !== false) {
$sNewDate = $oDate->format($oAttDef->GetInternalFormat());
$this->m_aData[$iRow][$iCol] = $sNewDate;
- }
- else
- {
+ } else {
// almost impossible ti reproduce since even incorrect dates with correct formats are formated and $oDate will not be false
// Leave the cell unchanged
- $aResult[$iRow]["__STATUS__"]= new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-DateFormat'));
+ $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-DateFormat'));
$aResult[$iRow][$iCol] = new CellStatus_Issue($sValue, null, $sErrorMsg);
}
}
- }
- else
- {
+ } else {
$this->m_aData[$iRow][$iCol] = '';
}
}
@@ -1232,9 +1128,8 @@ class BulkChange
// Compute the results
//
- if (!is_null($this->m_sSynchroScope))
- {
- $aVisited = array();
+ if (!is_null($this->m_sSynchroScope)) {
+ $aVisited = [];
}
$iPreviousTimeLimit = ini_get('max_execution_time');
$iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
@@ -1245,8 +1140,8 @@ class BulkChange
foreach ($this->m_aData as $iRow => $aRowData) {
set_time_limit(intval($iLoopTimeLimit));
// Stop if not the good number of cols in $aRowData
- if($this->m_iNbCol>0 && count($aRowData) != $this->m_iNbCol){
- $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue(Dict::Format('UI:CSVReport-Row-Issue-NbField',count($aRowData),$this->m_iNbCol) );
+ if ($this->m_iNbCol > 0 && count($aRowData) != $this->m_iNbCol) {
+ $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue(Dict::Format('UI:CSVReport-Row-Issue-NbField', count($aRowData), $this->m_iNbCol));
continue;
}
@@ -1354,31 +1249,24 @@ class BulkChange
// Fill in the blanks - the result matrix is expected to be 100% complete
//
- foreach($this->m_aData as $iRow => $aRowData)
- {
- foreach($this->m_aAttList as $iCol)
- {
- if (!array_key_exists($iCol, $aResult[$iRow]))
- {
- if(isset($aRowData[$iCol])) {
+ foreach ($this->m_aData as $iRow => $aRowData) {
+ foreach ($this->m_aAttList as $iCol) {
+ if (!array_key_exists($iCol, $aResult[$iRow])) {
+ if (isset($aRowData[$iCol])) {
$aResult[$iRow][$iCol] = new CellStatus_Void($aRowData[$iCol]);
} else {
$aResult[$iRow][$iCol] = new CellStatus_Issue('', null, Dict::S('UI:CSVReport-Value-Issue-NoValue'));
}
}
}
- foreach($this->m_aExtKeys as $sAttCode => $aForeignAtts)
- {
- if (!array_key_exists($sAttCode, $aResult[$iRow]))
- {
+ foreach ($this->m_aExtKeys as $sAttCode => $aForeignAtts) {
+ if (!array_key_exists($sAttCode, $aResult[$iRow])) {
$aResult[$iRow][$sAttCode] = new CellStatus_Void('n/a');
}
- foreach ($aForeignAtts as $sForeignAttCode => $iCol)
- {
- if (!array_key_exists($iCol, $aResult[$iRow]))
- {
+ foreach ($aForeignAtts as $sForeignAttCode => $iCol) {
+ if (!array_key_exists($iCol, $aResult[$iRow])) {
// The foreign attribute is one of our reconciliation key
- if(isset($aRowData[$iCol])) {
+ if (isset($aRowData[$iCol])) {
$aResult[$iRow][$iCol] = new CellStatus_Void($aRowData[$iCol]);
} else {
$aResult[$iRow][$iCol] = new CellStatus_Issue('', null, 'UI:CSVReport-Value-Issue-NoValue');
@@ -1394,11 +1282,10 @@ class BulkChange
/**
* Display the history of bulk imports
*/
- static function DisplayImportHistory(WebPage $oPage, $bFromAjax = false, $bShowAll = false)
+ public static function DisplayImportHistory(WebPage $oPage, $bFromAjax = false, $bShowAll = false)
{
$sAjaxDivId = "CSVImportHistory";
- if (!$bFromAjax)
- {
+ if (!$bFromAjax) {
$oPage->add('');
}
@@ -1407,53 +1294,45 @@ class BulkChange
$oBulkChangeSearch = DBObjectSearch::FromOQL("SELECT CMDBChange WHERE origin IN ('csv-interactive', 'csv-import.php')");
$iQueryLimit = $bShowAll ? 0 : appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit());
- $oBulkChanges = new DBObjectSet($oBulkChangeSearch, array('date' => false), array(), null, $iQueryLimit);
+ $oBulkChanges = new DBObjectSet($oBulkChangeSearch, ['date' => false], [], null, $iQueryLimit);
$oAppContext = new ApplicationContext();
$bLimitExceeded = false;
- if ($oBulkChanges->Count() > (appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit())))
- {
+ if ($oBulkChanges->Count() > (appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit()))) {
$bLimitExceeded = true;
- if (!$bShowAll)
- {
+ if (!$bShowAll) {
$iMaxObjects = appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit());
$oBulkChanges->SetLimit($iMaxObjects);
}
}
$oBulkChanges->Seek(0);
- $aDetails = array();
- while ($oChange = $oBulkChanges->Fetch())
- {
+ $aDetails = [];
+ while ($oChange = $oBulkChanges->Fetch()) {
$sDate = '
'.$oChange->Get('date').' ';
$sUser = $oChange->GetUserName();
- if (preg_match('/^(.*)\\(CSV\\)$/i', $oChange->Get('userinfo'), $aMatches))
- {
+ if (preg_match('/^(.*)\\(CSV\\)$/i', $oChange->Get('userinfo'), $aMatches)) {
$sUser = $aMatches[1];
- }
- else
- {
+ } else {
$sUser = $oChange->Get('userinfo');
}
$oOpSearch = DBObjectSearch::FromOQL("SELECT CMDBChangeOpCreate WHERE change = :change_id");
- $oOpSet = new DBObjectSet($oOpSearch, array(), array('change_id' => $oChange->GetKey()));
+ $oOpSet = new DBObjectSet($oOpSearch, [], ['change_id' => $oChange->GetKey()]);
$iCreated = $oOpSet->Count();
// Get the class from the first item found (assumption: a CSV load is done for a single class)
- if ($oCreateOp = $oOpSet->Fetch())
- {
+ if ($oCreateOp = $oOpSet->Fetch()) {
$sClass = $oCreateOp->Get('objclass');
}
$oOpSearch = DBObjectSearch::FromOQL("SELECT CMDBChangeOpSetAttribute WHERE change = :change_id");
- $oOpSet = new DBObjectSet($oOpSearch, array(), array('change_id' => $oChange->GetKey()));
+ $oOpSet = new DBObjectSet($oOpSearch, [], ['change_id' => $oChange->GetKey()]);
- $aModified = array();
- $aAttList = array();
- while ($oModified = $oOpSet->Fetch())
- {
+ $aModified = [];
+ $aAttList = [];
+ while ($oModified = $oOpSet->Fetch()) {
// Get the class (if not done earlier on object creation)
$sClass = $oModified->Get('objclass');
$iKey = $oModified->Get('objkey');
@@ -1466,28 +1345,23 @@ class BulkChange
// Assumption: there is only one class of objects being loaded
// Then the last class found gives us the class for every object
- if ( ($iModified > 0) || ($iCreated > 0))
- {
- $aDetails[] = array('date' => $sDate, 'user' => $sUser, 'class' => $sClass, 'created' => $iCreated, 'modified' => $iModified);
+ if (($iModified > 0) || ($iCreated > 0)) {
+ $aDetails[] = ['date' => $sDate, 'user' => $sUser, 'class' => $sClass, 'created' => $iCreated, 'modified' => $iModified];
}
}
- $aConfig = array( 'date' => array('label' => Dict::S('UI:History:Date'), 'description' => Dict::S('UI:History:Date+')),
- 'user' => array('label' => Dict::S('UI:History:User'), 'description' => Dict::S('UI:History:User+')),
- 'class' => array('label' => Dict::S('Core:AttributeClass'), 'description' => Dict::S('Core:AttributeClass+')),
- 'created' => array('label' => Dict::S('UI:History:StatsCreations'), 'description' => Dict::S('UI:History:StatsCreations+')),
- 'modified' => array('label' => Dict::S('UI:History:StatsModifs'), 'description' => Dict::S('UI:History:StatsModifs+')),
- );
+ $aConfig = [ 'date' => ['label' => Dict::S('UI:History:Date'), 'description' => Dict::S('UI:History:Date+')],
+ 'user' => ['label' => Dict::S('UI:History:User'), 'description' => Dict::S('UI:History:User+')],
+ 'class' => ['label' => Dict::S('Core:AttributeClass'), 'description' => Dict::S('Core:AttributeClass+')],
+ 'created' => ['label' => Dict::S('UI:History:StatsCreations'), 'description' => Dict::S('UI:History:StatsCreations+')],
+ 'modified' => ['label' => Dict::S('UI:History:StatsModifs'), 'description' => Dict::S('UI:History:StatsModifs+')],
+ ];
- if ($bLimitExceeded)
- {
- if ($bShowAll)
- {
+ if ($bLimitExceeded) {
+ if ($bShowAll) {
// Collapsible list
$oPage->add('
'.Dict::Format('UI:CountOfResults', $oBulkChanges->Count()).' '.Dict::S('UI:CollapseList').'
');
- }
- else
- {
+ } else {
// Truncated list
$iMinDisplayLimit = appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit());
$sCollapsedLabel = Dict::Format('UI:TruncatedResults', $iMinDisplayLimit, $oBulkChanges->Count());
@@ -1501,7 +1375,6 @@ class BulkChange
EOF
);
-
$sAppContext = $oAppContext->GetForLink();
$oPage->add_script(
<<
table($aConfig, $aDetails);
- if (!$bFromAjax)
- {
+ if (!$bFromAjax) {
$oPage->add(' ');
}
}
@@ -1537,137 +1407,104 @@ EOF
* @param $iChange
* @throws Exception
*/
- static function DisplayImportHistoryDetails(iTopWebPage $oPage, $iChange)
+ public static function DisplayImportHistoryDetails(iTopWebPage $oPage, $iChange)
{
- if ($iChange == 0)
- {
+ if ($iChange == 0) {
throw new Exception("Missing parameter changeid");
}
$oChange = MetaModel::GetObject('CMDBChange', $iChange, false);
- if (is_null($oChange))
- {
+ if (is_null($oChange)) {
throw new Exception("Unknown change: $iChange");
}
$oPage->add("
".Dict::Format('UI:History:BulkImportDetails', $oChange->Get('date'), $oChange->GetUserName())." \n");
// Assumption : change made one single class of objects
- $aObjects = array();
- $aAttributes = array(); // array of attcode => occurences
+ $aObjects = [];
+ $aAttributes = []; // array of attcode => occurences
$oOpSearch = DBObjectSearch::FromOQL("SELECT CMDBChangeOp WHERE change = :change_id");
- $oOpSet = new DBObjectSet($oOpSearch, array(), array('change_id' => $iChange));
- while ($oOperation = $oOpSet->Fetch())
- {
+ $oOpSet = new DBObjectSet($oOpSearch, [], ['change_id' => $iChange]);
+ while ($oOperation = $oOpSet->Fetch()) {
$sClass = $oOperation->Get('objclass');
$iKey = $oOperation->Get('objkey');
$iObjId = "$sClass::$iKey";
- if (!isset($aObjects[$iObjId]))
- {
- $aObjects[$iObjId] = array();
+ if (!isset($aObjects[$iObjId])) {
+ $aObjects[$iObjId] = [];
$aObjects[$iObjId]['__class__'] = $sClass;
$aObjects[$iObjId]['__id__'] = $iKey;
}
- if (get_class($oOperation) == 'CMDBChangeOpCreate')
- {
+ if (get_class($oOperation) == 'CMDBChangeOpCreate') {
$aObjects[$iObjId]['__created__'] = true;
- }
- elseif ($oOperation instanceof CMDBChangeOpSetAttribute)
- {
+ } elseif ($oOperation instanceof CMDBChangeOpSetAttribute) {
$sAttCode = $oOperation->Get('attcode');
- if ((get_class($oOperation) == 'CMDBChangeOpSetAttributeScalar') || (get_class($oOperation) == 'CMDBChangeOpSetAttributeURL'))
- {
+ if ((get_class($oOperation) == 'CMDBChangeOpSetAttributeScalar') || (get_class($oOperation) == 'CMDBChangeOpSetAttributeURL')) {
$oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
- if ($oAttDef->IsExternalKey())
- {
+ if ($oAttDef->IsExternalKey()) {
$sOldValue = Dict::S('UI:UndefinedObject');
- if ($oOperation->Get('oldvalue') != 0)
- {
+ if ($oOperation->Get('oldvalue') != 0) {
$oOldTarget = MetaModel::GetObject($oAttDef->GetTargetClass(), $oOperation->Get('oldvalue'));
$sOldValue = $oOldTarget->GetHyperlink();
}
$sNewValue = Dict::S('UI:UndefinedObject');
- if ($oOperation->Get('newvalue') != 0)
- {
+ if ($oOperation->Get('newvalue') != 0) {
$oNewTarget = MetaModel::GetObject($oAttDef->GetTargetClass(), $oOperation->Get('newvalue'));
$sNewValue = $oNewTarget->GetHyperlink();
}
- }
- else
- {
+ } else {
$sOldValue = $oOperation->GetAsHTML('oldvalue');
$sNewValue = $oOperation->GetAsHTML('newvalue');
}
$aObjects[$iObjId][$sAttCode] = $sOldValue.' -> '.$sNewValue;
- }
- else
- {
+ } else {
$aObjects[$iObjId][$sAttCode] = 'n/a';
}
- if (isset($aAttributes[$sAttCode]))
- {
+ if (isset($aAttributes[$sAttCode])) {
$aAttributes[$sAttCode]++;
- }
- else
- {
+ } else {
$aAttributes[$sAttCode] = 1;
}
}
}
- $aDetails = array();
- foreach($aObjects as $iUId => $aObjData)
- {
- $aRow = array();
+ $aDetails = [];
+ foreach ($aObjects as $iUId => $aObjData) {
+ $aRow = [];
$oObject = MetaModel::GetObject($aObjData['__class__'], $aObjData['__id__'], false);
- if (is_null($oObject))
- {
+ if (is_null($oObject)) {
$aRow['object'] = $aObjData['__class__'].'::'.$aObjData['__id__'].' (deleted)';
- }
- else
- {
+ } else {
$aRow['object'] = $oObject->GetHyperlink();
}
- if (isset($aObjData['__created__']))
- {
+ if (isset($aObjData['__created__'])) {
$aRow['operation'] = Dict::S('Change:ObjectCreated');
- }
- else
- {
+ } else {
$aRow['operation'] = Dict::S('Change:ObjectModified');
}
- foreach ($aAttributes as $sAttCode => $iOccurences)
- {
- if (isset($aObjData[$sAttCode]))
- {
+ foreach ($aAttributes as $sAttCode => $iOccurences) {
+ if (isset($aObjData[$sAttCode])) {
$aRow[$sAttCode] = $aObjData[$sAttCode];
- }
- elseif (!is_null($oObject))
- {
+ } elseif (!is_null($oObject)) {
// This is the current vaslue: $oObject->GetAsHtml($sAttCode)
// whereas we are displaying the value that was set at the time
// the object was created
// This requires addtional coding...let's do that later
$aRow[$sAttCode] = '';
- }
- else
- {
+ } else {
$aRow[$sAttCode] = '';
}
}
$aDetails[] = $aRow;
}
- $aConfig = array();
- $aConfig['object'] = array('label' => MetaModel::GetName($sClass), 'description' => MetaModel::GetClassDescription($sClass));
- $aConfig['operation'] = array('label' => Dict::S('UI:History:Changes'), 'description' => Dict::S('UI:History:Changes+'));
- foreach ($aAttributes as $sAttCode => $iOccurences)
- {
- $aConfig[$sAttCode] = array('label' => MetaModel::GetLabel($sClass, $sAttCode), 'description' => MetaModel::GetDescription($sClass, $sAttCode));
+ $aConfig = [];
+ $aConfig['object'] = ['label' => MetaModel::GetName($sClass), 'description' => MetaModel::GetClassDescription($sClass)];
+ $aConfig['operation'] = ['label' => Dict::S('UI:History:Changes'), 'description' => Dict::S('UI:History:Changes+')];
+ foreach ($aAttributes as $sAttCode => $iOccurences) {
+ $aConfig[$sAttCode] = ['label' => MetaModel::GetLabel($sClass, $sAttCode), 'description' => MetaModel::GetDescription($sClass, $sAttCode)];
}
$oPage->table($aConfig, $aDetails);
}
}
-
diff --git a/core/bulkexport.class.inc.php b/core/bulkexport.class.inc.php
index 69d83a42b..d74370db0 100644
--- a/core/bulkexport.class.inc.php
+++ b/core/bulkexport.class.inc.php
@@ -1,4 +1,5 @@
'core/cmdb',
"key_type" => 'autoincrement',
- "name_attcode" => array('created'),
+ "name_attcode" => ['created'],
"state_attcode" => '',
- "reconc_keys" => array(),
+ "reconc_keys" => [],
"db_table" => 'priv_bulk_export_result',
"db_key_field" => 'id',
"db_finalclass_field" => '',
"display_template" => '',
- );
+ ];
MetaModel::Init_Params($aParams);
- MetaModel::Init_AddAttribute(new AttributeDateTime("created", array("allowed_values"=>null, "sql"=>"created", "default_value"=>"NOW()", "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeInteger("user_id", array("allowed_values"=>null, "sql"=>"user_id", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeInteger("chunk_size", array("allowed_values"=>null, "sql"=>"chunk_size", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeString("format", array("allowed_values"=>null, "sql"=>"format", "default_value"=>'', "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeString("temp_file_path", array("allowed_values"=>null, "sql"=>"temp_file_path", "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeLongText("search", array("allowed_values"=>null, "sql"=>"search", "default_value"=>'', "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeLongText("status_info", array("allowed_values"=>null, "sql"=>"status_info", "default_value"=>'', "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeBoolean("localize_output", array("allowed_values"=>null, "sql"=>"localize_output", "default_value"=>true, "is_null_allowed"=>true, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeDateTime("created", ["allowed_values" => null, "sql" => "created", "default_value" => "NOW()", "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeInteger("user_id", ["allowed_values" => null, "sql" => "user_id", "default_value" => 0, "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeInteger("chunk_size", ["allowed_values" => null, "sql" => "chunk_size", "default_value" => 0, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeString("format", ["allowed_values" => null, "sql" => "format", "default_value" => '', "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeString("temp_file_path", ["allowed_values" => null, "sql" => "temp_file_path", "default_value" => '', "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeLongText("search", ["allowed_values" => null, "sql" => "search", "default_value" => '', "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeLongText("status_info", ["allowed_values" => null, "sql" => "status_info", "default_value" => '', "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeBoolean("localize_output", ["allowed_values" => null, "sql" => "localize_output", "default_value" => true, "is_null_allowed" => true, "depends_on" => []]));
}
@@ -100,23 +101,21 @@ class BulkExportResultGC implements iBackgroundProcess
{
public function GetPeriodicity()
{
- return 24*3600; // seconds
+ return 24 * 3600; // seconds
}
public function Process($iTimeLimit)
{
- $sDateLimit = date(AttributeDateTime::GetSQLFormat(), time() - 24*3600); // Every BulkExportResult older than one day will be deleted
+ $sDateLimit = date(AttributeDateTime::GetSQLFormat(), time() - 24 * 3600); // Every BulkExportResult older than one day will be deleted
$sOQL = "SELECT BulkExportResult WHERE created < '$sDateLimit'";
$iProcessed = 0;
- while (time() < $iTimeLimit)
- {
+ while (time() < $iTimeLimit) {
// Next one ?
- $oSet = new CMDBObjectSet(DBObjectSearch::FromOQL($sOQL), array('created' => true) /* order by*/, array(), null, 1 /* limit count */);
- $oSet->OptimizeColumnLoad(array('BulkExportResult' => array('temp_file_path')));
+ $oSet = new CMDBObjectSet(DBObjectSearch::FromOQL($sOQL), ['created' => true] /* order by*/, [], null, 1 /* limit count */);
+ $oSet->OptimizeColumnLoad(['BulkExportResult' => ['temp_file_path']]);
$oResult = $oSet->Fetch();
- if (is_null($oResult))
- {
+ if (is_null($oResult)) {
// Nothing to be done
break;
}
@@ -160,28 +159,24 @@ abstract class BulkExport
$this->bLocalizeOutput = false;
}
- /**
- * Find the first class capable of exporting the data in the given format
- *
- * @param string $sFormatCode The lowercase format (e.g. html, csv, spreadsheet, xlsx, xml, json, pdf...)
- * @param DBSearch $oSearch The search/filter defining the set of objects to export or null when listing the supported formats
- *
- * @return BulkExport|null
- * @throws ReflectionException
- */
- static public function FindExporter($sFormatCode, $oSearch = null)
+ /**
+ * Find the first class capable of exporting the data in the given format
+ *
+ * @param string $sFormatCode The lowercase format (e.g. html, csv, spreadsheet, xlsx, xml, json, pdf...)
+ * @param DBSearch $oSearch The search/filter defining the set of objects to export or null when listing the supported formats
+ *
+ * @return BulkExport|null
+ * @throws ReflectionException
+ */
+ public static function FindExporter($sFormatCode, $oSearch = null)
{
- foreach(get_declared_classes() as $sPHPClass)
- {
+ foreach (get_declared_classes() as $sPHPClass) {
$oRefClass = new ReflectionClass($sPHPClass);
- if ($oRefClass->isSubclassOf('BulkExport') && !$oRefClass->isAbstract())
- {
+ if ($oRefClass->isSubclassOf('BulkExport') && !$oRefClass->isAbstract()) {
/** @var BulkExport $oBulkExporter */
$oBulkExporter = new $sPHPClass();
- if ($oBulkExporter->IsFormatSupported($sFormatCode, $oSearch))
- {
- if ($oSearch)
- {
+ if ($oBulkExporter->IsFormatSupported($sFormatCode, $oSearch)) {
+ if ($oSearch) {
$oBulkExporter->SetObjectList($oSearch);
}
return $oBulkExporter;
@@ -191,37 +186,34 @@ abstract class BulkExport
return null;
}
- /**
- * Find the exporter corresponding to the given persistent token
- *
- * @param int $iPersistentToken The identifier of the BulkExportResult object storing the information
- *
- * @return BulkExport|null
- * @throws ArchivedObjectException
- * @throws CoreException
- * @throws ReflectionException
- */
- static public function FindExporterFromToken($iPersistentToken = null)
+ /**
+ * Find the exporter corresponding to the given persistent token
+ *
+ * @param int $iPersistentToken The identifier of the BulkExportResult object storing the information
+ *
+ * @return BulkExport|null
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ * @throws ReflectionException
+ */
+ public static function FindExporterFromToken($iPersistentToken = null)
{
$oBulkExporter = null;
$oInfo = MetaModel::GetObject('BulkExportResult', $iPersistentToken, false);
- if ($oInfo && ($oInfo->Get('user_id') == UserRights::GetUserId()))
- {
+ if ($oInfo && ($oInfo->Get('user_id') == UserRights::GetUserId())) {
$sFormatCode = $oInfo->Get('format');
- $aStatusInfo = json_decode($oInfo->Get('status_info'),true);
+ $aStatusInfo = json_decode($oInfo->Get('status_info'), true);
$oSearch = DBObjectSearch::unserialize($oInfo->Get('search'));
$oSearch->SetShowObsoleteData($aStatusInfo['show_obsolete_data']);
$oBulkExporter = self::FindExporter($sFormatCode, $oSearch);
- if ($oBulkExporter)
- {
+ if ($oBulkExporter) {
$oBulkExporter->SetFormat($sFormatCode);
$oBulkExporter->SetObjectList($oSearch);
$oBulkExporter->SetChunkSize($oInfo->Get('chunk_size'));
$oBulkExporter->SetStatusInfo($aStatusInfo);
- $oBulkExporter->SetLocalizeOutput($oInfo->Get('localize_output'));
-
+ $oBulkExporter->SetLocalizeOutput($oInfo->Get('localize_output'));
$oBulkExporter->sTmpFile = $oInfo->Get('temp_file_path');
$oBulkExporter->oBulkExportResult = $oInfo;
@@ -236,13 +228,11 @@ abstract class BulkExport
*/
public function AppendToTmpFile($data)
{
- if ($this->sTmpFile == '')
- {
+ if ($this->sTmpFile == '') {
$this->sTmpFile = $this->MakeTmpFile($this->GetFileExtension());
}
$hFile = fopen($this->sTmpFile, 'ab');
- if ($hFile !== false)
- {
+ if ($hFile !== false) {
fwrite($hFile, $data);
fclose($hFile);
}
@@ -257,15 +247,13 @@ abstract class BulkExport
* Lists all possible export formats. The output is a hash array in the form: 'format_code' => 'localized format label'
* @return array :string
*/
- static public function FindSupportedFormats()
+ public static function FindSupportedFormats()
{
- $aSupportedFormats = array();
- foreach(get_declared_classes() as $sPHPClass)
- {
+ $aSupportedFormats = [];
+ foreach (get_declared_classes() as $sPHPClass) {
$oRefClass = new ReflectionClass($sPHPClass);
- if ($oRefClass->isSubClassOf('BulkExport') && !$oRefClass->isAbstract())
- {
- $oBulkExporter = new $sPHPClass;
+ if ($oRefClass->isSubClassOf('BulkExport') && !$oRefClass->isAbstract()) {
+ $oBulkExporter = new $sPHPClass();
$aFormats = $oBulkExporter->GetSupportedFormats();
$aSupportedFormats = array_merge($aSupportedFormats, $aFormats);
}
@@ -282,13 +270,13 @@ abstract class BulkExport
$this->iChunkSize = $iChunkSize;
}
- /**
- * @param $bLocalizeOutput
- */
- public function SetLocalizeOutput($bLocalizeOutput)
- {
- $this->bLocalizeOutput = $bLocalizeOutput;
- }
+ /**
+ * @param $bLocalizeOutput
+ */
+ public function SetLocalizeOutput($bLocalizeOutput)
+ {
+ $this->bLocalizeOutput = $bLocalizeOutput;
+ }
/**
* (non-PHPdoc)
@@ -320,10 +308,9 @@ abstract class BulkExport
*/
public function GetSupportedFormats()
{
- return array(); // return array('csv' => Dict::S('UI:ExportFormatCSV'));
+ return []; // return array('csv' => Dict::S('UI:ExportFormatCSV'));
}
-
public function SetHttpHeaders(WebPage $oPage)
{
}
@@ -347,14 +334,13 @@ abstract class BulkExport
public function SaveState()
{
- if ($this->oBulkExportResult === null)
- {
+ if ($this->oBulkExportResult === null) {
$this->oBulkExportResult = new BulkExportResult();
$this->oBulkExportResult->Set('format', $this->sFormatCode);
$this->oBulkExportResult->Set('search', $this->oSearch->serialize());
$this->oBulkExportResult->Set('chunk_size', $this->iChunkSize);
- $this->oBulkExportResult->Set('localize_output', $this->bLocalizeOutput);
- }
+ $this->oBulkExportResult->Set('localize_output', $this->bLocalizeOutput);
+ }
$this->oBulkExportResult->Set('status_info', json_encode($this->GetStatusInfo()));
$this->oBulkExportResult->Set('temp_file_path', $this->sTmpFile);
utils::PushArchiveMode(false);
@@ -365,11 +351,9 @@ abstract class BulkExport
public function Cleanup()
{
- if (($this->oBulkExportResult && (!$this->oBulkExportResult->IsNew())))
- {
+ if (($this->oBulkExportResult && (!$this->oBulkExportResult->IsNew()))) {
$sFilename = $this->oBulkExportResult->Get('temp_file_path');
- if ($sFilename != '')
- {
+ if ($sFilename != '') {
@unlink($sFilename);
}
utils::PushArchiveMode(false);
@@ -380,7 +364,7 @@ abstract class BulkExport
public function EnumFormParts()
{
- return array();
+ return [];
}
/**
@@ -464,25 +448,21 @@ abstract class BulkExport
*/
protected function MakeTmpFile($sExtension)
{
- if(!is_dir(utils::GetDataPath()."bulk_export"))
- {
+ if (!is_dir(utils::GetDataPath()."bulk_export")) {
@mkdir(utils::GetDataPath()."bulk_export", 0777, true /* recursive */);
clearstatcache();
}
- if (!is_writable(utils::GetDataPath()."bulk_export"))
- {
+ if (!is_writable(utils::GetDataPath()."bulk_export")) {
throw new Exception('Data directory "'.utils::GetDataPath().'bulk_export" could not be written.');
}
$iNum = rand();
- do
- {
+ do {
$iNum++;
$sToken = sprintf("%08x", $iNum);
$sFileName = utils::GetDataPath()."bulk_export/$sToken.".$sExtension;
$hFile = @fopen($sFileName, 'x');
- }
- while($hFile === false);
+ } while ($hFile === false);
fclose($hFile);
return $sFileName;
@@ -492,8 +472,7 @@ abstract class BulkExport
// The built-in exports
require_once(APPROOT.'core/tabularbulkexport.class.inc.php');
require_once(APPROOT.'core/htmlbulkexport.class.inc.php');
-if (extension_loaded('gd'))
-{
+if (extension_loaded('gd')) {
// PDF export - via TCPDF - requires GD
require_once(APPROOT.'core/pdfbulkexport.class.inc.php');
}
@@ -501,4 +480,3 @@ require_once(APPROOT.'core/csvbulkexport.class.inc.php');
require_once(APPROOT.'core/excelbulkexport.class.inc.php');
require_once(APPROOT.'core/spreadsheetbulkexport.class.inc.php');
require_once(APPROOT.'core/xmlbulkexport.class.inc.php');
-
diff --git a/core/cmdbobject.class.inc.php b/core/cmdbobject.class.inc.php
index ea490edff..1d7a6065e 100644
--- a/core/cmdbobject.class.inc.php
+++ b/core/cmdbobject.class.inc.php
@@ -1,4 +1,5 @@
-
/**
* Class cmdbObject
*
@@ -24,7 +24,6 @@
* @license http://opensource.org/licenses/AGPL-3.0
*/
-
/**
* cmdbObjectClass
* the file to include, then the core is yours
@@ -148,8 +147,7 @@ abstract class CMDBObject extends DBObject
*/
public static function GetCurrentChange($bAutoCreate = true)
{
- if ($bAutoCreate && is_null(self::$m_oCurrChange))
- {
+ if ($bAutoCreate && is_null(self::$m_oCurrChange)) {
self::CreateChange();
}
return self::$m_oCurrChange;
@@ -214,7 +212,7 @@ abstract class CMDBObject extends DBObject
return CMDBChange::GetCurrentUserName();
} else {
//N°5135 - add impersonation information in activity log/current cmdb change
- if (UserRights::IsImpersonated()){
+ if (UserRights::IsImpersonated()) {
return sprintf("%s (%s)", CMDBChange::GetCurrentUserName(), self::$m_sInfo);
} else {
return self::$m_sInfo;
@@ -234,12 +232,9 @@ abstract class CMDBObject extends DBObject
if (is_null(self::$m_sUserId)
//N°5135 - indicate impersonation inside changelogs
&& (false === UserRights::IsImpersonated())
- )
- {
+ ) {
return CMDBChange::GetCurrentUserId();
- }
- else
- {
+ } else {
return self::$m_sUserId;
}
}
@@ -249,12 +244,9 @@ abstract class CMDBObject extends DBObject
*/
protected static function GetTrackOrigin()
{
- if (is_null(self::$m_sOrigin))
- {
+ if (is_null(self::$m_sOrigin)) {
return 'interactive';
- }
- else
- {
+ } else {
return self::$m_sOrigin;
}
}
@@ -382,14 +374,10 @@ abstract class CMDBObject extends DBObject
// $aValues is an array of $sAttCode => $value
//
- foreach ($aValues as $sAttCode=> $value)
- {
- if (array_key_exists($sAttCode, $aOrigValues))
- {
+ foreach ($aValues as $sAttCode => $value) {
+ if (array_key_exists($sAttCode, $aOrigValues)) {
$original = $aOrigValues[$sAttCode];
- }
- else
- {
+ } else {
$original = null;
}
$this->RecordAttChange($sAttCode, $original, $value);
@@ -431,8 +419,7 @@ abstract class CMDBObject extends DBObject
$bOriginal = $this->Get('archive_flag');
parent::DBArchive();
- if (!$bOriginal)
- {
+ if (!$bOriginal) {
utils::PushArchiveMode(false);
$this->RecordAttChange('archive_flag', false, true);
utils::PopArchiveMode();
@@ -445,8 +432,7 @@ abstract class CMDBObject extends DBObject
$bOriginal = $this->Get('archive_flag');
parent::DBUnarchive();
- if ($bOriginal)
- {
+ if ($bOriginal) {
utils::PushArchiveMode(false);
$this->RecordAttChange('archive_flag', true, false);
utils::PopArchiveMode();
@@ -454,8 +440,6 @@ abstract class CMDBObject extends DBObject
}
}
-
-
/**
* TODO: investigate how to get rid of this class that was made to workaround some language limitation... or a poor design!
*
@@ -471,7 +455,7 @@ class CMDBObjectSet extends DBObjectSet
// just to get the right object class in return.
// I have to think again to those things: maybe it will work fine if a have a constructor define here (?)
- static public function FromScratch($sClass)
+ public static function FromScratch($sClass)
{
$oFilter = new DBObjectSearch($sClass);
$oFilter->AddConditionExpression(new FalseExpression());
@@ -483,14 +467,14 @@ class CMDBObjectSet extends DBObjectSet
// create an object set ex nihilo
// input = array of objects
- static public function FromArray($sClass, $aObjects)
+ public static function FromArray($sClass, $aObjects)
{
$oRetSet = self::FromScratch($sClass);
$oRetSet->AddObjectArray($aObjects, $sClass);
return $oRetSet;
}
- static public function FromArrayAssoc($aClasses, $aObjects)
+ public static function FromArrayAssoc($aClasses, $aObjects)
{
// In a perfect world, we should create a complete tree of DBObjectSearch,
// but as we lack most of the information related to the objects,
@@ -502,8 +486,7 @@ class CMDBObjectSet extends DBObjectSet
$oRetSet = new CMDBObjectSet($oFilter);
$oRetSet->m_bLoaded = true; // no DB load
- foreach($aObjects as $rowIndex => $aObjectsByClassAlias)
- {
+ foreach ($aObjects as $rowIndex => $aObjectsByClassAlias) {
$oRetSet->AddObjectExtended($aObjectsByClassAlias);
}
return $oRetSet;
diff --git a/core/cmdbsource.class.inc.php b/core/cmdbsource.class.inc.php
index 0323d34e7..b688bc2bc 100644
--- a/core/cmdbsource.class.inc.php
+++ b/core/cmdbsource.class.inc.php
@@ -1,4 +1,5 @@
-
/**
* DB Server abstraction
*
@@ -29,7 +29,6 @@ use Combodo\iTop\Core\DbConnectionWrapper;
require_once('MyHelpers.class.inc.php');
require_once(APPROOT.'core/kpi.class.inc.php');
-
/**
* CMDBSource
* database access wrapper
@@ -38,21 +37,20 @@ require_once(APPROOT.'core/kpi.class.inc.php');
*/
class CMDBSource
{
- const ENUM_DB_VENDOR_MYSQL = 'MySQL';
- const ENUM_DB_VENDOR_MARIADB = 'MariaDB';
- const ENUM_DB_VENDOR_PERCONA = 'Percona';
-
+ public const ENUM_DB_VENDOR_MYSQL = 'MySQL';
+ public const ENUM_DB_VENDOR_MARIADB = 'MariaDB';
+ public const ENUM_DB_VENDOR_PERCONA = 'Percona';
/**
* Error: 1205 SQLSTATE: HY000 (ER_LOCK_WAIT_TIMEOUT)
* Message: Lock wait timeout exceeded; try restarting transaction
*/
- const MYSQL_ERRNO_WAIT_TIMEOUT = 1205;
+ public const MYSQL_ERRNO_WAIT_TIMEOUT = 1205;
/**
* Error: 1213 SQLSTATE: 40001 (ER_LOCK_DEADLOCK)
* Message: Deadlock found when trying to get lock; try restarting transaction
*/
- const MYSQL_ERRNO_DEADLOCK = 1213;
+ public const MYSQL_ERRNO_DEADLOCK = 1213;
protected static $m_sDBHost;
protected static $m_sDBUser;
@@ -123,9 +121,13 @@ class CMDBSource
* @throws \MySQLException
*/
public static function Init(
- $sServer, $sUser, $sPwd, $sSource = '', $bTlsEnabled = false, $sTlsCA = null
- )
- {
+ $sServer,
+ $sUser,
+ $sPwd,
+ $sSource = '',
+ $bTlsEnabled = false,
+ $sTlsCA = null
+ ) {
self::$m_sDBHost = $sServer;
self::$m_sDBUser = $sUser;
self::$m_sDBPwd = $sPwd;
@@ -152,7 +154,13 @@ class CMDBSource
* @uses IsOpenedDbConnectionUsingTls when asking for a TLS connection, to check if it was really opened using TLS
*/
public static function GetMysqliInstance(
- $sDbHost, $sUser, $sPwd, $sSource = '', $bTlsEnabled = false, $sTlsCa = null, $bCheckTlsAfterConnection = false
+ $sDbHost,
+ $sUser,
+ $sPwd,
+ $sSource = '',
+ $bTlsEnabled = false,
+ $sTlsCa = null,
+ $bCheckTlsAfterConnection = false
) {
$sServer = null;
$iPort = null;
@@ -164,12 +172,10 @@ class CMDBSource
// but some other errors will still cause the query() method to return false !!!
mysqli_report(MYSQLI_REPORT_STRICT);
- try
- {
+ try {
$oMysqli = new mysqli();
- if ($bTlsEnabled)
- {
+ if ($bTlsEnabled) {
$iFlags = (empty($sTlsCa))
? MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT
: MYSQLI_CLIENT_SSL;
@@ -179,31 +185,31 @@ class CMDBSource
$oMysqli->ssl_set($bTlsEnabled, $sTlsCert, $sTlsCa, $sTlsCaPath, $sTlsCipher);
}
$oMysqli->real_connect($sServer, $sUser, $sPwd, '', $iPort, ini_get("mysqli.default_socket"), $iFlags);
- }
- catch(mysqli_sql_exception $e)
- {
- throw new MySQLException('Could not connect to the DB server', array('host' => $sServer, 'user' => $sUser),$e);
+ } catch (mysqli_sql_exception $e) {
+ throw new MySQLException('Could not connect to the DB server', ['host' => $sServer, 'user' => $sUser], $e);
}
if ($bTlsEnabled
&& $bCheckTlsAfterConnection
- && !self::IsOpenedDbConnectionUsingTls($oMysqli))
- {
- throw new MySQLException("Connection to the database is not encrypted whereas it was opened using TLS parameters",
- null, null, $oMysqli);
+ && !self::IsOpenedDbConnectionUsingTls($oMysqli)) {
+ throw new MySQLException(
+ "Connection to the database is not encrypted whereas it was opened using TLS parameters",
+ null,
+ null,
+ $oMysqli
+ );
}
- if (!empty($sSource))
- {
- try
- {
+ if (!empty($sSource)) {
+ try {
mysqli_report(MYSQLI_REPORT_STRICT); // Errors, in the next query, will throw mysqli_sql_exception
$oMysqli->query("USE `$sSource`");
- }
- catch(mysqli_sql_exception $e)
- {
- throw new MySQLException('Could not select DB',
- array('host' => $sServer, 'user' => $sUser, 'db_name' => $sSource), $e);
+ } catch (mysqli_sql_exception $e) {
+ throw new MySQLException(
+ 'Could not select DB',
+ ['host' => $sServer, 'user' => $sUser, 'db_name' => $sSource],
+ $e
+ );
}
}
@@ -235,7 +241,7 @@ class CMDBSource
$iConnectInfoCount = count($aConnectInfo);
if ($bUsePersistentConnection && ($iConnectInfoCount == 3)) {
$iPort = (int)($aConnectInfo[2]);
- } else if (!$bUsePersistentConnection && ($iConnectInfoCount == 2)) {
+ } elseif (!$bUsePersistentConnection && ($iConnectInfoCount == 2)) {
$iPort = (int)($aConnectInfo[1]);
}
}
@@ -278,12 +284,9 @@ class CMDBSource
*/
private static function IsMySqlVarNonEmpty($sVarName, $oMysqli)
{
- try
- {
+ try {
$sResult = self::QueryToScalar("SHOW SESSION STATUS LIKE '$sVarName'", 1, $oMysqli);
- }
- catch (MySQLQueryHasNoResultException $e)
- {
+ } catch (MySQLQueryHasNoResultException $e) {
$sResult = null;
}
@@ -292,14 +295,10 @@ class CMDBSource
public static function SetCharacterSet($sCharset = DEFAULT_CHARACTER_SET, $sCollation = DEFAULT_COLLATION)
{
- if (strlen($sCharset) > 0)
- {
- if (strlen($sCollation) > 0)
- {
+ if (strlen($sCharset) > 0) {
+ if (strlen($sCollation) > 0) {
self::Query("SET NAMES '$sCharset' COLLATE '$sCollation'");
- }
- else
- {
+ } else {
self::Query("SET NAMES '$sCharset'");
}
}
@@ -309,8 +308,7 @@ class CMDBSource
{
// Note: requires the installation of MySQL special tables,
// otherwise, only 'SYSTEM' or "+10:00' may be specified which is NOT sufficient because of day light saving times
- if (!is_null($sTimezone))
- {
+ if (!is_null($sTimezone)) {
$sQuotedTimezone = self::Quote($sTimezone);
self::Query("SET time_zone = $sQuotedTimezone");
}
@@ -325,18 +323,16 @@ class CMDBSource
public static function IsDB($sSource)
{
- try
- {
+ try {
$aDBs = self::ListDB();
- foreach($aDBs as $sDBName)
- {
- // perform a case insensitive test because on Windows the table names become lowercase :-(
- if (strtolower($sDBName) == strtolower($sSource)) return true;
+ foreach ($aDBs as $sDBName) {
+ // perform a case insensitive test because on Windows the table names become lowercase :-(
+ if (strtolower($sDBName) == strtolower($sSource)) {
+ return true;
+ }
}
return false;
- }
- catch(Exception $e)
- {
+ } catch (Exception $e) {
// In case we don't have rights to enumerate the databases
// Let's try to connect directly
/** @noinspection NullPointerExceptionInspection this shouldn't be called with un-init DB */
@@ -368,13 +364,10 @@ class CMDBSource
{
$sDBVendor = static::ENUM_DB_VENDOR_MYSQL;
- $sVersionComment = static::GetServerVariable('version') . ' - ' . static::GetServerVariable('version_comment');
- if(preg_match('/mariadb/i', $sVersionComment) === 1)
- {
+ $sVersionComment = static::GetServerVariable('version').' - '.static::GetServerVariable('version_comment');
+ if (preg_match('/mariadb/i', $sVersionComment) === 1) {
$sDBVendor = static::ENUM_DB_VENDOR_MARIADB;
- }
- else if(preg_match('/percona/i', $sVersionComment) === 1)
- {
+ } elseif (preg_match('/percona/i', $sVersionComment) === 1) {
$sDBVendor = static::ENUM_DB_VENDOR_PERCONA;
}
@@ -390,7 +383,7 @@ class CMDBSource
{
/** @noinspection NullPointerExceptionInspection this shouldn't be called with un-init DB */
if (!((bool)DbConnectionWrapper::GetDbConnection(true)->query("USE `$sSource`"))) {
- throw new MySQLException('Could not select DB', array('db_name' => $sSource));
+ throw new MySQLException('Could not select DB', ['db_name' => $sSource]);
}
self::$m_sDBName = $sSource;
}
@@ -409,13 +402,11 @@ class CMDBSource
public static function DropDB($sDBToDrop = '')
{
- if (empty($sDBToDrop))
- {
+ if (empty($sDBToDrop)) {
$sDBToDrop = self::$m_sDBName;
}
self::Query("DROP DATABASE `$sDBToDrop`");
- if ($sDBToDrop == self::$m_sDBName)
- {
+ if ($sDBToDrop == self::$m_sDBName) {
self::$m_sDBName = '';
}
self::_TablesInfoCacheReset(); // reset the table info cache!
@@ -468,10 +459,22 @@ class CMDBSource
}
}
- public static function DBHost() {return self::$m_sDBHost;}
- public static function DBUser() {return self::$m_sDBUser;}
- public static function DBPwd() {return self::$m_sDBPwd;}
- public static function DBName() {return self::$m_sDBName;}
+ public static function DBHost()
+ {
+ return self::$m_sDBHost;
+ }
+ public static function DBUser()
+ {
+ return self::$m_sDBUser;
+ }
+ public static function DBPwd()
+ {
+ return self::$m_sDBPwd;
+ }
+ public static function DBName()
+ {
+ return self::$m_sDBName;
+ }
/**
* Quote variable and protect against SQL injection attacks
@@ -486,24 +489,20 @@ class CMDBSource
*/
public static function Quote($value, $bAlways = false, $cQuoteStyle = "'")
{
- if (is_null($value))
- {
+ if (is_null($value)) {
return 'NULL';
}
- if (is_array($value))
- {
- $aRes = array();
- foreach ($value as $key => $itemvalue)
- {
+ if (is_array($value)) {
+ $aRes = [];
+ foreach ($value as $key => $itemvalue) {
$aRes[$key] = self::Quote($itemvalue, $bAlways, $cQuoteStyle);
}
return $aRes;
}
// Quote if not a number or a numeric string
- if ($bAlways || is_string($value))
- {
+ if ($bAlways || is_string($value)) {
/** @noinspection NullPointerExceptionInspection this shouldn't be called with un-init DB */
$value = $cQuoteStyle.DbConnectionWrapper::GetDbConnection()->real_escape_string($value).$cQuoteStyle;
}
@@ -520,8 +519,7 @@ class CMDBSource
*/
private static function RemoveSurroundingQuotes($sValue)
{
- if (utils::StartsWith($sValue, '\'') && utils::EndsWith($sValue, '\''))
- {
+ if (utils::StartsWith($sValue, '\'') && utils::EndsWith($sValue, '\'')) {
$sValue = substr($sValue, 1, -1);
}
@@ -531,34 +529,30 @@ class CMDBSource
/**
* @param string $sSQLQuery
*
- * @return mysqli_result|null
- * @throws MySQLException
- * @throws MySQLHasGoneAwayException
+ * @return mysqli_result|null
+ * @throws MySQLException
+ * @throws MySQLHasGoneAwayException
*
* @since 2.7.0 N°679 handles nested transactions
*/
public static function Query($sSQLQuery)
{
- if (preg_match('/^START TRANSACTION;?$/i', $sSQLQuery))
- {
+ if (preg_match('/^START TRANSACTION;?$/i', $sSQLQuery)) {
self::StartTransaction();
return null;
}
- if (preg_match('/^COMMIT;?$/i', $sSQLQuery))
- {
+ if (preg_match('/^COMMIT;?$/i', $sSQLQuery)) {
self::Commit();
return null;
}
- if (preg_match('/^ROLLBACK;?$/i', $sSQLQuery))
- {
+ if (preg_match('/^ROLLBACK;?$/i', $sSQLQuery)) {
self::Rollback();
return null;
}
-
return self::DBQuery($sSQLQuery);
}
@@ -585,20 +579,17 @@ class CMDBSource
}
$oKPI = new ExecutionKPI();
- try
- {
+ try {
/** @noinspection NullPointerExceptionInspection this shouldn't be called with un-init DB */
$oResult = DbConnectionWrapper::GetDbConnection(true)->query($sSql);
- }
- catch (mysqli_sql_exception $e)
- {
+ } catch (mysqli_sql_exception $e) {
self::LogDeadLock($e, true);
- throw new MySQLException('Failed to issue SQL query', array('query' => $sSql, $e));
+ throw new MySQLException('Failed to issue SQL query', ['query' => $sSql, $e]);
} finally {
- $oKPI->ComputeStats('Query exec (mySQL)', $sSql);
- }
+ $oKPI->ComputeStats('Query exec (mySQL)', $sSql);
+ }
if ($oResult === false) {
- $aContext = array('query' => $sSql);
+ $aContext = ['query' => $sSql];
$iMySqlErrorNo = DbConnectionWrapper::GetDbConnection(true)->errno;
$aMySqlHasGoneAwayErrorCodes = MySQLHasGoneAwayException::getErrorCodes();
@@ -627,7 +618,7 @@ class CMDBSource
// checks MySQL error code
if ($bCheckMysqliErrno) {
$iMySqlErrorNo = DbConnectionWrapper::GetDbConnection($bForQuery)->errno;
- if (!in_array($iMySqlErrorNo, array(self::MYSQL_ERRNO_WAIT_TIMEOUT, self::MYSQL_ERRNO_DEADLOCK))) {
+ if (!in_array($iMySqlErrorNo, [self::MYSQL_ERRNO_WAIT_TIMEOUT, self::MYSQL_ERRNO_DEADLOCK])) {
return;
}
} else {
@@ -641,21 +632,19 @@ class CMDBSource
if ($oError !== false) {
$aData = $oError->fetch_all(MYSQLI_ASSOC);
$sInnodbStatus = $aData[0];
- }
- else
- {
+ } else {
$sInnodbStatus = 'Get status query cannot execute';
}
// log !
$sMessage = "deadlock detected: user= $sUser; errno=$iMySqlErrorNo";
- $aLogContext = array(
+ $aLogContext = [
'userinfo' => $sUser,
'errno' => $iMySqlErrorNo,
'ex_msg' => $e->getMessage(),
'callstack' => $e->getTraceAsString(),
'data' => $sInnodbStatus,
- );
+ ];
DeadLockLog::Info($sMessage, $iMySqlErrorNo, $aLogContext);
IssueLog::Error($sMessage, LogChannels::DEADLOCK, [
@@ -677,7 +666,7 @@ class CMDBSource
*/
private static function StartTransaction()
{
- $aStackTrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT , 3);
+ $aStackTrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 3);
$bHasExistingTransactions = self::IsInsideTransaction();
if (!$bHasExistingTransactions) {
@@ -702,8 +691,8 @@ class CMDBSource
*/
private static function Commit()
{
- $aStackTrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT , 3);
- if(isset($aStackTrace[2]['class']) && isset($aStackTrace[2]['function'])) {
+ $aStackTrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 3);
+ if (isset($aStackTrace[2]['class']) && isset($aStackTrace[2]['function'])) {
$sCaller = 'From '.$aStackTrace[1]['file'].'('.$aStackTrace[1]['line'].'): '.$aStackTrace[2]['class'].'->'.$aStackTrace[2]['function'].'()';
} else {
$sCaller = 'From '.$aStackTrace[1]['file'].'('.$aStackTrace[1]['line'].') ';
@@ -740,8 +729,8 @@ class CMDBSource
*/
private static function Rollback()
{
- $aStackTrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT , 3);
- if(isset($aStackTrace[2]['class']) && isset($aStackTrace[2]['function'])) {
+ $aStackTrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 3);
+ if (isset($aStackTrace[2]['class']) && isset($aStackTrace[2]['function'])) {
$sCaller = 'From '.$aStackTrace[1]['file'].'('.$aStackTrace[1]['line'].'): '.$aStackTrace[2]['class'].'->'.$aStackTrace[2]['function'].'()';
} else {
$sCaller = 'From '.$aStackTrace[1]['file'].'('.$aStackTrace[1]['line'].') ';
@@ -790,8 +779,7 @@ class CMDBSource
*/
private static function RemoveLastTransactionLevel()
{
- if (self::$m_iTransactionLevel === 0)
- {
+ if (self::$m_iTransactionLevel === 0) {
return;
}
@@ -819,12 +807,10 @@ class CMDBSource
return false;
}
-
public static function GetInsertId()
{
$iRes = DbConnectionWrapper::GetDbConnection()->insert_id;
- if (is_null($iRes))
- {
+ if (is_null($iRes)) {
return 0;
}
return $iRes;
@@ -832,8 +818,7 @@ class CMDBSource
public static function InsertInto($sSQLQuery)
{
- if (self::Query($sSQLQuery))
- {
+ if (self::Query($sSQLQuery)) {
return self::GetInsertId();
}
return false;
@@ -869,31 +854,26 @@ class CMDBSource
try {
/** @noinspection NullPointerExceptionInspection this shouldn't happen : either cnx is passed or the DB was init */
$oResult = $oMysqliForQuery->query($sSql);
- }
- catch (mysqli_sql_exception $e) {
+ } catch (mysqli_sql_exception $e) {
$oKPI->ComputeStats('Query exec (mySQL)', $sSql);
- throw new MySQLException('Failed to issue SQL query', array('query' => $sSql, $e));
+ throw new MySQLException('Failed to issue SQL query', ['query' => $sSql, $e]);
}
$oKPI->ComputeStats('Query exec (mySQL)', $sSql);
if ($oResult === false) {
- throw new MySQLException('Failed to issue SQL query', array('query' => $sSql));
+ throw new MySQLException('Failed to issue SQL query', ['query' => $sSql]);
}
- if ($aRow = $oResult->fetch_array(MYSQLI_BOTH))
- {
+ if ($aRow = $oResult->fetch_array(MYSQLI_BOTH)) {
$res = $aRow[$iCol];
- }
- else
- {
+ } else {
$oResult->free();
- throw new MySQLQueryHasNoResultException('Found no result for query', array('query' => $sSql));
+ throw new MySQLQueryHasNoResultException('Found no result for query', ['query' => $sSql]);
}
$oResult->free();
return $res;
}
-
/**
* @param string $sSql
* @param int $iMode
@@ -903,26 +883,21 @@ class CMDBSource
*/
public static function QueryToArray($sSql, $iMode = MYSQLI_BOTH)
{
- $aData = array();
+ $aData = [];
$oKPI = new ExecutionKPI();
- try
- {
+ try {
/** @noinspection NullPointerExceptionInspection this shouldn't be called with un-init DB */
$oResult = DbConnectionWrapper::GetDbConnection(true)->query($sSql);
- }
- catch(mysqli_sql_exception $e)
- {
+ } catch (mysqli_sql_exception $e) {
$oKPI->ComputeStats('Query exec (mySQL)', $sSql);
- throw new MySQLException('Failed to issue SQL query', array('query' => $sSql, $e));
+ throw new MySQLException('Failed to issue SQL query', ['query' => $sSql, $e]);
}
$oKPI->ComputeStats('Query exec (mySQL)', $sSql);
- if ($oResult === false)
- {
- throw new MySQLException('Failed to issue SQL query', array('query' => $sSql));
+ if ($oResult === false) {
+ throw new MySQLException('Failed to issue SQL query', ['query' => $sSql]);
}
- while ($aRow = $oResult->fetch_array($iMode))
- {
+ while ($aRow = $oResult->fetch_array($iMode)) {
$aData[] = $aRow;
}
$oResult->free();
@@ -938,10 +913,9 @@ class CMDBSource
*/
public static function QueryToCol($sSql, $col)
{
- $aColumn = array();
+ $aColumn = [];
$aData = self::QueryToArray($sSql);
- foreach($aData as $aRow)
- {
+ foreach ($aData as $aRow) {
@$aColumn[] = $aRow[$col];
}
return $aColumn;
@@ -955,26 +929,21 @@ class CMDBSource
*/
public static function ExplainQuery($sSql)
{
- $aData = array();
- try
- {
+ $aData = [];
+ try {
/** @noinspection NullPointerExceptionInspection this shouldn't be called with un-init DB */
$oResult = DbConnectionWrapper::GetDbConnection(true)->query($sSql);
+ } catch (mysqli_sql_exception $e) {
+ throw new MySQLException('Failed to issue SQL query', ['query' => $sSql, $e]);
}
- catch(mysqli_sql_exception $e)
- {
- throw new MySQLException('Failed to issue SQL query', array('query' => $sSql, $e));
- }
- if ($oResult === false)
- {
- throw new MySQLException('Failed to issue SQL query', array('query' => $sSql));
+ if ($oResult === false) {
+ throw new MySQLException('Failed to issue SQL query', ['query' => $sSql]);
}
$aNames = self::GetColumns($oResult, $sSql);
$aData[] = $aNames;
- while ($aRow = $oResult->fetch_array(MYSQLI_ASSOC))
- {
+ while ($aRow = $oResult->fetch_array(MYSQLI_ASSOC)) {
$aData[] = $aRow;
}
$oResult->free();
@@ -989,22 +958,17 @@ class CMDBSource
*/
public static function TestQuery($sSql)
{
- try
- {
+ try {
/** @noinspection NullPointerExceptionInspection this shouldn't be called with un-init DB */
$oResult = DbConnectionWrapper::GetDbConnection(true)->query($sSql);
+ } catch (mysqli_sql_exception $e) {
+ throw new MySQLException('Failed to issue SQL query', ['query' => $sSql, $e]);
}
- catch(mysqli_sql_exception $e)
- {
- throw new MySQLException('Failed to issue SQL query', array('query' => $sSql, $e));
- }
- if ($oResult === false)
- {
- throw new MySQLException('Failed to issue SQL query', array('query' => $sSql));
+ if ($oResult === false) {
+ throw new MySQLException('Failed to issue SQL query', ['query' => $sSql]);
}
- if (is_object($oResult))
- {
+ if (is_object($oResult)) {
$oResult->free();
}
return '';
@@ -1034,16 +998,12 @@ class CMDBSource
*/
public static function GetColumns($oResult, $sSql)
{
- $aNames = array();
- for ($i = 0; $i < (($___mysqli_tmp = $oResult->field_count) ? $___mysqli_tmp : 0) ; $i++)
- {
+ $aNames = [];
+ for ($i = 0; $i < (($___mysqli_tmp = $oResult->field_count) ? $___mysqli_tmp : 0) ; $i++) {
$meta = $oResult->fetch_field_direct($i);
- if (!$meta)
- {
- throw new MySQLException('mysql_fetch_field: No information available', array('query'=>$sSql, 'i'=>$i));
- }
- else
- {
+ if (!$meta) {
+ throw new MySQLException('mysql_fetch_field: No information available', ['query' => $sSql, 'i' => $i]);
+ } else {
$aNames[] = $meta->name;
}
}
@@ -1070,20 +1030,32 @@ class CMDBSource
public static function IsKey($sTable, $iKey)
{
$aTableInfo = self::GetTableInfo($sTable);
- if (empty($aTableInfo)) return false;
- if (!array_key_exists($iKey, $aTableInfo["Fields"])) return false;
+ if (empty($aTableInfo)) {
+ return false;
+ }
+ if (!array_key_exists($iKey, $aTableInfo["Fields"])) {
+ return false;
+ }
$aFieldData = $aTableInfo["Fields"][$iKey];
- if (!array_key_exists("Key", $aFieldData)) return false;
+ if (!array_key_exists("Key", $aFieldData)) {
+ return false;
+ }
return ($aFieldData["Key"] == "PRI");
}
public static function IsAutoIncrement($sTable, $sField)
{
$aTableInfo = self::GetTableInfo($sTable);
- if (empty($aTableInfo)) return false;
- if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
+ if (empty($aTableInfo)) {
+ return false;
+ }
+ if (!array_key_exists($sField, $aTableInfo["Fields"])) {
+ return false;
+ }
$aFieldData = $aTableInfo["Fields"][$sField];
- if (!array_key_exists("Extra", $aFieldData)) return false;
+ if (!array_key_exists("Extra", $aFieldData)) {
+ return false;
+ }
//MyHelpers::debug_breakpoint($aFieldData);
return (strstr($aFieldData["Extra"], "auto_increment"));
}
@@ -1091,16 +1063,24 @@ class CMDBSource
public static function IsField($sTable, $sField)
{
$aTableInfo = self::GetTableInfo($sTable);
- if (empty($aTableInfo)) return false;
- if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
+ if (empty($aTableInfo)) {
+ return false;
+ }
+ if (!array_key_exists($sField, $aTableInfo["Fields"])) {
+ return false;
+ }
return true;
}
public static function IsNullAllowed($sTable, $sField)
{
$aTableInfo = self::GetTableInfo($sTable);
- if (empty($aTableInfo)) return false;
- if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
+ if (empty($aTableInfo)) {
+ return false;
+ }
+ if (!array_key_exists($sField, $aTableInfo["Fields"])) {
+ return false;
+ }
$aFieldData = $aTableInfo["Fields"][$sField];
return (strtolower($aFieldData["Null"]) == "yes");
}
@@ -1108,20 +1088,22 @@ class CMDBSource
public static function GetFieldType($sTable, $sField)
{
$aTableInfo = self::GetTableInfo($sTable);
- if (empty($aTableInfo)) return false;
- if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
+ if (empty($aTableInfo)) {
+ return false;
+ }
+ if (!array_key_exists($sField, $aTableInfo["Fields"])) {
+ return false;
+ }
$aFieldData = $aTableInfo["Fields"][$sField];
return ($aFieldData["Type"]);
}
private static function IsNumericType($aFieldData)
{
- $aNumericTypes = array('tinyint(', 'decimal(', 'int(' );
+ $aNumericTypes = ['tinyint(', 'decimal(', 'int(' ];
$sType = strtolower($aFieldData["Type"]);
- foreach ($aNumericTypes as $sNumericType)
- {
- if (strpos($sType, $sNumericType) === 0)
- {
+ foreach ($aNumericTypes as $sNumericType) {
+ if (strpos($sType, $sNumericType) === 0) {
return true;
}
}
@@ -1154,21 +1136,18 @@ class CMDBSource
[$sItopFieldDataType, $sItopFieldTypeOptions, $sItopFieldOtherOptions] = static::GetFieldDataTypeAndOptions($sItopGeneratedFieldType);
[$sDbFieldDataType, $sDbFieldTypeOptions, $sDbFieldOtherOptions] = static::GetFieldDataTypeAndOptions($sDbFieldType);
- if (strcasecmp($sItopFieldDataType, $sDbFieldDataType) !== 0)
- {
+ if (strcasecmp($sItopFieldDataType, $sDbFieldDataType) !== 0) {
return false;
}
- if (strcmp($sItopFieldTypeOptions, $sDbFieldTypeOptions) !== 0)
- {
+ if (strcmp($sItopFieldTypeOptions, $sDbFieldTypeOptions) !== 0) {
// case sensitive comp as we need to check case for enum possible values for example
return false;
}
// remove the default value NULL added by MariadDB
$sMariaDbDefaultNull = ' DEFAULT \'NULL\'';
- if (utils::EndsWith($sDbFieldOtherOptions, $sMariaDbDefaultNull))
- {
+ if (utils::EndsWith($sDbFieldOtherOptions, $sMariaDbDefaultNull)) {
$sDbFieldOtherOptions = substr($sDbFieldOtherOptions, 0, -strlen($sMariaDbDefaultNull));
}
// remove quotes around default values (always present in MariaDB)
@@ -1176,17 +1155,16 @@ class CMDBSource
'/( DEFAULT )\'([^\']+)\'/',
function ($aMatches) use ($sItopFieldDataType) {
// ENUM default values should keep quotes, but all other numeric values don't have quotes
- if (is_numeric($aMatches[2]) && ($sItopFieldDataType !== 'ENUM'))
- {
+ if (is_numeric($aMatches[2]) && ($sItopFieldDataType !== 'ENUM')) {
return $aMatches[1].$aMatches[2];
}
return $aMatches[0];
},
- $sDbFieldOtherOptions);
+ $sDbFieldOtherOptions
+ );
- if (strcasecmp($sItopFieldOtherOptions, $sDbFieldOtherOptions) !== 0)
- {
+ if (strcasecmp($sItopFieldOtherOptions, $sDbFieldOtherOptions) !== 0) {
return false;
}
@@ -1211,10 +1189,10 @@ class CMDBSource
$sDataType = isset($aMatches[1]) ? $aMatches[1] : '';
- if (strcasecmp($sDataType, 'ENUM') === 0){
- try{
+ if (strcasecmp($sDataType, 'ENUM') === 0) {
+ try {
return self::GetEnumOptions($sDataType, $sCompleteFieldType);
- }catch(CoreException $e){
+ } catch (CoreException $e) {
//do nothing ; especially do not block setup.
IssueLog::Warning("enum was not parsed properly: $sCompleteFieldType. it should not happen during setup.");
}
@@ -1223,7 +1201,7 @@ class CMDBSource
$sTypeOptions = isset($aMatches[2]) ? $aMatches[3] : '';
$sOtherOptions = isset($aMatches[4]) ? $aMatches[4] : '';
- return array($sDataType, $sTypeOptions, $sOtherOptions);
+ return [$sDataType, $sTypeOptions, $sOtherOptions];
}
/**
@@ -1244,16 +1222,16 @@ class CMDBSource
$iFirstOpeningParenthesis = strpos($sCompleteFieldType, '(');
$iLastEndingParenthesis = strrpos($sCompleteFieldType, ')');
- if ($iFirstOpeningParenthesis === false || $iLastEndingParenthesis === false ){
+ if ($iFirstOpeningParenthesis === false || $iLastEndingParenthesis === false) {
//should never happen as GetFieldDataTypeAndOptions regexp matched.
//except if regexp is modiied/broken somehow one day...
- throw new CoreException("GetEnumOptions issue with $sDataType parsing : " . $sCompleteFieldType);
+ throw new CoreException("GetEnumOptions issue with $sDataType parsing : ".$sCompleteFieldType);
}
$sTypeOptions = substr($sCompleteFieldType, $iFirstOpeningParenthesis + 1, $iLastEndingParenthesis - 1);
$sOtherOptions = substr($sCompleteFieldType, $iLastEndingParenthesis + 1);
- return array($sDataType, $sTypeOptions, $sOtherOptions);
+ return [$sDataType, $sTypeOptions, $sOtherOptions];
}
/**
@@ -1266,47 +1244,40 @@ class CMDBSource
public static function GetFieldSpec($sTable, $sField)
{
$aTableInfo = self::GetTableInfo($sTable);
- if (empty($aTableInfo)) return false;
- if (!array_key_exists($sField, $aTableInfo["Fields"])) return false;
+ if (empty($aTableInfo)) {
+ return false;
+ }
+ if (!array_key_exists($sField, $aTableInfo["Fields"])) {
+ return false;
+ }
$aFieldData = $aTableInfo["Fields"][$sField];
$sRet = $aFieldData["Type"];
$sColumnCharset = $aFieldData["Charset"];
$sColumnCollation = $aFieldData["Collation"];
- if (!empty($sColumnCharset))
- {
+ if (!empty($sColumnCharset)) {
$sRet .= ' CHARACTER SET '.$sColumnCharset;
$sRet .= ' COLLATE '.$sColumnCollation;
}
- if ($aFieldData["Null"] == 'NO')
- {
+ if ($aFieldData["Null"] == 'NO') {
$sRet .= ' NOT NULL';
}
- if (is_numeric($aFieldData["Default"]))
- {
- if (strtolower(substr($aFieldData["Type"], 0, 5)) == 'enum(')
- {
+ if (is_numeric($aFieldData["Default"])) {
+ if (strtolower(substr($aFieldData["Type"], 0, 5)) == 'enum(') {
// Force quotes to match the column declaration statement
$sRet .= ' DEFAULT '.self::Quote($aFieldData["Default"], true);
- }
- else
- {
- if (self::IsNumericType($aFieldData))
- {
+ } else {
+ if (self::IsNumericType($aFieldData)) {
$sRet .= ' DEFAULT '.$aFieldData["Default"];
- }
- else
- {
+ } else {
$default = $aFieldData["Default"] + 0; // Coerce to a numeric variable
$sRet .= ' DEFAULT '.self::Quote($default);
}
}
- }
- elseif (is_string($aFieldData["Default"]) == 'string')
- {
+ } elseif (is_string($aFieldData["Default"]) == 'string') {
$sDefaultValue = static::RemoveSurroundingQuotes($aFieldData["Default"]);
$sRet .= ' DEFAULT '.self::Quote($sDefaultValue);
}
@@ -1317,28 +1288,29 @@ class CMDBSource
public static function HasIndex($sTable, $sIndexId, $aFields = null, $aLength = null)
{
$aTableInfo = self::GetTableInfo($sTable);
- if (empty($aTableInfo)) return false;
- if (!array_key_exists($sIndexId, $aTableInfo['Indexes'])) return false;
+ if (empty($aTableInfo)) {
+ return false;
+ }
+ if (!array_key_exists($sIndexId, $aTableInfo['Indexes'])) {
+ return false;
+ }
- if ($aFields == null)
- {
+ if ($aFields == null) {
// Just searching for the name
return true;
}
// Compare the columns
$sSearchedIndex = implode(',', $aFields);
- $aColumnNames = array();
- $aSubParts = array();
- foreach($aTableInfo['Indexes'][$sIndexId] as $aIndexDef)
- {
+ $aColumnNames = [];
+ $aSubParts = [];
+ foreach ($aTableInfo['Indexes'][$sIndexId] as $aIndexDef) {
$aColumnNames[] = $aIndexDef['Column_name'];
$aSubParts[] = $aIndexDef['Sub_part'];
}
$sExistingIndex = implode(',', $aColumnNames);
- if (is_null($aLength))
- {
+ if (is_null($aLength)) {
return ($sSearchedIndex == $sExistingIndex);
}
@@ -1354,21 +1326,20 @@ class CMDBSource
assert(!empty($sTable));
$aTableInfo = self::GetTableInfo($sTable);
- if (empty($aTableInfo)) return array(); // #@# or an error ?
+ if (empty($aTableInfo)) {
+ return [];
+ } // #@# or an error ?
return array_keys($aTableInfo["Fields"]);
}
// Cache the information about existing tables, and their fields
- private static $m_aTablesInfo = array();
+ private static $m_aTablesInfo = [];
private static function _TablesInfoCacheReset($sTableName = null)
{
- if (is_null($sTableName))
- {
- self::$m_aTablesInfo = array();
- }
- else
- {
+ if (is_null($sTableName)) {
+ self::$m_aTablesInfo = [];
+ } else {
self::$m_aTablesInfo[strtolower($sTableName)] = null;
}
}
@@ -1381,8 +1352,7 @@ class CMDBSource
private static function _TableInfoCacheInit($sTableName)
{
if (isset(self::$m_aTablesInfo[strtolower($sTableName)])
- && (self::$m_aTablesInfo[strtolower($sTableName)] != null))
- {
+ && (self::$m_aTablesInfo[strtolower($sTableName)] != null)) {
return;
}
@@ -1392,7 +1362,7 @@ class CMDBSource
// Get table informations
// We were using SHOW COLUMNS FROM... but this don't return charset and collation info !
// so since 2.5 and #1001 (switch to utf8mb4) we're using INFORMATION_SCHEMA !
- $aMapping = array(
+ $aMapping = [
"Name" => "COLUMN_NAME",
"Type" => "COLUMN_TYPE",
"Null" => "IS_NULLABLE",
@@ -1402,28 +1372,24 @@ class CMDBSource
"Charset" => "CHARACTER_SET_NAME",
"Collation" => "COLLATION_NAME",
"CharMaxLength" => "CHARACTER_MAXIMUM_LENGTH",
- );
+ ];
$sColumns = implode(', ', $aMapping);
$sDBName = self::$m_sDBName;
$aFields = self::QueryToArray("SELECT $sColumns FROM information_schema.`COLUMNS` WHERE table_schema = '$sDBName' AND table_name = '$sTableName';");
- foreach ($aFields as $aFieldData)
- {
- $aFields = array();
- foreach($aMapping as $sKey => $sColumn)
- {
+ foreach ($aFields as $aFieldData) {
+ $aFields = [];
+ foreach ($aMapping as $sKey => $sColumn) {
$aFields[$sKey] = $aFieldData[$sColumn];
}
$sFieldName = $aFieldData["COLUMN_NAME"];
self::$m_aTablesInfo[strtolower($sTableName)]["Fields"][$sFieldName] = $aFields;
}
- if (!is_null(self::$m_aTablesInfo[strtolower($sTableName)]))
- {
+ if (!is_null(self::$m_aTablesInfo[strtolower($sTableName)])) {
$aIndexes = self::QueryToArray("SHOW INDEXES FROM `$sTableName`");
- $aMyIndexes = array();
- foreach ($aIndexes as $aIndexColumn)
- {
- $aMyIndexes[$aIndexColumn['Key_name']][$aIndexColumn['Seq_in_index']-1] = $aIndexColumn;
+ $aMyIndexes = [];
+ foreach ($aIndexes as $aIndexColumn) {
+ $aMyIndexes[$aIndexColumn['Key_name']][$aIndexColumn['Seq_in_index'] - 1] = $aIndexColumn;
}
self::$m_aTablesInfo[strtolower($sTableName)]["Indexes"] = $aMyIndexes;
}
@@ -1459,12 +1425,10 @@ class CMDBSource
$sTableCharset = $aTableInfo[0]['CHARACTER_SET_NAME'];
$sTableCollation = $aTableInfo[0]['TABLE_COLLATION'];
- if ((DEFAULT_CHARACTER_SET == $sTableCharset) && (DEFAULT_COLLATION == $sTableCollation))
- {
+ if ((DEFAULT_CHARACTER_SET == $sTableCharset) && (DEFAULT_COLLATION == $sTableCollation)) {
return null;
}
-
return 'ALTER TABLE `'.$sTableName.'` '.self::GetSqlStringColumnDefinition().';';
}
@@ -1478,23 +1442,18 @@ class CMDBSource
public static function DumpTable($sTable)
{
$sSql = "SELECT * FROM `$sTable`";
- try
- {
+ try {
/** @noinspection NullPointerExceptionInspection this shouldn't be called with un-init DB */
$oResult = DbConnectionWrapper::GetDbConnection(true)->query($sSql);
+ } catch (mysqli_sql_exception $e) {
+ throw new MySQLException('Failed to issue SQL query', ['query' => $sSql], $e);
}
- catch(mysqli_sql_exception $e)
- {
- throw new MySQLException('Failed to issue SQL query', array('query' => $sSql), $e);
- }
- if ($oResult === false)
- {
- throw new MySQLException('Failed to issue SQL query', array('query' => $sSql));
+ if ($oResult === false) {
+ throw new MySQLException('Failed to issue SQL query', ['query' => $sSql]);
}
- $aRows = array();
- while ($aRow = $oResult->fetch_array(MYSQLI_ASSOC))
- {
+ $aRows = [];
+ while ($aRow = $oResult->fetch_array(MYSQLI_ASSOC)) {
$aRows[] = $aRow;
}
$oResult->free();
@@ -1519,19 +1478,15 @@ class CMDBSource
*/
public static function GetRawPrivileges()
{
- try
- {
+ try {
$oResult = self::Query('SHOW GRANTS'); // [ FOR CURRENT_USER()]
- }
- catch(MySQLException $e)
- {
+ } catch (MySQLException $e) {
$iCode = self::GetErrNo();
return "Current user not allowed to see his own privileges (could not access to the database 'mysql' - $iCode)";
}
- $aRes = array();
- while ($aRow = $oResult->fetch_array(MYSQLI_NUM))
- {
+ $aRes = [];
+ while ($aRow = $oResult->fetch_array(MYSQLI_NUM)) {
// so far, only one column...
$aRes[] = implode('/', $aRow);
}
@@ -1546,17 +1501,13 @@ class CMDBSource
*/
public static function IsSlaveServer()
{
- try
- {
+ try {
$oResult = self::Query('SHOW SLAVE STATUS');
- }
- catch(MySQLException $e)
- {
- throw new CoreException("Current user not allowed to check the status", array('mysql_error' => $e->getMessage()));
+ } catch (MySQLException $e) {
+ throw new CoreException("Current user not allowed to check the status", ['mysql_error' => $e->getMessage()]);
}
- if ($oResult->num_rows == 0)
- {
+ if ($oResult->num_rows == 0) {
return false;
}
@@ -1564,40 +1515,35 @@ class CMDBSource
$aRow = $oResult->fetch_array(MYSQLI_ASSOC);
$oResult->free();
- if (!isset($aRow['Slave_IO_Running']))
- {
+ if (!isset($aRow['Slave_IO_Running'])) {
return false;
}
- if (!isset($aRow['Slave_SQL_Running']))
- {
+ if (!isset($aRow['Slave_SQL_Running'])) {
return false;
}
// If at least one slave thread is running, then we consider that the slave is enabled
- if ($aRow['Slave_IO_Running'] == 'Yes')
- {
+ if ($aRow['Slave_IO_Running'] == 'Yes') {
return true;
}
- if ($aRow['Slave_SQL_Running'] == 'Yes')
- {
+ if ($aRow['Slave_SQL_Running'] == 'Yes') {
return true;
}
return false;
}
- public static function GetClusterNb()
- {
- $result = 0;
- $sSql = "SHOW STATUS LIKE 'wsrep_cluster_size';";
- $aRows = self::QueryToArray($sSql);
- if (count($aRows) > 0)
- {
- $result = $aRows[0]['Value'];
- }
- return intval($result);
- }
+ public static function GetClusterNb()
+ {
+ $result = 0;
+ $sSql = "SHOW STATUS LIKE 'wsrep_cluster_size';";
+ $aRows = self::QueryToArray($sSql);
+ if (count($aRows) > 0) {
+ $result = $aRows[0]['Value'];
+ }
+ return intval($result);
+ }
- /**
+ /**
* @see https://dev.mysql.com/doc/refman/5.7/en/charset-database.html
* @return string query to upgrade database charset and collation if needed, null if not
* @throws \MySQLException
@@ -1613,8 +1559,7 @@ class CMDBSource
$sDBCharset = $aDBInfo[0]['DEFAULT_CHARACTER_SET_NAME'];
$sDBCollation = $aDBInfo[0]['DEFAULT_COLLATION_NAME'];
- if ((DEFAULT_CHARACTER_SET == $sDBCharset) && (DEFAULT_COLLATION == $sDBCollation))
- {
+ if ((DEFAULT_CHARACTER_SET == $sDBCharset) && (DEFAULT_COLLATION == $sDBCollation)) {
return null;
}
@@ -1631,8 +1576,7 @@ class CMDBSource
*/
public static function IsSslModeDBVersion()
{
- if (static::GetDBVendor() === static::ENUM_DB_VENDOR_MYSQL)
- {
+ if (static::GetDBVendor() === static::ENUM_DB_VENDOR_MYSQL) {
//Mysql 5.7.0 and upper deprecated --ssl and uses --ssl-mode instead
return version_compare(static::GetDBVersion(), '5.7.11', '>=');
}
diff --git a/core/config.class.inc.php b/core/config.class.inc.php
index 68e4d2d6f..079ae5385 100644
--- a/core/config.class.inc.php
+++ b/core/config.class.inc.php
@@ -1,4 +1,5 @@
true,
],
'export_pdf_font' => [ // @since 2.7.0 PR #49 / N°1947
- 'type' => 'string',
- 'description' => 'Font used when generating a PDF file',
- 'default' => 'DejaVuSans', // DejaVuSans is a UTF-8 Unicode font, embedded in the TCPPDF lib we're using
- // Standard PDF fonts like helvetica or times newroman are NOT Unicode
- // A new DroidSansFallback can be used to improve CJK support (se PR #49)
- 'value' => '',
- 'source_of_value' => '',
- 'show_in_conf_sample' => false,
+ 'type' => 'string',
+ 'description' => 'Font used when generating a PDF file',
+ 'default' => 'DejaVuSans', // DejaVuSans is a UTF-8 Unicode font, embedded in the TCPPDF lib we're using
+ // Standard PDF fonts like helvetica or times newroman are NOT Unicode
+ // A new DroidSansFallback can be used to improve CJK support (se PR #49)
+ 'value' => '',
+ 'source_of_value' => '',
+ 'show_in_conf_sample' => false,
],
'access_mode' => [
'type' => 'integer',
@@ -891,7 +890,7 @@ class Config
'source_of_value' => '',
'show_in_conf_sample' => false,
],
- 'forgot_password.url' => [
+ 'forgot_password.url' => [
'type' => 'string',
'description' => 'Set this value to your "forgot password" service URL if it should be handled out of '.ITOP_APPLICATION_SHORT.'. Note that it will apply to all users (iTop users, LDAP users, ...)',
'default' => '',
@@ -1803,7 +1802,7 @@ class Config
'default' => ITOP_APPLICATION.'/'.ITOP_VERSION,
'source_of_value' => '',
'show_in_conf_sample' => false,
- ]
+ ],
];
public function IsProperty($sPropCode)
@@ -1811,7 +1810,6 @@ class Config
return (array_key_exists($sPropCode, $this->m_aSettings));
}
-
/**
* @return string identifier that can be used for example to name WebStorage/SessionStorage keys (they
* are related to a whole domain, and a domain can host multiple itop)
@@ -1845,8 +1843,7 @@ class Config
$value = $this->oConfigPlaceholdersResolver->Resolve($value);
- switch ($sType)
- {
+ switch ($sType) {
case 'bool':
$value = (bool)$value;
break;
@@ -1854,7 +1851,7 @@ class Config
$value = (string)$value;
break;
case 'integer':
- $value = (integer)$value;
+ $value = (int)$value;
break;
case 'float':
$value = (float)$value;
@@ -1862,11 +1859,10 @@ class Config
case 'array':
break;
default:
- throw new CoreException('Unknown type for setting', array('property' => $sPropCode, 'type' => $sType));
+ throw new CoreException('Unknown type for setting', ['property' => $sPropCode, 'type' => $sType]);
}
- if ($this->m_aSettings[$sPropCode]['value'] == $value)
- {
+ if ($this->m_aSettings[$sPropCode]['value'] == $value) {
//when you set the exact same value than the previous one, then, you still can preserve the non evaluated version and so on preserve vars/jokers.
$bCanOverride = true;
}
@@ -2008,15 +2004,13 @@ class Config
$this->oConfigPlaceholdersResolver = new ConfigPlaceholdersResolver();
$this->m_sFile = $sConfigFile;
- if (is_null($sConfigFile))
- {
+ if (is_null($sConfigFile)) {
$bLoadConfig = false;
}
$this->m_aAddons = [];
- foreach ($this->m_aSettings as $sPropCode => $aSettingInfo)
- {
+ foreach ($this->m_aSettings as $sPropCode => $aSettingInfo) {
$this->m_aSettings[$sPropCode]['value'] = $aSettingInfo['default'];
}
@@ -2032,7 +2026,7 @@ class Config
$this->m_sDefaultLanguage = 'EN US';
$this->m_sAllowedLoginTypes = DEFAULT_ALLOWED_LOGIN_TYPES;
$this->m_sExtAuthVariable = DEFAULT_EXT_AUTH_VARIABLE;
- $this->m_aCharsets = array();
+ $this->m_aCharsets = [];
$this->m_bQueryCacheEnabled = DEFAULT_QUERY_CACHE_ENABLED;
$this->m_iPasswordHashAlgo = DEFAULT_HASH_ALGO;
$this->m_sAppSecret = bin2hex(random_bytes(16));
@@ -2042,10 +2036,9 @@ class Config
$this->m_sEncryptionLibrary = isset($aEncryptParams['lib']) ? $aEncryptParams['lib'] : DEFAULT_ENCRYPTION_LIB;
$this->m_sEncryptionKey = isset($aEncryptParams['key']) ? $aEncryptParams['key'] : DEFAULT_ENCRYPTION_KEY;
- $this->m_aModuleSettings = array();
+ $this->m_aModuleSettings = [];
- if ($bLoadConfig)
- {
+ if ($bLoadConfig) {
$this->Load($sConfigFile);
$this->Verify();
}
@@ -2074,14 +2067,14 @@ class Config
*/
protected function CheckFile($sPurpose, $sFileName)
{
- if (!file_exists($sFileName))
- {
- throw new ConfigException("Could not find $sPurpose file", array('file' => $sFileName));
+ if (!file_exists($sFileName)) {
+ throw new ConfigException("Could not find $sPurpose file", ['file' => $sFileName]);
}
- if (!is_readable($sFileName))
- {
- throw new ConfigException("Could not read $sPurpose file (the file exists but cannot be read). Do you have the rights to access this file?",
- array('file' => $sFileName));
+ if (!is_readable($sFileName)) {
+ throw new ConfigException(
+ "Could not read $sPurpose file (the file exists but cannot be read). Do you have the rights to access this file?",
+ ['file' => $sFileName]
+ );
}
}
@@ -2108,64 +2101,58 @@ class Config
// This does not work on several lines
// preg_match('/^<\\?php(.*)\\?'.'>$/', $sConfigCode, $aMatches)...
// So, I've implemented a solution suggested in the PHP doc (search for phpWrapper)
- try
- {
+ try {
ob_start();
eval('?'.'>'.trim($sConfigCode));
$sNoise = trim(ob_get_contents());
ob_end_clean();
- }
- catch (Error $e)
- {
+ } catch (Error $e) {
// PHP 7
- throw new ConfigException('Error in configuration file',
- array('file' => $sConfigFile, 'error' => $e->getMessage().' at line '.$e->getLine()));
- }
- catch (Exception $e)
- {
+ throw new ConfigException(
+ 'Error in configuration file',
+ ['file' => $sConfigFile, 'error' => $e->getMessage().' at line '.$e->getLine()]
+ );
+ } catch (Exception $e) {
// well, never reach in case of parsing error :-(
// will be improved in PHP 6 ?
- throw new ConfigException('Error in configuration file',
- array('file' => $sConfigFile, 'error' => $e->getMessage()));
+ throw new ConfigException(
+ 'Error in configuration file',
+ ['file' => $sConfigFile, 'error' => $e->getMessage()]
+ );
}
- if (strlen($sNoise) > 0)
- {
+ if (strlen($sNoise) > 0) {
// Note: sNoise is an html output, but so far it was ok for me (e.g. showing the entire call stack)
- throw new ConfigException('Syntax error in configuration file',
- array('file' => $sConfigFile, 'error' => ''.utils::EscapeHtml($sNoise, ENT_QUOTES).' '));
+ throw new ConfigException(
+ 'Syntax error in configuration file',
+ ['file' => $sConfigFile, 'error' => ''.utils::EscapeHtml($sNoise, ENT_QUOTES).' ']
+ );
}
- if (!isset($MySettings) || !is_array($MySettings))
- {
- throw new ConfigException('Missing array in configuration file',
- array('file' => $sConfigFile, 'expected' => '$MySettings'));
+ if (!isset($MySettings) || !is_array($MySettings)) {
+ throw new ConfigException(
+ 'Missing array in configuration file',
+ ['file' => $sConfigFile, 'expected' => '$MySettings']
+ );
}
- if (!array_key_exists('addons', $MyModules) || !array_key_exists('user rights', $MyModules['addons']))
- {
+ if (!array_key_exists('addons', $MyModules) || !array_key_exists('user rights', $MyModules['addons'])) {
// Add one, by default
$MyModules['addons']['user rights'] = 'addons/userrights/userrightsprofile.class.inc.php';
$this->m_aAddons = $MyModules['addons'];
}
- foreach ($MySettings as $sPropCode => $rawvalue)
- {
- if ($this->IsProperty($sPropCode))
- {
- if (is_string($rawvalue))
- {
+ foreach ($MySettings as $sPropCode => $rawvalue) {
+ if ($this->IsProperty($sPropCode)) {
+ if (is_string($rawvalue)) {
$value = trim($rawvalue);
- }
- else
- {
+ } else {
$value = $rawvalue;
}
$this->Set($sPropCode, $value, $sConfigFile, true);
}
}
- if (file_exists(READONLY_MODE_FILE))
- {
+ if (file_exists(READONLY_MODE_FILE)) {
$this->Set('access_mode', ACCESS_READONLY, READONLY_MODE_FILE);
}
@@ -2181,14 +2168,14 @@ class Config
$this->m_iFastReloadInterval = isset($MySettings['fast_reload_interval']) ? trim($MySettings['fast_reload_interval']) : DEFAULT_FAST_RELOAD_INTERVAL;
$this->m_bSecureConnectionRequired = isset($MySettings['secure_connection_required']) ? (bool)trim($MySettings['secure_connection_required']) : DEFAULT_SECURE_CONNECTION_REQUIRED;
- $this->m_aModuleSettings = isset($MyModuleSettings) ? $MyModuleSettings : array();
+ $this->m_aModuleSettings = isset($MyModuleSettings) ? $MyModuleSettings : [];
$this->m_sDefaultLanguage = isset($MySettings['default_language']) ? trim($MySettings['default_language']) : 'EN US';
$this->m_sAllowedLoginTypes = isset($MySettings['allowed_login_types']) ? trim($MySettings['allowed_login_types']) : DEFAULT_ALLOWED_LOGIN_TYPES;
$this->m_sExtAuthVariable = isset($MySettings['ext_auth_variable']) ? trim($MySettings['ext_auth_variable']) : DEFAULT_EXT_AUTH_VARIABLE;
$this->m_sEncryptionKey = isset($MySettings['encryption_key']) ? trim($MySettings['encryption_key']) : $this->m_sEncryptionKey;
$this->m_sEncryptionLibrary = isset($MySettings['encryption_library']) ? trim($MySettings['encryption_library']) : $this->m_sEncryptionLibrary;
- $this->m_aCharsets = isset($MySettings['csv_import_charsets']) ? $MySettings['csv_import_charsets'] : array();
+ $this->m_aCharsets = isset($MySettings['csv_import_charsets']) ? $MySettings['csv_import_charsets'] : [];
$this->m_iPasswordHashAlgo = isset($MySettings['password_hash_algo']) ? $MySettings['password_hash_algo'] : $this->m_iPasswordHashAlgo;
}
@@ -2210,8 +2197,7 @@ class Config
*/
public function GetModuleSetting($sModule, $sProperty, $defaultvalue = null)
{
- if (isset($this->m_aModuleSettings[$sModule][$sProperty]))
- {
+ if (isset($this->m_aModuleSettings[$sModule][$sProperty])) {
return $this->m_aModuleSettings[$sModule][$sProperty];
}
@@ -2233,11 +2219,9 @@ class Config
public function GetModuleParameter($sModule, $sProperty, $defaultvalue = null)
{
$ret = $defaultvalue;
- if (class_exists('ModulesXMLParameters'))
- {
+ if (class_exists('ModulesXMLParameters')) {
$aAllParams = ModulesXMLParameters::GetData($sModule);
- if (array_key_exists($sProperty, $aAllParams))
- {
+ if (array_key_exists($sProperty, $aAllParams)) {
$ret = $aAllParams[$sProperty];
}
}
@@ -2255,10 +2239,10 @@ class Config
*/
public function GetAddons()
{
- if (array_key_exists("user rights", $this->m_aAddons)) {
+ if (array_key_exists("user rights", $this->m_aAddons)) {
return $this->m_aAddons;
} else {
- return array_merge($this->m_aAddons,['user rights' => 'addons/userrights/userrightsprofile.class.inc.php']);
+ return array_merge($this->m_aAddons, ['user rights' => 'addons/userrights/userrightsprofile.class.inc.php']);
}
}
@@ -2438,7 +2422,7 @@ class Config
public function AddAllowedLoginTypes($sLoginMode)
{
$aAllowedLoginTypes = $this->GetAllowedLoginTypes();
- if (in_array($sLoginMode, $aAllowedLoginTypes)){
+ if (in_array($sLoginMode, $aAllowedLoginTypes)) {
return;
}
@@ -2461,7 +2445,6 @@ class Config
$this->m_sAppSecret = $sKey;
}
-
public function SetCSVImportCharsets($aCharsets)
{
$this->m_aCharsets = $aCharsets;
@@ -2474,12 +2457,9 @@ class Config
public function GetLoadedFile()
{
- if (is_null($this->m_sFile))
- {
+ if (is_null($this->m_sFile)) {
return '';
- }
- else
- {
+ } else {
return $this->m_sFile;
}
}
@@ -2491,9 +2471,8 @@ class Config
*/
public function ToArray()
{
- $aSettings = array();
- foreach ($this->m_aSettings as $sPropCode => $aSettingInfo)
- {
+ $aSettings = [];
+ foreach ($this->m_aSettings as $sPropCode => $aSettingInfo) {
$aSettings[$sPropCode] = $aSettingInfo['value'];
}
$aSettings['log_global'] = $this->m_bLogGlobal;
@@ -2514,15 +2493,12 @@ class Config
$aSettings['csv_import_charsets'] = $this->m_aCharsets;
$aSettings['password_hash_algo'] = $this->m_iPasswordHashAlgo;
- foreach ($this->m_aModuleSettings as $sModule => $aProperties)
- {
- foreach ($aProperties as $sProperty => $value)
- {
+ foreach ($this->m_aModuleSettings as $sModule => $aProperties) {
+ foreach ($aProperties as $sProperty => $value) {
$aSettings['module_settings'][$sModule][$sProperty] = $value;
}
}
- foreach ($this->m_aAddons as $sKey => $sFile)
- {
+ foreach ($this->m_aAddons as $sKey => $sFile) {
$aSettings['addon_list'][] = $sFile;
}
@@ -2541,22 +2517,18 @@ class Config
*/
public function WriteToFile($sFileName = '')
{
- if (empty($sFileName))
- {
+ if (empty($sFileName)) {
$sFileName = $this->m_sFile;
}
$oHandle = null;
$sConfig = null;
- if ($this->m_sFile !== null && is_file($this->m_sFile))
- {
+ if ($this->m_sFile !== null && is_file($this->m_sFile)) {
$oHandle = fopen($this->m_sFile, 'r');
$index = 0;
- while (!flock($oHandle, LOCK_SH))
- {
- if ($index > 50)
- {
- throw new ConfigException("Could not read to configuration file", array('file' => $this->m_sFile));
+ while (!flock($oHandle, LOCK_SH)) {
+ if ($index > 50) {
+ throw new ConfigException("Could not read to configuration file", ['file' => $this->m_sFile]);
}
usleep(100000);
$index++;
@@ -2564,61 +2536,59 @@ class Config
$sConfig = file_get_contents($this->m_sFile);
}
$this->oItopConfigParser = new iTopConfigParser($sConfig);
- if ($oHandle !==null)
- {
+ if ($oHandle !== null) {
flock($oHandle, LOCK_UN);
}
$hFile = @fopen($sFileName, 'w');
- if ($hFile !== false)
- {
+ if ($hFile !== false) {
fwrite($hFile, "m_aSettings;
// Old fashioned boolean settings
- $aBoolValues = array(
+ $aBoolValues = [
'log_global' => $this->m_bLogGlobal,
'log_notification' => $this->m_bLogNotification,
'log_issue' => $this->m_bLogIssue,
'log_web_service' => $this->m_bLogWebService,
'secure_connection_required' => $this->m_bSecureConnectionRequired,
- );
- foreach ($aBoolValues as $sKey => $bValue)
- {
- $aConfigSettings[$sKey] = array(
+ ];
+ foreach ($aBoolValues as $sKey => $bValue) {
+ $aConfigSettings[$sKey] = [
'show_in_conf_sample' => true,
'type' => 'bool',
'value' => $bValue,
- );
+ ];
}
// Old fashioned integer settings
- $aIntValues = array(
+ $aIntValues = [
'fast_reload_interval' => $this->m_iFastReloadInterval,
'max_display_limit' => $this->m_iMaxDisplayLimit,
'min_display_limit' => $this->m_iMinDisplayLimit,
'standard_reload_interval' => $this->m_iStandardReloadInterval,
- );
- foreach ($aIntValues as $sKey => $iValue)
- {
- $aConfigSettings[$sKey] = array(
+ ];
+ foreach ($aIntValues as $sKey => $iValue) {
+ $aConfigSettings[$sKey] = [
'show_in_conf_sample' => true,
'type' => 'integer',
'value' => $iValue,
- );
+ ];
}
// Old fashioned remaining values
- $aOtherValues = array(
+ $aOtherValues = [
'default_language' => $this->m_sDefaultLanguage,
'allowed_login_types' => $this->m_sAllowedLoginTypes,
'ext_auth_variable' => $this->m_sExtAuthVariable,
@@ -2626,45 +2596,37 @@ class Config
'encryption_library' => $this->m_sEncryptionLibrary,
'csv_import_charsets' => $this->m_aCharsets,
'password_hash_algo' => $this->m_iPasswordHashAlgo,
- );
- foreach ($aOtherValues as $sKey => $value)
- {
- $aConfigSettings[$sKey] = array(
+ ];
+ foreach ($aOtherValues as $sKey => $value) {
+ $aConfigSettings[$sKey] = [
'show_in_conf_sample' => true,
'type' => is_string($value) ? 'string' : 'mixed',
'value' => $value,
- );
+ ];
}
ksort($aConfigSettings);
fwrite($hFile, "\$MySettings = array(\n");
- foreach ($aConfigSettings as $sPropCode => $aSettingInfo)
- {
+ foreach ($aConfigSettings as $sPropCode => $aSettingInfo) {
// Write all values that are either always visible or present in the cloned config file
- if ($aSettingInfo['show_in_conf_sample'] || (!empty($aSettingInfo['source_of_value']) && ($aSettingInfo['source_of_value'] != 'unknown')))
- {
+ if ($aSettingInfo['show_in_conf_sample'] || (!empty($aSettingInfo['source_of_value']) && ($aSettingInfo['source_of_value'] != 'unknown'))) {
fwrite($hFile, "\n");
- if (isset($aSettingInfo['description']))
- {
+ if (isset($aSettingInfo['description'])) {
fwrite($hFile, "\t// $sPropCode: {$aSettingInfo['description']}\n");
}
- if (isset($aSettingInfo['default']))
- {
- $sComment = self::PrettyVarExport(null,$aSettingInfo['default'], "\t//\t\t", true);
- fwrite($hFile,"\t//\tdefault: {$sComment}\n");
+ if (isset($aSettingInfo['default'])) {
+ $sComment = self::PrettyVarExport(null, $aSettingInfo['default'], "\t//\t\t", true);
+ fwrite($hFile, "\t//\tdefault: {$sComment}\n");
}
- if (isset($this->m_aCanOverrideSettings[$sPropCode]) && $this->m_aCanOverrideSettings[$sPropCode])
- {
+ if (isset($this->m_aCanOverrideSettings[$sPropCode]) && $this->m_aCanOverrideSettings[$sPropCode]) {
$aParserValue = $this->oItopConfigParser->GetVarValue('MySettings', $sPropCode);
- }
- else
- {
+ } else {
$aParserValue = null;
}
- $sSeenAs = self::PrettyVarExport($aParserValue,$aSettingInfo['value'], "\t");
+ $sSeenAs = self::PrettyVarExport($aParserValue, $aSettingInfo['value'], "\t");
fwrite($hFile, "\t'$sPropCode' => $sSeenAs,\n");
}
}
@@ -2673,11 +2635,9 @@ class Config
fwrite($hFile, "\n");
fwrite($hFile, "/**\n *\n * Modules specific settings\n *\n */\n");
fwrite($hFile, "\$MyModuleSettings = array(\n");
- foreach ($this->m_aModuleSettings as $sModule => $aProperties)
- {
+ foreach ($this->m_aModuleSettings as $sModule => $aProperties) {
fwrite($hFile, "\t'$sModule' => array (\n");
- foreach ($aProperties as $sProperty => $value)
- {
+ foreach ($aProperties as $sProperty => $value) {
$sNiceExport = self::PrettyVarExport($this->oItopConfigParser->GetVarValue('MyModuleSettings', $sProperty), $value, "\t\t");
fwrite($hFile, "\t\t'$sProperty' => $sNiceExport,\n");
}
@@ -2692,8 +2652,7 @@ class Config
fwrite($hFile, " */\n");
fwrite($hFile, "\$MyModules = array(\n");
$aParserValue = $this->oItopConfigParser->GetVarValue('MyModules', 'addons');
- if ($aParserValue['found'])
- {
+ if ($aParserValue['found']) {
fwrite($hFile, "\t'addons' => {$aParserValue['value']},\n");
}
fwrite($hFile, ");\n");
@@ -2704,10 +2663,8 @@ class Config
utils::SetConfig($this);
return $bReturn;
- }
- else
- {
- throw new ConfigException("Could not write to configuration file", array('file' => $sFileName));
+ } else {
+ throw new ConfigException("Could not write to configuration file", ['file' => $sFileName]);
}
}
@@ -2728,32 +2685,25 @@ class Config
*/
public function UpdateFromParams($aParamValues, $sModulesDir = null, $bPreserveModuleSettings = false)
{
- if (isset($aParamValues['application_path']))
- {
+ if (isset($aParamValues['application_path'])) {
$this->Set('app_root_url', $aParamValues['application_path']);
}
- if (isset($aParamValues['graphviz_path']))
- {
+ if (isset($aParamValues['graphviz_path'])) {
$this->Set('graphviz_path', $aParamValues['graphviz_path']);
}
- if (isset($aParamValues['mode']) && isset($aParamValues['language']))
- {
- if (($aParamValues['mode'] == 'install') || $this->GetDefaultLanguage() == '')
- {
+ if (isset($aParamValues['mode']) && isset($aParamValues['language'])) {
+ if (($aParamValues['mode'] == 'install') || $this->GetDefaultLanguage() == '') {
$this->SetDefaultLanguage($aParamValues['language']);
}
}
- if (isset($aParamValues['db_server']))
- {
+ if (isset($aParamValues['db_server'])) {
$this->Set('db_host', $aParamValues['db_server']);
$this->Set('db_user', $aParamValues['db_user']);
$this->Set('db_pwd', $aParamValues['db_pwd']);
$sDBName = $aParamValues['db_name'];
- if ($sDBName == '')
- {
+ if ($sDBName == '') {
// Todo - obsolete after the transition to the new setup (2.0) is complete (WARNING: used by the designer)
- if (isset($aParamValues['new_db_name']))
- {
+ if (isset($aParamValues['new_db_name'])) {
$sDBName = $aParamValues['new_db_name'];
}
}
@@ -2761,39 +2711,29 @@ class Config
$this->Set('db_subname', $aParamValues['db_prefix']);
$bDbTlsEnabled = (bool)$aParamValues['db_tls_enabled'];
- if ($bDbTlsEnabled)
- {
+ if ($bDbTlsEnabled) {
$this->Set('db_tls.enabled', $bDbTlsEnabled, 'UpdateFromParams');
- }
- else
- {
+ } else {
// disabled : we don't want parameter in the file
$this->Set('db_tls.enabled', $bDbTlsEnabled, null);
}
$sDbTlsCa = $bDbTlsEnabled ? $aParamValues['db_tls_ca'] : null;
- if (isset($sDbTlsCa) && !empty($sDbTlsCa))
- {
+ if (isset($sDbTlsCa) && !empty($sDbTlsCa)) {
$this->Set('db_tls.ca', $sDbTlsCa, 'UpdateFromParams');
- }
- else
- {
+ } else {
// empty parameter : we don't want it in the file
$this->Set('db_tls.ca', null, null);
}
}
- if (isset($aParamValues['selected_modules']))
- {
+ if (isset($aParamValues['selected_modules'])) {
$aSelectedModules = explode(',', $aParamValues['selected_modules']);
- }
- else
- {
+ } else {
$aSelectedModules = null;
}
$this->UpdateIncludes($sModulesDir, $aSelectedModules);
- if (isset($aParamValues['source_dir']))
- {
+ if (isset($aParamValues['source_dir'])) {
$this->Set('source_dir', $aParamValues['source_dir']);
}
}
@@ -2811,8 +2751,7 @@ class Config
*/
public function UpdateIncludes($sModulesDir, $aSelectedModules = null)
{
- if ($sModulesDir === null)
- {
+ if ($sModulesDir === null) {
return;
}
@@ -2820,23 +2759,16 @@ class Config
$oEmptyConfig = new Config('dummy_file', false); // Do NOT load any config file, just set the default values
$aAddOns = $oEmptyConfig->GetAddOns();
- $aModules = ModuleDiscovery::GetAvailableModules(array(APPROOT.$sModulesDir));
- foreach ($aModules as $sModuleId => $aModuleInfo)
- {
- list ($sModuleName, $sModuleVersion) = ModuleDiscovery::GetModuleName($sModuleId);
- if (is_null($aSelectedModules) || in_array($sModuleName, $aSelectedModules))
- {
- if (isset($aModuleInfo['settings']))
- {
- list ($sName, $sVersion) = ModuleDiscovery::GetModuleName($sModuleId);
- foreach ($aModuleInfo['settings'] as $sProperty => $value)
- {
- if (isset($this->m_aModuleSettings[$sName][$sProperty]))
- {
+ $aModules = ModuleDiscovery::GetAvailableModules([APPROOT.$sModulesDir]);
+ foreach ($aModules as $sModuleId => $aModuleInfo) {
+ list($sModuleName, $sModuleVersion) = ModuleDiscovery::GetModuleName($sModuleId);
+ if (is_null($aSelectedModules) || in_array($sModuleName, $aSelectedModules)) {
+ if (isset($aModuleInfo['settings'])) {
+ list($sName, $sVersion) = ModuleDiscovery::GetModuleName($sModuleId);
+ foreach ($aModuleInfo['settings'] as $sProperty => $value) {
+ if (isset($this->m_aModuleSettings[$sName][$sProperty])) {
// Do nothing keep the original value
- }
- else
- {
+ } else {
$this->SetModuleSetting($sName, $sProperty, $value);
}
}
@@ -2857,10 +2789,8 @@ class Config
*/
protected static function ChangePrefix(&$aStrings, $sSearchPrefix, $sNewPrefix)
{
- foreach ($aStrings as &$sFile)
- {
- if (substr($sFile, 0, strlen($sSearchPrefix)) == $sSearchPrefix)
- {
+ foreach ($aStrings as &$sFile) {
+ if (substr($sFile, 0, strlen($sSearchPrefix)) == $sSearchPrefix) {
$sFile = $sNewPrefix.substr($sFile, strlen($sSearchPrefix));
}
}
@@ -2891,22 +2821,19 @@ class Config
*/
protected static function PrettyVarExport($aParserValue, $value, $sIndentation, $bForceIndentation = false)
{
- if (is_array($aParserValue) && $aParserValue['found'])
- {
+ if (is_array($aParserValue) && $aParserValue['found']) {
return $aParserValue['value'];
}
$sExport = var_export($value, true);
- $sNiceExport = str_replace(array("\r\n", "\n", "\r"), "\n".$sIndentation, trim($sExport));
- if (!$bForceIndentation)
- {
+ $sNiceExport = str_replace(["\r\n", "\n", "\r"], "\n".$sIndentation, trim($sExport));
+ if (!$bForceIndentation) {
/** @var array $aImported */
$aImported = null;
eval('$aImported='.$sNiceExport.';');
// Check if adding the identations at the beginning of each line
// did not modify the values (in case of a string containing a line break)
- if ($aImported != $value)
- {
+ if ($aImported != $value) {
$sNiceExport = $sExport;
}
}
@@ -2935,37 +2862,31 @@ class ConfigPlaceholdersResolver
public function Resolve($rawValue)
{
- if (empty($this->aEnv['ITOP_CONFIG_PLACEHOLDERS']) && empty($this->aServer['ITOP_CONFIG_PLACEHOLDERS']))
- {
+ if (empty($this->aEnv['ITOP_CONFIG_PLACEHOLDERS']) && empty($this->aServer['ITOP_CONFIG_PLACEHOLDERS'])) {
return $rawValue;
}
- if (is_array($rawValue))
- {
- $aResolvedRawValue = array();
- foreach ($rawValue as $key => $value)
- {
+ if (is_array($rawValue)) {
+ $aResolvedRawValue = [];
+ foreach ($rawValue as $key => $value) {
$aResolvedRawValue[$key] = $this->Resolve($value);
}
return $aResolvedRawValue;
}
- if (!is_string($rawValue))
- {
+ if (!is_string($rawValue)) {
return $rawValue;
}
$sPattern = '/\%(env|server)\((\w+)\)(?:\?:(\w*))?\%/'; //3 capturing groups, ie `%env(HTTP_PORT)?:8080%` produce: `env` `HTTP_PORT` and `8080`.
- if (! preg_match_all($sPattern, $rawValue, $aMatchesCollection, PREG_SET_ORDER))
- {
+ if (! preg_match_all($sPattern, $rawValue, $aMatchesCollection, PREG_SET_ORDER)) {
return $rawValue;
}
$sValue = $rawValue;
- foreach ($aMatchesCollection as $aMatches)
- {
+ foreach ($aMatchesCollection as $aMatches) {
$sWholeMask = $aMatches[0];
$sSource = $aMatches[1];
$sKey = $aMatches[2];
@@ -2981,35 +2902,27 @@ class ConfigPlaceholdersResolver
private function Get($sSourceName, $sKey, $sDefault, $sWholeMask)
{
- if ('env' == $sSourceName)
- {
+ if ('env' == $sSourceName) {
$aSource = $this->aEnv;
- }
- else if ('server' == $sSourceName)
- {
+ } elseif ('server' == $sSourceName) {
$aSource = $this->aServer;
- }
- else
- {
+ } else {
$sErrorMessage = sprintf('unsupported source name "%s" into "%s"', $sSourceName, $sWholeMask);
- IssueLog::Error($sErrorMessage, self::class, array($sSourceName, $sKey, $sDefault, $sWholeMask));
+ IssueLog::Error($sErrorMessage, self::class, [$sSourceName, $sKey, $sDefault, $sWholeMask]);
throw new ConfigException($sErrorMessage);
}
- if (array_key_exists($sKey, $aSource))
- {
+ if (array_key_exists($sKey, $aSource)) {
return $aSource[$sKey];
}
- if (null !== $sDefault)
- {
+ if (null !== $sDefault) {
return $sDefault;
}
$sErrorMessage = sprintf('key "%s" not found into "%s" while expanding', $sSourceName, $sWholeMask);
- IssueLog::Error($sErrorMessage, self::class, array($sSourceName, $sKey, $sDefault, $sWholeMask));
+ IssueLog::Error($sErrorMessage, self::class, [$sSourceName, $sKey, $sDefault, $sWholeMask]);
throw new ConfigException($sErrorMessage);
}
-
}
diff --git a/core/dbobject.class.php b/core/dbobject.class.php
index e4b8a9ff4..5367f10ff 100644
--- a/core/dbobject.class.php
+++ b/core/dbobject.class.php
@@ -1,4 +1,5 @@
array of ('table' => array of (array of )) */
- private static $m_aBulkInsertItems = array();
+ private static $m_aBulkInsertItems = [];
/** @var array class => array of ('table' => array of ) */
- private static $m_aBulkInsertCols = array();
- private static $m_bBulkInsert = false;
+ private static $m_aBulkInsertCols = [];
+ private static $m_bBulkInsert = false;
/** @var bool true IF the object is mapped to a DB record */
protected $m_bIsInDB = false;
protected $m_iKey = null;
/** @var array attcode => value : corresponding current value (the new value passed to {@see DBObject::Set()}). Reset during {@see DBObject::DBUpdate()} */
- private $m_aCurrValues = array();
+ private $m_aCurrValues = [];
/** @var array attcode => value : previous values before the {@see DBObject::Set()} call. Array is reset at the end of {@see DBObject::DBUpdate()} */
- protected $m_aOrigValues = array();
+ protected $m_aOrigValues = [];
protected $m_aExtendedData = null;
- /**
- * @var bool Is dirty (true) if a modification is ongoing.
- *
- * @internal The object may have incorrect external keys, then any attempt of reload must be avoided
- */
+ /**
+ * @var bool Is dirty (true) if a modification is ongoing.
+ *
+ * @internal The object may have incorrect external keys, then any attempt of reload must be avoided
+ */
private $m_bDirty = false;
/**
@@ -148,9 +147,9 @@ abstract class DBObject implements iDisplay
/** @var bool Compound objects can be partially loaded */
private $m_bFullyLoaded = false;
/** @var array Compound objects can be partially loaded, array of sAttCode */
- private $m_aLoadedAtt = array();
+ private $m_aLoadedAtt = [];
/** @var array list of (potentially) modified sAttCodes */
- protected $m_aTouchedAtt = array();
+ protected $m_aTouchedAtt = [];
/**
* @var array real modification status
* for each attCode can be:
@@ -158,7 +157,7 @@ abstract class DBObject implements iDisplay
* * true => modified,
* * false => not modified (the same value as the original value was set)
*/
- protected $m_aModifiedAtt = array();
+ protected $m_aModifiedAtt = [];
/**
* @var array attname => value : value before the last {@see DBObject::Set()} call. Set at the beginning of {@see DBObject::DBUpdate()}.
* @see DBObject::ListPreviousValuesForUpdatedAttributes() getter for this attribute
@@ -176,7 +175,7 @@ abstract class DBObject implements iDisplay
*/
protected $m_aSynchroData = null;
protected $m_sHighlightCode = null;
- protected $m_aCallbacks = array();
+ protected $m_aCallbacks = [];
/**
* @var string local events suffix
*/
@@ -207,7 +206,7 @@ abstract class DBObject implements iDisplay
// Protect DBUpdate against infinite loop
protected $iUpdateLoopCount;
- const MAX_UPDATE_LOOP_COUNT = 10;
+ public const MAX_UPDATE_LOOP_COUNT = 10;
private $aEventListeners = [];
private array $aAllowedTransitions = [];
@@ -233,12 +232,11 @@ abstract class DBObject implements iDisplay
public function __construct($aRow = null, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
{
$this->iUpdateLoopCount = 0;
- if (!empty($aRow))
- {
+ if (!empty($aRow)) {
$this->FromRow($aRow, $sClassAlias, $aAttToLoad, $aExtendedDataSpec);
$this->m_bFullyLoaded = $this->IsFullyLoaded();
- $this->m_aTouchedAtt = array();
- $this->m_aModifiedAtt = array();
+ $this->m_aTouchedAtt = [];
+ $this->m_aModifiedAtt = [];
$this->m_sObjectUniqId = get_class($this).'::'.$this->GetKey().'_'.uniqId('', true);
$this->RegisterEventListeners();
return;
@@ -249,8 +247,7 @@ abstract class DBObject implements iDisplay
$this->m_iKey = self::GetNextTempId(get_class($this));
// set default values
- foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
- {
+ foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) {
$this->m_aCurrValues[$sAttCode] = $this->GetDefaultValue($sAttCode);
$this->m_aOrigValues[$sAttCode] = null;
if (!$oAttDef->IsExternalField() && !$oAttDef instanceof AttributeFriendlyName) {
@@ -277,128 +274,124 @@ abstract class DBObject implements iDisplay
/**
* Update meta-attributes depending on the given attribute list
*
- * @internal
- *
- * @param array|null $aAttCodes List of att codes
- *
+ * @internal
+ *
+ * @param array|null $aAttCodes List of att codes
+ *
* @throws \CoreException
*/
protected function UpdateMetaAttributes($aAttCodes = null)
{
- if (is_null($aAttCodes))
- {
+ if (is_null($aAttCodes)) {
$aAttCodes = MetaModel::GetAttributesList(get_class($this));
}
- foreach ($aAttCodes as $sAttCode)
- {
- foreach (MetaModel::ListMetaAttributes(get_class($this), $sAttCode) as $sMetaAttCode => $oMetaAttDef)
- {
+ foreach ($aAttCodes as $sAttCode) {
+ foreach (MetaModel::ListMetaAttributes(get_class($this), $sAttCode) as $sMetaAttCode => $oMetaAttDef) {
/** @var \AttributeMetaEnum $oMetaAttDef */
$this->_Set($sMetaAttCode, $oMetaAttDef->MapValue($this));
}
}
}
- /**
- * Mark the object as dirty
- *
- * Once dirty the object may be written to the DB, it is NOT possible to reload it
- * or at least not possible to reload it the same way
- *
- * @internal
- */
+ /**
+ * Mark the object as dirty
+ *
+ * Once dirty the object may be written to the DB, it is NOT possible to reload it
+ * or at least not possible to reload it the same way
+ *
+ * @internal
+ */
public function RegisterAsDirty()
{
$this->m_bDirty = true;
}
- /**
- * Whether the object is already persisted in DB or not.
- *
- * @api
- *
- * @return bool
- */
+ /**
+ * Whether the object is already persisted in DB or not.
+ *
+ * @api
+ *
+ * @return bool
+ */
public function IsNew()
{
return (!$this->m_bIsInDB);
}
- /**
- * Returns an Id for memory objects
- *
- * @internal
- *
- * @param string $sClass
- *
- * @return int
- * @throws CoreException
- */
- static protected function GetNextTempId($sClass)
+ /**
+ * Returns an Id for memory objects
+ *
+ * @internal
+ *
+ * @param string $sClass
+ *
+ * @return int
+ * @throws CoreException
+ */
+ protected static function GetNextTempId($sClass)
{
$sRootClass = MetaModel::GetRootClass($sClass);
- if (!array_key_exists($sRootClass, self::$m_aMemoryObjectsByClass))
- {
+ if (!array_key_exists($sRootClass, self::$m_aMemoryObjectsByClass)) {
self::$m_aMemoryObjectsByClass[$sRootClass] = 0;
}
self::$m_aMemoryObjectsByClass[$sRootClass]++;
return (- self::$m_aMemoryObjectsByClass[$sRootClass]);
}
- /**
- * HTML String representation of the object
- *
- * Only a few meaningful information will be returned.
- * This representation is for debugging purposes, and is subject to change.
- * The returned string is raw HTML
- *
- * @return string
- * @throws CoreException
- */
+ /**
+ * HTML String representation of the object
+ *
+ * Only a few meaningful information will be returned.
+ * This representation is for debugging purposes, and is subject to change.
+ * The returned string is raw HTML
+ *
+ * @return string
+ * @throws CoreException
+ */
public function __toString()
{
- $sRet = '';
- $sClass = get_class($this);
- $sRootClass = MetaModel::GetRootClass($sClass);
- $iPKey = $this->GetKey();
- $sFriendlyname = $this->GetAsHTML('friendlyname');
- $sRet .= "$sClass ::$iPKey ($sFriendlyname) \n";
- return $sRet;
+ $sRet = '';
+ $sClass = get_class($this);
+ $sRootClass = MetaModel::GetRootClass($sClass);
+ $iPKey = $this->GetKey();
+ $sFriendlyname = $this->GetAsHTML('friendlyname');
+ $sRet .= "$sClass ::$iPKey ($sFriendlyname) \n";
+ return $sRet;
}
- /**
- * Alias of DBObject::Reload()
- *
- * Restore initial values
- *
- * @see Reload()
- *
- * @throws CoreException
- */
+ /**
+ * Alias of DBObject::Reload()
+ *
+ * Restore initial values
+ *
+ * @see Reload()
+ *
+ * @throws CoreException
+ */
public function DBRevert()
{
$this->Reload();
}
- /**
- * Is the current instance fully or partially loaded.
- *
- * This method compute the state in realtime.
- * In almost every case it is preferable to use DBObject::m_bFullyLoaded.
- *
- * @internal
- * @see m_bFullyLoaded
- *
- * @return bool
- * @throws CoreException
- */
+ /**
+ * Is the current instance fully or partially loaded.
+ *
+ * This method compute the state in realtime.
+ * In almost every case it is preferable to use DBObject::m_bFullyLoaded.
+ *
+ * @internal
+ * @see m_bFullyLoaded
+ *
+ * @return bool
+ * @throws CoreException
+ */
protected function IsFullyLoaded()
{
- foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
- {
- if (!$oAttDef->LoadInObject()) continue;
- if (!isset($this->m_aLoadedAtt[$sAttCode]) || !$this->m_aLoadedAtt[$sAttCode])
- {
+ foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) {
+ if (!$oAttDef->LoadInObject()) {
+ continue;
+ }
+ if (!isset($this->m_aLoadedAtt[$sAttCode]) || !$this->m_aLoadedAtt[$sAttCode]) {
return false;
}
}
@@ -406,11 +399,11 @@ abstract class DBObject implements iDisplay
}
/**
- * Reload the object from the DB.
- *
- * This is mostly used after a lazy load (automatically performed by the framework)
- * This will erase any pending changes.
- *
+ * Reload the object from the DB.
+ *
+ * This is mostly used after a lazy load (automatically performed by the framework)
+ * This will erase any pending changes.
+ *
* @throws CoreException
*/
public function Reload()
@@ -418,21 +411,21 @@ abstract class DBObject implements iDisplay
assert($this->m_bIsInDB);
$this->FireEvent(EVENT_DB_OBJECT_RELOAD);
$aRow = MetaModel::MakeSingleRow(get_class($this), $this->m_iKey, false /* must be found */, true /* AllowAllData */);
- if (empty($aRow))
- {
- $sErrorMessage = "Failed to reload object of class '".get_class($this)."', id = ".$this->m_iKey.', DBIsReadOnly = '.(int) MetaModel::DBIsReadOnly();
+ if (empty($aRow)) {
+ $sErrorMessage = "Failed to reload object of class '".get_class($this)."', id = ".$this->m_iKey.', DBIsReadOnly = '.(int) MetaModel::DBIsReadOnly();
- IssueLog::Error("$sErrorMessage:\n".MyHelpers::get_callstack_text(1));
- throw new CoreException("$sErrorMessage (see the log for more information)");
+ IssueLog::Error("$sErrorMessage:\n".MyHelpers::get_callstack_text(1));
+ throw new CoreException("$sErrorMessage (see the log for more information)");
}
$this->FromRow($aRow);
// Process linked set attributes
//
- foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
- {
- if (!$oAttDef->IsLinkSet()) continue;
+ foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) {
+ if (!$oAttDef->IsLinkSet()) {
+ continue;
+ }
$this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue($this);
$this->m_aOrigValues[$sAttCode] = clone $this->m_aCurrValues[$sAttCode];
@@ -440,37 +433,36 @@ abstract class DBObject implements iDisplay
}
$this->m_bFullyLoaded = true;
- $this->m_aTouchedAtt = array();
- $this->m_aModifiedAtt = array();
+ $this->m_aTouchedAtt = [];
+ $this->m_aModifiedAtt = [];
}
- /**
- * Initialize the instance against a given structured array
- *
- * @internal
- * @see GetExtendedData() extended data
- *
- * @param array $aRow an array under the form: ` => `
- * @param string $sClassAlias if not null, it is preprended to the `` part of $aRow
- * @param null|array $aAttToLoad List of attribute that will be fetched against the database anyway
- * @param null|array $aExtendedDataSpec List of attribute that will be marked as DBObject::GetExtendedData()
- *
- * @return bool
- * @throws CoreException
- */
+ /**
+ * Initialize the instance against a given structured array
+ *
+ * @internal
+ * @see GetExtendedData() extended data
+ *
+ * @param array $aRow an array under the form: ` => `
+ * @param string $sClassAlias if not null, it is preprended to the `` part of $aRow
+ * @param null|array $aAttToLoad List of attribute that will be fetched against the database anyway
+ * @param null|array $aExtendedDataSpec List of attribute that will be marked as DBObject::GetExtendedData()
+ *
+ * @return bool
+ * @throws CoreException
+ */
protected function FromRow($aRow, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
{
- if (strlen($sClassAlias) == 0)
- {
+ if (strlen($sClassAlias) == 0) {
// Default to the current class
$sClassAlias = get_class($this);
}
$this->m_iKey = null;
$this->m_bIsInDB = true;
- $this->m_aCurrValues = array();
- $this->m_aOrigValues = array();
- $this->m_aLoadedAtt = array();
+ $this->m_aCurrValues = [];
+ $this->m_aOrigValues = [];
+ $this->m_aLoadedAtt = [];
$this->m_bCheckStatus = true;
$this->m_aCheckIssues = [];
$this->m_bSecurityIssue = [];
@@ -478,21 +470,16 @@ abstract class DBObject implements iDisplay
// Get the key
//
$sKeyField = $sClassAlias."id";
- if (!array_key_exists($sKeyField, $aRow))
- {
+ if (!array_key_exists($sKeyField, $aRow)) {
// #@# Bug ?
throw new CoreException("Missing key for class '".get_class($this)."'");
}
$iPKey = $aRow[$sKeyField];
- if (!self::IsValidPKey($iPKey))
- {
- if (is_null($iPKey))
- {
+ if (!self::IsValidPKey($iPKey)) {
+ if (is_null($iPKey)) {
throw new CoreException("Missing object id in query result (found null)");
- }
- else
- {
+ } else {
throw new CoreException("An object id must be an integer value ($iPKey)");
}
}
@@ -501,27 +488,26 @@ abstract class DBObject implements iDisplay
// Build the object from an array of "attCode"=>"value")
//
$bFullyLoaded = true; // ... set to false if any attribute is not found
- if (is_null($aAttToLoad) || !array_key_exists($sClassAlias, $aAttToLoad))
- {
+ if (is_null($aAttToLoad) || !array_key_exists($sClassAlias, $aAttToLoad)) {
$aAttList = MetaModel::ListAttributeDefs(get_class($this));
- }
- else
- {
+ } else {
$aAttList = $aAttToLoad[$sClassAlias];
}
- foreach($aAttList as $sAttCode=>$oAttDef)
- {
+ foreach ($aAttList as $sAttCode => $oAttDef) {
// Skip links (could not be loaded by the mean of this query)
/** @var \AttributeDefinition $oAttDef */
- if ($oAttDef->IsLinkSet()) continue;
+ if ($oAttDef->IsLinkSet()) {
+ continue;
+ }
- if (!$oAttDef->LoadInObject()) continue;
+ if (!$oAttDef->LoadInObject()) {
+ continue;
+ }
unset($value);
$bIsDefined = false;
- if ($oAttDef->LoadFromClassTables())
- {
+ if ($oAttDef->LoadFromClassTables()) {
// Note: we assume that, for a given attribute, if it can be loaded,
// then one column will be found with an empty suffix, the others have a suffix
// Take care: the function isset will return false in case the value is null,
@@ -538,46 +524,34 @@ abstract class DBObject implements iDisplay
}
}
- if (!$bIsDefined && array_key_exists($sAttRef, $aRow))
- {
+ if (!$bIsDefined && array_key_exists($sAttRef, $aRow)) {
$value = $oAttDef->FromSQLToValue($aRow, $sAttRef);
$bIsDefined = true;
}
- }
- else
- {
+ } else {
$value = $oAttDef->ReadExternalValues($this);
$bIsDefined = true;
}
- if ($bIsDefined)
- {
+ if ($bIsDefined) {
$this->m_aCurrValues[$sAttCode] = $value;
- if (is_object($value))
- {
+ if (is_object($value)) {
$this->m_aOrigValues[$sAttCode] = clone $value;
- }
- else
- {
+ } else {
$this->m_aOrigValues[$sAttCode] = $value;
}
$this->m_aLoadedAtt[$sAttCode] = true;
- }
- else
- {
+ } else {
// This attribute was expected and not found in the query columns
$bFullyLoaded = false;
}
}
// Load extended data
- if ($aExtendedDataSpec != null)
- {
- foreach($aExtendedDataSpec['fields'] as $sColumn)
- {
+ if ($aExtendedDataSpec != null) {
+ foreach ($aExtendedDataSpec['fields'] as $sColumn) {
$sColRef = $sClassAlias.'_extdata_'.$sColumn;
- if (array_key_exists($sColRef, $aRow))
- {
+ if (array_key_exists($sColRef, $aRow)) {
$this->m_aExtendedData[$sColumn] = $aRow[$sColRef];
}
}
@@ -585,18 +559,18 @@ abstract class DBObject implements iDisplay
return $bFullyLoaded;
}
- /**
- * Protected raw Setter
- *
- * This method is an internal plumbing : it sets the value without doing any of the required processes.
- * The exposed API Setter is DBObject::Set()
- *
- * @internal
- * @see Set()
- *
- * @param string $sAttCode
- * @param mixed $value
- */
+ /**
+ * Protected raw Setter
+ *
+ * This method is an internal plumbing : it sets the value without doing any of the required processes.
+ * The exposed API Setter is DBObject::Set()
+ *
+ * @internal
+ * @see Set()
+ *
+ * @param string $sAttCode
+ * @param mixed $value
+ */
protected function _Set($sAttCode, $value)
{
$this->m_aCurrValues[$sAttCode] = $value;
@@ -604,25 +578,24 @@ abstract class DBObject implements iDisplay
unset($this->m_aModifiedAtt[$sAttCode]);
}
-
- /**
- * Attributes setter
- *
- * Set $sAttCode to $value.
- * The value must be valid according to the type of attribute : see the different {@see AttributeDefinition::MakeRealValue()} implementations
- * The value will not be recorded into the DB until DBObject::DBWrite() is called.
- *
- * @api
- *
- * @param string $sAttCode
- * @param mixed $value
- *
- * @return bool
- * @throws CoreException
- * @throws CoreUnexpectedValue
- *
- * @see DBWrite()
- */
+ /**
+ * Attributes setter
+ *
+ * Set $sAttCode to $value.
+ * The value must be valid according to the type of attribute : see the different {@see AttributeDefinition::MakeRealValue()} implementations
+ * The value will not be recorded into the DB until DBObject::DBWrite() is called.
+ *
+ * @api
+ *
+ * @param string $sAttCode
+ * @param mixed $value
+ *
+ * @return bool
+ * @throws CoreException
+ * @throws CoreUnexpectedValue
+ *
+ * @see DBWrite()
+ */
public function Set($sAttCode, $value)
{
if (!utils::StartsWith(get_class($this), 'CMDBChange') && $this->GetKey() > 0) {
@@ -676,8 +649,7 @@ abstract class DBObject implements iDisplay
/** @var \DBObject $value */
$this->m_aCurrValues[$sCode] = $value->Get($oDef->GetExtAttCode());
$this->m_aLoadedAtt[$sCode] = true;
- }
- elseif ($oDef->IsBasedOnOQLExpression()) {
+ } elseif ($oDef->IsBasedOnOQLExpression()) {
$this->m_aCurrValues[$sCode] = $this->GetDefaultValue($sCode);
unset($this->m_aLoadedAtt[$sCode]);
}
@@ -704,7 +676,7 @@ abstract class DBObject implements iDisplay
}
$this->_Set($sAttCode, $realvalue);
- $this->UpdateMetaAttributes(array($sAttCode));
+ $this->UpdateMetaAttributes([$sAttCode]);
// The object has changed, reset caches
$this->m_bCheckStatus = null;
@@ -717,13 +689,13 @@ abstract class DBObject implements iDisplay
}
/**
- * Helper to set a value only if it is currently undefined
- *
- * Call Set() only of the internal representation of the attribute is null.
- *
- * @api
- * @see Set()
- *
+ * Helper to set a value only if it is currently undefined
+ *
+ * Call Set() only of the internal representation of the attribute is null.
+ *
+ * @api
+ * @see Set()
+ *
* @param string $sAttCode
* @param mixed $value
*
@@ -736,26 +708,25 @@ abstract class DBObject implements iDisplay
{
$oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
$oCurrentValue = $this->Get($sAttCode);
- if ($oAttDef->IsNull($oCurrentValue))
- {
+ if ($oAttDef->IsNull($oCurrentValue)) {
$this->Set($sAttCode, $value);
}
}
- /**
- * Helper to set a value that fits the attribute max size
- *
- * compare $sValue against the field's max size in the database, and truncate it's ending in order to make it fit.
- * If $sValue is short enough, nothing is done.
- *
- * @api
- *
- * @param string $sAttCode
- * @param string $sValue
- *
- * @throws CoreException
- * @throws CoreUnexpectedValue
- */
+ /**
+ * Helper to set a value that fits the attribute max size
+ *
+ * compare $sValue against the field's max size in the database, and truncate it's ending in order to make it fit.
+ * If $sValue is short enough, nothing is done.
+ *
+ * @api
+ *
+ * @param string $sAttCode
+ * @param string $sValue
+ *
+ * @throws CoreException
+ * @throws CoreUnexpectedValue
+ */
public function SetTrim($sAttCode, $sValue)
{
$oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
@@ -785,20 +756,21 @@ abstract class DBObject implements iDisplay
// Activate any existing trigger
$sClass = get_class($this);
- $aParams = array('class_list' => MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
- $oSet = new DBObjectSet(DBObjectSearch::FromOQL('SELECT TriggerOnObjectDelete AS t WHERE t.target_class IN (:class_list)'), array(),
- $aParams);
+ $aParams = ['class_list' => MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL)];
+ $oSet = new DBObjectSet(
+ DBObjectSearch::FromOQL('SELECT TriggerOnObjectDelete AS t WHERE t.target_class IN (:class_list)'),
+ [],
+ $aParams
+ );
while ($oTrigger = $oSet->Fetch()) {
/** @var \TriggerOnObjectDelete $oTrigger */
try {
$oKPI = new ExecutionKPI();
$oTrigger->DoActivate($this->ToArgs('this'));
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$oTrigger->LogException($e, $this);
utils::EnrichRaisedException($oTrigger, $e);
- }
- finally {
+ } finally {
$oKPI->ComputeStatsForExtension($this, 'TriggerOnObjectDelete');
}
}
@@ -847,18 +819,18 @@ abstract class DBObject implements iDisplay
}
/**
- * Get the label of an attribute.
- *
- * Shortcut to the field's AttributeDefinition->GetLabel()
- *
- * @api
- *
- * @param string $sAttCode
- *
- * @return string
- *
- * @throws Exception
- */
+ * Get the label of an attribute.
+ *
+ * Shortcut to the field's AttributeDefinition->GetLabel()
+ *
+ * @api
+ *
+ * @param string $sAttCode
+ *
+ * @return string
+ *
+ * @throws Exception
+ */
public function GetLabel($sAttCode)
{
$oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
@@ -883,55 +855,45 @@ abstract class DBObject implements iDisplay
*/
public function Get($sAttCode)
{
- if (($iPos = strpos($sAttCode, '->')) === false)
- {
+ if (($iPos = strpos($sAttCode, '->')) === false) {
return $this->GetStrict($sAttCode);
- }
- else
- {
+ } else {
$sExtKeyAttCode = substr($sAttCode, 0, $iPos);
$sRemoteAttCode = substr($sAttCode, $iPos + 2);
- if (!MetaModel::IsValidAttCode(get_class($this), $sExtKeyAttCode))
- {
+ if (!MetaModel::IsValidAttCode(get_class($this), $sExtKeyAttCode)) {
throw new CoreException("Unknown external key '$sExtKeyAttCode' for the class ".get_class($this));
}
$oExtFieldAtt = MetaModel::FindExternalField(get_class($this), $sExtKeyAttCode, $sRemoteAttCode);
- if (!is_null($oExtFieldAtt))
- {
+ if (!is_null($oExtFieldAtt)) {
/** @var \AttributeExternalField $oExtFieldAtt */
return $this->GetStrict($oExtFieldAtt->GetCode());
- }
- else
- {
+ } else {
$oKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode);
/** @var \AttributeExternalKey $oKeyAttDef */
$sRemoteClass = $oKeyAttDef->GetTargetClass();
$oRemoteObj = MetaModel::GetObject($sRemoteClass, $this->GetStrict($sExtKeyAttCode), false);
- if (is_null($oRemoteObj))
- {
+ if (is_null($oRemoteObj)) {
return '';
- }
- else
- {
+ } else {
return $oRemoteObj->Get($sRemoteAttCode);
}
}
}
}
- /**
- * Getter : get values from the current object
- *
- * @internal
- * @see Get
- *
- * @param string $sAttCode
- *
- * @return int|mixed|null
- * @throws ArchivedObjectException
- * @throws CoreException
- */
+ /**
+ * Getter : get values from the current object
+ *
+ * @internal
+ * @see Get
+ *
+ * @param string $sAttCode
+ *
+ * @return int|mixed|null
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ */
public function GetStrict($sAttCode)
{
if ($sAttCode == 'id') {
@@ -961,8 +923,7 @@ abstract class DBObject implements iDisplay
/** @var \AttributeExternalField $oAttDef */
$sExtKeyAttCode = $oAttDef->GetKeyAttCode();
- if (($iRemote = $this->Get($sExtKeyAttCode)) && ($iRemote > 0)) // Objects in memory have negative IDs
- {
+ if (($iRemote = $this->Get($sExtKeyAttCode)) && ($iRemote > 0)) { // Objects in memory have negative IDs
$oExtKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode);
// Note: "allow all data" must be enabled because the external fields are always visible
// to the current user even if this is not the case for the remote object
@@ -990,7 +951,6 @@ abstract class DBObject implements iDisplay
$value = $this->m_aCurrValues[$sAttCode];
}
-
if ($value instanceof ormLinkSet) {
$value->Rewind();
}
@@ -998,23 +958,22 @@ abstract class DBObject implements iDisplay
return $value;
}
- /**
- * @see \DBObject::ListPreviousValuesForUpdatedAttributes() to get previous values anywhere in the CRUD stack
- * @see https://www.itophub.io/wiki/page?id=latest%3Acustomization%3Asequence_crud iTop CRUD stack documentation
- *
- * @param string $sAttCode
- *
- * @return mixed|null the value as it was before changed with {@see DBObject::Set()}.
- * Returns null if the attribute wasn't changed.
- * Values are reset during {@see DBObject::DBUpdate()}
- *
- * @throws CoreException if the attribute is unknown for the current object
- * @uses DBObject::$m_aOrigValues
- */
+ /**
+ * @see \DBObject::ListPreviousValuesForUpdatedAttributes() to get previous values anywhere in the CRUD stack
+ * @see https://www.itophub.io/wiki/page?id=latest%3Acustomization%3Asequence_crud iTop CRUD stack documentation
+ *
+ * @param string $sAttCode
+ *
+ * @return mixed|null the value as it was before changed with {@see DBObject::Set()}.
+ * Returns null if the attribute wasn't changed.
+ * Values are reset during {@see DBObject::DBUpdate()}
+ *
+ * @throws CoreException if the attribute is unknown for the current object
+ * @uses DBObject::$m_aOrigValues
+ */
public function GetOriginal($sAttCode)
{
- if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
- {
+ if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this)))) {
throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
}
$aOrigValues = $this->m_aOrigValues;
@@ -1026,31 +985,31 @@ abstract class DBObject implements iDisplay
return $this->m_aCurrValues;
}
- /**
- * Returns the default value of the $sAttCode.
- *
- * Returns the default value of the given attribute.
- *
- * @internal
- *
- * @param string $sAttCode
- *
- * @return mixed
- *
- * @throws Exception
- */
+ /**
+ * Returns the default value of the $sAttCode.
+ *
+ * Returns the default value of the given attribute.
+ *
+ * @internal
+ *
+ * @param string $sAttCode
+ *
+ * @return mixed
+ *
+ * @throws Exception
+ */
public function GetDefaultValue($sAttCode)
- {
- $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
- return $oAttDef->GetDefaultValue($this);
- }
+ {
+ $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
+ return $oAttDef->GetDefaultValue($this);
+ }
/**
* Returns data loaded by the mean of a dynamic and explicit JOIN
- *
- * @internal
- *
- * @return array|null
+ *
+ * @internal
+ *
+ * @return array|null
*/
public function GetExtendedData()
{
@@ -1058,14 +1017,14 @@ abstract class DBObject implements iDisplay
}
/**
- * Set the HighlightCode
- *
- * Switch to $sCode if it has a greater rank than the current code
- *
- * @internal
- * @used-by DBObject::ComputeHighlightCode()
- * @see m_sHighlightCode
- *
+ * Set the HighlightCode
+ *
+ * Switch to $sCode if it has a greater rank than the current code
+ *
+ * @internal
+ * @used-by DBObject::ComputeHighlightCode()
+ * @see m_sHighlightCode
+ *
* @param string $sCode
*
* @return void
@@ -1074,16 +1033,13 @@ abstract class DBObject implements iDisplay
{
$aHighlightScale = MetaModel::GetHighlightScale(get_class($this));
$fCurrentRank = 0.0;
- if (($this->m_sHighlightCode !== null) && array_key_exists($this->m_sHighlightCode, $aHighlightScale))
- {
+ if (($this->m_sHighlightCode !== null) && array_key_exists($this->m_sHighlightCode, $aHighlightScale)) {
$fCurrentRank = $aHighlightScale[$this->m_sHighlightCode]['rank'];
}
- if (array_key_exists($sCode, $aHighlightScale))
- {
+ if (array_key_exists($sCode, $aHighlightScale)) {
$fRank = $aHighlightScale[$sCode]['rank'];
- if ($fRank > $fCurrentRank)
- {
+ if ($fRank > $fCurrentRank) {
$this->m_sHighlightCode = $sCode;
}
}
@@ -1091,10 +1047,10 @@ abstract class DBObject implements iDisplay
/**
* Get the current HighlightCode
- *
- * @internal
- * @used-by DBObject::ComputeHighlightCode()
- *
+ *
+ * @internal
+ * @used-by DBObject::ComputeHighlightCode()
+ *
* @return string|null The Hightlight code (null if none set, meaning rank = 0)
*/
protected function GetHighlightCode()
@@ -1102,35 +1058,31 @@ abstract class DBObject implements iDisplay
return $this->m_sHighlightCode;
}
- /**
- * Compute the highlightCode
- *
- * @internal
- *
- * @example When TTR, then TTR of a UserRequest is greater thant a defined scale, the item is highlighted in the listings
- *
- * @return string|null The Hightlight code (null if none set, meaning rank = 0)
- *
- * @throws ArchivedObjectException
- * @throws CoreException
- */
+ /**
+ * Compute the highlightCode
+ *
+ * @internal
+ *
+ * @example When TTR, then TTR of a UserRequest is greater thant a defined scale, the item is highlighted in the listings
+ *
+ * @return string|null The Hightlight code (null if none set, meaning rank = 0)
+ *
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ */
protected function ComputeHighlightCode()
{
- if (MetaModel::HasLifecycle(get_class($this)))
- {
+ if (MetaModel::HasLifecycle(get_class($this))) {
$sState = $this->GetState();
$sCode = MetaModel::GetHighlightCode(get_class($this), $sState);
$this->SetHighlightCode($sCode);
}
// The check for each StopWatch if a HighlightCode is effective
- foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
- {
- if ($oAttDef instanceof AttributeStopWatch)
- {
+ foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) {
+ if ($oAttDef instanceof AttributeStopWatch) {
$oStopWatch = $this->Get($sAttCode);
$sCode = $oStopWatch->GetHighlightCode();
- if ($sCode !== '')
- {
+ if ($sCode !== '') {
$this->SetHighlightCode($sCode);
}
}
@@ -1138,28 +1090,27 @@ abstract class DBObject implements iDisplay
return $this->GetHighlightCode();
}
- /**
- * Updates the value of an external field by (re)loading the object
- * corresponding to the external key and getting the value from it
- *
- * UNUSED ?
- *
- * @internal
- * @todo: check if this is dead code.
- *
- * @param string $sAttCode Attribute code of the external field to update
- *
- * @return void
- *
- * @throws ArchivedObjectException
- * @throws CoreException
- * @throws CoreUnexpectedValue
- */
+ /**
+ * Updates the value of an external field by (re)loading the object
+ * corresponding to the external key and getting the value from it
+ *
+ * UNUSED ?
+ *
+ * @internal
+ * @todo: check if this is dead code.
+ *
+ * @param string $sAttCode Attribute code of the external field to update
+ *
+ * @return void
+ *
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ * @throws CoreUnexpectedValue
+ */
protected function UpdateExternalField($sAttCode)
{
$oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
- if ($oAttDef->IsExternalField())
- {
+ if ($oAttDef->IsExternalField()) {
/** @var \AttributeExternalField $oAttDef */
$sTargetClass = $oAttDef->GetTargetClass();
$objkey = $this->Get($oAttDef->GetKeyAttCode());
@@ -1167,8 +1118,7 @@ abstract class DBObject implements iDisplay
// to the current user even if this is not the case for the remote object
// This is consistent with the behavior of the lists
$oObj = MetaModel::GetObject($sTargetClass, $objkey, true, true);
- if (is_object($oObj))
- {
+ if (is_object($oObj)) {
$value = $oObj->Get($oAttDef->GetExtAttCode());
$this->Set($sAttCode, $value);
}
@@ -1177,9 +1127,9 @@ abstract class DBObject implements iDisplay
/**
* Overridable callback
- *
+ *
* @internal this method is elligible to the "overwritable-hook" tag. But it is willingly excluded.
- * @used-by DoComputeValues()
+ * @used-by DoComputeValues()
*/
public function ComputeValues()
{
@@ -1199,11 +1149,16 @@ abstract class DBObject implements iDisplay
// First check that we are not currently computing the fields
// (yes, we need to do some things like Set/Get to compute the fields which will in turn trigger the update...)
- foreach (debug_backtrace() as $aCallInfo)
- {
- if (!array_key_exists("class", $aCallInfo)) continue;
- if ($aCallInfo["class"] != get_class($this)) continue;
- if ($aCallInfo["function"] != "ComputeValues") continue;
+ foreach (debug_backtrace() as $aCallInfo) {
+ if (!array_key_exists("class", $aCallInfo)) {
+ continue;
+ }
+ if ($aCallInfo["class"] != get_class($this)) {
+ continue;
+ }
+ if ($aCallInfo["function"] != "ComputeValues") {
+ continue;
+ }
return; //skip!
}
$this->FireEventComputeValues($this->sStimulusBeingApplied);
@@ -1212,40 +1167,36 @@ abstract class DBObject implements iDisplay
$oKPI->ComputeStatsForExtension($this, 'ComputeValues');
}
- /**
- * @api
- *
- * @param string $sAttCode
- * @param bool $bLocalize
- *
- * @return string $sAttCode formatted as HTML for the console details forms (when viewing, not when editing !)
- * The returned string is already escaped, and as such is protected against XSS
- * The markup relies on a few assumptions (CSS) that could change without notice
- *
- * @throws ArchivedObjectException
- * @throws CoreException
- * @throws DictExceptionMissingString
- *
- * @see \Combodo\iTop\Form\Field\Field for rendering in portal forms
- */
+ /**
+ * @api
+ *
+ * @param string $sAttCode
+ * @param bool $bLocalize
+ *
+ * @return string $sAttCode formatted as HTML for the console details forms (when viewing, not when editing !)
+ * The returned string is already escaped, and as such is protected against XSS
+ * The markup relies on a few assumptions (CSS) that could change without notice
+ *
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ * @throws DictExceptionMissingString
+ *
+ * @see \Combodo\iTop\Form\Field\Field for rendering in portal forms
+ */
public function GetAsHTML($sAttCode, $bLocalize = true)
{
$sClass = get_class($this);
$oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
- if ($oAtt->IsExternalKey(EXTKEY_ABSOLUTE))
- {
+ if ($oAtt->IsExternalKey(EXTKEY_ABSOLUTE)) {
//return $this->Get($sAttCode.'_friendlyname');
/** @var \AttributeExternalKey $oAtt */
$sTargetClass = $oAtt->GetTargetClass(EXTKEY_ABSOLUTE);
$iTargetKey = $this->Get($sAttCode);
- if ($iTargetKey < 0)
- {
+ if ($iTargetKey < 0) {
// the key points to an object that exists only in memory... no hyperlink points to it yet
return '';
- }
- else
- {
+ } else {
$sHtmlLabel = utils::EscapeHtml($this->Get($sAttCode.'_friendlyname'));
$bArchived = $this->IsArchived($sAttCode);
$bObsolete = $this->IsObsolete($sAttCode);
@@ -1258,183 +1209,175 @@ abstract class DBObject implements iDisplay
return $oAtt->GetAsHTML($this->Get($sAttCode), $this, $bLocalize);
}
- /**
- * Get the value as it must be in the edit areas (forms)
- *
- * Makes a raw text representation of the value.
- *
- * @internal
- *
- * @param string $sAttCode
- *
- * @return int|mixed|string
- *
- * @throws ArchivedObjectException
- * @throws CoreException
- */
+ /**
+ * Get the value as it must be in the edit areas (forms)
+ *
+ * Makes a raw text representation of the value.
+ *
+ * @internal
+ *
+ * @param string $sAttCode
+ *
+ * @return int|mixed|string
+ *
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ */
public function GetEditValue($sAttCode)
{
$sClass = get_class($this);
$oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
- if ($oAtt->IsExternalKey())
- {
+ if ($oAtt->IsExternalKey()) {
/** @var \AttributeExternalKey $oAtt */
$sTargetClass = $oAtt->GetTargetClass();
- if ($this->IsNew())
- {
+ if ($this->IsNew()) {
// The current object exists only in memory, don't try to query it in the DB !
// instead let's query for the object pointed by the external key, and get its name
$targetObjId = $this->Get($sAttCode);
$oTargetObj = MetaModel::GetObject($sTargetClass, $targetObjId, false); // false => not sure it exists
- if (is_object($oTargetObj))
- {
+ if (is_object($oTargetObj)) {
$sEditValue = $oTargetObj->GetName();
- }
- else
- {
+ } else {
$sEditValue = 0;
}
- }
- else
- {
+ } else {
$sEditValue = $this->Get($sAttCode.'_friendlyname');
}
- }
- else
- {
+ } else {
$sEditValue = $oAtt->GetEditValue($this->Get($sAttCode), $this);
}
return $sEditValue;
}
- /**
- * Get $sAttCode formatted as XML
- *
- * The returned value is a text that is suitable for insertion into an XML node.
- * Depending on the type of attribute, the returned text is either:
- * * A literal, with XML entities already escaped,
- * * XML
- *
- * @api
- *
- * @param string $sAttCode
- * @param bool $bLocalize
- *
- * @return mixed
- *
- * @throws ArchivedObjectException
- * @throws CoreException
- */
+ /**
+ * Get $sAttCode formatted as XML
+ *
+ * The returned value is a text that is suitable for insertion into an XML node.
+ * Depending on the type of attribute, the returned text is either:
+ * * A literal, with XML entities already escaped,
+ * * XML
+ *
+ * @api
+ *
+ * @param string $sAttCode
+ * @param bool $bLocalize
+ *
+ * @return mixed
+ *
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ */
public function GetAsXML($sAttCode, $bLocalize = true)
{
$oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
return $oAtt->GetAsXML($this->Get($sAttCode), $this, $bLocalize);
}
- /**
- * Get $sAttCode formatted as CSV
- *
- * @api
- *
- * @param string $sAttCode
- * @param string $sSeparator
- * @param string $sTextQualifier
- * @param bool $bLocalize
- * @param bool $bConvertToPlainText
- *
- * @return string
- *
- * @throws ArchivedObjectException
- * @throws CoreException
- */
+ /**
+ * Get $sAttCode formatted as CSV
+ *
+ * @api
+ *
+ * @param string $sAttCode
+ * @param string $sSeparator
+ * @param string $sTextQualifier
+ * @param bool $bLocalize
+ * @param bool $bConvertToPlainText
+ *
+ * @return string
+ *
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ */
public function GetAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"', $bLocalize = true, $bConvertToPlainText = false)
{
$oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
return $oAtt->GetAsCSV($this->Get($sAttCode), $sSeparator, $sTextQualifier, $this, $bLocalize, $bConvertToPlainText);
}
- /**
- *
- * @see GetAsHTML()
- * @see GetOriginal()
- *
- * @param string $sAttCode
- * @param bool $bLocalize
- *
- * @return string
- * @throws CoreException
- */
+ /**
+ *
+ * @see GetAsHTML()
+ * @see GetOriginal()
+ *
+ * @param string $sAttCode
+ * @param bool $bLocalize
+ *
+ * @return string
+ * @throws CoreException
+ */
public function GetOriginalAsHTML($sAttCode, $bLocalize = true)
{
$oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
return $oAtt->GetAsHTML($this->GetOriginal($sAttCode), $this, $bLocalize);
}
- /**
- *
- * @see GetAsXML()
- * @see GetOriginal()
- *
- * @param string $sAttCode
- * @param bool $bLocalize
- *
- * @return mixed
- * @throws CoreException
- */
+ /**
+ *
+ * @see GetAsXML()
+ * @see GetOriginal()
+ *
+ * @param string $sAttCode
+ * @param bool $bLocalize
+ *
+ * @return mixed
+ * @throws CoreException
+ */
public function GetOriginalAsXML($sAttCode, $bLocalize = true)
{
$oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
return $oAtt->GetAsXML($this->GetOriginal($sAttCode), $this, $bLocalize);
}
- /**
- *
- * @see GetAsCSV()
- * @see GetOriginal()
- *
- * @param string $sAttCode
- * @param string $sSeparator
- * @param string $sTextQualifier
- * @param bool $bLocalize
- * @param bool $bConvertToPlainText
- *
- * @return string
- * @throws CoreException
- */
+ /**
+ *
+ * @see GetAsCSV()
+ * @see GetOriginal()
+ *
+ * @param string $sAttCode
+ * @param string $sSeparator
+ * @param string $sTextQualifier
+ * @param bool $bLocalize
+ * @param bool $bConvertToPlainText
+ *
+ * @return string
+ * @throws CoreException
+ */
public function GetOriginalAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"', $bLocalize = true, $bConvertToPlainText = false)
{
$oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
return $oAtt->GetAsCSV($this->GetOriginal($sAttCode), $sSeparator, $sTextQualifier, $this, $bLocalize, $bConvertToPlainText);
}
- /**
- * Return an hyperlink pointing to <$sObjClass, $sObjKey>
- *
- * @internal
- *
- * @param string $sObjClass
- * @param string $sObjKey
- * @param string $sHtmlLabel Label with HTML entities escaped (< escaped as <)
- * @param null|string $sUrlMakerClass if not null, the class must expose a public method ''MakeObjectUrl(string $sObjClass, string $sObjKey)''
- * @param bool $bWithNavigationContext
- * @param bool $bArchived
- * @param bool $bObsolete
- *
- * @return string the HTML markup pointing to <$sObjClass, $sObjKey>
- *
- * @throws \ArchivedObjectException
- * @throws \CoreException
- * @throws \DictExceptionMissingString
- */
+ /**
+ * Return an hyperlink pointing to <$sObjClass, $sObjKey>
+ *
+ * @internal
+ *
+ * @param string $sObjClass
+ * @param string $sObjKey
+ * @param string $sHtmlLabel Label with HTML entities escaped (< escaped as <)
+ * @param null|string $sUrlMakerClass if not null, the class must expose a public method ''MakeObjectUrl(string $sObjClass, string $sObjKey)''
+ * @param bool $bWithNavigationContext
+ * @param bool $bArchived
+ * @param bool $bObsolete
+ *
+ * @return string the HTML markup pointing to <$sObjClass, $sObjKey>
+ *
+ * @throws \ArchivedObjectException
+ * @throws \CoreException
+ * @throws \DictExceptionMissingString
+ */
public static function MakeHyperLink($sObjClass, $sObjKey, $sHtmlLabel = '', $sUrlMakerClass = null, $bWithNavigationContext = true, $bArchived = false, $bObsolete = false, $bIgnorePreview = false)
{
- if ($sObjKey <= 0) return ''.Dict::S('UI:UndefinedObject').' '; // Objects built in memory have negative IDs
+ if ($sObjKey <= 0) {
+ return ''.Dict::S('UI:UndefinedObject').' ';
+ } // Objects built in memory have negative IDs
// Safety net
//
- if (empty($sHtmlLabel))
- {
+ if (empty($sHtmlLabel)) {
// If the object if not issued from a query but constructed programmatically
// the label may be empty. In this case run a query to get the object's friendly name
$sObjOql = 'SELECT '.$sObjClass.' WHERE id='.$sObjKey;
@@ -1459,29 +1402,21 @@ abstract class DBObject implements iDisplay
$sUrl = ApplicationContext::MakeObjectUrl($sObjClass, $sObjKey, $sUrlMakerClass, $bWithNavigationContext);
$bClickable = !$bArchived || utils::IsArchiveMode();
- if ($bArchived)
- {
+ if ($bArchived) {
$sSpanClass = 'archived';
$sFA = 'fa-archive object-archived';
$sHint = Dict::S('ObjectRef:Archived');
- }
- elseif ($bObsolete)
- {
+ } elseif ($bObsolete) {
$sSpanClass = 'obsolete';
$sFA = 'fa-eye-slash object-obsolete';
$sHint = Dict::S('ObjectRef:Obsolete');
- }
- else
- {
+ } else {
$sSpanClass = '';
$sFA = '';
}
- if ($sFA == '')
- {
+ if ($sFA == '') {
$sIcon = '';
- }
- else
- {
+ } else {
if ($bClickable) {
$sIcon = " ";
} else {
@@ -1489,63 +1424,57 @@ abstract class DBObject implements iDisplay
}
}
- if ($bClickable && (strlen($sUrl) > 0))
- {
+ if ($bClickable && (strlen($sUrl) > 0)) {
$sHLink = "$sIcon$sHtmlLabel ";
- }
- else
- {
+ } else {
$sHLink = $sIcon.$sHtmlLabel;
}
$sPreview = '';
- if(SummaryCardService::IsAllowedForClass($sObjClass) && $bIgnorePreview === false){
+ if (SummaryCardService::IsAllowedForClass($sObjClass) && $bIgnorePreview === false) {
$sPreview = SummaryCardService::GetHyperlinkMarkup($sObjClass, $sObjKey);
}
$sRet = "$sHLink ";
return $sRet;
}
- /**
- * Return an hyperlink pointing to the current DBObject
- *
- * @api
- *
- * @param string $sUrlMakerClass
- * @param bool $bWithNavigationContext
- * @param string $sLabel
- *
- * @return string
- *
- * @throws ArchivedObjectException
- * @throws CoreException
- * @throws DictExceptionMissingString
- */
+ /**
+ * Return an hyperlink pointing to the current DBObject
+ *
+ * @api
+ *
+ * @param string $sUrlMakerClass
+ * @param bool $bWithNavigationContext
+ * @param string $sLabel
+ *
+ * @return string
+ *
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ * @throws DictExceptionMissingString
+ */
public function GetHyperlink($sUrlMakerClass = null, $bWithNavigationContext = true, $sLabel = null, $bIgnorePreview = false)
{
- if($sLabel === null)
- {
- $sLabel = $this->GetName();
- }
+ if ($sLabel === null) {
+ $sLabel = $this->GetName();
+ }
$bArchived = $this->IsArchived();
$bObsolete = $this->IsObsolete();
return self::MakeHyperLink(get_class($this), $this->GetKey(), $sLabel, $sUrlMakerClass, $bWithNavigationContext, $bArchived, $bObsolete, $bIgnorePreview);
}
- /**
- * @internal
- *
- * @param string $sClass
- *
- * @return mixed
- */
+ /**
+ * @internal
+ *
+ * @param string $sClass
+ *
+ * @return mixed
+ */
public static function ComputeStandardUIPage($sClass)
{
- static $aUIPagesCache = array(); // Cache to store the php page used to display each class of object
- if (!isset($aUIPagesCache[$sClass]))
- {
+ static $aUIPagesCache = []; // Cache to store the php page used to display each class of object
+ if (!isset($aUIPagesCache[$sClass])) {
$UIPage = false;
- if (is_callable("$sClass::GetUIPage"))
- {
+ if (is_callable("$sClass::GetUIPage")) {
$UIPage = eval("return $sClass::GetUIPage();"); // May return false in case of error
}
$aUIPagesCache[$sClass] = $UIPage === false ? './UI.php' : $UIPage;
@@ -1554,93 +1483,87 @@ abstract class DBObject implements iDisplay
return $sPage;
}
- /**
- * @internal
- *
- * @return string
- */
+ /**
+ * @internal
+ *
+ * @return string
+ */
public static function GetUIPage()
{
return 'UI.php';
}
-
-
-
- /**
- * Whether $value is valid as a primary key
- *
- * @internal
- *
- * @param string $value
- *
- * @return bool
- */
+ /**
+ * Whether $value is valid as a primary key
+ *
+ * @internal
+ *
+ * @param string $value
+ *
+ * @return bool
+ */
public static function IsValidPKey($value)
{
- // this function could be in the metamodel ?
+ // this function could be in the metamodel ?
return ((string)$value === (string)(int)$value);
}
- /**
- * Primary key Getter
- *
- * Get the id
- *
- * @api
- *
- * @return string|null
- */
+ /**
+ * Primary key Getter
+ *
+ * Get the id
+ *
+ * @api
+ *
+ * @return string|null
+ */
public function GetKey()
{
return $this->m_iKey;
}
- /**
- * Primary key Setter
- * Usable only for not yet persisted DBObjects
- *
- * @internal
- *
- * @param int $iNewKey the desired identifier
- *
- * @throws CoreException
- */
+ /**
+ * Primary key Setter
+ * Usable only for not yet persisted DBObjects
+ *
+ * @internal
+ *
+ * @param int $iNewKey the desired identifier
+ *
+ * @throws CoreException
+ */
public function SetKey($iNewKey)
{
- if (!self::IsValidPKey($iNewKey))
- {
+ if (!self::IsValidPKey($iNewKey)) {
throw new CoreException("An object id must be an integer value ($iNewKey)");
}
- if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey))
- {
+ if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey)) {
throw new CoreException("Changing the key ({$this->m_iKey} to $iNewKey) on an object (class {".get_class($this).") wich already exists in the Database");
}
$this->m_iKey = $iNewKey;
}
- /**
- * Get the icon representing this object
- *
- * @api
- *
- * @param boolean $bImgTag If true the result is a full IMG tag (or an empty string if no icon is defined)
- *
- * @return string Either the full IMG tag ($bImgTag == true) or just the URL to the icon file
- * @throws ArchivedObjectException
- * @throws CoreException
- */
+ /**
+ * Get the icon representing this object
+ *
+ * @api
+ *
+ * @param boolean $bImgTag If true the result is a full IMG tag (or an empty string if no icon is defined)
+ *
+ * @return string Either the full IMG tag ($bImgTag == true) or just the URL to the icon file
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ */
public function GetIcon($bImgTag = true)
{
$sClass = get_class($this);
- if($this->HasHighlightIcon()) {
+ if ($this->HasHighlightIcon()) {
$sIconUrl = MetaModel::GetHighlightScale($sClass)[$this->ComputeHighlightCode()]['icon'];
- if($bImgTag) {
+ if ($bImgTag) {
return " ";
- }
- else {
+ } else {
return $sIconUrl;
}
}
@@ -1649,10 +1572,9 @@ abstract class DBObject implements iDisplay
$sImageAttCode = MetaModel::GetImageAttributeCode($sClass);
$sIconUrl = $this->HasInstanceIcon() ? $this->Get($sImageAttCode)->GetDisplayURL($sClass, $this->GetKey(), $sImageAttCode) : '';
if (strlen($sIconUrl) > 0) {
- if($bImgTag) {
+ if ($bImgTag) {
return " ";
- }
- else {
+ } else {
return $sIconUrl;
}
}
@@ -1695,11 +1617,9 @@ abstract class DBObject implements iDisplay
$sCode = $this->ComputeHighlightCode();
$sClass = get_class($this);
- if($sCode != '')
- {
+ if ($sCode != '') {
$aHighlightScale = MetaModel::GetHighlightScale($sClass);
- if (array_key_exists($sCode, $aHighlightScale))
- {
+ if (array_key_exists($sCode, $aHighlightScale)) {
$bHasHighlightIcon = true;
}
}
@@ -1711,9 +1631,9 @@ abstract class DBObject implements iDisplay
* Get the label of a class
*
* Returns the label as defined in the dictionary for the language of the current user
- *
- * @api
- *
+ *
+ * @api
+ *
* @return string (empty for default name scheme)
*/
public static function GetClassName($sClass)
@@ -1726,14 +1646,14 @@ abstract class DBObject implements iDisplay
* Get the description of a class
*
* Returns the label as defined in the dictionary for the language of the current user
- *
- * @internal
- *
+ *
+ * @internal
+ *
* @param string $sClass
*
* @return string
*/
- final static public function GetClassDescription($sClass)
+ final public static function GetClassDescription($sClass)
{
$sStringCode = 'Class:'.$sClass.'+';
return Dict::S($sStringCode, '');
@@ -1748,7 +1668,7 @@ abstract class DBObject implements iDisplay
* @since 3.0.0 N°580 New $sType parameter
* @since 3.3.0 N°4107 Should never be overriden
*/
- public final function GetName($sType = FriendlyNameType::SHORT)
+ final public function GetName($sType = FriendlyNameType::SHORT)
{
return utils::EscapeHtml($this->GetRawName($sType));
}
@@ -1778,69 +1698,60 @@ abstract class DBObject implements iDisplay
}
/**
- * Helper to get the state
- *
- * @api
- *
+ * Helper to get the state
+ *
+ * @api
+ *
* @return mixed|string '' if no state attribute, object representing its value otherwise
* @throws \CoreException
*/
public function GetState()
{
$sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
- if (empty($sStateAttCode))
- {
+ if (empty($sStateAttCode)) {
return '';
- }
- else
- {
+ } else {
return $this->Get($sStateAttCode);
}
}
- /**
- * Get the label (raw text) of the current state
- * helper for MetaModel::GetStateLabel()
- *
- * @api
- *
- * @return mixed|string
- *
- * @throws ArchivedObjectException
- * @throws CoreException
- */
+ /**
+ * Get the label (raw text) of the current state
+ * helper for MetaModel::GetStateLabel()
+ *
+ * @api
+ *
+ * @return mixed|string
+ *
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ */
public function GetStateLabel()
{
$sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
- if (empty($sStateAttCode))
- {
+ if (empty($sStateAttCode)) {
return '';
- }
- else
- {
+ } else {
$sStateValue = $this->Get($sStateAttCode);
return MetaModel::GetStateLabel(get_class($this), $sStateValue);
}
}
- /**
- * Get the description of the state
- *
- * @api
- *
- * @return mixed|string
- * @throws ArchivedObjectException
- * @throws CoreException
- */
+ /**
+ * Get the description of the state
+ *
+ * @api
+ *
+ * @return mixed|string
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ */
public function GetStateDescription()
{
$sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
- if (empty($sStateAttCode))
- {
+ if (empty($sStateAttCode)) {
return '';
- }
- else
- {
+ } else {
$sStateValue = $this->Get($sStateAttCode);
return MetaModel::GetStateDescription(get_class($this), $sStateValue);
}
@@ -1856,15 +1767,14 @@ abstract class DBObject implements iDisplay
return null;
}
-
/**
* Get predefined objects
- *
+ *
* The predefined objects will be synchronized with the DB at each install/upgrade
- * As soon as a class has predefined objects, then nobody can create nor delete objects
- *
- * @internal
- *
+ * As soon as a class has predefined objects, then nobody can create nor delete objects
+ *
+ * @internal
+ *
* @return array An array of id => array of attcode => php value(so-called "real value": integer, string, ormDocument, DBObjectSet, etc.)
*/
public static function GetPredefinedObjects()
@@ -1873,10 +1783,10 @@ abstract class DBObject implements iDisplay
}
/**
- * Get the flags for the given state
- *
- * @overwritable-hook You can extend this method in order to provide your own logic. If you do so, rely on the parent as a fallback if you have uncovered $sAttCode
- *
+ * Get the flags for the given state
+ *
+ * @overwritable-hook You can extend this method in order to provide your own logic. If you do so, rely on the parent as a fallback if you have uncovered $sAttCode
+ *
* @param string $sAttCode $sAttCode The code of the attribute
* @param array $aReasons To store the reasons why the attribute is read-only (info about the synchro replicas)
* @param string $sTargetState The target state in which to evaluate the flags, if empty the current state will be used
@@ -1884,41 +1794,34 @@ abstract class DBObject implements iDisplay
* @return integer the binary combination of flags for the given attribute in the given state of the object.
* Values can be one of the OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY, ... (see define in metamodel.class.php)
* Combine multiple values using the "|" operator, for example `OPT_ATT_READONLY | OPT_ATT_HIDDEN`.
- *
+ *
* @throws \CoreException
*
* @see GetInitialStateAttributeFlags for creation
*/
- public function GetAttributeFlags($sAttCode, &$aReasons = array(), $sTargetState = '')
+ public function GetAttributeFlags($sAttCode, &$aReasons = [], $sTargetState = '')
{
$iFlags = 0; // By default (if no life cycle) no flag at all
$sClass = get_class($this);
$aReadOnlyAtts = $this->GetReadOnlyAttributes();
- if (($aReadOnlyAtts != null) && (in_array($sAttCode, $aReadOnlyAtts)))
- {
+ if (($aReadOnlyAtts != null) && (in_array($sAttCode, $aReadOnlyAtts))) {
return OPT_ATT_READONLY;
}
- if (MetaModel::HasLifecycle($sClass))
- {
- if ($sTargetState != '')
- {
+ if (MetaModel::HasLifecycle($sClass)) {
+ if ($sTargetState != '') {
$iFlags = MetaModel::GetAttributeFlags($sClass, $sTargetState, $sAttCode);
- }
- else
- {
+ } else {
$sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
$iFlags = MetaModel::GetAttributeFlags($sClass, $this->Get($sStateAttCode), $sAttCode);
}
}
- $aReasons = array();
+ $aReasons = [];
$iSynchroFlags = 0;
- if ($this->InSyncScope())
- {
+ if ($this->InSyncScope()) {
$iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
- if ($iSynchroFlags & OPT_ATT_SLAVE)
- {
+ if ($iSynchroFlags & OPT_ATT_SLAVE) {
$iSynchroFlags |= OPT_ATT_READONLY;
}
}
@@ -1926,117 +1829,113 @@ abstract class DBObject implements iDisplay
return $iFlags | $iSynchroFlags | $iExtensionsFlags; // Combine both sets of flags
}
- /**
- * Whether the attribute is read-only
- *
- * @internal
- *
- * @param string $sAttCode
- * @param array $aReasons To store the reasons why the attribute is read-only (info about the synchro replicas)
- *
- * @return int Values can be one of the OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY, ... (see define in metamodel.class.php)
- *
- * @throws \CoreException
- */
- public function IsAttributeReadOnlyForCurrentState($sAttCode, &$aReasons = array())
+ /**
+ * Whether the attribute is read-only
+ *
+ * @internal
+ *
+ * @param string $sAttCode
+ * @param array $aReasons To store the reasons why the attribute is read-only (info about the synchro replicas)
+ *
+ * @return int Values can be one of the OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY, ... (see define in metamodel.class.php)
+ *
+ * @throws \CoreException
+ */
+ public function IsAttributeReadOnlyForCurrentState($sAttCode, &$aReasons = [])
{
$iAttFlags = $this->GetAttributeFlags($sAttCode, $aReasons);
return ($iAttFlags & OPT_ATT_READONLY);
}
- /**
- * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
- * for the given attribute in a transition
- *
- * @internal
- *
- * @param string $sAttCode $sAttCode The code of the attribute
- * @param string $sStimulus The stimulus code to apply
- * @param array|null $aReasons To store the reasons why the attribute is read-only (info about the synchro replicas)
- * @param string $sOriginState The state from which to apply $sStimulus, if empty current state will be used
- *
- * @return integer Flags: the binary combination of the flags applicable to this attribute
- * @throws ArchivedObjectException
- * @throws CoreException
- */
- public function GetTransitionFlags($sAttCode, $sStimulus, &$aReasons = array(), $sOriginState = '')
- {
- $iFlags = 0; // By default (if no lifecycle) no flag at all
- $sClass = get_class($this);
+ /**
+ * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
+ * for the given attribute in a transition
+ *
+ * @internal
+ *
+ * @param string $sAttCode $sAttCode The code of the attribute
+ * @param string $sStimulus The stimulus code to apply
+ * @param array|null $aReasons To store the reasons why the attribute is read-only (info about the synchro replicas)
+ * @param string $sOriginState The state from which to apply $sStimulus, if empty current state will be used
+ *
+ * @return integer Flags: the binary combination of the flags applicable to this attribute
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ */
+ public function GetTransitionFlags($sAttCode, $sStimulus, &$aReasons = [], $sOriginState = '')
+ {
+ $iFlags = 0; // By default (if no lifecycle) no flag at all
+ $sClass = get_class($this);
- // If no state attribute, there is no lifecycle
- if (!MetaModel::HasLifecycle($sClass))
- {
- return $iFlags;
- }
+ // If no state attribute, there is no lifecycle
+ if (!MetaModel::HasLifecycle($sClass)) {
+ return $iFlags;
+ }
- // Retrieving current state if necessary
- if ($sOriginState === '')
- {
- $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
- $sOriginState = $this->Get($sStateAttCode);
- }
+ // Retrieving current state if necessary
+ if ($sOriginState === '') {
+ $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
+ $sOriginState = $this->Get($sStateAttCode);
+ }
- // Retrieving attribute flags
- $iAttributeFlags = $this->GetAttributeFlags($sAttCode, $aReasons, $sOriginState);
+ // Retrieving attribute flags
+ $iAttributeFlags = $this->GetAttributeFlags($sAttCode, $aReasons, $sOriginState);
- // Retrieving transition flags
- $iTransitionFlags = MetaModel::GetTransitionFlags($sClass, $sOriginState, $sStimulus, $sAttCode);
+ // Retrieving transition flags
+ $iTransitionFlags = MetaModel::GetTransitionFlags($sClass, $sOriginState, $sStimulus, $sAttCode);
- // Merging transition flags with attribute flags
- $iFlags = $iTransitionFlags | $iAttributeFlags;
+ // Merging transition flags with attribute flags
+ $iFlags = $iTransitionFlags | $iAttributeFlags;
- return $iFlags;
- }
+ return $iFlags;
+ }
- /**
- * Returns an array of attribute codes (with their flags) when $sStimulus is applied on the object in the $sOriginState state.
- * Note: Attributes (and flags) from the target state and the transition are combined.
- *
- * @internal
- *
- * @param string $sStimulus
- * @param string $sOriginState Default is current state
- *
- * @return array
- * @throws CoreException
- */
- public function GetTransitionAttributes($sStimulus, $sOriginState = null)
- {
- $sObjClass = get_class($this);
+ /**
+ * Returns an array of attribute codes (with their flags) when $sStimulus is applied on the object in the $sOriginState state.
+ * Note: Attributes (and flags) from the target state and the transition are combined.
+ *
+ * @internal
+ *
+ * @param string $sStimulus
+ * @param string $sOriginState Default is current state
+ *
+ * @return array
+ * @throws CoreException
+ */
+ public function GetTransitionAttributes($sStimulus, $sOriginState = null)
+ {
+ $sObjClass = get_class($this);
- // Defining current state as origin state if not specified
- if($sOriginState === null)
- {
- $sOriginState = $this->GetState();
- }
+ // Defining current state as origin state if not specified
+ if ($sOriginState === null) {
+ $sOriginState = $this->GetState();
+ }
- $aAttributes = MetaModel::GetTransitionAttributes($sObjClass, $sStimulus, $sOriginState);
+ $aAttributes = MetaModel::GetTransitionAttributes($sObjClass, $sStimulus, $sOriginState);
- return $aAttributes;
- }
+ return $aAttributes;
+ }
/**
* @param string $sAttCode The code of the attribute
* @param array $aReasons
*
- * @overwritable-hook You can extend this method in order to provide your own logic
- *
+ * @overwritable-hook You can extend this method in order to provide your own logic
+ *
* @return integer The binary combination of the flags for the given attribute for the current state of the object considered as an INITIAL state.
* Values can be one of the OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY, ... (see define in metamodel.class.php)
- *
+ *
* @throws \CoreException
*
* @see GetAttributeFlags when modifying the object
*/
- public function GetInitialStateAttributeFlags($sAttCode, &$aReasons = array())
+ public function GetInitialStateAttributeFlags($sAttCode, &$aReasons = [])
{
$iFlags = 0;
$sClass = get_class($this);
- if (MetaModel::HasLifecycle($sClass))
- {
+ if (MetaModel::HasLifecycle($sClass)) {
$sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
$iFlags = MetaModel::GetInitialStateAttributeFlags($sClass, $this->Get($sStateAttCode), $sAttCode);
}
@@ -2062,89 +1961,63 @@ abstract class DBObject implements iDisplay
*/
public function CheckValue($sAttCode, $value = null)
{
- if (!is_null($value))
- {
+ if (!is_null($value)) {
$toCheck = $value;
- }
- else
- {
+ } else {
$toCheck = $this->Get($sAttCode);
}
$oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
- if (!$oAtt->IsWritable())
- {
+ if (!$oAtt->IsWritable()) {
return true;
- }
- elseif ($oAtt->IsNull($toCheck))
- {
- if ($oAtt->IsNullAllowed())
- {
+ } elseif ($oAtt->IsNull($toCheck)) {
+ if ($oAtt->IsNullAllowed()) {
return true;
- }
- else
- {
+ } else {
return "Null not allowed";
}
- }
- elseif ($oAtt->IsExternalKey())
- {
- if (!MetaModel::SkipCheckExtKeys())
- {
+ } elseif ($oAtt->IsExternalKey()) {
+ if (!MetaModel::SkipCheckExtKeys()) {
/** @var \AttributeExternalKey $oAtt */
$sTargetClass = $oAtt->GetTargetClass();
if (false === MetaModel::IsObjectInDB($sTargetClass, $toCheck)) {
return "Target object not found ({$sTargetClass}::{$toCheck})";
}
}
- if ($oAtt->IsHierarchicalKey())
- {
+ if ($oAtt->IsHierarchicalKey()) {
// This check cannot be deactivated since otherwise the user may break things by a CSV import of a bulk modify
- $aValues = $oAtt->GetAllowedValues(array('this' => $this));
- if (!array_key_exists($toCheck, $aValues))
- {
+ $aValues = $oAtt->GetAllowedValues(['this' => $this]);
+ if (!array_key_exists($toCheck, $aValues)) {
return "Value not allowed [$toCheck]";
}
}
- }
- elseif ($oAtt instanceof AttributeTagSet)
- {
- if (is_string($toCheck))
- {
+ } elseif ($oAtt instanceof AttributeTagSet) {
+ if (is_string($toCheck)) {
$oTag = new ormTagSet(get_class($this), $sAttCode, $oAtt->GetMaxItems());
- try
- {
+ try {
$oTag->SetValues(explode(' ', $toCheck));
- } catch (Exception $e)
- {
+ } catch (Exception $e) {
return "Tag value '$toCheck' is not a valid tag list";
}
return true;
}
- if ($toCheck instanceof ormTagSet)
- {
+ if ($toCheck instanceof ormTagSet) {
return true;
}
return "Bad type";
- }
- elseif ($oAtt instanceof AttributeSet)
- {
- if (is_string($toCheck))
- {
+ } elseif ($oAtt instanceof AttributeSet) {
+ if (is_string($toCheck)) {
$oTag = new ormSet(get_class($this), $sAttCode, $oAtt->GetMaxItems());
- try
- {
- $aValues = array();
- foreach(explode(',', $toCheck) as $sValue)
- {
+ try {
+ $aValues = [];
+ foreach (explode(',', $toCheck) as $sValue) {
$aValues[] = trim($sValue);
}
$oTag->SetValues($aValues);
- } catch (Exception $e)
- {
+ } catch (Exception $e) {
return "Set value '$toCheck' is not a valid set";
}
@@ -2173,9 +2046,7 @@ abstract class DBObject implements iDisplay
if (!$oAtt->CheckFormat($toCheck)) {
return "Wrong format [$toCheck]";
}
- }
- else
- {
+ } else {
return $oAtt->CheckValue($this, $toCheck);
}
return true;
@@ -2194,11 +2065,11 @@ abstract class DBObject implements iDisplay
}
/**
- * @internal
- *
+ * @internal
+ *
* @throws \CoreException
* @throws \OQLException
- *
+ *
* @since 2.6.0 N°659 uniqueness constraint
* @api
*/
@@ -2207,28 +2078,23 @@ abstract class DBObject implements iDisplay
$sCurrentClass = get_class($this);
$aUniquenessRules = MetaModel::GetUniquenessRules($sCurrentClass);
- foreach ($aUniquenessRules as $sUniquenessRuleId => $aUniquenessRuleProperties)
- {
- if ($aUniquenessRuleProperties['disabled'] === true)
- {
+ foreach ($aUniquenessRules as $sUniquenessRuleId => $aUniquenessRuleProperties) {
+ if ($aUniquenessRuleProperties['disabled'] === true) {
continue;
}
// No iTopMutex so there might be concurrent access !
// But the necessary lock would have a high performance cost :(
$bHasDuplicates = $this->HasObjectsInDbForUniquenessRule($sUniquenessRuleId, $aUniquenessRuleProperties);
- if ($bHasDuplicates)
- {
+ if ($bHasDuplicates) {
$bIsBlockingRule = $aUniquenessRuleProperties['is_blocking'];
- if (is_null($bIsBlockingRule))
- {
+ if (is_null($bIsBlockingRule)) {
$bIsBlockingRule = true;
}
$sErrorMessage = $this->GetUniquenessRuleMessage($sUniquenessRuleId);
- if ($bIsBlockingRule)
- {
+ if ($bIsBlockingRule) {
$this->m_aCheckIssues[] = $sErrorMessage;
continue;
}
@@ -2239,9 +2105,9 @@ abstract class DBObject implements iDisplay
}
/**
- *
- * @internal
- *
+ *
+ * @internal
+ *
* @param string $sUniquenessRuleId
*
* @return string dict key : Class:$sClassName/UniquenessRule:$sUniquenessRuleId if none then will use Core:UniquenessDefaultError
@@ -2270,7 +2136,7 @@ abstract class DBObject implements iDisplay
$oString = new TemplateString($sTemplate);
- return $oString->Render(array('this' => $this));
+ return $oString->Render(['this' => $this]);
}
/**
@@ -2323,8 +2189,7 @@ abstract class DBObject implements iDisplay
}
return Dict::Format($sMessageKey, ...$aPlaceholdersData);
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
ExceptionLog::LogException($e);
return null;
@@ -2355,36 +2220,33 @@ abstract class DBObject implements iDisplay
}
/**
- * @param array $aUniquenessRuleProperties uniqueness rule properties
+ * @param array $aUniquenessRuleProperties uniqueness rule properties
*
- * @param string $sUniquenessRuleId uniqueness rule ID
+ * @param string $sUniquenessRuleId uniqueness rule ID
* @return \DBSearch
* @throws \OQLException
- * @throws \CoreException
- *
- * @internal
- *
- * @since 2.6.0 N°659 uniqueness constraint
- * @since 2.7.11 3.1.2 3.2.0 N°4314 Fix Uniqueness rules not working with Silo
+ * @throws \CoreException
+ *
+ * @internal
+ *
+ * @since 2.6.0 N°659 uniqueness constraint
+ * @since 2.7.11 3.1.2 3.2.0 N°4314 Fix Uniqueness rules not working with Silo
*/
protected function GetSearchForUniquenessRule($sUniquenessRuleId, $aUniquenessRuleProperties)
{
$sRuleRootClass = $aUniquenessRuleProperties['root_class'];
$sOqlUniquenessQuery = "SELECT $sRuleRootClass";
- if (!(empty($sUniquenessFilter = $aUniquenessRuleProperties['filter'])))
- {
+ if (!(empty($sUniquenessFilter = $aUniquenessRuleProperties['filter']))) {
$sOqlUniquenessQuery .= ' WHERE '.$sUniquenessFilter;
}
/** @var \DBObjectSearch $oUniquenessQuery */
$oUniquenessQuery = DBObjectSearch::FromOQL($sOqlUniquenessQuery);
- if (!$this->IsNew())
- {
+ if (!$this->IsNew()) {
$oUniquenessQuery->AddCondition('id', $this->GetKey(), '<>');
}
- foreach ($aUniquenessRuleProperties['attributes'] as $sAttributeCode)
- {
+ foreach ($aUniquenessRuleProperties['attributes'] as $sAttributeCode) {
$attributeValue = $this->Get($sAttributeCode);
$oUniquenessQuery->AddCondition($sAttributeCode, $attributeValue, '=');
}
@@ -2441,9 +2303,11 @@ abstract class DBObject implements iDisplay
}
if (!empty($aDuplicatesFields)) {
- $this->m_aCheckWarnings[] = Dict::Format('Core:AttributeLinkedSetDuplicatesFound',
+ $this->m_aCheckWarnings[] = Dict::Format(
+ 'Core:AttributeLinkedSetDuplicatesFound',
$oAttDef->GetLabel(),
- implode(', ', $aDuplicatesFields));
+ implode(', ', $aDuplicatesFields)
+ );
}
}
@@ -2456,8 +2320,8 @@ abstract class DBObject implements iDisplay
* @overwritable-hook You can extend this method in order to provide your own logic.
* @see CheckToWrite()
* @see $m_aCheckIssues
- * @see $m_aCheckWarnings
- *
+ * @see $m_aCheckWarnings
+ *
* @throws \ArchivedObjectException
* @throws \CoreException
* @throws \OQLException
@@ -2468,7 +2332,7 @@ abstract class DBObject implements iDisplay
$aChanges = $this->ListChanges();
- foreach($aChanges as $sAttCode => $value) {
+ foreach ($aChanges as $sAttCode => $value) {
$res = $this->CheckValue($sAttCode);
if ($res !== true) {
$sAttLabel = $this->GetLabel($sAttCode);
@@ -2478,31 +2342,25 @@ abstract class DBObject implements iDisplay
$this->DoCheckLinkedSetDuplicates($sAttCode, $value);
}
- if (count($this->m_aCheckIssues) > 0)
- {
+ if (count($this->m_aCheckIssues) > 0) {
// No need to check consistency between attributes if any of them has
// an unexpected value
return;
}
$res = $this->CheckConsistency();
- if ($res !== true)
- {
+ if ($res !== true) {
// $res contains the error description
$this->m_aCheckIssues[] = Dict::Format('Core:CheckConsistencyError', $res);
}
// Synchronization: are we attempting to modify an attribute for which an external source is master?
//
- if ($this->m_bIsInDB && $this->InSyncScope() && (count($aChanges) > 0))
- {
- foreach($aChanges as $sAttCode => $value)
- {
+ if ($this->m_bIsInDB && $this->InSyncScope() && (count($aChanges) > 0)) {
+ foreach ($aChanges as $sAttCode => $value) {
$iFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
- if ($iFlags & OPT_ATT_SLAVE)
- {
+ if ($iFlags & OPT_ATT_SLAVE) {
// Note: $aReasonInfo['name'] could be reported (the task owning the attribute)
- if (!empty($aReasons))
- {
+ if (!empty($aReasons)) {
$sAttLabel = $this->GetLabel($sAttCode);
$this->m_aCheckIssues[] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $sAttLabel, $sAttCode);
}
@@ -2547,7 +2405,7 @@ abstract class DBObject implements iDisplay
}
}
- final static protected function GetObjectIfNotInCRUDStack($sClass, $sKey)
+ final protected static function GetObjectIfNotInCRUDStack($sClass, $sKey)
{
if (DBObject::IsObjectCurrentlyInCrud($sClass, $sKey)) {
return null;
@@ -2581,7 +2439,7 @@ abstract class DBObject implements iDisplay
if ($this->IsNew()) {
$this->CheckToWriteForSingleTargetObject_Internal('add', $oTargetObject, $sAttCodeMirrorLink, false);
- } else if ($bIsCheckToDelete) {
+ } elseif ($bIsCheckToDelete) {
$this->CheckToWriteForSingleTargetObject_Internal('remove', $oTargetObject, $sAttCodeMirrorLink, true);
} else {
if (array_key_exists($sExtKeyWithMirrorLinkAttCode, $aChanges)) {
@@ -2636,32 +2494,30 @@ abstract class DBObject implements iDisplay
}
/**
- * @api
- * @api-advanced
- *
+ * @api
+ * @api-advanced
+ *
* @return array containing :
* * $m_bCheckStatus
* * $m_aCheckIssues
* * $m_bSecurityIssue
*
- * @see $m_bCheckStatus
- * @see $m_aCheckIssues
- * @see $m_bSecurityIssue
- *
+ * @see $m_bCheckStatus
+ * @see $m_aCheckIssues
+ * @see $m_bSecurityIssue
+ *
* @throws \ArchivedObjectException
* @throws \CoreException
* @throws \OQLException
*/
final public function CheckToWrite($bDoComputeValues = true)
{
- if (MetaModel::SkipCheckToWrite())
- {
- return array(true, array());
+ if (MetaModel::SkipCheckToWrite()) {
+ return [true, []];
}
- if (is_null($this->m_bCheckStatus))
- {
- $this->m_aCheckIssues = array();
+ if (is_null($this->m_bCheckStatus)) {
+ $this->m_aCheckIssues = [];
if ($bDoComputeValues) {
$this->DoComputeValues();
@@ -2674,21 +2530,18 @@ abstract class DBObject implements iDisplay
$oKPI = new ExecutionKPI();
$this->DoCheckToWrite();
- $oKPI->ComputeStatsForExtension($this, 'DoCheckToWrite');
+ $oKPI->ComputeStatsForExtension($this, 'DoCheckToWrite');
$this->CheckToWriteForTargetObjects();
- if (count($this->m_aCheckIssues) == 0)
- {
+ if (count($this->m_aCheckIssues) == 0) {
$this->m_bCheckStatus = true;
- }
- else
- {
+ } else {
$this->m_bCheckStatus = false;
}
}
- return array($this->m_bCheckStatus, $this->m_aCheckIssues, $this->m_bSecurityIssue);
+ return [$this->m_bCheckStatus, $this->m_aCheckIssues, $this->m_bSecurityIssue];
}
/**
@@ -2745,7 +2598,7 @@ abstract class DBObject implements iDisplay
if (($oAttDef instanceof AttributeHierarchicalKey) || ($oAttDef instanceof AttributeExternalKey)) {
$sRemoteObjectClass = $oAttDef->GetTargetClass();
$sRemoteObjectKey = $this->Get($sAttDefCode);
- } else if ($oAttDef instanceof AttributeObjectKey) {
+ } elseif ($oAttDef instanceof AttributeObjectKey) {
$sRemoteObjectClassAttCode = $oAttDef->Get('class_attcode');
$sRemoteObjectClass = $this->Get($sRemoteObjectClassAttCode);
$sRemoteObjectKey = $this->Get($sAttDefCode);
@@ -2761,7 +2614,7 @@ abstract class DBObject implements iDisplay
// 0 : Undefined ext. key (EG. non-mandatory and no value provided)
// < 0 : Non yet persisted object
- /** @noinspection TypeUnsafeComparisonInspection Non-strict comparison as object ID can be string */
+ /** @noinspection TypeUnsafeComparisonInspection Non-strict comparison as object ID can be string */
if ($sRemoteObjectKey <= 0) {
continue;
}
@@ -2777,94 +2630,86 @@ abstract class DBObject implements iDisplay
*
* an array of displayable error is added in {@see DBObject::$m_aDeleteIssues}
*
- * @internal
- *
+ * @internal
+ *
* @param \DeletionPlan $oDeletionPlan
*
* @throws \CoreException
*/
protected function DoCheckToDelete(&$oDeletionPlan)
{
- if ($this->InSyncScope())
- {
+ if ($this->InSyncScope()) {
- foreach ($this->GetSynchroData() as $iSourceId => $aSourceData)
- {
- foreach ($aSourceData['replica'] as $oReplica)
- {
+ foreach ($this->GetSynchroData() as $iSourceId => $aSourceData) {
+ foreach ($aSourceData['replica'] as $oReplica) {
$oDeletionPlan->AddToDelete($oReplica, DEL_SILENT);
}
/** @var \SynchroDataSource $oDataSource */
$oDataSource = $aSourceData['source'];
- if ($oDataSource->GetKey() == SynchroExecution::GetCurrentTaskId())
- {
+ if ($oDataSource->GetKey() == SynchroExecution::GetCurrentTaskId()) {
// The current task has the right to delete the object
continue;
}
$oReplica = reset($aSourceData['replica']); // Take the first one
- if ($oReplica->Get('status_dest_creator') != 1)
- {
+ if ($oReplica->Get('status_dest_creator') != 1) {
// The object is not owned by the task
continue;
}
$sLink = $oDataSource->GetName();
$sUserDeletePolicy = $oDataSource->Get('user_delete_policy');
- switch($sUserDeletePolicy)
- {
- case 'nobody':
- $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink);
- break;
-
- case 'administrators':
- if (!UserRights::IsAdministrator())
- {
+ switch ($sUserDeletePolicy) {
+ case 'nobody':
$this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink);
- }
- break;
+ break;
- case 'everybody':
- default:
- // Ok
- break;
+ case 'administrators':
+ if (!UserRights::IsAdministrator()) {
+ $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink);
+ }
+ break;
+
+ case 'everybody':
+ default:
+ // Ok
+ break;
}
}
}
}
- /**
- * @internal
- *
- * @param \DeletionPlan $oDeletionPlan
- *
- * @return bool
- * @throws CoreException
- */
+ /**
+ * @internal
+ *
+ * @param \DeletionPlan $oDeletionPlan
+ *
+ * @return bool
+ * @throws CoreException
+ */
public function CheckToDelete(&$oDeletionPlan)
- {
+ {
$this->AddCurrentObjectInCrudStack('DELETE');
try {
$this->MakeDeletionPlan($oDeletionPlan);
$oDeletionPlan->ComputeResults();
- }
- finally {
+ } finally {
$this->RemoveCurrentObjectInCrudStack();
}
return (!$oDeletionPlan->FoundStopper());
}
- /**
- * @internal
- *
- * @param array $aProposal
- *
- * @return array
- * @throws Exception
- */
+ /**
+ * @internal
+ *
+ * @param array $aProposal
+ *
+ * @return array
+ * @throws Exception
+ */
protected function ListChangedValues(array $aProposal)
{
- $aDelta = array();
+ $aDelta = [];
$sClass = get_class($this);
if (MetaModel::HasLifecycle($sClass) && utils::IsNotNullOrEmptyString($this->sStimulusBeingApplied)) {
$sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
@@ -2873,52 +2718,36 @@ abstract class DBObject implements iDisplay
$aDelta[$sStateAttCode] = $this->m_aCurrValues[$sStateAttCode];
}
}
- foreach ($aProposal as $sAtt => $proposedValue)
- {
- if (!array_key_exists($sAtt, $this->m_aOrigValues))
- {
+ foreach ($aProposal as $sAtt => $proposedValue) {
+ if (!array_key_exists($sAtt, $this->m_aOrigValues)) {
// The value was not set
$aDelta[$sAtt] = $proposedValue;
- }
- elseif(!array_key_exists($sAtt, $this->m_aTouchedAtt) || (array_key_exists($sAtt, $this->m_aModifiedAtt) && $this->m_aModifiedAtt[$sAtt] == false))
- {
+ } elseif (!array_key_exists($sAtt, $this->m_aTouchedAtt) || (array_key_exists($sAtt, $this->m_aModifiedAtt) && $this->m_aModifiedAtt[$sAtt] == false)) {
// This attCode was never set, cannot be modified
// or the same value - as the original value - was set, and has been verified as equivalent to the original value
continue;
- }
- else if (array_key_exists($sAtt, $this->m_aModifiedAtt) && $this->m_aModifiedAtt[$sAtt] == true)
- {
+ } elseif (array_key_exists($sAtt, $this->m_aModifiedAtt) && $this->m_aModifiedAtt[$sAtt] == true) {
// We already know that the value is really modified
$aDelta[$sAtt] = $proposedValue;
- }
- elseif(is_object($proposedValue))
- {
+ } elseif (is_object($proposedValue)) {
$oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAtt);
// The value is an object, the comparison is not strict
- if (!$oAttDef->Equals($this->m_aOrigValues[$sAtt], $proposedValue))
- {
+ if (!$oAttDef->Equals($this->m_aOrigValues[$sAtt], $proposedValue)) {
$aDelta[$sAtt] = $proposedValue;
$this->m_aModifiedAtt[$sAtt] = true; // Really modified
- }
- else
- {
+ } else {
$this->m_aModifiedAtt[$sAtt] = false; // Not really modified
}
- }
- else
- {
+ } else {
// The value is a scalar, the comparison must be 100% strict
- if($this->m_aOrigValues[$sAtt] !== $proposedValue)
- {
+ if ($this->m_aOrigValues[$sAtt] !== $proposedValue) {
//echo "$sAtt:\n";
//var_dump($this->m_aOrigValues[$sAtt]);
//var_dump($proposedValue);
//echo " \n";
$aDelta[$sAtt] = $proposedValue;
$this->m_aModifiedAtt[$sAtt] = true; // Really modified
- }
- else
- {
+ } else {
$this->m_aModifiedAtt[$sAtt] = false; // Not really modified
}
}
@@ -2962,15 +2791,13 @@ abstract class DBObject implements iDisplay
*/
public function ListPreviousValuesForUpdatedAttributes()
{
- if (empty($this->m_aPreviousValuesForUpdatedAttributes))
- {
- return array();
+ if (empty($this->m_aPreviousValuesForUpdatedAttributes)) {
+ return [];
}
return $this->m_aPreviousValuesForUpdatedAttributes;
}
-
/**
* Whether an object was modified since last read from the DB or not
* (ie: does it differ from the DB ?)
@@ -2996,33 +2823,27 @@ abstract class DBObject implements iDisplay
*/
public function Equals($oSibling)
{
- if (get_class($oSibling) != get_class($this))
- {
+ if (get_class($oSibling) != get_class($this)) {
return false;
}
- if ($this->GetKey() != $oSibling->GetKey())
- {
+ if ($this->GetKey() != $oSibling->GetKey()) {
return false;
}
- if ($this->m_bIsInDB)
- {
+ if ($this->m_bIsInDB) {
// If one has changed, then consider them as being different
- if ($this->IsModified() || $oSibling->IsModified())
- {
+ if ($this->IsModified() || $oSibling->IsModified()) {
return false;
}
- }
- else
- {
+ } else {
// Todo - implement this case (loop on every attribute)
//foreach(MetaModel::ListAttributeDefs(get_class($this) as $sAttCode => $oAttDef)
//{
- //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
- //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
- //if (!$oAttDef->Equals($this->m_CurrentValues[$sAttCode], $oSibling->m_CurrentValues[$sAttCode]))
- //{
- //return false;
- //}
+ //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
+ //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
+ //if (!$oAttDef->Equals($this->m_CurrentValues[$sAttCode], $oSibling->m_CurrentValues[$sAttCode]))
+ //{
+ //return false;
+ //}
//}
return false;
}
@@ -3031,27 +2852,32 @@ abstract class DBObject implements iDisplay
/**
* Used only by insert, Meant to be overloaded
- *
- * @overwritable-hook You can extend this method in order to provide your own logic.
+ *
+ * @overwritable-hook You can extend this method in order to provide your own logic.
*/
protected function OnObjectKeyReady()
- {
- }
+ {
+ }
/**
* used both by insert/update
*
- * @internal
- *
+ * @internal
+ *
* @throws \CoreException
*/
private function DBWriteLinks()
{
- foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
- {
- if (!$oAttDef->IsLinkSet()) continue;
- if (!array_key_exists($sAttCode, $this->m_aTouchedAtt)) continue;
- if (array_key_exists($sAttCode, $this->m_aModifiedAtt) && ($this->m_aModifiedAtt[$sAttCode] == false)) continue;
+ foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) {
+ if (!$oAttDef->IsLinkSet()) {
+ continue;
+ }
+ if (!array_key_exists($sAttCode, $this->m_aTouchedAtt)) {
+ continue;
+ }
+ if (array_key_exists($sAttCode, $this->m_aModifiedAtt) && ($this->m_aModifiedAtt[$sAttCode] == false)) {
+ continue;
+ }
/** @var \ormLinkSet $oLinkSet */
$oLinkSet = $this->m_aCurrValues[$sAttCode];
@@ -3062,49 +2888,53 @@ abstract class DBObject implements iDisplay
/**
* Used both by insert/update
*
- * @internal
- *
+ * @internal
+ *
* @throws \CoreException
*/
private function WriteExternalAttributes()
{
- foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
- {
- if (!$oAttDef->LoadInObject()) continue;
- if (!array_key_exists($sAttCode, $this->m_aTouchedAtt)) continue;
- if (array_key_exists($sAttCode, $this->m_aModifiedAtt) && ($this->m_aModifiedAtt[$sAttCode] === false)) continue;
+ foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) {
+ if (!$oAttDef->LoadInObject()) {
+ continue;
+ }
+ if (!array_key_exists($sAttCode, $this->m_aTouchedAtt)) {
+ continue;
+ }
+ if (array_key_exists($sAttCode, $this->m_aModifiedAtt) && ($this->m_aModifiedAtt[$sAttCode] === false)) {
+ continue;
+ }
$oAttDef->WriteExternalValues($this);
}
}
-
- /**
- * Note: this is experimental - it was designed to speed up the setup of iTop
- * Known limitations:
- * - does not work with multi-table classes (issue with the unique id to maintain in several tables)
- * - the id of the object is not updated
- *
- * @internal
- * @experimental
- */
- static public final function BulkInsertStart()
+ /**
+ * Note: this is experimental - it was designed to speed up the setup of iTop
+ * Known limitations:
+ * - does not work with multi-table classes (issue with the unique id to maintain in several tables)
+ * - the id of the object is not updated
+ *
+ * @internal
+ * @experimental
+ */
+ final public static function BulkInsertStart()
{
self::$m_bBulkInsert = true;
}
- /**
- *
- * @internal
- * @experimental
- */
- static public final function BulkInsertFlush()
+ /**
+ *
+ * @internal
+ * @experimental
+ */
+ final public static function BulkInsertFlush()
{
- if (!self::$m_bBulkInsert) return;
+ if (!self::$m_bBulkInsert) {
+ return;
+ }
- foreach(self::$m_aBulkInsertCols as $sClass => $aTables)
- {
- foreach ($aTables as $sTable => $sColumns)
- {
+ foreach (self::$m_aBulkInsertCols as $sClass => $aTables) {
+ foreach ($aTables as $sTable => $sColumns) {
$sValues = implode(', ', self::$m_aBulkInsertItems[$sClass][$sTable]);
$sInsertSQL = "INSERT INTO `$sTable` ($sColumns) VALUES $sValues";
CMDBSource::InsertInto($sInsertSQL);
@@ -3112,15 +2942,15 @@ abstract class DBObject implements iDisplay
}
// Reset
- self::$m_aBulkInsertItems = array();
- self::$m_aBulkInsertCols = array();
+ self::$m_aBulkInsertItems = [];
+ self::$m_aBulkInsertCols = [];
self::$m_bBulkInsert = false;
}
/**
* Persists new object in the DB
- *
- * @internal
+ *
+ * @internal
*
* @param string $sTableClass
*
@@ -3132,65 +2962,57 @@ abstract class DBObject implements iDisplay
{
$sTable = MetaModel::DBGetTable($sTableClass);
// Abstract classes or classes having no specific attribute do not have an associated table
- if ($sTable == '') { return false; }
+ if ($sTable == '') {
+ return false;
+ }
$sClass = get_class($this);
// fields in first array, values in the second
- $aFieldsToWrite = array();
- $aValuesToWrite = array();
+ $aFieldsToWrite = [];
+ $aValuesToWrite = [];
- if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
- {
+ if (!empty($this->m_iKey) && ($this->m_iKey >= 0)) {
// Add it to the list of fields to write
$aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
$aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
}
- $aHierarchicalKeys = array();
+ $aHierarchicalKeys = [];
- foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef) {
+ foreach (MetaModel::ListAttributeDefs($sTableClass) as $sAttCode => $oAttDef) {
// Skip this attribute if not defined in this table
if ((!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode) && !$oAttDef->CopyOnAllTables())
|| $oAttDef->IsExternalField()) {
continue;
}
$aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
- foreach($aAttColumns as $sColumn => $sValue)
- {
+ foreach ($aAttColumns as $sColumn => $sValue) {
$aFieldsToWrite[] = "`$sColumn`";
$aValuesToWrite[] = CMDBSource::Quote($sValue);
}
- if ($oAttDef->IsHierarchicalKey())
- {
+ if ($oAttDef->IsHierarchicalKey()) {
$aHierarchicalKeys[$sAttCode] = $oAttDef;
}
}
- if (count($aValuesToWrite) == 0) { return false; }
-
- if (MetaModel::DBIsReadOnly())
- {
- $iNewKey = -1;
+ if (count($aValuesToWrite) == 0) {
+ return false;
}
- else
- {
- if (self::$m_bBulkInsert)
- {
- if (!isset(self::$m_aBulkInsertCols[$sClass][$sTable]))
- {
+
+ if (MetaModel::DBIsReadOnly()) {
+ $iNewKey = -1;
+ } else {
+ if (self::$m_bBulkInsert) {
+ if (!isset(self::$m_aBulkInsertCols[$sClass][$sTable])) {
self::$m_aBulkInsertCols[$sClass][$sTable] = implode(', ', $aFieldsToWrite);
}
- self::$m_aBulkInsertItems[$sClass][$sTable][] = '('.implode (', ', $aValuesToWrite).')';
+ self::$m_aBulkInsertItems[$sClass][$sTable][] = '('.implode(', ', $aValuesToWrite).')';
$iNewKey = 999999; // TODO - compute next id....
- }
- else
- {
- if (count($aHierarchicalKeys) > 0)
- {
- foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
- {
+ } else {
+ if (count($aHierarchicalKeys) > 0) {
+ foreach ($aHierarchicalKeys as $sAttCode => $oAttDef) {
$aValues = MetaModel::HKInsertChildUnder($this->m_aCurrValues[$sAttCode], $oAttDef, $sTable);
$aFieldsToWrite[] = '`'.$oAttDef->GetSQLRight().'`';
$aValuesToWrite[] = $aValues[$oAttDef->GetSQLRight()];
@@ -3203,8 +3025,7 @@ abstract class DBObject implements iDisplay
}
}
// Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
- if (empty($this->m_iKey))
- {
+ if (empty($this->m_iKey)) {
// Take the autonumber
$this->m_iKey = "$iNewKey";
}
@@ -3248,75 +3069,72 @@ abstract class DBObject implements iDisplay
return $this->m_iKey;
}
- /**
- * @internal
- *
- * @param array $aAuthorizedExtKeys
- * @param array $aStatements
- * @param string $sTableClass
- *
- * @throws CoreException
- * @throws MySQLException
- */
+ /**
+ * @internal
+ *
+ * @param array $aAuthorizedExtKeys
+ * @param array $aStatements
+ * @param string $sTableClass
+ *
+ * @throws CoreException
+ * @throws MySQLException
+ */
protected function MakeInsertStatementSingleTable($aAuthorizedExtKeys, &$aStatements, $sTableClass)
{
$sTable = MetaModel::DBGetTable($sTableClass);
// Abstract classes or classes having no specific attribute do not have an associated table
- if ($sTable == '') return;
+ if ($sTable == '') {
+ return;
+ }
// fields in first array, values in the second
- $aFieldsToWrite = array();
- $aValuesToWrite = array();
+ $aFieldsToWrite = [];
+ $aValuesToWrite = [];
- if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
- {
+ if (!empty($this->m_iKey) && ($this->m_iKey >= 0)) {
// Add it to the list of fields to write
$aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
$aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
}
- $aHierarchicalKeys = array();
- foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode => $oAttDef)
- {
+ $aHierarchicalKeys = [];
+ foreach (MetaModel::ListAttributeDefs($sTableClass) as $sAttCode => $oAttDef) {
// Skip this attribute if not defined in this table
if ((!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode))
|| $oAttDef->IsExternalField()) {
continue;
};
// Skip link set that can still be undefined though the object is 100% loaded
- if ($oAttDef->IsLinkSet()) continue;
+ if ($oAttDef->IsLinkSet()) {
+ continue;
+ }
$value = $this->m_aCurrValues[$sAttCode];
- if ($oAttDef->IsExternalKey())
- {
+ if ($oAttDef->IsExternalKey()) {
/** @var \AttributeExternalKey $oAttDef */
$sTargetClass = $oAttDef->GetTargetClass();
- if (is_array($aAuthorizedExtKeys))
- {
- if (!array_key_exists($sTargetClass, $aAuthorizedExtKeys) || !array_key_exists($value, $aAuthorizedExtKeys[$sTargetClass]))
- {
+ if (is_array($aAuthorizedExtKeys)) {
+ if (!array_key_exists($sTargetClass, $aAuthorizedExtKeys) || !array_key_exists($value, $aAuthorizedExtKeys[$sTargetClass])) {
$value = 0;
}
}
}
$aAttColumns = $oAttDef->GetSQLValues($value);
- foreach($aAttColumns as $sColumn => $sValue)
- {
+ foreach ($aAttColumns as $sColumn => $sValue) {
$aFieldsToWrite[] = "`$sColumn`";
$aValuesToWrite[] = CMDBSource::Quote($sValue);
}
- if ($oAttDef->IsHierarchicalKey())
- {
+ if ($oAttDef->IsHierarchicalKey()) {
$aHierarchicalKeys[$sAttCode] = $oAttDef;
}
}
- if (count($aValuesToWrite) == 0) return;
+ if (count($aValuesToWrite) == 0) {
+ return;
+ }
- if (count($aHierarchicalKeys) > 0)
- {
- foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
- {
+ if (count($aHierarchicalKeys) > 0) {
+ foreach ($aHierarchicalKeys as $sAttCode => $oAttDef) {
$aValues = MetaModel::HKInsertChildUnder($this->m_aCurrValues[$sAttCode], $oAttDef, $sTable);
$aFieldsToWrite[] = '`'.$oAttDef->GetSQLRight().'`';
$aValuesToWrite[] = $aValues[$oAttDef->GetSQLRight()];
@@ -3327,15 +3145,15 @@ abstract class DBObject implements iDisplay
$aStatements[] = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).");";
}
- /**
- * @internal
- *
- * @param array $aAuthorizedExtKeys
- * @param array $aStatements
- *
- * @throws CoreException
- * @throws MySQLException
- */
+ /**
+ * @internal
+ *
+ * @param array $aAuthorizedExtKeys
+ * @param array $aStatements
+ *
+ * @throws CoreException
+ * @throws MySQLException
+ */
public function MakeInsertStatements($aAuthorizedExtKeys, &$aStatements)
{
$sClass = get_class($this);
@@ -3345,15 +3163,15 @@ abstract class DBObject implements iDisplay
$this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sRootClass);
// Then do the leaf class, if different from the root class
- if ($sClass != $sRootClass)
- {
+ if ($sClass != $sRootClass) {
$this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sClass);
}
// Then do the other classes
- foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
- {
- if ($sParentClass == $sRootClass) continue;
+ foreach (MetaModel::EnumParentClasses($sClass) as $sParentClass) {
+ if ($sParentClass == $sRootClass) {
+ continue;
+ }
$this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sParentClass);
}
}
@@ -3361,11 +3179,11 @@ abstract class DBObject implements iDisplay
/**
* Persist an object to the DB, for the first time
*
- * @api
- * @see DBWrite
- *
+ * @api
+ * @see DBWrite
+ *
* @return string|null inserted object key
- *
+ *
* @throws \ArchivedObjectException
* @throws \CoreCannotSaveObjectException
* @throws \CoreException
@@ -3411,13 +3229,13 @@ abstract class DBObject implements iDisplay
// If not automatically computed, then check that the key is given by the caller
if (!MetaModel::IsAutoIncrementKey($sRootClass)) {
if (empty($this->m_iKey)) {
- throw new CoreWarning('Missing key for the object to write - This class is supposed to have a user defined key, not an autonumber', array('class' => $sRootClass));
+ throw new CoreWarning('Missing key for the object to write - This class is supposed to have a user defined key, not an autonumber', ['class' => $sRootClass]);
}
}
[$bRes, $aIssues] = $this->CheckToWrite(false);
if (!$bRes) {
- throw new CoreCannotSaveObjectException(array('issues' => $aIssues, 'class' => get_class($this), 'id' => $this->GetKey()));
+ throw new CoreCannotSaveObjectException(['issues' => $aIssues, 'class' => get_class($this), 'id' => $this->GetKey()]);
}
if ($this->m_iKey < 0) {
@@ -3479,8 +3297,7 @@ abstract class DBObject implements iDisplay
CMDBSource::Query('COMMIT');
}
break;
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
IssueLog::Error($e->getMessage());
if ($bIsTransactionEnabled) {
CMDBSource::Query('ROLLBACK');
@@ -3515,16 +3332,14 @@ abstract class DBObject implements iDisplay
try {
$this->PostInsertActions();
- }
- finally {
+ } finally {
MetaModel::StopReentranceProtection($this);
}
if ((count($this->ListChanges()) !== 0)) {
$this->DBUpdate();
}
- }
- finally {
+ } finally {
$this->RemoveCurrentObjectInCrudStack();
}
@@ -3548,14 +3363,13 @@ abstract class DBObject implements iDisplay
// Activate any existing trigger
$sClass = get_class($this);
- $aParams = array('class_list' => MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
- $oSet = new DBObjectSet(DBObjectSearch::FromOQL('SELECT TriggerOnObjectCreate AS t WHERE t.target_class IN (:class_list)'), array(), $aParams);
+ $aParams = ['class_list' => MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL)];
+ $oSet = new DBObjectSet(DBObjectSearch::FromOQL('SELECT TriggerOnObjectCreate AS t WHERE t.target_class IN (:class_list)'), [], $aParams);
while ($oTrigger = $oSet->Fetch()) {
/** @var \TriggerOnObjectCreate $oTrigger */
try {
$oTrigger->DoActivate($this->ToArgs('this'));
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$oTrigger->LogException($e, $this);
utils::EnrichRaisedException($oTrigger, $e);
}
@@ -3568,23 +3382,23 @@ abstract class DBObject implements iDisplay
$this->ActivateOnObjectUpdateTriggersForTargetObjects();
}
- /**
- * Creates a copy of the current object into the database
- *
- * @internal
- *
- * @param null $iNewKey
- *
- * @return int|null the id of the newly created object
- *
- * @throws ArchivedObjectException
- * @throws CoreCannotSaveObjectException
- * @throws CoreException
- * @throws CoreUnexpectedValue
- * @throws CoreWarning
- * @throws MySQLException
- * @throws OQLException
- */
+ /**
+ * Creates a copy of the current object into the database
+ *
+ * @internal
+ *
+ * @param null $iNewKey
+ *
+ * @return int|null the id of the newly created object
+ *
+ * @throws ArchivedObjectException
+ * @throws CoreCannotSaveObjectException
+ * @throws CoreException
+ * @throws CoreUnexpectedValue
+ * @throws CoreWarning
+ * @throws MySQLException
+ * @throws OQLException
+ */
public function DBClone($iNewKey = null)
{
$this->m_bIsInDB = false;
@@ -3629,8 +3443,7 @@ abstract class DBObject implements iDisplay
return false;
}
- if (!$this->m_bIsInDB)
- {
+ if (!$this->m_bIsInDB) {
throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
}
$sClass = get_class($this);
@@ -3641,7 +3454,6 @@ abstract class DBObject implements iDisplay
// Protect against infinite loop
$this->iUpdateLoopCount++;
-
try {
$this->DoComputeValues();
$this->ComputeStopWatchesDeadline(false);
@@ -3672,8 +3484,8 @@ abstract class DBObject implements iDisplay
// Activate any existing trigger
$sClass = get_class($this);
- $aHierarchicalKeys = array();
- $aDBChanges = array();
+ $aHierarchicalKeys = [];
+ $aDBChanges = [];
foreach ($aChanges as $sAttCode => $currentValue) {
$oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
if ($oAttDef->IsBasedOnDBColumns()) {
@@ -3748,7 +3560,7 @@ abstract class DBObject implements iDisplay
$this->DBWriteLinks();
$this->WriteExternalAttributes();
- $this->HandleTemporaryDescriptor();
+ $this->HandleTemporaryDescriptor();
if (count($aChanges) != 0) {
$this->RecordAttChanges($aChanges, $aOriginalValues);
@@ -3758,8 +3570,7 @@ abstract class DBObject implements iDisplay
CMDBSource::Query('COMMIT');
}
break;
- }
- catch (MySQLException $e) {
+ } catch (MySQLException $e) {
IssueLog::Error($e->getMessage());
if ($bIsTransactionEnabled) {
CMDBSource::Query('ROLLBACK');
@@ -3775,17 +3586,15 @@ abstract class DBObject implements iDisplay
}
}
}
- $aErrors = array($e->getMessage());
+ $aErrors = [$e->getMessage()];
throw new CoreCannotSaveObjectException(['id' => $this->GetKey(), 'class' => $sClass, 'issues' => $aErrors], $e);
- }
- catch (CoreCannotSaveObjectException $e) {
+ } catch (CoreCannotSaveObjectException $e) {
IssueLog::Error($e->getMessage());
if ($bIsTransactionEnabled) {
CMDBSource::Query('ROLLBACK');
}
throw $e;
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
IssueLog::Error($e->getMessage());
if ($bIsTransactionEnabled) {
CMDBSource::Query('ROLLBACK');
@@ -3799,8 +3608,8 @@ abstract class DBObject implements iDisplay
// new values are already in the object (call {@see DBObject::Get()} to get them)
// call {@see DBObject::ListPreviousValuesForUpdatedAttributes()} to get changed fields and previous values
$this->m_bDirty = false;
- $this->m_aTouchedAtt = array();
- $this->m_aModifiedAtt = array();
+ $this->m_aTouchedAtt = [];
+ $this->m_aModifiedAtt = [];
// Reset original values although the object has not been reloaded
foreach ($this->m_aLoadedAtt as $sAttCode => $bLoaded) {
if ($bLoaded) {
@@ -3818,14 +3627,12 @@ abstract class DBObject implements iDisplay
try {
$this->PostUpdateActions($this->m_aPreviousValuesForUpdatedAttributes, $sClass);
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->LogCRUDExit(__METHOD__, 'Error: '.$e->getMessage());
$aErrors = [$e->getMessage()];
throw new CoreException($e->getMessage(), ['id' => $this->GetKey(), 'class' => $sClass, 'issues' => $aErrors]);
}
- }
- finally {
+ } finally {
MetaModel::StopReentranceProtection($this);
}
@@ -3837,8 +3644,7 @@ abstract class DBObject implements iDisplay
}
$this->DBUpdate();
}
- }
- finally {
+ } finally {
$this->RemoveCurrentObjectInCrudStack();
$this->iUpdateLoopCount--;
}
@@ -3874,35 +3680,32 @@ abstract class DBObject implements iDisplay
$this->ActivateOnObjectUpdateTriggersForTargetObjects();
$sClass = get_class($this);
- if (utils::IsNotNullOrEmptyString($sStimulusBeingApplied))
- {
+ if (utils::IsNotNullOrEmptyString($sStimulusBeingApplied)) {
$sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
$sPreviousState = $this->m_aPreviousValuesForUpdatedAttributes[$sStateAttCode];
// Change state triggers...
- $aParams = array(
+ $aParams = [
'class_list' => MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL),
'previous_state' => $sPreviousState,
'new_state' => $this->Get($sStateAttCode),
- );
- $oSet = new DBObjectSet(DBObjectSearch::FromOQL('SELECT TriggerOnStateLeave AS t WHERE t.target_class IN (:class_list) AND t.state=:previous_state'), array(), $aParams);
+ ];
+ $oSet = new DBObjectSet(DBObjectSearch::FromOQL('SELECT TriggerOnStateLeave AS t WHERE t.target_class IN (:class_list) AND t.state=:previous_state'), [], $aParams);
while ($oTrigger = $oSet->Fetch()) {
/** @var \TriggerOnStateLeave $oTrigger */
try {
$oTrigger->DoActivate($this->ToArgs('this'));
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$oTrigger->LogException($e, $this);
utils::EnrichRaisedException($oTrigger, $e);
}
}
- $oSet = new DBObjectSet(DBObjectSearch::FromOQL('SELECT TriggerOnStateEnter AS t WHERE t.target_class IN (:class_list) AND t.state=:new_state'), array(), $aParams);
+ $oSet = new DBObjectSet(DBObjectSearch::FromOQL('SELECT TriggerOnStateEnter AS t WHERE t.target_class IN (:class_list) AND t.state=:new_state'), [], $aParams);
while ($oTrigger = $oSet->Fetch()) {
/** @var \TriggerOnStateEnter $oTrigger */
try {
$oTrigger->DoActivate($this->ToArgs('this'));
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$oTrigger->LogException($e, $this);
utils::EnrichRaisedException($oTrigger, $e);
}
@@ -3932,15 +3735,17 @@ abstract class DBObject implements iDisplay
// - TriggerOnObjectUpdate
$aClassList = MetaModel::EnumParentClasses(get_class($oObject), ENUM_PARENT_CLASSES_ALL);
- $aParams = array('class_list' => $aClassList);
- $oSet = new DBObjectSet(DBObjectSearch::FromOQL('SELECT TriggerOnObjectUpdate AS t WHERE t.target_class IN (:class_list)'),
- array(), $aParams);
+ $aParams = ['class_list' => $aClassList];
+ $oSet = new DBObjectSet(
+ DBObjectSearch::FromOQL('SELECT TriggerOnObjectUpdate AS t WHERE t.target_class IN (:class_list)'),
+ [],
+ $aParams
+ );
while ($oTrigger = $oSet->Fetch()) {
/** @var \TriggerOnObjectUpdate $oTrigger */
try {
$oTrigger->DoActivateForSpecificAttributes($oObject->ToArgs(), $aAttributes);
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$oTrigger->LogException($e, $oObject);
utils::EnrichRaisedException($oTrigger, $e);
}
@@ -3969,13 +3774,13 @@ abstract class DBObject implements iDisplay
$sClass = get_class($this);
// dirty object not allowed
- if($this->m_bDirty){
+ if ($this->m_bDirty) {
throw new CoreException("Invalid DBIncrement usage, dirty objects are not allowed. Call DBUpdate before calling DBIncrement.");
}
// ensure attribute type is AttributeInteger
$oAttr = MetaModel::GetAttributeDef($sClass, $sAttCode);
- if(!$oAttr instanceof AttributeInteger){
+ if (!$oAttr instanceof AttributeInteger) {
throw new CoreException(sprintf("Invalid DBIncrement usage, attribute type of {$sAttCode} is %s. Only AttributeInteger are compatibles with DBIncrement.", get_class($oAttr)));
}
@@ -4045,8 +3850,7 @@ abstract class DBObject implements iDisplay
$aParams = ['class_list' => MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL)];
$oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnObjectMention AS t WHERE t.target_class IN (:class_list)"), [], $aParams);
- while ($oTrigger = $oSet->Fetch())
- {
+ while ($oTrigger = $oSet->Fetch()) {
/** @var \TriggerOnObjectMention $oTrigger */
try {
// Ensure to handle only mentioned object in the trigger's scope
@@ -4055,8 +3859,7 @@ abstract class DBObject implements iDisplay
}
$oTrigger->DoActivate($aTriggerArgs);
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
utils::EnrichRaisedException($oTrigger, $e);
}
}
@@ -4075,12 +3878,11 @@ abstract class DBObject implements iDisplay
* @since 3.1.0 N°6299 - change visibility
* @throws \Exception
*/
- protected final function InitPreviousValuesForUpdatedAttributes()
+ final protected function InitPreviousValuesForUpdatedAttributes()
{
- $aChanges= $this->ListChanges();
- if (empty($aChanges))
- {
- $this->m_aPreviousValuesForUpdatedAttributes = array();
+ $aChanges = $this->ListChanges();
+ if (empty($aChanges)) {
+ $this->m_aPreviousValuesForUpdatedAttributes = [];
return;
}
@@ -4106,29 +3908,28 @@ abstract class DBObject implements iDisplay
*/
public function DBWrite()
{
- if ($this->m_bIsInDB)
- {
+ if ($this->m_bIsInDB) {
return $this->DBUpdate();
- }
- else
- {
+ } else {
return $this->DBInsert();
}
}
- /**
- * @internal
- *
- * @param string $sTableClass
- *
- * @throws CoreException
- * @throws MySQLException
- */
+ /**
+ * @internal
+ *
+ * @param string $sTableClass
+ *
+ * @throws CoreException
+ * @throws MySQLException
+ */
private function DBDeleteSingleTable($sTableClass)
{
$sTable = MetaModel::DBGetTable($sTableClass);
// Abstract classes or classes having no specific attribute do not have an associated table
- if ($sTable == '') return;
+ if ($sTable == '') {
+ return;
+ }
$sPKField = '`'.MetaModel::DBGetKey($sTableClass).'`';
$sKey = CMDBSource::Quote($this->m_iKey);
@@ -4152,8 +3953,7 @@ abstract class DBObject implements iDisplay
{
$this->LogCRUDEnter(__METHOD__);
- if (MetaModel::DBIsReadOnly())
- {
+ if (MetaModel::DBIsReadOnly()) {
$this->LogCRUDExit(__METHOD__, 'DB is read-only');
return;
}
@@ -4162,10 +3962,8 @@ abstract class DBObject implements iDisplay
$this->RecordObjDeletion($this->m_iKey); // May cause a reload for storing history information
- foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
- {
- if ($oAttDef->IsHierarchicalKey())
- {
+ foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) {
+ if ($oAttDef->IsHierarchicalKey()) {
// Update the left & right indexes for each hierarchical key
$sTable = $sTable = MetaModel::DBGetTable(get_class($this), $sAttCode);
/** @var \AttributeHierarchicalKey $oAttDef */
@@ -4179,12 +3977,9 @@ abstract class DBObject implements iDisplay
// No new parent for now, insert completely at the right of the tree
$sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
$aRes = CMDBSource::QueryToArray($sSQL);
- if (count($aRes) == 0)
- {
+ if (count($aRes) == 0) {
$iNewLeft = 1;
- }
- else
- {
+ } else {
$iNewLeft = $aRes[0]['max'] + 1;
}
MetaModel::HKReplugBranch($iNewLeft, $iNewLeft + $iDelta - 1, $oAttDef, $sTable);
@@ -4193,51 +3988,38 @@ abstract class DBObject implements iDisplay
}
$iTransactionRetry = 1;
$bIsTransactionEnabled = MetaModel::GetConfig()->Get('db_core_transactions_enabled');
- if ($bIsTransactionEnabled)
- {
+ if ($bIsTransactionEnabled) {
// TODO Deep clone this object before the transaction (to use it in case of rollback)
// $iTransactionRetryCount = MetaModel::GetConfig()->Get('db_core_transactions_retry_count');
$iTransactionRetryCount = 1;
$iTransactionRetryDelay = MetaModel::GetConfig()->Get('db_core_transactions_retry_delay_ms');
$iTransactionRetry = $iTransactionRetryCount;
}
- while ($iTransactionRetry > 0)
- {
- try
- {
+ while ($iTransactionRetry > 0) {
+ try {
$iTransactionRetry--;
- if ($bIsTransactionEnabled)
- {
+ if ($bIsTransactionEnabled) {
CMDBSource::Query('START TRANSACTION');
}
- foreach (MetaModel::EnumParentClasses(get_class($this), ENUM_PARENT_CLASSES_ALL) as $sParentClass)
- {
+ foreach (MetaModel::EnumParentClasses(get_class($this), ENUM_PARENT_CLASSES_ALL) as $sParentClass) {
$this->DBDeleteSingleTable($sParentClass);
}
- if ($bIsTransactionEnabled)
- {
+ if ($bIsTransactionEnabled) {
CMDBSource::Query('COMMIT');
}
break;
- }
- catch (MySQLException $e)
- {
+ } catch (MySQLException $e) {
IssueLog::Error($e->getMessage());
- if ($bIsTransactionEnabled)
- {
+ if ($bIsTransactionEnabled) {
CMDBSource::Query('ROLLBACK');
- if (!CMDBSource::IsInsideTransaction() && CMDBSource::IsDeadlockException($e))
- {
+ if (!CMDBSource::IsInsideTransaction() && CMDBSource::IsDeadlockException($e)) {
// Deadlock found when trying to get lock; try restarting transaction
- if ($iTransactionRetry > 0)
- {
+ if ($iTransactionRetry > 0) {
// wait and retry
IssueLog::Error("Delete TRANSACTION Retrying...");
usleep(random_int(1, 5) * 1000 * $iTransactionRetryDelay * ($iTransactionRetryCount - $iTransactionRetry));
continue;
- }
- else
- {
+ } else {
IssueLog::Error("Delete Deadlock TRANSACTION prevention failed.");
}
}
@@ -4260,28 +4042,28 @@ abstract class DBObject implements iDisplay
// Thought the key is not reset, using DBInsert or DBWrite will create an object having the same characteristics and a new ID. DBUpdate is protected
}
- /**
- * Delete an object
- *
- * First, checks if the object can be deleted regarding database integrity.
- * If the answer is yes, it performs any required cleanup (delete other objects or reset external keys) in addition to the object
- * deletion.
- *
- * @api
- *
- * @param \DeletionPlan $oDeletionPlan Do not use: aims at dealing with recursion
- *
- * @return DeletionPlan The detailed description of cleanup operation that have been performed
- *
- * @throws ArchivedObjectException
- * @throws CoreCannotSaveObjectException
- * @throws CoreException
- * @throws CoreUnexpectedValue
- * @throws DeleteException
- * @throws MySQLException
- * @throws MySQLHasGoneAwayException
- * @throws OQLException
- */
+ /**
+ * Delete an object
+ *
+ * First, checks if the object can be deleted regarding database integrity.
+ * If the answer is yes, it performs any required cleanup (delete other objects or reset external keys) in addition to the object
+ * deletion.
+ *
+ * @api
+ *
+ * @param \DeletionPlan $oDeletionPlan Do not use: aims at dealing with recursion
+ *
+ * @return DeletionPlan The detailed description of cleanup operation that have been performed
+ *
+ * @throws ArchivedObjectException
+ * @throws CoreCannotSaveObjectException
+ * @throws CoreException
+ * @throws CoreUnexpectedValue
+ * @throws DeleteException
+ * @throws MySQLException
+ * @throws MySQLHasGoneAwayException
+ * @throws OQLException
+ */
public function DBDelete(&$oDeletionPlan = null)
{
$this->LogCRUDEnter(__METHOD__);
@@ -4297,10 +4079,9 @@ abstract class DBObject implements iDisplay
if (false === $this->CheckToDelete($oDeletionPlan)) {
$aIssues = $oDeletionPlan->GetIssues();
$this->LogCRUDError(__METHOD__, ' Errors: '.implode(', ', $aIssues));
- throw new DeleteException('Found issue(s)', array('target_class' => get_class($this), 'target_id' => $this->GetKey(), 'issues' => implode(', ', $aIssues)));
+ throw new DeleteException('Found issue(s)', ['target_class' => get_class($this), 'target_id' => $this->GetKey(), 'issues' => implode(', ', $aIssues)]);
}
-
// Getting and setting time limit are not symmetric:
// www.php.net/manual/fr/function.set-time-limit.php#72305
$iPreviousTimeLimit = ini_get('max_execution_time');
@@ -4320,8 +4101,7 @@ abstract class DBObject implements iDisplay
$oToDelete->AddCurrentObjectInCrudStack('DELETE');
try {
$oToDelete->DBDeleteSingleObject();
- }
- finally {
+ } finally {
$oToDelete->RemoveCurrentObjectInCrudStack();
}
}
@@ -4348,14 +4128,14 @@ abstract class DBObject implements iDisplay
return $oDeletionPlan;
}
- /**
- * @overwritable-hook You can extend this method in order to provide your own logic.
- *
- * @return array
- *
- * @throws ArchivedObjectException
- * @throws CoreException
- */
+ /**
+ * @overwritable-hook You can extend this method in order to provide your own logic.
+ *
+ * @return array
+ *
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ */
public function EnumTransitions()
{
$sClass = get_class($this);
@@ -4383,7 +4163,7 @@ abstract class DBObject implements iDisplay
$aStimuli = MetaModel::EnumStimuli($sClass);
// Sort $aSortedTransitions based on labels from $aStimuli
- uksort($aSortedTransitions, function($sKey1, $sKey2) use ($aStimuli) {
+ uksort($aSortedTransitions, function ($sKey1, $sKey2) use ($aStimuli) {
// If any transition is not in $aStimuli, put it at the end even though it's a weird situation
if ((false === isset($aStimuli[$sKey1])) || (false === isset($aStimuli[$sKey2]))) {
return 1;
@@ -4403,7 +4183,7 @@ abstract class DBObject implements iDisplay
$aStatesSortFromDatamodel = array_keys($aAllowedValues);
// Sort $aSortedTransitions based on the states sort from the datamodel
- uksort($aSortedTransitions, function($sKey1, $sKey2) use ($aSortedTransitions, $aStatesSortFromDatamodel) {
+ uksort($aSortedTransitions, function ($sKey1, $sKey2) use ($aSortedTransitions, $aStatesSortFromDatamodel) {
$sTargetState1 = $aSortedTransitions[$sKey1]['target_state'];
$sTargetState2 = $aSortedTransitions[$sKey2]['target_state'];
@@ -4461,25 +4241,24 @@ abstract class DBObject implements iDisplay
}
}
- /**
- * Helper to reset a stop-watch
- * Suitable for use as a lifecycle action
- *
- * @api
- *
- * @param string $sAttCode
- *
- * @return bool
- *
- * @throws ArchivedObjectException
- * @throws CoreException
- * @throws CoreUnexpectedValue
- */
+ /**
+ * Helper to reset a stop-watch
+ * Suitable for use as a lifecycle action
+ *
+ * @api
+ *
+ * @param string $sAttCode
+ *
+ * @return bool
+ *
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ * @throws CoreUnexpectedValue
+ */
public function ResetStopWatch($sAttCode)
{
$oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
- if (!$oAttDef instanceof AttributeStopWatch)
- {
+ if (!$oAttDef instanceof AttributeStopWatch) {
throw new CoreException("Invalid stop watch id: '$sAttCode'");
}
$oSW = $this->Get($sAttCode);
@@ -4512,8 +4291,7 @@ abstract class DBObject implements iDisplay
$this->LogCRUDEnter(__METHOD__, "Code: $sStimulusCode");
$sClass = get_class($this);
- if (!MetaModel::HasLifecycle($sClass))
- {
+ if (!MetaModel::HasLifecycle($sClass)) {
throw new CoreException('No lifecycle for the class '.$sClass);
}
@@ -4521,15 +4299,14 @@ abstract class DBObject implements iDisplay
$sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
$aStateTransitions = $this->EnumTransitions();
- if (!array_key_exists($sStimulusCode, $aStateTransitions))
- {
+ if (!array_key_exists($sStimulusCode, $aStateTransitions)) {
// This stimulus has no effect in the current state... do nothing
IssueLog::Error("$sClass: Transition $sStimulusCode is not allowed in ".$this->Get($sStateAttCode));
return false;
}
// save current object values in case of an action failure (in memory rollback)
- $aBackupValues = array();
- foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) {
+ $aBackupValues = [];
+ foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) {
if (isset($this->m_aCurrValues[$sAttCode])) {
$value = $this->m_aCurrValues[$sAttCode];
if (is_object($value)) {
@@ -4560,19 +4337,18 @@ abstract class DBObject implements iDisplay
foreach ($aTransitionDef['actions'] as $actionHandler) {
if (is_string($actionHandler)) {
// Old (pre-2.1.0 modules) action definition without any parameter
- $aActionCallSpec = array($this, $actionHandler);
+ $aActionCallSpec = [$this, $actionHandler];
$sActionDesc = $sClass.'::'.$actionHandler;
if (!is_callable($aActionCallSpec)) {
throw new CoreException("Unable to call action: $sClass::$actionHandler");
}
$bRet = call_user_func($aActionCallSpec, $sStimulusCode);
- } else // if (is_array($actionHandler))
- {
+ } else { // if (is_array($actionHandler))
// New syntax: 'verb' and typed parameters
$sAction = $actionHandler['verb'];
$sActionDesc = "$sClass::$sAction";
- $aParams = array();
+ $aParams = [];
foreach ($actionHandler['params'] as $aDefinition) {
$sParamType = array_key_exists('type', $aDefinition) ? $aDefinition['type'] : 'string';
switch ($sParamType) {
@@ -4598,7 +4374,7 @@ abstract class DBObject implements iDisplay
}
$aParams[] = $value;
}
- $aCallSpec = array($this, $sAction);
+ $aCallSpec = [$this, $sAction];
$bRet = call_user_func_array($aCallSpec, $aParams);
}
// if one call fails, the whole is considered as failed
@@ -4615,17 +4391,13 @@ abstract class DBObject implements iDisplay
}
$this->RemoveCurrentObjectInCrudStack();
}
- if ($bSuccess)
- {
+ if ($bSuccess) {
$this->sStimulusBeingApplied = $sStimulusCode;
// Stop watches
- foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
- {
- if ($oAttDef instanceof AttributeStopWatch)
- {
+ foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) {
+ if ($oAttDef instanceof AttributeStopWatch) {
$oSW = $this->Get($sAttCode);
- if (in_array($sNewState, $oAttDef->GetStates()))
- {
+ if (in_array($sNewState, $oAttDef->GetStates())) {
$oSW->Start($this, $oAttDef);
} else {
$oSW->Stop($this, $oAttDef);
@@ -4637,12 +4409,9 @@ abstract class DBObject implements iDisplay
if (!$bDoNotWrite) {
$this->DBWrite();
}
- }
- else
- {
+ } else {
// At least one action failed, rollback the object value to its previous value
- foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
- {
+ foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) {
$this->m_aCurrValues[$sAttCode] = $aBackupValues[$sAttCode];
}
}
@@ -4666,10 +4435,10 @@ abstract class DBObject implements iDisplay
/**
* Helper to recover the default value (aka when an object is being created)
- * Suitable for use as a lifecycle action
- *
- * @api
- *
+ * Suitable for use as a lifecycle action
+ *
+ * @api
+ *
*/
public function Reset($sAttCode)
{
@@ -4678,35 +4447,26 @@ abstract class DBObject implements iDisplay
}
/**
- * Helper to copy the value of an attribute to another one
- * Suitable for use as a lifecycle action
- *
- * @api
+ * Helper to copy the value of an attribute to another one
+ * Suitable for use as a lifecycle action
+ *
+ * @api
*/
public function Copy($sDestAttCode, $sSourceAttCode)
{
$oTypeValueToCopy = MetaModel::GetAttributeDef(get_class($this), $sSourceAttCode);
$oTypeValueDest = MetaModel::GetAttributeDef(get_class($this), $sDestAttCode);
- if ($oTypeValueToCopy instanceof AttributeText && $oTypeValueDest instanceof AttributeText)
- {
- if ($oTypeValueToCopy->GetFormat() == $oTypeValueDest->GetFormat())
- {
+ if ($oTypeValueToCopy instanceof AttributeText && $oTypeValueDest instanceof AttributeText) {
+ if ($oTypeValueToCopy->GetFormat() == $oTypeValueDest->GetFormat()) {
$sValueToCopy = $this->Get($sSourceAttCode);
- }
- else
- {
- if ($oTypeValueToCopy->GetFormat() == 'text')// and $oTypeValueDest->GetFormat()=='HTML'
- {
+ } else {
+ if ($oTypeValueToCopy->GetFormat() == 'text') {// and $oTypeValueDest->GetFormat()=='HTML'
$sValueToCopy = $this->GetAsHTML($sSourceAttCode);
- }
- else
- {// $oTypeValueToCopy->GetFormat() == 'HTML' and $oTypeValueDest->GetFormat()=='Text'
+ } else {// $oTypeValueToCopy->GetFormat() == 'HTML' and $oTypeValueDest->GetFormat()=='Text'
$sValueToCopy = utils::HtmlToText($this->Get($sSourceAttCode));
}
}
- }
- else
- {
+ } else {
$sValueToCopy = $this->Get($sSourceAttCode);
}
$this->Set($sDestAttCode, $sValueToCopy);
@@ -4714,19 +4474,19 @@ abstract class DBObject implements iDisplay
return true;
}
- /**
- * Helper to set the current date/time for the given attribute
- * Suitable for use as a lifecycle action
- *
- * @api
- *
- * @param string $sAttCode
- *
- * @return bool
- *
- * @throws CoreException
- * @throws CoreUnexpectedValue
- */
+ /**
+ * Helper to set the current date/time for the given attribute
+ * Suitable for use as a lifecycle action
+ *
+ * @api
+ *
+ * @param string $sAttCode
+ *
+ * @return bool
+ *
+ * @throws CoreException
+ * @throws CoreUnexpectedValue
+ */
public function SetCurrentDate($sAttCode)
{
$this->Set($sAttCode, time());
@@ -4832,7 +4592,6 @@ abstract class DBObject implements iDisplay
}
}
-
/**
* Helper to set the current logged in user for the given attribute
* Suitable for use as a lifecycle action
@@ -4864,42 +4623,34 @@ abstract class DBObject implements iDisplay
return true;
}
- /**
- * Helper to set the current logged in CONTACT for the given attribute
- * Suitable for use as a lifecycle action
- *
- * @api
- *
- * @param string $sAttCode
- *
- * @return bool
- * @throws ArchivedObjectException
- * @throws CoreException
- * @throws CoreUnexpectedValue
- */
+ /**
+ * Helper to set the current logged in CONTACT for the given attribute
+ * Suitable for use as a lifecycle action
+ *
+ * @api
+ *
+ * @param string $sAttCode
+ *
+ * @return bool
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ * @throws CoreUnexpectedValue
+ */
public function SetCurrentPerson($sAttCode)
{
$oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
- if ($oAttDef instanceof AttributeString)
- {
+ if ($oAttDef instanceof AttributeString) {
$iPerson = UserRights::GetContactId();
- if ($iPerson == 0)
- {
+ if ($iPerson == 0) {
$this->Set($sAttCode, '');
- }
- else
- {
+ } else {
$oPerson = MetaModel::GetObject('Person', $iPerson);
$this->Set($sAttCode, $oPerson->Get('friendlyname'));
}
- }
- else
- {
- if ($oAttDef->IsExternalKey())
- {
+ } else {
+ if ($oAttDef->IsExternalKey()) {
/** @var \AttributeExternalKey $oAttDef */
- if (!MetaModel::IsParentClass($oAttDef->GetTargetClass(), 'Person'))
- {
+ if (!MetaModel::IsParentClass($oAttDef->GetTargetClass(), 'Person')) {
throw new Exception("SetCurrentContact: the attribute $sAttCode must be an external key to 'Person' or any other class above 'Person', found '".$oAttDef->GetTargetClass()."'");
}
}
@@ -4908,31 +4659,29 @@ abstract class DBObject implements iDisplay
return true;
}
- /**
- * Helper to set the time elapsed since a reference point
- * Suitable for use as a lifecycle action
- *
- * @api
- *
- * @param string $sAttCode
- * @param string $sRefAttCode
- * @param string|null $sWorkingTimeComputer
- *
- * @return bool
- * @throws ArchivedObjectException
- * @throws CoreException
- * @throws CoreUnexpectedValue
- */
+ /**
+ * Helper to set the time elapsed since a reference point
+ * Suitable for use as a lifecycle action
+ *
+ * @api
+ *
+ * @param string $sAttCode
+ * @param string $sRefAttCode
+ * @param string|null $sWorkingTimeComputer
+ *
+ * @return bool
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ * @throws CoreUnexpectedValue
+ */
public function SetElapsedTime($sAttCode, $sRefAttCode, $sWorkingTimeComputer = null)
{
- if (is_null($sWorkingTimeComputer))
- {
+ if (is_null($sWorkingTimeComputer)) {
$sWorkingTimeComputer = MetaModel::GetWorkingTime(get_class($this));
}
$oComputer = new $sWorkingTimeComputer();
- $aCallSpec = array($oComputer, 'GetOpenDuration');
- if (!is_callable($aCallSpec))
- {
+ $aCallSpec = [$oComputer, 'GetOpenDuration'];
+ if (!is_callable($aCallSpec)) {
throw new CoreException("Unknown class/verb '$sWorkingTimeComputer/GetOpenDuration'");
}
@@ -4940,14 +4689,12 @@ abstract class DBObject implements iDisplay
$oStartDate = new DateTime('@'.$iStartTime); // setTimestamp not available in PHP 5.2
$oEndDate = new DateTime(); // now
- if (class_exists('WorkingTimeRecorder'))
- {
+ if (class_exists('WorkingTimeRecorder')) {
$sClass = get_class($this);
- WorkingTimeRecorder::Start($this, time(), "DBObject-SetElapsedTime-$sAttCode-$sRefAttCode", 'Core:ExplainWTC:ElapsedTime', array("Class:$sClass/Attribute:$sAttCode"));
+ WorkingTimeRecorder::Start($this, time(), "DBObject-SetElapsedTime-$sAttCode-$sRefAttCode", 'Core:ExplainWTC:ElapsedTime', ["Class:$sClass/Attribute:$sAttCode"]);
}
$iElapsed = call_user_func($aCallSpec, $this, $oStartDate, $oEndDate);
- if (class_exists('WorkingTimeRecorder'))
- {
+ if (class_exists('WorkingTimeRecorder')) {
WorkingTimeRecorder::End();
}
@@ -4955,219 +4702,197 @@ abstract class DBObject implements iDisplay
return true;
}
-
- /**
- * Create query parameters (SELECT ... WHERE service = :this->service_id)
- * to be used with the APIs DBObjectSearch/DBObjectSet
- *
- * Starting 2.0.2 the parameters are computed on demand, at the lowest level,
- * in VariableExpression::Render()
- *
- * @internal
- *
- * @param string $sArgName
- *
- * @return array
- */
+ /**
+ * Create query parameters (SELECT ... WHERE service = :this->service_id)
+ * to be used with the APIs DBObjectSearch/DBObjectSet
+ *
+ * Starting 2.0.2 the parameters are computed on demand, at the lowest level,
+ * in VariableExpression::Render()
+ *
+ * @internal
+ *
+ * @param string $sArgName
+ *
+ * @return array
+ */
public function ToArgsForQuery($sArgName = 'this')
{
- return array($sArgName.'->object()' => $this);
+ return [$sArgName.'->object()' => $this];
}
- /**
- * Create template placeholders: now equivalent to ToArgsForQuery since the actual
- * template placeholders are computed on demand.
- *
- * @internal
- *
- * @param string $sArgName
- *
- * @return array
- */
+ /**
+ * Create template placeholders: now equivalent to ToArgsForQuery since the actual
+ * template placeholders are computed on demand.
+ *
+ * @internal
+ *
+ * @param string $sArgName
+ *
+ * @return array
+ */
public function ToArgs($sArgName = 'this')
{
return $this->ToArgsForQuery($sArgName);
}
- /**
- * Get various representations of the value, for insertion into a template (e.g. in Notifications)
- *
- * @internal
- *
- * @param string $sPlaceholderAttCode
- *
- * @return int|mixed|string|null
- * @throws ArchivedObjectException
- * @throws CoreException
- * @throws DictExceptionMissingString
- */
+ /**
+ * Get various representations of the value, for insertion into a template (e.g. in Notifications)
+ *
+ * @internal
+ *
+ * @param string $sPlaceholderAttCode
+ *
+ * @return int|mixed|string|null
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ * @throws DictExceptionMissingString
+ */
public function GetForTemplate($sPlaceholderAttCode)
{
$ret = null;
- if (preg_match('/^([^-]+)-(>|>)(.+)$/', $sPlaceholderAttCode, $aMatches)) // Support both syntaxes: this->xxx or this->xxx for HTML compatibility
- {
+ if (preg_match('/^([^-]+)-(>|>)(.+)$/', $sPlaceholderAttCode, $aMatches)) { // Support both syntaxes: this->xxx or this->xxx for HTML compatibility
$sExtKeyAttCode = $aMatches[1];
$sRemoteAttCode = $aMatches[3];
- if (!MetaModel::IsValidAttCode(get_class($this), $sExtKeyAttCode))
- {
+ if (!MetaModel::IsValidAttCode(get_class($this), $sExtKeyAttCode)) {
throw new CoreException("Unknown attribute '$sExtKeyAttCode' for the class ".get_class($this));
}
$oKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode);
- if (!$oKeyAttDef instanceof AttributeExternalKey)
- {
+ if (!$oKeyAttDef instanceof AttributeExternalKey) {
throw new CoreException("'$sExtKeyAttCode' is not an external key of the class ".get_class($this));
}
$sRemoteClass = $oKeyAttDef->GetTargetClass();
$oRemoteObj = MetaModel::GetObject($sRemoteClass, $this->GetStrict($sExtKeyAttCode), false);
- if (is_null($oRemoteObj))
- {
+ if (is_null($oRemoteObj)) {
$ret = Dict::S('UI:UndefinedObject');
- }
- else
- {
+ } else {
// Recurse
$ret = $oRemoteObj->GetForTemplate($sRemoteAttCode);
}
- }
- else
- {
- switch($sPlaceholderAttCode)
- {
+ } else {
+ switch ($sPlaceholderAttCode) {
case 'id':
- $ret = $this->GetKey();
- break;
+ $ret = $this->GetKey();
+ break;
case 'name()':
- $ret = $this->GetName();
- break;
+ $ret = $this->GetName();
+ break;
default:
- if (preg_match('/^([^(]+)\\((.*)\\)$/', $sPlaceholderAttCode, $aMatches))
- {
- $sVerb = $aMatches[1];
- $sAttCode = $aMatches[2];
- }
- else
- {
- $sVerb = '';
- $sAttCode = $sPlaceholderAttCode;
- }
-
- if (in_array($sVerb, ['hyperlink', 'url']))
- {
- $sPortalId = ($sAttCode === '') ? 'console' : $sAttCode;
- if (!array_key_exists($sPortalId, self::$aPortalToURLMaker))
- {
- throw new Exception("Unknown portal id '$sPortalId' in placeholder '$sPlaceholderAttCode''");
+ if (preg_match('/^([^(]+)\\((.*)\\)$/', $sPlaceholderAttCode, $aMatches)) {
+ $sVerb = $aMatches[1];
+ $sAttCode = $aMatches[2];
+ } else {
+ $sVerb = '';
+ $sAttCode = $sPlaceholderAttCode;
}
- if($sVerb == 'hyperlink')
- {
- $ret = $this->GetHyperlink(self::$aPortalToURLMaker[$sPortalId], false);
+ if (in_array($sVerb, ['hyperlink', 'url'])) {
+ $sPortalId = ($sAttCode === '') ? 'console' : $sAttCode;
+ if (!array_key_exists($sPortalId, self::$aPortalToURLMaker)) {
+ throw new Exception("Unknown portal id '$sPortalId' in placeholder '$sPlaceholderAttCode''");
+ }
+
+ if ($sVerb == 'hyperlink') {
+ $ret = $this->GetHyperlink(self::$aPortalToURLMaker[$sPortalId], false);
+ } else {
+ $ret = ApplicationContext::MakeObjectUrl(get_class($this), $this->GetKey(), self::$aPortalToURLMaker[$sPortalId], false);
+ }
+ } else {
+ $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
+ $ret = $oAttDef->GetForTemplate($this->Get($sAttCode), $sVerb, $this);
}
- else
- {
- $ret = ApplicationContext::MakeObjectUrl(get_class($this), $this->GetKey(), self::$aPortalToURLMaker[$sPortalId], false);
- }
- }
- else
- {
- $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
- $ret = $oAttDef->GetForTemplate($this->Get($sAttCode), $sVerb, $this);
- }
}
- if ($ret === null)
- {
+ if ($ret === null) {
$ret = '';
}
}
return $ret;
}
- static protected $aPortalToURLMaker = array('console' => 'iTopStandardURLMaker', 'portal' => 'PortalURLMaker');
+ protected static $aPortalToURLMaker = ['console' => 'iTopStandardURLMaker', 'portal' => 'PortalURLMaker'];
/**
* Associate a portal to a class that implements iDBObjectURLMaker,
* and which will be invoked with placeholders like $this->org_id->hyperlink(portal)$
*
- * @internal
- *
+ * @internal
+ *
* @param string $sPortalId Identifies the portal. Conventions: the main portal is 'console', The user requests portal is 'portal'.
* @param string $sUrlMakerClass
*/
- static public function RegisterURLMakerClass($sPortalId, $sUrlMakerClass)
+ public static function RegisterURLMakerClass($sPortalId, $sUrlMakerClass)
{
self::$aPortalToURLMaker[$sPortalId] = $sUrlMakerClass;
}
/**
* this method is called before the object is inserted into DB.
- *
- *
+ *
+ *
* @overwritable-hook You can extend this method in order to provide your own logic.
*/
protected function OnInsert()
{
}
- /**
- * this method is called after the object is inserted into DB.
- *
- * @overwritable-hook You can extend this method in order to provide your own logic.
- */
+ /**
+ * this method is called after the object is inserted into DB.
+ *
+ * @overwritable-hook You can extend this method in order to provide your own logic.
+ */
protected function AfterInsert()
{
}
- /**
- * this method is called before the object is updated into DB.
- *
- * @overwritable-hook You can extend this method in order to provide your own logic.
- */
+ /**
+ * this method is called before the object is updated into DB.
+ *
+ * @overwritable-hook You can extend this method in order to provide your own logic.
+ */
protected function OnUpdate()
{
}
- /**
- * @overwritable-hook You can extend this method in order to provide your own logic.
- *
- * This method is called after the object is updated into DB, and just before the {@see DBObject::Reload()} call.
- *
- * Warning : do not use {@see DBObject::ListChanges()} as it will return an empty array !
- * Use instead {@see DBObject::ListPreviousValuesForUpdatedAttributes()} to get modified fields and their previous values,
- * and {@see DBObject::Get()} to get the persisted value for a given attribute.
- *
- * @since 2.7.0 N°2293 can access object changes by calling {@see DBObject::ListPreviousValuesForUpdatedAttributes()}
- */
+ /**
+ * @overwritable-hook You can extend this method in order to provide your own logic.
+ *
+ * This method is called after the object is updated into DB, and just before the {@see DBObject::Reload()} call.
+ *
+ * Warning : do not use {@see DBObject::ListChanges()} as it will return an empty array !
+ * Use instead {@see DBObject::ListPreviousValuesForUpdatedAttributes()} to get modified fields and their previous values,
+ * and {@see DBObject::Get()} to get the persisted value for a given attribute.
+ *
+ * @since 2.7.0 N°2293 can access object changes by calling {@see DBObject::ListPreviousValuesForUpdatedAttributes()}
+ */
protected function AfterUpdate()
{
}
- /**
- * this method is called before the object is deleted into DB.
- *
- * @overwritable-hook You can extend this method in order to provide your own logic.
- */
+ /**
+ * this method is called before the object is deleted into DB.
+ *
+ * @overwritable-hook You can extend this method in order to provide your own logic.
+ */
protected function OnDelete()
{
}
- /**
- * this method is called after the object is deleted into DB.
- *
- * @overwritable-hook You can extend this method in order to provide your own logic.
- */
+ /**
+ * this method is called after the object is deleted into DB.
+ *
+ * @overwritable-hook You can extend this method in order to provide your own logic.
+ */
protected function AfterDelete()
{
}
-
/**
* Common to the recording of link set changes (add/remove/modify)
*
- * @internal
- *
+ * @internal
+ *
* @param $iLinkSetOwnerId
* @param \AttributeLinkedSet $oLinkSet
* @param $sChangeOpClass
@@ -5180,39 +4905,31 @@ abstract class DBObject implements iDisplay
*/
private function PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, $sChangeOpClass, $aOriginalValues = null)
{
- if ($iLinkSetOwnerId <= 0)
- {
+ if ($iLinkSetOwnerId <= 0) {
return null;
}
- if (!is_subclass_of($oLinkSet->GetHostClass(), 'CMDBObject'))
- {
+ if (!is_subclass_of($oLinkSet->GetHostClass(), 'CMDBObject')) {
// The link set owner class does not keep track of its history
return null;
}
// Determine the linked item class and id
//
- if ($oLinkSet->IsIndirect())
- {
+ if ($oLinkSet->IsIndirect()) {
// The "item" is on the other end (N-N links)
/** @var \AttributeLinkedSetIndirect $oLinkSet */
$sExtKeyToRemote = $oLinkSet->GetExtKeyToRemote();
$oExtKeyToRemote = MetaModel::GetAttributeDef(get_class($this), $sExtKeyToRemote);
/** @var \AttributeExternalKey $oExtKeyToRemote */
$sItemClass = $oExtKeyToRemote->GetTargetClass();
- if ($aOriginalValues)
- {
+ if ($aOriginalValues) {
// Get the value from the original values
$iItemId = $aOriginalValues[$sExtKeyToRemote];
- }
- else
- {
+ } else {
$iItemId = $this->Get($sExtKeyToRemote);
}
- }
- else
- {
+ } else {
// I am the "item" (1-N links)
$sItemClass = get_class($this);
$iItemId = $this->GetKey();
@@ -5221,8 +4938,7 @@ abstract class DBObject implements iDisplay
// Get the remote object, to determine its exact class
// Possible optimization: implement a tool in MetaModel, to get the final class of an object (not always querying + query reduced to a select on the root table!
$oOwner = MetaModel::GetObject($oLinkSet->GetHostClass(), $iLinkSetOwnerId, false);
- if ($oOwner)
- {
+ if ($oOwner) {
$sLinkSetOwnerClass = get_class($oOwner);
$oMyChangeOp = MetaModel::NewObject($sChangeOpClass);
@@ -5232,9 +4948,7 @@ abstract class DBObject implements iDisplay
$oMyChangeOp->Set("item_class", $sItemClass);
$oMyChangeOp->Set("item_id", $iItemId);
return $oMyChangeOp;
- }
- else
- {
+ } else {
// Depending on the deletion order, it may happen that the id is already invalid... ignore
return null;
}
@@ -5247,21 +4961,18 @@ abstract class DBObject implements iDisplay
*/
private function RecordLinkSetListChange($bAdd = true)
{
- foreach(MetaModel::GetTrackForwardExternalKeys(get_class($this)) as $sExtKeyAttCode => $oLinkSet)
- {
+ foreach (MetaModel::GetTrackForwardExternalKeys(get_class($this)) as $sExtKeyAttCode => $oLinkSet) {
/** @var \AttributeLinkedSet $oLinkSet */
- if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_LIST) == 0) continue;
+ if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_LIST) == 0) {
+ continue;
+ }
$iLinkSetOwnerId = $this->Get($sExtKeyAttCode);
$oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove');
- if ($oMyChangeOp)
- {
- if ($bAdd)
- {
+ if ($oMyChangeOp) {
+ if ($bAdd) {
$oMyChangeOp->Set("type", "added");
- }
- else
- {
+ } else {
$oMyChangeOp->Set("type", "removed");
}
$oMyChangeOp->DBInsertNoReload();
@@ -5277,55 +4988,52 @@ abstract class DBObject implements iDisplay
$this->RecordLinkSetListChange(true);
}
- /**
- * @internal
- */
+ /**
+ * @internal
+ */
protected function RecordObjDeletion($objkey)
{
$this->RecordLinkSetListChange(false);
}
- /**
- * @internal
- */
+ /**
+ * @internal
+ */
protected function RecordAttChanges(array $aValues, array $aOrigValues)
{
- foreach(MetaModel::GetTrackForwardExternalKeys(get_class($this)) as $sExtKeyAttCode => $oLinkSet)
- {
+ foreach (MetaModel::GetTrackForwardExternalKeys(get_class($this)) as $sExtKeyAttCode => $oLinkSet) {
- if (array_key_exists($sExtKeyAttCode, $aValues))
- {
+ if (array_key_exists($sExtKeyAttCode, $aValues)) {
/** @var \AttributeLinkedSet $oLinkSet */
- if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_LIST) == 0) continue;
+ if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_LIST) == 0) {
+ continue;
+ }
// Keep track of link added/removed
//
$iLinkSetOwnerNext = $aValues[$sExtKeyAttCode];
$oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerNext, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove');
- if ($oMyChangeOp)
- {
+ if ($oMyChangeOp) {
$oMyChangeOp->Set("type", "added");
$oMyChangeOp->DBInsertNoReload();
}
$iLinkSetOwnerPrevious = $aOrigValues[$sExtKeyAttCode];
$oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerPrevious, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove', $aOrigValues);
- if ($oMyChangeOp)
- {
+ if ($oMyChangeOp) {
$oMyChangeOp->Set("type", "removed");
$oMyChangeOp->DBInsertNoReload();
}
- }
- else
- {
+ } else {
// Keep track of link changes
//
- if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_DETAILS) == 0) continue;
+ if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_DETAILS) == 0) {
+ continue;
+ }
$iLinkSetOwnerId = $this->Get($sExtKeyAttCode);
$oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, 'CMDBChangeOpSetAttributeLinksTune');
- if ($oMyChangeOp)
- {
+ if ($oMyChangeOp) {
$oMyChangeOp->Set("link_id", $this->GetKey());
$oMyChangeOp->DBInsertNoReload();
}
@@ -5333,31 +5041,29 @@ abstract class DBObject implements iDisplay
}
}
-
-
- /**
- * Reserved: do not overload
- *
- * @internal
- */
+ /**
+ * Reserved: do not overload
+ *
+ * @internal
+ */
public static function GetRelationQueriesEx($sRelCode)
{
- return array();
+ return [];
}
- /**
- * Compute the "RelatedObjects" (forward or "down" direction) for the object
- * for the specified relation
- *
- * @internal
- *
- * @param string $sRelCode The code of the relation to use for the computation
- * @param int $iMaxDepth Maximum recursion depth
- * @param bool $bEnableRedundancy
- *
- * @return RelationGraph The graph of all the related objects
- * @throws CoreException
- */
+ /**
+ * Compute the "RelatedObjects" (forward or "down" direction) for the object
+ * for the specified relation
+ *
+ * @internal
+ *
+ * @param string $sRelCode The code of the relation to use for the computation
+ * @param int $iMaxDepth Maximum recursion depth
+ * @param bool $bEnableRedundancy
+ *
+ * @return RelationGraph The graph of all the related objects
+ * @throws CoreException
+ */
public function GetRelatedObjectsDown($sRelCode, $iMaxDepth = 99, $bEnableRedundancy = true)
{
$oGraph = new RelationGraph();
@@ -5366,19 +5072,19 @@ abstract class DBObject implements iDisplay
return $oGraph;
}
- /**
- * Compute the "RelatedObjects" (reverse or "up" direction) for the object
- * for the specified relation
- *
- * @internal
- *
- * @param string $sRelCode The code of the relation to use for the computation
- * @param int $iMaxDepth Maximum recursion depth
- * @param bool $bEnableRedundancy
- *
- * @return RelationGraph The graph of all the related objects
- * @throws CoreException
- */
+ /**
+ * Compute the "RelatedObjects" (reverse or "up" direction) for the object
+ * for the specified relation
+ *
+ * @internal
+ *
+ * @param string $sRelCode The code of the relation to use for the computation
+ * @param int $iMaxDepth Maximum recursion depth
+ * @param bool $bEnableRedundancy
+ *
+ * @return RelationGraph The graph of all the related objects
+ * @throws CoreException
+ */
public function GetRelatedObjectsUp($sRelCode, $iMaxDepth = 99, $bEnableRedundancy = true)
{
$oGraph = new RelationGraph();
@@ -5401,32 +5107,32 @@ abstract class DBObject implements iDisplay
*/
protected function GetReferencingObjectsForDeletion($bAllowAllData = false)
{
- $aDependentObjects = array();
+ $aDependentObjects = [];
$aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
- foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
- {
+ foreach ($aRererencingMe as $sRemoteClass => $aExtKeys) {
/** @var \AttributeExternalKey $oExtKeyAttDef */
- foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
- {
+ foreach ($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef) {
// skip if external key doesn't require the deletion cascading
- if($oExtKeyAttDef->GetDeletionPropagationOption() === DEL_NONE) continue;
+ if ($oExtKeyAttDef->GetDeletionPropagationOption() === DEL_NONE) {
+ continue;
+ }
// skip if this external key is behind an external field
- if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
+ if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) {
+ continue;
+ }
$oSearch = new DBObjectSearch($sRemoteClass);
$oSearch->AddCondition($sExtKeyAttCode, $this->GetKey(), '=');
- if ($bAllowAllData)
- {
+ if ($bAllowAllData) {
$oSearch->AllowAllData();
}
$oSet = new CMDBObjectSet($oSearch);
- if ($oSet->CountExceeds(0))
- {
- $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
+ if ($oSet->CountExceeds(0)) {
+ $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = [
'attribute' => $oExtKeyAttDef,
'objects' => $oSet,
- );
+ ];
}
}
}
@@ -5434,19 +5140,18 @@ abstract class DBObject implements iDisplay
}
/**
- * @internal
- *
+ * @internal
+ *
* @param \DeletionPlan $oDeletionPlan
* @param array $aVisited
* @param int $iDeleteOption
*
* @throws \CoreException
*/
- private function MakeDeletionPlan(&$oDeletionPlan, $aVisited = array(), $iDeleteOption = null)
+ private function MakeDeletionPlan(&$oDeletionPlan, $aVisited = [], $iDeleteOption = null)
{
static $iLoopTimeLimit = null;
- if ($iLoopTimeLimit == null)
- {
+ if ($iLoopTimeLimit == null) {
$iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
}
$sClass = get_class($this);
@@ -5454,22 +5159,19 @@ abstract class DBObject implements iDisplay
$oDeletionPlan->AddToDelete($this, $iDeleteOption);
- if (array_key_exists($sClass, $aVisited))
- {
- if (in_array($iThisId, $aVisited[$sClass]))
- {
+ if (array_key_exists($sClass, $aVisited)) {
+ if (in_array($iThisId, $aVisited[$sClass])) {
return;
}
}
$aVisited[$sClass] = $iThisId;
- if ($iDeleteOption == DEL_MANUAL)
- {
+ if ($iDeleteOption == DEL_MANUAL) {
// Stop the recursion here
return;
}
// Check the node itself
- $this->m_aDeleteIssues = array(); // Ok
+ $this->m_aDeleteIssues = []; // Ok
$this->FireEventCheckToDelete($oDeletionPlan);
$this->DoCheckToDelete($oDeletionPlan);
$this->CheckToWriteForTargetObjects(true);
@@ -5479,10 +5181,8 @@ abstract class DBObject implements iDisplay
// www.php.net/manual/fr/function.set-time-limit.php#72305
$iPreviousTimeLimit = ini_get('max_execution_time');
- foreach ($this->GetReferencingObjectsForDeletion(true /* allow all data */) as $aPotentialDeletes)
- {
- foreach ($aPotentialDeletes as $aData)
- {
+ foreach ($this->GetReferencingObjectsForDeletion(true /* allow all data */) as $aPotentialDeletes) {
+ foreach ($aPotentialDeletes as $aData) {
set_time_limit(intval($iLoopTimeLimit));
/** @var \AttributeExternalKey $oAttDef */
@@ -5491,24 +5191,17 @@ abstract class DBObject implements iDisplay
/** @var \DBObjectSet $oDepSet */
$oDepSet = $aData['objects'];
$oDepSet->Rewind();
- while ($oDependentObj = $oDepSet->fetch())
- {
- if ($oAttDef->IsNullAllowed())
- {
+ while ($oDependentObj = $oDepSet->fetch()) {
+ if ($oAttDef->IsNullAllowed()) {
// Optional external key, list to reset
- if (($iDeletePropagationOption == DEL_MOVEUP) && ($oAttDef->IsHierarchicalKey()))
- {
+ if (($iDeletePropagationOption == DEL_MOVEUP) && ($oAttDef->IsHierarchicalKey())) {
// Move the child up one level i.e. set the same parent as the current object
$iParentId = $this->Get($oAttDef->GetCode());
$oDeletionPlan->AddToUpdate($oDependentObj, $oAttDef, $iParentId);
- }
- else
- {
+ } else {
$oDeletionPlan->AddToUpdate($oDependentObj, $oAttDef);
}
- }
- else
- {
+ } else {
// Mandatory external key, list to delete
$oDependentObj->MakeDeletionPlan($oDeletionPlan, $aVisited, $iDeletePropagationOption);
}
@@ -5520,8 +5213,8 @@ abstract class DBObject implements iDisplay
/**
* Get all the synchro data related to this object
- *
- * @internal
+ *
+ * @internal
*
* @return array of data_source_id => array
* * 'source' => $oSource,
@@ -5539,23 +5232,23 @@ abstract class DBObject implements iDisplay
if (!$bIncludeObsolete) {
$sOQL .= " AND replica.status != 'obsolete'";
}
- $oReplicaSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array('dest_class' => get_class($this), 'dest_id' => $this->GetKey()));
- $this->m_aSynchroData = array();
+ $oReplicaSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), [] /* order by*/, ['dest_class' => get_class($this), 'dest_id' => $this->GetKey()]);
+ $this->m_aSynchroData = [];
while ($aData = $oReplicaSet->FetchAssoc()) {
/** @var \DBObject[] $aData */
$iSourceId = $aData['datasource']->GetKey();
if (!array_key_exists($iSourceId, $this->m_aSynchroData)) {
- $aAttributes = array();
+ $aAttributes = [];
$oAttrSet = $aData['datasource']->Get('attribute_list');
while ($oSyncAttr = $oAttrSet->Fetch()) {
/** @var \DBObject $oSyncAttr */
$aAttributes[$oSyncAttr->Get('attcode')] = $oSyncAttr;
}
- $this->m_aSynchroData[$iSourceId] = array(
+ $this->m_aSynchroData[$iSourceId] = [
'source' => $aData['datasource'],
'attributes' => $aAttributes,
- 'replica' => array()
- );
+ 'replica' => [],
+ ];
}
// Assumption: $aData['datasource'] will not be null because the data source id is always set...
$this->m_aSynchroData[$iSourceId]['replica'][] = $aData['replica'];
@@ -5564,20 +5257,20 @@ abstract class DBObject implements iDisplay
return $this->m_aSynchroData;
}
- /**
- *
- * @internal
- *
- * @param string $sAttCode
- * @param array $aReason
- *
- * @return int
- * @throws ArchivedObjectException
- * @throws CoreException
- * @throws CoreUnexpectedValue
- * @throws MySQLException
- * @throws OQLException
- */
+ /**
+ *
+ * @internal
+ *
+ * @param string $sAttCode
+ * @param array $aReason
+ *
+ * @return int
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ * @throws CoreUnexpectedValue
+ * @throws MySQLException
+ * @throws OQLException
+ */
public function GetSynchroReplicaFlags($sAttCode, &$aReason)
{
$iFlags = OPT_ATT_NORMAL;
@@ -5592,12 +5285,11 @@ abstract class DBObject implements iDisplay
if (array_key_exists($sAttCode, $aSourceData['attributes'])) {
/** @var \DBObject $oSyncAttr */
$oSyncAttr = $aSourceData['attributes'][$sAttCode];
- if (($oSyncAttr->Get('update') == 1) && ($oSyncAttr->Get('update_policy') == 'master_locked'))
- {
+ if (($oSyncAttr->Get('update') == 1) && ($oSyncAttr->Get('update_policy') == 'master_locked')) {
$iFlags |= OPT_ATT_SLAVE;
/** @var \SynchroDataSource $oSource */
$sUrl = $oSource->GetApplicationUrl($this, $oReplica);
- $aReason[] = array('name' => $oSource->GetName(), 'description' => $oSource->Get('description'), 'url_application' => $sUrl);
+ $aReason[] = ['name' => $oSource->GetName(), 'description' => $oSource->Get('description'), 'url_application' => $sUrl];
}
}
}
@@ -5605,9 +5297,9 @@ abstract class DBObject implements iDisplay
}
/**
- *
- * @internal
- *
+ *
+ * @internal
+ *
* @return bool true if this object is used in a data synchro
* @throws \CoreException
* @throws \CoreUnexpectedValue
@@ -5622,22 +5314,18 @@ abstract class DBObject implements iDisplay
// Optimization: cache the list of Data Sources and classes candidates for synchro
//
static $aSynchroClasses = null;
- if (is_null($aSynchroClasses))
- {
- $aSynchroClasses = array();
+ if (is_null($aSynchroClasses)) {
+ $aSynchroClasses = [];
$sOQL = "SELECT SynchroDataSource AS datasource";
- $oSourceSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array());
- while($oSource = $oSourceSet->Fetch())
- {
+ $oSourceSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), [] /* order by*/, []);
+ while ($oSource = $oSourceSet->Fetch()) {
$sTarget = $oSource->Get('scope_class');
$aSynchroClasses[] = $sTarget;
}
}
- foreach($aSynchroClasses as $sClass)
- {
- if ($this instanceof $sClass)
- {
+ foreach ($aSynchroClasses as $sClass) {
+ if ($this instanceof $sClass) {
return true;
}
}
@@ -5649,86 +5337,79 @@ abstract class DBObject implements iDisplay
//
/////////////////////////////////////////////////////////////////////////
- /**
- * @internal
- *
- * @param string $sContextParam
- *
- * @return string|null
- */
+ /**
+ * @internal
+ *
+ * @param string $sContextParam
+ *
+ * @return string|null
+ */
public static function MapContextParam($sContextParam)
{
return null;
}
- /**
- * @internal
- *
- * @return String
- * @throws ArchivedObjectException
- * @throws CoreException
- */
+ /**
+ * @internal
+ *
+ * @return String
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ */
public function GetHilightClass()
{
$sCode = $this->ComputeHighlightCode();
- if($sCode != '')
- {
+ if ($sCode != '') {
$aHighlightScale = MetaModel::GetHighlightScale(get_class($this));
- if (array_key_exists($sCode, $aHighlightScale))
- {
+ if (array_key_exists($sCode, $aHighlightScale)) {
return $aHighlightScale[$sCode]['color'];
}
}
return HILIGHT_CLASS_NONE;
}
- /**
- * @internal
- *
- * @param WebPage $oPage
- * @param bool $bEditMode
- *
- * @throws ArchivedObjectException
- * @throws CoreException
- * @throws DictExceptionMissingString
- */
+ /**
+ * @internal
+ *
+ * @param WebPage $oPage
+ * @param bool $bEditMode
+ *
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ * @throws DictExceptionMissingString
+ */
public function DisplayDetails(WebPage $oPage, $bEditMode = false)
{
$oPage->add(''.MetaModel::GetName(get_class($this)).': '.$this->GetName().' ');
- $aValues = array();
+ $aValues = [];
$aList = MetaModel::FlattenZList(MetaModel::GetZListItems(get_class($this), 'details'));
- if (empty($aList))
- {
+ if (empty($aList)) {
$aList = array_keys(MetaModel::ListAttributeDefs(get_class($this)));
}
- foreach($aList as $sAttCode)
- {
- $aValues[$sAttCode] = array('label' => MetaModel::GetLabel(get_class($this), $sAttCode), 'value' => $this->GetAsHTML($sAttCode));
+ foreach ($aList as $sAttCode) {
+ $aValues[$sAttCode] = ['label' => MetaModel::GetLabel(get_class($this), $sAttCode), 'value' => $this->GetAsHTML($sAttCode)];
}
$oPage->details($aValues);
}
- /**
- * Computes a text-like fingerprint identifying the content of the object
- * but excluding the specified columns
- *
- * @internal
- *
- * @param $aExcludedColumns array The list of columns to exclude
- *
- * @return string
- * @throws ArchivedObjectException
- * @throws CoreException
- */
- public function Fingerprint($aExcludedColumns = array())
+ /**
+ * Computes a text-like fingerprint identifying the content of the object
+ * but excluding the specified columns
+ *
+ * @internal
+ *
+ * @param $aExcludedColumns array The list of columns to exclude
+ *
+ * @return string
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ */
+ public function Fingerprint($aExcludedColumns = [])
{
$sFingerprint = '';
- foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
- {
- if (!in_array($sAttCode, $aExcludedColumns))
- {
- if ($oAttDef->IsPartOfFingerprint())
- {
+ foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) {
+ if (!in_array($sAttCode, $aExcludedColumns)) {
+ if ($oAttDef->IsPartOfFingerprint()) {
$sFingerprint .= chr(0).$oAttDef->Fingerprint($this->Get($sAttCode));
}
}
@@ -5739,8 +5420,8 @@ abstract class DBObject implements iDisplay
/**
* Execute a set of scripted actions onto the current object
* See ExecAction for the syntax and features of the scripted actions
- *
- * @internal
+ *
+ * @internal
*
* @param $aActions array of statements (e.g. "set(name, Made after $source->name$)")
* @param $aSourceObjects array of Alias => Context objects (Convention: some statements require the 'source' element
@@ -5748,42 +5429,31 @@ abstract class DBObject implements iDisplay
*/
public function ExecActions($aActions, $aSourceObjects)
{
- foreach($aActions as $sAction)
- {
- try
- {
- if (preg_match('/^(\S*)\s*\((.*)\)$/ms', $sAction, $aMatches)) // multiline and newline matched by a dot
- {
+ foreach ($aActions as $sAction) {
+ try {
+ if (preg_match('/^(\S*)\s*\((.*)\)$/ms', $sAction, $aMatches)) { // multiline and newline matched by a dot
$sVerb = trim($aMatches[1]);
$sParams = $aMatches[2];
// the coma is the separator for the parameters
// comas can be escaped: \,
- $sParams = str_replace(array("\\\\", "\\,"), array("__backslash__", "__coma__"), $sParams);
+ $sParams = str_replace(["\\\\", "\\,"], ["__backslash__", "__coma__"], $sParams);
$sParams = trim($sParams);
- if (strlen($sParams) == 0)
- {
- $aParams = array();
- }
- else
- {
+ if (strlen($sParams) == 0) {
+ $aParams = [];
+ } else {
$aParams = explode(',', $sParams);
- foreach ($aParams as &$sParam)
- {
- $sParam = str_replace(array("__backslash__", "__coma__"), array("\\", ","), $sParam);
+ foreach ($aParams as &$sParam) {
+ $sParam = str_replace(["__backslash__", "__coma__"], ["\\", ","], $sParam);
$sParam = trim($sParam);
}
}
$this->ExecAction($sVerb, $aParams, $aSourceObjects);
- }
- else
- {
+ } else {
throw new Exception("Invalid syntax");
}
- }
- catch(Exception $e)
- {
+ } catch (Exception $e) {
throw new Exception('Action: '.$sAction.' - '.$e->getMessage());
}
}
@@ -5792,8 +5462,8 @@ abstract class DBObject implements iDisplay
/**
* Helper to copy an attribute between two objects (in memory)
* Originally designed for ExecAction()
- *
- * @internal
+ *
+ * @internal
*
* @param \DBObject $oSourceObject
* @param $sSourceAttCode
@@ -5805,8 +5475,7 @@ abstract class DBObject implements iDisplay
*/
public function CopyAttribute($oSourceObject, $sSourceAttCode, $sDestAttCode)
{
- if ($sSourceAttCode == 'id')
- {
+ if ($sSourceAttCode == 'id') {
$oSourceAttDef = null;
} else {
if (!MetaModel::IsValidAttCode(get_class($this), $sDestAttCode)) {
@@ -5838,9 +5507,7 @@ abstract class DBObject implements iDisplay
$oDestSet->AddItem($oLinkClone);
}
$this->Set($sDestAttCode, $oDestSet);
- }
- else
- {
+ } else {
$this->Set($sDestAttCode, $oSourceObject->Get($sSourceAttCode));
}
}
@@ -5858,9 +5525,9 @@ abstract class DBObject implements iDisplay
* - add_to_list (source_key_att, dest_att, lnk_att, lnk_att_value)
* - apply_stimulus (stimulus)
* - call_method (method_name)
- *
- *
- * @internal
+ *
+ *
+ * @internal
*
* @param $sVerb string Any of the verb listed above (e.g. "set")
* @param $aParams array of strings (e.g. array('name', 'copied from $source->name$')
@@ -5871,48 +5538,39 @@ abstract class DBObject implements iDisplay
*/
public function ExecAction($sVerb, $aParams, $aSourceObjects)
{
- switch($sVerb)
- {
+ switch ($sVerb) {
case 'clone':
- if (!array_key_exists('source', $aSourceObjects))
- {
+ if (!array_key_exists('source', $aSourceObjects)) {
throw new Exception('Missing conventional "source" object');
}
$oObjectToRead = $aSourceObjects['source'];
- foreach($aParams as $sAttCode)
- {
+ foreach ($aParams as $sAttCode) {
$this->CopyAttribute($oObjectToRead, $sAttCode, $sAttCode);
}
break;
case 'clone_scalars':
- if (!array_key_exists('source', $aSourceObjects))
- {
+ if (!array_key_exists('source', $aSourceObjects)) {
throw new Exception('Missing conventional "source" object');
}
$oObjectToRead = $aSourceObjects['source'];
- foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
- {
- if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
- {
+ foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) {
+ if ($oAttDef->IsScalar() && $oAttDef->IsWritable()) {
$this->CopyAttribute($oObjectToRead, $sAttCode, $sAttCode);
}
}
break;
case 'copy':
- if (!array_key_exists('source', $aSourceObjects))
- {
+ if (!array_key_exists('source', $aSourceObjects)) {
throw new Exception('Missing conventional "source" object');
}
$oObjectToRead = $aSourceObjects['source'];
- if (!array_key_exists(0, $aParams))
- {
+ if (!array_key_exists(0, $aParams)) {
throw new Exception('Missing argument #1: source attribute');
}
$sSourceAttCode = $aParams[0];
- if (!array_key_exists(1, $aParams))
- {
+ if (!array_key_exists(1, $aParams)) {
throw new Exception('Missing argument #2: target attribute');
}
$sDestAttCode = $aParams[1];
@@ -5920,26 +5578,22 @@ abstract class DBObject implements iDisplay
break;
case 'reset':
- if (!array_key_exists(0, $aParams))
- {
+ if (!array_key_exists(0, $aParams)) {
throw new Exception('Missing argument #1: target attribute');
}
$sAttCode = $aParams[0];
- if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode))
- {
+ if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode)) {
throw new Exception("Unknown attribute ".get_class($this)."::".$sAttCode);
}
$this->Set($sAttCode, $this->GetDefaultValue($sAttCode));
break;
case 'nullify':
- if (!array_key_exists(0, $aParams))
- {
+ if (!array_key_exists(0, $aParams)) {
throw new Exception('Missing argument #1: target attribute');
}
$sAttCode = $aParams[0];
- if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode))
- {
+ if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode)) {
throw new Exception("Unknown attribute ".get_class($this)."::".$sAttCode);
}
$oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
@@ -5947,23 +5601,19 @@ abstract class DBObject implements iDisplay
break;
case 'set':
- if (!array_key_exists(0, $aParams))
- {
+ if (!array_key_exists(0, $aParams)) {
throw new Exception('Missing argument #1: target attribute');
}
$sAttCode = $aParams[0];
- if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode))
- {
+ if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode)) {
throw new Exception("Unknown attribute ".get_class($this)."::".$sAttCode);
}
- if (!array_key_exists(1, $aParams))
- {
+ if (!array_key_exists(1, $aParams)) {
throw new Exception('Missing argument #2: value to set');
}
$sRawValue = $aParams[1];
- $aContext = array();
- foreach ($aSourceObjects as $sAlias => $oObject)
- {
+ $aContext = [];
+ foreach ($aSourceObjects as $sAlias => $oObject) {
$aContext = array_merge($aContext, $oObject->ToArgs($sAlias));
}
$aContext['current_contact_id'] = UserRights::GetContactId();
@@ -5975,23 +5625,19 @@ abstract class DBObject implements iDisplay
break;
case 'append':
- if (!array_key_exists(0, $aParams))
- {
+ if (!array_key_exists(0, $aParams)) {
throw new Exception('Missing argument #1: target attribute');
}
$sAttCode = $aParams[0];
- if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode))
- {
+ if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode)) {
throw new Exception("Unknown attribute ".get_class($this)."::".$sAttCode);
}
- if (!array_key_exists(1, $aParams))
- {
+ if (!array_key_exists(1, $aParams)) {
throw new Exception('Missing argument #2: value to append');
}
$sRawAddendum = $aParams[1];
- $aContext = array();
- foreach ($aSourceObjects as $sAlias => $oObject)
- {
+ $aContext = [];
+ foreach ($aSourceObjects as $sAlias => $oObject) {
$aContext = array_merge($aContext, $oObject->ToArgs($sAlias));
}
$aContext['current_contact_id'] = UserRights::GetContactId();
@@ -6003,38 +5649,31 @@ abstract class DBObject implements iDisplay
break;
case 'add_to_list':
- if (!array_key_exists('source', $aSourceObjects))
- {
+ if (!array_key_exists('source', $aSourceObjects)) {
throw new Exception('Missing conventional "source" object');
}
$oObjectToRead = $aSourceObjects['source'];
- if (!array_key_exists(0, $aParams))
- {
+ if (!array_key_exists(0, $aParams)) {
throw new Exception('Missing argument #1: source attribute');
}
$sSourceKeyAttCode = $aParams[0];
- if (($sSourceKeyAttCode != 'id') && !MetaModel::IsValidAttCode(get_class($oObjectToRead), $sSourceKeyAttCode))
- {
+ if (($sSourceKeyAttCode != 'id') && !MetaModel::IsValidAttCode(get_class($oObjectToRead), $sSourceKeyAttCode)) {
throw new Exception("Unknown attribute ".get_class($oObjectToRead)."::".$sSourceKeyAttCode);
}
- if (!array_key_exists(1, $aParams))
- {
+ if (!array_key_exists(1, $aParams)) {
throw new Exception('Missing argument #2: target attribute (link set)');
}
$sTargetListAttCode = $aParams[1]; // indirect !!!
- if (!MetaModel::IsValidAttCode(get_class($this), $sTargetListAttCode))
- {
+ if (!MetaModel::IsValidAttCode(get_class($this), $sTargetListAttCode)) {
throw new Exception("Unknown attribute ".get_class($this)."::".$sTargetListAttCode);
}
- if (isset($aParams[2]) && isset($aParams[3]))
- {
+ if (isset($aParams[2]) && isset($aParams[3])) {
$sRoleAttCode = $aParams[2];
$sRoleValue = $aParams[3];
}
$iObjKey = $oObjectToRead->Get($sSourceKeyAttCode);
- if ($iObjKey > 0)
- {
+ if ($iObjKey > 0) {
$oLinkSet = $this->Get($sTargetListAttCode);
/** @var \AttributeLinkedSetIndirect $oListAttDef */
@@ -6042,10 +5681,8 @@ abstract class DBObject implements iDisplay
/** @var \AttributeLinkedSet $oListAttDef */
$oLnk = MetaModel::NewObject($oListAttDef->GetLinkedClass());
$oLnk->Set($oListAttDef->GetExtKeyToRemote(), $iObjKey);
- if (isset($sRoleAttCode))
- {
- if (!MetaModel::IsValidAttCode(get_class($oLnk), $sRoleAttCode))
- {
+ if (isset($sRoleAttCode)) {
+ if (!MetaModel::IsValidAttCode(get_class($oLnk), $sRoleAttCode)) {
throw new Exception("Unknown attribute ".get_class($oLnk)."::".$sRoleAttCode);
}
$oLnk->Set($sRoleAttCode, $sRoleValue);
@@ -6056,8 +5693,7 @@ abstract class DBObject implements iDisplay
break;
case 'apply_stimulus':
- if (!array_key_exists(0, $aParams))
- {
+ if (!array_key_exists(0, $aParams)) {
throw new Exception('Missing argument #1: stimulus');
}
$sStimulus = $aParams[0];
@@ -6065,19 +5701,16 @@ abstract class DBObject implements iDisplay
break;
case 'call_method':
- if (!array_key_exists('source', $aSourceObjects))
- {
+ if (!array_key_exists('source', $aSourceObjects)) {
throw new Exception('Missing conventional "source" object');
}
$oObjectToRead = $aSourceObjects['source'];
- if (!array_key_exists(0, $aParams))
- {
+ if (!array_key_exists(0, $aParams)) {
throw new Exception('Missing argument #1: method name');
}
$sMethod = $aParams[0];
- $aCallSpec = array($this, $sMethod);
- if (!is_callable($aCallSpec))
- {
+ $aCallSpec = [$this, $sMethod];
+ if (!is_callable($aCallSpec)) {
throw new Exception("Unknown method ".get_class($this)."::".$sMethod.'()');
}
// Note: $oObjectToRead has been preserved when adding $aSourceObjects, so as to remain backward compatible with methods having only 1 parameter ($oObjectToRead�
@@ -6089,51 +5722,49 @@ abstract class DBObject implements iDisplay
}
}
- /**
- * Is the object archived
- *
- * @api
- *
- * @param string|null $sKeyAttCode
- *
- * @return bool
- * @throws ArchivedObjectException
- * @throws CoreException
- */
+ /**
+ * Is the object archived
+ *
+ * @api
+ *
+ * @param string|null $sKeyAttCode
+ *
+ * @return bool
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ */
public function IsArchived($sKeyAttCode = null)
{
$bRet = false;
$sFlagAttCode = is_null($sKeyAttCode) ? 'archive_flag' : $sKeyAttCode.'_archive_flag';
- if (MetaModel::IsValidAttCode(get_class($this), $sFlagAttCode) && $this->Get($sFlagAttCode))
- {
- $bRet = true;
- }
- return $bRet;
- }
-
- /**
- * Is the object obsolete
- *
- * @param string|null $sKeyAttCode
- *
- * @return bool
- * @throws ArchivedObjectException
- * @throws CoreException
- */
- public function IsObsolete($sKeyAttCode = null)
- {
- $bRet = false;
- $sFlagAttCode = is_null($sKeyAttCode) ? 'obsolescence_flag' : $sKeyAttCode.'_obsolescence_flag';
- if (MetaModel::IsValidAttCode(get_class($this), $sFlagAttCode) && $this->Get($sFlagAttCode))
- {
+ if (MetaModel::IsValidAttCode(get_class($this), $sFlagAttCode) && $this->Get($sFlagAttCode)) {
$bRet = true;
}
return $bRet;
}
/**
- * @internal
- *
+ * Is the object obsolete
+ *
+ * @param string|null $sKeyAttCode
+ *
+ * @return bool
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ */
+ public function IsObsolete($sKeyAttCode = null)
+ {
+ $bRet = false;
+ $sFlagAttCode = is_null($sKeyAttCode) ? 'obsolescence_flag' : $sKeyAttCode.'_obsolescence_flag';
+ if (MetaModel::IsValidAttCode(get_class($this), $sFlagAttCode) && $this->Get($sFlagAttCode)) {
+ $bRet = true;
+ }
+ return $bRet;
+ }
+
+ /**
+ * @internal
+ *
* Sets the archive_flag For all of the class hierarchy
* Also update the archive_date :
*
@@ -6151,8 +5782,7 @@ abstract class DBObject implements iDisplay
*/
protected function DBWriteArchiveFlag($bArchive)
{
- if (!MetaModel::IsArchivable(get_class($this)))
- {
+ if (!MetaModel::IsArchivable(get_class($this))) {
throw new Exception(get_class($this).' is not an archivable class');
}
@@ -6163,24 +5793,21 @@ abstract class DBObject implements iDisplay
$sArchiveRoot = MetaModel::GetAttributeOrigin($sClass, 'archive_flag');
$sRootTable = MetaModel::DBGetTable($sArchiveRoot);
$sRootKey = MetaModel::DBGetKey($sArchiveRoot);
- $aJoins = array("`$sRootTable`");
- $aUpdates = array();
- foreach (MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL) as $sParentClass)
- {
- if (!MetaModel::IsValidAttCode($sParentClass, 'archive_flag')) continue;
+ $aJoins = ["`$sRootTable`"];
+ $aUpdates = [];
+ foreach (MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL) as $sParentClass) {
+ if (!MetaModel::IsValidAttCode($sParentClass, 'archive_flag')) {
+ continue;
+ }
$sTable = MetaModel::DBGetTable($sParentClass);
$aUpdates[] = "`$sTable`.`archive_flag` = $iFlag";
- if ($sParentClass == $sArchiveRoot)
- {
- if (!$bArchive || $this->Get('archive_date') == '')
- {
+ if ($sParentClass == $sArchiveRoot) {
+ if (!$bArchive || $this->Get('archive_date') == '') {
// Erase or set the date (do not change it)
$aUpdates[] = "`$sTable`.`archive_date` = $sDate";
}
- }
- else
- {
+ } else {
$sKey = MetaModel::DBGetKey($sParentClass);
$aJoins[] = "`$sTable` ON `$sTable`.`$sKey` = `$sRootTable`.`$sRootKey`";
}
@@ -6203,10 +5830,10 @@ abstract class DBObject implements iDisplay
$this->FireEventArchive();
}
- /**
- * @throws Exception
- * @uses DBWriteArchiveFlag
- */
+ /**
+ * @throws Exception
+ * @uses DBWriteArchiveFlag
+ */
public function DBUnarchive()
{
$this->DBWriteArchiveFlag(false);
@@ -6217,21 +5844,19 @@ abstract class DBObject implements iDisplay
$this->FireEventUnArchive();
}
-
- /**
- * @internal
- *
- * @param string $sClass Needs to be an instanciable class
- *
- * @return DBObject
- * @throws CoreException
- * @throws CoreUnexpectedValue
- */
+ /**
+ * @internal
+ *
+ * @param string $sClass Needs to be an instanciable class
+ *
+ * @return DBObject
+ * @throws CoreException
+ * @throws CoreUnexpectedValue
+ */
public static function MakeDefaultInstance($sClass)
{
$oObj = MetaModel::NewObject($sClass);
- if (MetaModel::HasLifecycle($sClass))
- {
+ if (MetaModel::HasLifecycle($sClass)) {
$sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
$sTargetState = MetaModel::GetDefaultState($sClass);
$oObj->Set($sStateAttCode, $sTargetState);
@@ -6241,7 +5866,7 @@ abstract class DBObject implements iDisplay
/**
* Complete a new object with data from context
- *
+ *
* @overwritable-hook You can extend this method in order to provide your own logic.
*
* @see https://www.itophub.io/wiki/page?id=latest%3Acustomization%3Aform_prefill wiki tutorial
@@ -6263,7 +5888,7 @@ abstract class DBObject implements iDisplay
* Complete an object after a state transition with data from context
*
* @overwritable-hook You can extend this method in order to provide your own logic.
- *
+ *
* @see https://www.itophub.io/wiki/page?id=latest%3Acustomization%3Aform_prefill wiki tutorial
*
* @param array $aContextParam Context used for creation form prefilling. Contains those keys :
@@ -6313,7 +5938,7 @@ abstract class DBObject implements iDisplay
*/
public function PrefillForm($sOperation, &$aContextParam)
{
- switch($sOperation){
+ switch ($sOperation) {
case 'creation_from_0':
case 'creation_from_extkey':
case 'creation_from_editinplace':
@@ -6333,7 +5958,7 @@ abstract class DBObject implements iDisplay
public function EvaluateExpression(Expression $oExpression)
{
$aFields = $oExpression->ListRequiredFields();
- $aArgs = array();
+ $aArgs = [];
foreach ($aFields as $sFieldDesc) {
$aFieldParts = explode('.', $sFieldDesc);
if (count($aFieldParts) == 2) {
@@ -6496,7 +6121,7 @@ abstract class DBObject implements iDisplay
return OPT_ATT_NORMAL;
}
- public final function GetListeners(): array
+ final public function GetListeners(): array
{
$aListeners = [];
foreach ($this->aEventListeners as $aEventListener) {
@@ -6522,12 +6147,12 @@ abstract class DBObject implements iDisplay
{
$aEventCallbacks = $this->aEventListeners[$sEvent] ?? [];
- $aEventCallbacks[] = array(
+ $aEventCallbacks[] = [
'event' => $sEvent,
'callback' => $callback,
'priority' => $fPriority,
'module' => $sModuleId,
- );
+ ];
usort($aEventCallbacks, function ($a, $b) {
$fPriorityA = $a['priority'];
$fPriorityB = $b['priority'];
@@ -6550,7 +6175,7 @@ abstract class DBObject implements iDisplay
* @throws \Exception
* @since 3.1.0
*/
- public function FireEvent(string $sEvent, array $aEventData = array()): void
+ public function FireEvent(string $sEvent, array $aEventData = []): void
{
$aEventData['debug_info'] = 'from: '.get_class($this).':'.$this->GetKey();
$aEventData['object'] = $this;
@@ -6569,20 +6194,17 @@ abstract class DBObject implements iDisplay
EventServiceLog::Debug("Fire event '$sEvent' calling '".get_class($this).":$sCallback'");
try {
call_user_func([$this, $sCallback], new EventData($sEvent, null, $aEventData));
- }
- catch (EventException $e) {
+ } catch (EventException $e) {
EventServiceLog::Error("Event '$sEvent' for '$sCallback'} failed with blocking error: ".$e->getMessage());
throw $e;
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$sMessage = "Event '$sEvent' for '$sCallback'} failed with non-blocking error: ".$e->getMessage();
EventServiceLog::Error($sMessage);
if (is_null($oFirstException)) {
$sFirstExceptionMessage = $sMessage;
$oFirstException = $e;
}
- }
- finally {
+ } finally {
if (!$oKPI->ComputeStatsForExtension($this, $sCallback, "Event: $sEvent")) {
$sSignature = ModuleService::GetInstance()->GetModuleMethodSignature($this, $sCallback);
$oKPI->ComputeStats('FireEvent', "$sEvent callback: $sSignature");
@@ -6952,4 +6574,3 @@ abstract class DBObject implements iDisplay
return array_key_exists($sSection, $this->aContext);
}
}
-
diff --git a/core/dbobjectsearch.class.php b/core/dbobjectsearch.class.php
index 5f3ca1047..7e1ae9d8f 100644
--- a/core/dbobjectsearch.class.php
+++ b/core/dbobjectsearch.class.php
@@ -1,4 +1,5 @@
m_aSelectedClasses = array($sClassAlias => $sClass);
- $this->m_aClasses = array($sClassAlias => $sClass);
- $this->m_oSearchCondition = new TrueExpression;
- $this->m_aParams = array();
- $this->m_aPointingTo = array();
- $this->m_aReferencedBy = array();
+ $this->m_aSelectedClasses = [$sClassAlias => $sClass];
+ $this->m_aClasses = [$sClassAlias => $sClass];
+ $this->m_oSearchCondition = new TrueExpression();
+ $this->m_aParams = [];
+ $this->m_aPointingTo = [];
+ $this->m_aReferencedBy = [];
}
- public function AllowAllData($bAllowAllData = true) {
+ public function AllowAllData($bAllowAllData = true)
+ {
$this->m_bAllowAllData = $bAllowAllData;
$this->m_oSearchCondition->Browse(function ($oThisExpression) use ($bAllowAllData) {
@@ -76,32 +78,37 @@ class DBObjectSearch extends DBSearch
});
}
- public function IsAllDataAllowed() {
+ public function IsAllDataAllowed()
+ {
return $this->m_bAllowAllData;
}
- protected function IsDataFiltered() {
+ protected function IsDataFiltered()
+ {
return $this->m_bDataFiltered;
}
- protected function SetDataFiltered() {
+ protected function SetDataFiltered()
+ {
$this->m_bDataFiltered = true;
}
// Create a search definition that leads to 0 result, still a valid search object
- public static function FromEmptySet($sClass) {
+ public static function FromEmptySet($sClass)
+ {
$oResultFilter = new DBObjectSearch($sClass);
- $oResultFilter->m_oSearchCondition = new FalseExpression;
+ $oResultFilter->m_oSearchCondition = new FalseExpression();
return $oResultFilter;
}
-
- public function GetJoinedClasses() {
+ public function GetJoinedClasses()
+ {
return $this->m_aClasses;
}
- public function GetClassName($sAlias) {
+ public function GetClassName($sAlias)
+ {
if (array_key_exists($sAlias, $this->m_aSelectedClasses)) {
return $this->m_aSelectedClasses[$sAlias];
} else {
@@ -140,26 +147,20 @@ class DBObjectSearch extends DBSearch
*/
public function ChangeClass($sNewClass, $sAlias = null)
{
- if (is_null($sAlias))
- {
+ if (is_null($sAlias)) {
$sAlias = $this->GetClassAlias();
- }
- else
- {
- if (!array_key_exists($sAlias, $this->m_aSelectedClasses))
- {
+ } else {
+ if (!array_key_exists($sAlias, $this->m_aSelectedClasses)) {
// discard silently - necessary when recursing on the related nodes (see code below)
return;
}
}
$sCurrClass = $this->GetClassName($sAlias);
- if ($sNewClass == $sCurrClass)
- {
+ if ($sNewClass == $sCurrClass) {
// Skip silently
return;
}
- if (!MetaModel::IsParentClass($sCurrClass, $sNewClass))
- {
+ if (!MetaModel::IsParentClass($sCurrClass, $sNewClass)) {
throw new Exception("Could not change the search class from '$sCurrClass' to '$sNewClass'. Only child classes are permitted.");
}
@@ -170,24 +171,17 @@ class DBObjectSearch extends DBSearch
// Change for all the related node (yes, this was necessary with some queries - strange effects otherwise)
//
- foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
- {
- foreach($aPointingTo as $iOperatorCode => $aFilter)
- {
- foreach($aFilter as $oExtFilter)
- {
+ foreach ($this->m_aPointingTo as $sExtKeyAttCode => $aPointingTo) {
+ foreach ($aPointingTo as $iOperatorCode => $aFilter) {
+ foreach ($aFilter as $oExtFilter) {
$oExtFilter->ChangeClass($sNewClass, $sAlias);
}
}
}
- foreach($this->m_aReferencedBy as $sForeignClass => $aReferences)
- {
- foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
- {
- foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
- {
- foreach ($aFilters as $oForeignFilter)
- {
+ foreach ($this->m_aReferencedBy as $sForeignClass => $aReferences) {
+ foreach ($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) {
+ foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) {
+ foreach ($aFilters as $oForeignFilter) {
$oForeignFilter->ChangeClass($sNewClass, $sAlias);
}
}
@@ -206,11 +200,9 @@ class DBObjectSearch extends DBSearch
*/
public function SetSelectedClasses($aSelectedClasses)
{
- $this->m_aSelectedClasses = array();
- foreach ($aSelectedClasses as $sAlias)
- {
- if (!array_key_exists($sAlias, $this->m_aClasses))
- {
+ $this->m_aSelectedClasses = [];
+ foreach ($aSelectedClasses as $sAlias) {
+ if (!array_key_exists($sAlias, $this->m_aClasses)) {
throw new CoreException("SetSelectedClasses: Invalid class alias $sAlias");
}
$this->m_aSelectedClasses[$sAlias] = $this->m_aClasses[$sAlias];
@@ -229,38 +221,28 @@ class DBObjectSearch extends DBSearch
public function RenameAlias($sOldName, $sNewName)
{
$bFound = false;
- if (!array_key_exists($sOldName, $this->m_aClasses))
- {
+ if (!array_key_exists($sOldName, $this->m_aClasses)) {
return false;
}
- if (array_key_exists($sNewName, $this->m_aClasses))
- {
+ if (array_key_exists($sNewName, $this->m_aClasses)) {
throw new Exception("RenameAlias: alias '$sNewName' already used");
}
- $aClasses = array();
- foreach ($this->m_aClasses as $sAlias => $sClass)
- {
- if ($sAlias === $sOldName)
- {
+ $aClasses = [];
+ foreach ($this->m_aClasses as $sAlias => $sClass) {
+ if ($sAlias === $sOldName) {
$aClasses[$sNewName] = $sClass;
- }
- else
- {
+ } else {
$aClasses[$sAlias] = $sClass;
}
}
$this->m_aClasses = $aClasses;
- $aSelectedClasses = array();
- foreach ($this->m_aSelectedClasses as $sAlias => $sClass)
- {
- if ($sAlias === $sOldName)
- {
+ $aSelectedClasses = [];
+ foreach ($this->m_aSelectedClasses as $sAlias => $sClass) {
+ if ($sAlias === $sOldName) {
$aSelectedClasses[$sNewName] = $sClass;
- }
- else
- {
+ } else {
$aSelectedClasses[$sAlias] = $sClass;
}
}
@@ -268,24 +250,17 @@ class DBObjectSearch extends DBSearch
$this->m_oSearchCondition->RenameAlias($sOldName, $sNewName);
- foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
- {
- foreach($aPointingTo as $iOperatorCode => $aFilter)
- {
- foreach($aFilter as $oExtFilter)
- {
+ foreach ($this->m_aPointingTo as $sExtKeyAttCode => $aPointingTo) {
+ foreach ($aPointingTo as $iOperatorCode => $aFilter) {
+ foreach ($aFilter as $oExtFilter) {
$bFound = $oExtFilter->RenameAlias($sOldName, $sNewName) || $bFound;
}
}
}
- foreach($this->m_aReferencedBy as $sForeignClass => $aReferences)
- {
- foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
- {
- foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
- {
- foreach ($aFilters as $oForeignFilter)
- {
+ foreach ($this->m_aReferencedBy as $sForeignClass => $aReferences) {
+ foreach ($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) {
+ foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) {
+ foreach ($aFilters as $oForeignFilter) {
$bFound = $oForeignFilter->RenameAlias($sOldName, $sNewName) || $bFound;
}
}
@@ -301,21 +276,24 @@ class DBObjectSearch extends DBSearch
public function GetModifierProperties($sPluginClass)
{
- if (array_key_exists($sPluginClass, $this->m_aModifierProperties))
- {
+ if (array_key_exists($sPluginClass, $this->m_aModifierProperties)) {
return $this->m_aModifierProperties[$sPluginClass];
- }
- else
- {
- return array();
+ } else {
+ return [];
}
}
public function IsAny()
{
- if (!$this->m_oSearchCondition->IsTrue()) return false;
- if (count($this->m_aPointingTo) > 0) return false;
- if (count($this->m_aReferencedBy) > 0) return false;
+ if (!$this->m_oSearchCondition->IsTrue()) {
+ return false;
+ }
+ if (count($this->m_aPointingTo) > 0) {
+ return false;
+ }
+ if (count($this->m_aReferencedBy) > 0) {
+ return false;
+ }
return true;
}
@@ -327,14 +305,11 @@ class DBObjectSearch extends DBSearch
protected function TransferConditionExpression($oFilter, $aTranslation)
{
// Prevent collisions in the parameter names by renaming them if needed
- foreach($this->m_aParams as $sParam => $value)
- {
- if (array_key_exists($sParam, $oFilter->m_aParams) && ($value != $oFilter->m_aParams[$sParam]))
- {
+ foreach ($this->m_aParams as $sParam => $value) {
+ if (array_key_exists($sParam, $oFilter->m_aParams) && ($value != $oFilter->m_aParams[$sParam])) {
// Generate a new and unique name for the collinding parameter
$index = 1;
- while(array_key_exists($sParam.$index, $oFilter->m_aParams))
- {
+ while (array_key_exists($sParam.$index, $oFilter->m_aParams)) {
$index++;
}
$secondValue = $oFilter->m_aParams[$sParam];
@@ -352,19 +327,15 @@ class DBObjectSearch extends DBSearch
public function RenameParam($sOldName, $sNewName)
{
$this->m_oSearchCondition->RenameParam($sOldName, $sNewName);
- foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
- {
- foreach($aPointingTo as $iOperatorCode => $aFilter)
- {
- foreach($aFilter as $oExtFilter)
- {
+ foreach ($this->m_aPointingTo as $sExtKeyAttCode => $aPointingTo) {
+ foreach ($aPointingTo as $iOperatorCode => $aFilter) {
+ foreach ($aFilter as $oExtFilter) {
$oExtFilter->RenameParam($sOldName, $sNewName);
}
}
}
- foreach($this->m_aReferencedBy as $sForeignClass => $aReferences)
- {
- foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) {
+ foreach ($this->m_aReferencedBy as $sForeignClass => $aReferences) {
+ foreach ($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) {
foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) {
foreach ($aFilters as $oForeignFilter) {
$oForeignFilter->RenameParam($sOldName, $sNewName);
@@ -374,16 +345,19 @@ class DBObjectSearch extends DBSearch
}
}
- public function ResetCondition() {
+ public function ResetCondition()
+ {
$this->m_oSearchCondition = new TrueExpression();
// ? is that usefull/enough, do I need to rebuild the list after the subqueries ?
}
- public function MergeConditionExpression($oExpression) {
+ public function MergeConditionExpression($oExpression)
+ {
$this->m_oSearchCondition = $this->m_oSearchCondition->LogOr($oExpression);
}
- public function AddConditionExpression($oExpression) {
+ public function AddConditionExpression($oExpression)
+ {
$this->m_oSearchCondition = $this->m_oSearchCondition->LogAnd($oExpression);
$bRootSearchAllowAllData = $this->IsAllDataAllowed();
@@ -392,7 +366,8 @@ class DBObjectSearch extends DBSearch
});
}
- public function AddNameCondition($sName) {
+ public function AddNameCondition($sName)
+ {
$oValueExpr = new ScalarExpression($sName);
$oNameExpr = new FieldExpression('friendlyname', $this->GetClassAlias());
$oNewCondition = new BinaryExpression($oNameExpr, '=', $oValueExpr);
@@ -417,15 +392,15 @@ class DBObjectSearch extends DBSearch
*/
public function AddCondition($sFilterCode, $value, $sOpCode = null, $bParseSearchString = false)
{
- if (MetaModel::IsValidFilterCode($this->GetClass(),$sFilterCode) == false){
- /* $sArrayDesc = if (count($aData) == 0)
- {
- $sArrayDesc = "{}";
- }
- else
- {
- $sArrayDesc = "{".implode(", ", $aData)."}";
- }*/
+ if (MetaModel::IsValidFilterCode($this->GetClass(), $sFilterCode) == false) {
+ /* $sArrayDesc = if (count($aData) == 0)
+ {
+ $sArrayDesc = "{}";
+ }
+ else
+ {
+ $sArrayDesc = "{".implode(", ", $aData)."}";
+ }*/
throw new CoreException("Wrong value for '".$this->GetClass()."', found '$sFilterCode'");// while expecting a value in $sArrayDesc");
}
$oField = new FieldExpression($sFilterCode, $this->GetClassAlias());
@@ -440,81 +415,82 @@ class DBObjectSearch extends DBSearch
}
}
// Parse search strings if needed and if the filter code corresponds to a valid attcode
- if($bParseSearchString && MetaModel::IsValidAttCode($this->GetClass(), $sFilterCode))
- {
+ if ($bParseSearchString && MetaModel::IsValidAttCode($this->GetClass(), $sFilterCode)) {
$oAttDef = MetaModel::GetAttributeDef($this->GetClass(), $sFilterCode);
$value = $oAttDef->ParseSearchString($value);
}
// Preserve backward compatibility - quick n'dirty way to change that API semantic
//
- switch($sOpCode)
- {
- case 'SameDay':
- case 'SameMonth':
- case 'SameYear':
- case 'Today':
- case '>|':
- case '<|':
- case '=|':
- throw new CoreException('Deprecated operator, please consider using OQL (SQL) expressions like "(TO_DAYS(NOW()) - TO_DAYS(x)) AS AgeDays"', array('operator' => $sOpCode));
+ switch ($sOpCode) {
+ case 'SameDay':
+ case 'SameMonth':
+ case 'SameYear':
+ case 'Today':
+ case '>|':
+ case '<|':
+ case '=|':
+ throw new CoreException('Deprecated operator, please consider using OQL (SQL) expressions like "(TO_DAYS(NOW()) - TO_DAYS(x)) AS AgeDays"', ['operator' => $sOpCode]);
- case 'IN':
- if (!is_array($value)) $value = array($value);
- if (count($value) === 0) throw new Exception('AddCondition '.$sOpCode.': Value cannot be an empty array.');
- $sListExpr = '('.implode(', ', CMDBSource::Quote($value)).')';
- $sOQLCondition = $oField->RenderExpression()." IN $sListExpr";
- break;
-
- case 'NOTIN':
- if (!is_array($value)) $value = array($value);
- if (count($value) === 0) throw new Exception('AddCondition '.$sOpCode.': Value cannot be an empty array.');
- $sListExpr = '('.implode(', ', CMDBSource::Quote($value)).')';
- $sOQLCondition = $oField->RenderExpression()." NOT IN $sListExpr";
- break;
-
- case 'Contains':
- $this->m_aParams[$sFilterCode] = "%$value%";
- $sOperator = 'LIKE';
- break;
-
- case 'Begins with':
- $this->m_aParams[$sFilterCode] = "$value%";
- $sOperator = 'LIKE';
- break;
-
- case 'Finishes with':
- $this->m_aParams[$sFilterCode] = "%$value";
- $sOperator = 'LIKE';
- break;
-
- default:
- if ($value === null)
- {
- switch ($sOpCode)
- {
- case '=':
- $sOpCode = '*Expression*';
- $oExpression = new FunctionExpression('ISNULL', array($oField));
- break;
- case '!=':
- $sOpCode = '*Expression*';
- $oExpression = new FunctionExpression('ISNULL', array($oField));
- $oExpression = new BinaryExpression($oExpression, '=', new ScalarExpression(0));
- break;
- default:
- throw new Exception("AddCondition on null value: unsupported operator '$sOpCode''");
+ case 'IN':
+ if (!is_array($value)) {
+ $value = [$value];
+ }
+ if (count($value) === 0) {
+ throw new Exception('AddCondition '.$sOpCode.': Value cannot be an empty array.');
+ }
+ $sListExpr = '('.implode(', ', CMDBSource::Quote($value)).')';
+ $sOQLCondition = $oField->RenderExpression()." IN $sListExpr";
+ break;
+
+ case 'NOTIN':
+ if (!is_array($value)) {
+ $value = [$value];
+ }
+ if (count($value) === 0) {
+ throw new Exception('AddCondition '.$sOpCode.': Value cannot be an empty array.');
+ }
+ $sListExpr = '('.implode(', ', CMDBSource::Quote($value)).')';
+ $sOQLCondition = $oField->RenderExpression()." NOT IN $sListExpr";
+ break;
+
+ case 'Contains':
+ $this->m_aParams[$sFilterCode] = "%$value%";
+ $sOperator = 'LIKE';
+ break;
+
+ case 'Begins with':
+ $this->m_aParams[$sFilterCode] = "$value%";
+ $sOperator = 'LIKE';
+ break;
+
+ case 'Finishes with':
+ $this->m_aParams[$sFilterCode] = "%$value";
+ $sOperator = 'LIKE';
+ break;
+
+ default:
+ if ($value === null) {
+ switch ($sOpCode) {
+ case '=':
+ $sOpCode = '*Expression*';
+ $oExpression = new FunctionExpression('ISNULL', [$oField]);
+ break;
+ case '!=':
+ $sOpCode = '*Expression*';
+ $oExpression = new FunctionExpression('ISNULL', [$oField]);
+ $oExpression = new BinaryExpression($oExpression, '=', new ScalarExpression(0));
+ break;
+ default:
+ throw new Exception("AddCondition on null value: unsupported operator '$sOpCode''");
+ }
+ } else {
+ $this->m_aParams[$sFilterCode] = $value;
+ $sOperator = $sOpCode;
}
- }
- else
- {
- $this->m_aParams[$sFilterCode] = $value;
- $sOperator = $sOpCode;
- }
}
- switch($sOpCode)
- {
+ switch ($sOpCode) {
case '*Expression*':
$oNewCondition = $oExpression;
break;
@@ -562,7 +538,7 @@ class DBObjectSearch extends DBSearch
$oParamExpression = new VariableExpression($sInParamName);
$this->GetInternalParamsByRef()[$sInParamName] = $aValues;
- $oListExpression = new ListExpression(array($oParamExpression));
+ $oListExpression = new ListExpression([$oParamExpression]);
$oInCondition = new BinaryExpression($oFieldExpression, $sOperator, $oListExpression);
$this->AddConditionExpression($oInCondition);
@@ -582,19 +558,16 @@ class DBObjectSearch extends DBSearch
$sClass = $this->GetClass();
$iPos = strpos($sAttSpec, '->');
- if ($iPos !== false)
- {
+ if ($iPos !== false) {
$sAttCode = substr($sAttSpec, 0, $iPos);
$sSubSpec = substr($sAttSpec, $iPos + 2);
- if (!MetaModel::IsValidAttCode($sClass, $sAttCode))
- {
+ if (!MetaModel::IsValidAttCode($sClass, $sAttCode)) {
throw new Exception("Invalid attribute code '$sClass/$sAttCode' in condition specification '$sAttSpec'");
}
$oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
- if ($oAttDef->IsLinkSet())
- {
+ if ($oAttDef->IsLinkSet()) {
$sTargetClass = $oAttDef->GetLinkedClass();
$sExtKeyToMe = $oAttDef->GetExtKeyToMe();
@@ -602,35 +575,26 @@ class DBObjectSearch extends DBSearch
$oNewFilter->AddConditionAdvanced($sSubSpec, $value);
$this->AddCondition_ReferencedBy($oNewFilter, $sExtKeyToMe);
- }
- elseif ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
- {
+ } elseif ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) {
$sTargetClass = $oAttDef->GetTargetClass(EXTKEY_ABSOLUTE);
$oNewFilter = new DBObjectSearch($sTargetClass);
$oNewFilter->AddConditionAdvanced($sSubSpec, $value);
$this->AddCondition_PointingTo($oNewFilter, $sAttCode);
- }
- else
- {
+ } else {
throw new Exception("Attribute specification '$sAttSpec', '$sAttCode' should be either a link set or an external key");
}
- }
- else
- {
+ } else {
// $sAttSpec is an attribute code
//
- if (is_array($value))
- {
+ if (is_array($value)) {
$oField = new FieldExpression($sAttSpec, $this->GetClass());
$oListExpr = ListExpression::FromScalars($value);
$oInValues = new BinaryExpression($oField, 'IN', $oListExpr);
$this->AddConditionExpression($oInValues);
- }
- else
- {
+ } else {
$this->AddCondition($sAttSpec, $value);
}
}
@@ -641,9 +605,15 @@ class DBObjectSearch extends DBSearch
// Transform the full text condition into additional condition expression
$aAttCodes = [];
foreach (MetaModel::ListAttributeDefs($this->GetClass()) as $sAttCode => $oAttDef) {
- if (!$oAttDef->IsScalar()) continue;
- if ($oAttDef->IsExternalKey()) continue;
- if (!$oAttDef->IsSearchable()) continue;
+ if (!$oAttDef->IsScalar()) {
+ continue;
+ }
+ if ($oAttDef->IsExternalKey()) {
+ continue;
+ }
+ if (!$oAttDef->IsSearchable()) {
+ continue;
+ }
$aAttCodes[] = $sAttCode;
}
$this->AddCondition_FullTextOnAttributes($aAttCodes, $sNeedle);
@@ -665,7 +635,7 @@ class DBObjectSearch extends DBSearch
$oTextFields = new CharConcatWSExpression(' ', $aFullTextFields);
$sQueryParam = str_replace('.', '', uniqid('needle_', true));
- $oFlexNeedle = new CharConcatExpression(array(new ScalarExpression('%'), new VariableExpression($sQueryParam), new ScalarExpression('%')));
+ $oFlexNeedle = new CharConcatExpression([new ScalarExpression('%'), new VariableExpression($sQueryParam), new ScalarExpression('%')]);
$oNewCond = new BinaryExpression($oTextFields, 'LIKE', $oFlexNeedle);
$this->AddConditionExpression($oNewCond);
@@ -677,14 +647,11 @@ class DBObjectSearch extends DBSearch
protected function AddToNameSpace(&$aClassAliases, &$aAliasTranslation, $bTranslateMainAlias = true)
{
- if ($bTranslateMainAlias)
- {
+ if ($bTranslateMainAlias) {
$sOrigAlias = $this->GetFirstJoinedClassAlias();
- if (array_key_exists($sOrigAlias, $aClassAliases))
- {
+ if (array_key_exists($sOrigAlias, $aClassAliases)) {
$sNewAlias = MetaModel::GenerateUniqueAlias($aClassAliases, $sOrigAlias, $this->GetFirstJoinedClass());
- if (isset($this->m_aSelectedClasses[$sOrigAlias]))
- {
+ if (isset($this->m_aSelectedClasses[$sOrigAlias])) {
$this->m_aSelectedClasses[$sNewAlias] = $this->GetFirstJoinedClass();
unset($this->m_aSelectedClasses[$sOrigAlias]);
}
@@ -692,46 +659,35 @@ class DBObjectSearch extends DBSearch
// TEMPORARY ALGORITHM (m_aClasses is not correctly updated, it is not possible to add a subtree onto a subnode)
// Replace the element at the same position (unset + set is not enough because the hash array is ordered)
$aPrevList = $this->m_aClasses;
- $this->m_aClasses = array();
- foreach ($aPrevList as $sSomeAlias => $sSomeClass)
- {
- if ($sSomeAlias == $sOrigAlias)
- {
+ $this->m_aClasses = [];
+ foreach ($aPrevList as $sSomeAlias => $sSomeClass) {
+ if ($sSomeAlias == $sOrigAlias) {
$this->m_aClasses[$sNewAlias] = $sSomeClass; // note: GetFirstJoinedClass now returns '' !!!
- }
- else
- {
+ } else {
$this->m_aClasses[$sSomeAlias] = $sSomeClass;
}
}
-
+
// Translate the condition expression with the new alias
$aAliasTranslation[$sOrigAlias]['*'] = $sNewAlias;
}
-
+
// add the alias into the filter aliases list
$aClassAliases[$this->GetFirstJoinedClassAlias()] = $this->GetFirstJoinedClass();
}
-
- foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
- {
- foreach($aPointingTo as $iOperatorCode => $aFilter)
- {
- foreach($aFilter as $oFilter)
- {
+
+ foreach ($this->m_aPointingTo as $sExtKeyAttCode => $aPointingTo) {
+ foreach ($aPointingTo as $iOperatorCode => $aFilter) {
+ foreach ($aFilter as $oFilter) {
$oFilter->AddToNameSpace($aClassAliases, $aAliasTranslation);
}
}
}
- foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences)
- {
- foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
- {
- foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
- {
- foreach ($aFilters as $oForeignFilter)
- {
+ foreach ($this->m_aReferencedBy as $sForeignClass => $aReferences) {
+ foreach ($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) {
+ foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) {
+ foreach ($aFilters as $oForeignFilter) {
$oForeignFilter->AddToNameSpace($aClassAliases, $aAliasTranslation);
}
}
@@ -745,18 +701,17 @@ class DBObjectSearch extends DBSearch
* @param array $aClassAliases array of alias => class for the main query
* @param array $aAliasTranslation translation table of main query to apply to nested queries
*/
- public function RenameNestedQueriesAliasesInNameSpace($aClassAliases, $aAliasTranslation = array())
+ public function RenameNestedQueriesAliasesInNameSpace($aClassAliases, $aAliasTranslation = [])
{
$this->GetCriteria()->Browse(function ($oNode) use ($aClassAliases, $aAliasTranslation) {
- if ($oNode instanceof NestedQueryExpression)
- {
+ if ($oNode instanceof NestedQueryExpression) {
$oNestedQuery = $oNode->GetNestedQuery();
$oNestedQuery->RenameAliasesInNameSpace($aClassAliases, $aAliasTranslation);
}
});
}
- public function RenameAliasesInNameSpace($aClassAliases, $aAliasTranslation = array())
+ public function RenameAliasesInNameSpace($aClassAliases, $aAliasTranslation = [])
{
// Recurse in nested queries
$this->RenameNestedQueriesAliasesInNameSpace($aClassAliases, $aAliasTranslation);
@@ -775,37 +730,25 @@ class DBObjectSearch extends DBSearch
//
protected function GetNode($sAlias)
{
- if ($this->GetFirstJoinedClassAlias() == $sAlias)
- {
+ if ($this->GetFirstJoinedClassAlias() == $sAlias) {
return $this;
- }
- else
- {
- foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
- {
- foreach($aPointingTo as $iOperatorCode => $aFilter)
- {
- foreach($aFilter as $oFilter)
- {
+ } else {
+ foreach ($this->m_aPointingTo as $sExtKeyAttCode => $aPointingTo) {
+ foreach ($aPointingTo as $iOperatorCode => $aFilter) {
+ foreach ($aFilter as $oFilter) {
$ret = $oFilter->GetNode($sAlias);
- if (is_object($ret))
- {
+ if (is_object($ret)) {
return $ret;
}
}
}
}
- foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences)
- {
- foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
- {
- foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
- {
- foreach ($aFilters as $oForeignFilter)
- {
+ foreach ($this->m_aReferencedBy as $sForeignClass => $aReferences) {
+ foreach ($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) {
+ foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) {
+ foreach ($aFilters as $oForeignFilter) {
$ret = $oForeignFilter->GetNode($sAlias);
- if (is_object($ret))
- {
+ if (is_object($ret)) {
return $ret;
}
}
@@ -829,36 +772,27 @@ class DBObjectSearch extends DBSearch
*/
protected function UpdateRealiasingMap(&$aRealiasingMap, $aAliasTranslation)
{
- if ($aRealiasingMap !== null)
- {
- foreach ($aAliasTranslation as $sPrevAlias => $aRules)
- {
- if (!isset($aRules['*']))
- {
+ if ($aRealiasingMap !== null) {
+ foreach ($aAliasTranslation as $sPrevAlias => $aRules) {
+ if (!isset($aRules['*'])) {
continue;
}
$sNewAlias = $aRules['*'];
$bOriginalFound = false;
$iIndex = 0;
- foreach ($aRealiasingMap as $sOriginalAlias => $aAliases)
- {
+ foreach ($aRealiasingMap as $sOriginalAlias => $aAliases) {
$iIndex = array_search($sPrevAlias, $aAliases);
- if ($iIndex !== false)
- {
+ if ($iIndex !== false) {
$bOriginalFound = true;
break;
}
}
- if ($bOriginalFound)
- {
+ if ($bOriginalFound) {
$aRealiasingMap[$sOriginalAlias][$iIndex] = $sNewAlias;
- }
- else
- {
- if (!isset($aRealiasingMap[$sPrevAlias]) || !in_array($sNewAlias, $aRealiasingMap[$sPrevAlias]))
- {
+ } else {
+ if (!isset($aRealiasingMap[$sPrevAlias]) || !in_array($sNewAlias, $aRealiasingMap[$sPrevAlias])) {
$aRealiasingMap[$sPrevAlias][] = $sNewAlias;
}
}
@@ -878,25 +812,18 @@ class DBObjectSearch extends DBSearch
$aClasses[$this->GetFirstJoinedClassAlias()] = $this->GetFirstJoinedClass();
// Recurse in the query tree
- foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
- {
- foreach($aPointingTo as $iOperatorCode => $aFilter)
- {
- foreach($aFilter as $oFilter)
- {
+ foreach ($this->m_aPointingTo as $sExtKeyAttCode => $aPointingTo) {
+ foreach ($aPointingTo as $iOperatorCode => $aFilter) {
+ foreach ($aFilter as $oFilter) {
$oFilter->RecomputeClassList($aClasses);
}
}
}
- foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences)
- {
- foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
- {
- foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
- {
- foreach ($aFilters as $oForeignFilter)
- {
+ foreach ($this->m_aReferencedBy as $sForeignClass => $aReferences) {
+ foreach ($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) {
+ foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) {
+ foreach ($aFilters as $oForeignFilter) {
$oForeignFilter->RecomputeClassList($aClasses);
}
}
@@ -918,40 +845,33 @@ class DBObjectSearch extends DBSearch
*/
public function AddCondition_PointingTo(DBObjectSearch $oFilter, $sExtKeyAttCode, $iOperatorCode = TREE_OPERATOR_EQUALS, &$aRealiasingMap = null)
{
- if (!MetaModel::IsValidKeyAttCode($this->GetClass(), $sExtKeyAttCode))
- {
+ if (!MetaModel::IsValidKeyAttCode($this->GetClass(), $sExtKeyAttCode)) {
throw new CoreWarning("The attribute code '$sExtKeyAttCode' is not an external key of the class '{$this->GetClass()}'");
}
$oAttExtKey = MetaModel::GetAttributeDef($this->GetClass(), $sExtKeyAttCode);
- if(!MetaModel::IsSameFamilyBranch($oFilter->GetClass(), $oAttExtKey->GetTargetClass()))
- {
+ if (!MetaModel::IsSameFamilyBranch($oFilter->GetClass(), $oAttExtKey->GetTargetClass())) {
throw new CoreException("The specified filter (pointing to {$oFilter->GetClass()}) is not compatible with the key '{$this->GetClass()}::$sExtKeyAttCode', which is pointing to {$oAttExtKey->GetTargetClass()}");
}
- if(($iOperatorCode != TREE_OPERATOR_EQUALS) && !($oAttExtKey instanceof AttributeHierarchicalKey))
- {
+ if (($iOperatorCode != TREE_OPERATOR_EQUALS) && !($oAttExtKey instanceof AttributeHierarchicalKey)) {
throw new CoreException("The specified tree operator $iOperatorCode is not applicable to the key '{$this->GetClass()}::$sExtKeyAttCode', which is not a HierarchicalKey");
}
// Note: though it seems to be a good practice to clone the given source filter
// (as it was done and fixed an issue in Intersect())
// this was not implemented here because it was causing a regression (login as admin, select an org, click on any badge)
- // root cause: FromOQL relies on the fact that the passed filter can be modified later
+ // root cause: FromOQL relies on the fact that the passed filter can be modified later
// NO: $oFilter = $oFilter->DeepClone();
// See also: Trac #639, and self::AddCondition_ReferencedBy()
- $aAliasTranslation = array();
+ $aAliasTranslation = [];
$res = $this->AddCondition_PointingTo_InNameSpace($oFilter, $sExtKeyAttCode, $this->m_aClasses, $aAliasTranslation, $iOperatorCode);
$this->TransferConditionExpression($oFilter, $aAliasTranslation);
$this->UpdateRealiasingMap($aRealiasingMap, $aAliasTranslation);
- if (ENABLE_OPT && ($oFilter->GetClass() == $oFilter->GetFirstJoinedClass()))
- {
- if (isset($oFilter->m_aReferencedBy[$this->GetClass()][$sExtKeyAttCode][$iOperatorCode]))
- {
- foreach ($oFilter->m_aReferencedBy[$this->GetClass()][$sExtKeyAttCode][$iOperatorCode] as $oRemoteFilter)
- {
- if ($this->GetClass() == $oRemoteFilter->GetClass())
- {
+ if (ENABLE_OPT && ($oFilter->GetClass() == $oFilter->GetFirstJoinedClass())) {
+ if (isset($oFilter->m_aReferencedBy[$this->GetClass()][$sExtKeyAttCode][$iOperatorCode])) {
+ foreach ($oFilter->m_aReferencedBy[$this->GetClass()][$sExtKeyAttCode][$iOperatorCode] as $oRemoteFilter) {
+ if ($this->GetClass() == $oRemoteFilter->GetClass()) {
// Optimization - fold sibling query
- $aAliasTranslation = array();
+ $aAliasTranslation = [];
$this->MergeWith_InNamespace($oRemoteFilter, $this->m_aClasses, $aAliasTranslation);
unset($oFilter->m_aReferencedBy[$this->GetClass()][$sExtKeyAttCode][$iOperatorCode]);
$this->m_oSearchCondition = $this->m_oSearchCondition->Translate($aAliasTranslation, false, false);
@@ -980,21 +900,17 @@ class DBObjectSearch extends DBSearch
$oReceivingFilter = $this->GetNode($this->GetClassAlias());
$bMerged = false;
- if (ENABLE_OPT && isset($oReceivingFilter->m_aPointingTo[$sExtKeyAttCode][$iOperatorCode]))
- {
- foreach ($oReceivingFilter->m_aPointingTo[$sExtKeyAttCode][$iOperatorCode] as $oExisting)
- {
+ if (ENABLE_OPT && isset($oReceivingFilter->m_aPointingTo[$sExtKeyAttCode][$iOperatorCode])) {
+ foreach ($oReceivingFilter->m_aPointingTo[$sExtKeyAttCode][$iOperatorCode] as $oExisting) {
/** @var DBObjectSearch $oExisting */
- if ($oExisting->GetClass() == $oFilter->GetClass())
- {
+ if ($oExisting->GetClass() == $oFilter->GetClass()) {
$oExisting->MergeWith_InNamespace($oFilter, $aClassAliases, $aAliasTranslation);
$bMerged = true;
break;
}
}
}
- if (!$bMerged)
- {
+ if (!$bMerged) {
$oFilter->AddToNamespace($aClassAliases, $aAliasTranslation);
$oReceivingFilter->m_aPointingTo[$sExtKeyAttCode][$iOperatorCode][] = $oFilter;
}
@@ -1011,13 +927,11 @@ class DBObjectSearch extends DBSearch
public function AddCondition_ReferencedBy(DBObjectSearch $oFilter, $sForeignExtKeyAttCode, $iOperatorCode = TREE_OPERATOR_EQUALS, &$aRealiasingMap = null)
{
$sForeignClass = $oFilter->GetClass();
- if (!MetaModel::IsValidKeyAttCode($sForeignClass, $sForeignExtKeyAttCode))
- {
+ if (!MetaModel::IsValidKeyAttCode($sForeignClass, $sForeignExtKeyAttCode)) {
throw new CoreException("The attribute code '$sForeignExtKeyAttCode' is not an external key of the class '{$sForeignClass}'");
}
$oAttExtKey = MetaModel::GetAttributeDef($sForeignClass, $sForeignExtKeyAttCode);
- if(!MetaModel::IsSameFamilyBranch($this->GetClass(), $oAttExtKey->GetTargetClass()))
- {
+ if (!MetaModel::IsSameFamilyBranch($this->GetClass(), $oAttExtKey->GetTargetClass())) {
// à refaire en spécifique dans FromOQL
throw new CoreException("The specified filter (objects referencing an object of class {$this->GetClass()}) is not compatible with the key '{$sForeignClass}::$sForeignExtKeyAttCode', which is pointing to {$oAttExtKey->GetTargetClass()}");
}
@@ -1025,24 +939,20 @@ class DBObjectSearch extends DBSearch
// Note: though it seems to be a good practice to clone the given source filter
// (as it was done and fixed an issue in Intersect())
// this was not implemented here because it was causing a regression (login as admin, select an org, click on any badge)
- // root cause: FromOQL relies on the fact that the passed filter can be modified later
+ // root cause: FromOQL relies on the fact that the passed filter can be modified later
// NO: $oFilter = $oFilter->DeepClone();
// See also: Trac #639, and self::AddCondition_PointingTo()
- $aAliasTranslation = array();
+ $aAliasTranslation = [];
$this->AddCondition_ReferencedBy_InNameSpace($oFilter, $sForeignExtKeyAttCode, $this->m_aClasses, $aAliasTranslation, $iOperatorCode);
$this->TransferConditionExpression($oFilter, $aAliasTranslation);
$this->UpdateRealiasingMap($aRealiasingMap, $aAliasTranslation);
- if (ENABLE_OPT && ($oFilter->GetClass() == $oFilter->GetFirstJoinedClass()))
- {
- if (isset($oFilter->m_aPointingTo[$sForeignExtKeyAttCode][$iOperatorCode]))
- {
- foreach ($oFilter->m_aPointingTo[$sForeignExtKeyAttCode][$iOperatorCode] as $oRemoteFilter)
- {
- if ($this->GetClass() == $oRemoteFilter->GetClass())
- {
+ if (ENABLE_OPT && ($oFilter->GetClass() == $oFilter->GetFirstJoinedClass())) {
+ if (isset($oFilter->m_aPointingTo[$sForeignExtKeyAttCode][$iOperatorCode])) {
+ foreach ($oFilter->m_aPointingTo[$sForeignExtKeyAttCode][$iOperatorCode] as $oRemoteFilter) {
+ if ($this->GetClass() == $oRemoteFilter->GetClass()) {
// Optimization - fold sibling query
- $aAliasTranslation = array();
+ $aAliasTranslation = [];
$this->MergeWith_InNamespace($oRemoteFilter, $this->m_aClasses, $aAliasTranslation);
unset($oFilter->m_aPointingTo[$sForeignExtKeyAttCode][$iOperatorCode]);
$this->m_oSearchCondition = $this->m_oSearchCondition->Translate($aAliasTranslation, false, false);
@@ -1063,20 +973,16 @@ class DBObjectSearch extends DBSearch
$oReceivingFilter = $this->GetNode($this->GetClassAlias());
$bMerged = false;
- if (ENABLE_OPT && isset($oReceivingFilter->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode][$iOperatorCode]))
- {
- foreach ($oReceivingFilter->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode][$iOperatorCode] as $oExisting)
- {
- if ($oExisting->GetClass() == $oFilter->GetClass())
- {
+ if (ENABLE_OPT && isset($oReceivingFilter->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode][$iOperatorCode])) {
+ foreach ($oReceivingFilter->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode][$iOperatorCode] as $oExisting) {
+ if ($oExisting->GetClass() == $oFilter->GetClass()) {
$oExisting->MergeWith_InNamespace($oFilter, $aClassAliases, $aAliasTranslation);
$bMerged = true;
break;
}
}
}
- if (!$bMerged)
- {
+ if (!$bMerged) {
$oFilter->AddToNamespace($aClassAliases, $aAliasTranslation);
$oReceivingFilter->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode][$iOperatorCode][] = $oFilter;
}
@@ -1144,23 +1050,18 @@ class DBObjectSearch extends DBSearch
*/
private static function FilterSubClass(DBObjectSearch &$oSearch, $sClassAlias, DBSearch $oFilter, $aRootClasses)
{
- if (($oSearch->GetFirstJoinedClassAlias() == $sClassAlias))
- {
+ if (($oSearch->GetFirstJoinedClassAlias() == $sClassAlias)) {
$oSearch = $oSearch->IntersectSubClass($oFilter, $aRootClasses);
return $oSearch->GetCriteria();
}
/** @var Expression $oFilterExpression */
// Search in the filter tree where is the correct DBSearch
- foreach ($oSearch->m_aPointingTo as $sExtKey => $aPointingTo)
- {
- foreach ($aPointingTo as $iOperatorCode => $aFilters)
- {
- foreach ($aFilters as $index => $oExtFilter)
- {
+ foreach ($oSearch->m_aPointingTo as $sExtKey => $aPointingTo) {
+ foreach ($aPointingTo as $iOperatorCode => $aFilters) {
+ foreach ($aFilters as $index => $oExtFilter) {
$oFilterExpression = self::FilterSubClass($oExtFilter, $sClassAlias, $oFilter, $aRootClasses);
- if ($oFilterExpression !== false)
- {
+ if ($oFilterExpression !== false) {
$oSearch->m_aPointingTo[$sExtKey][$iOperatorCode][$index] = $oExtFilter;
return $oFilterExpression;
}
@@ -1168,17 +1069,12 @@ class DBObjectSearch extends DBSearch
}
}
- foreach($oSearch->m_aReferencedBy as $sForeignClass => $aReferences)
- {
- foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
- {
- foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
- {
- foreach ($aFilters as $index => $oForeignFilter)
- {
+ foreach ($oSearch->m_aReferencedBy as $sForeignClass => $aReferences) {
+ foreach ($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) {
+ foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) {
+ foreach ($aFilters as $index => $oForeignFilter) {
$oFilterExpression = self::FilterSubClass($oForeignFilter, $sClassAlias, $oFilter, $aRootClasses);
- if ($oFilterExpression !== false)
- {
+ if ($oFilterExpression !== false) {
$oSearch->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode][$iOperatorCode][$index] = $oForeignFilter;
return $oFilterExpression;
}
@@ -1196,24 +1092,19 @@ class DBObjectSearch extends DBSearch
*/
public function Intersect(DBSearch $oFilter)
{
- if ($oFilter instanceof DBUnionSearch)
- {
+ if ($oFilter instanceof DBUnionSearch) {
// Develop!
$aFilters = $oFilter->GetSearches();
- }
- else
- {
- $aFilters = array($oFilter);
+ } else {
+ $aFilters = [$oFilter];
}
- $aSearches = array();
- foreach ($aFilters as $oRightFilter)
- {
+ $aSearches = [];
+ foreach ($aFilters as $oRightFilter) {
$aSearches[] = $this->IntersectSubClass($oRightFilter, $this->m_aClasses);
}
- if (count($aSearches) == 1)
- {
+ if (count($aSearches) == 1) {
// return a DBObjectSearch
return $aSearches[0];
}
@@ -1257,7 +1148,7 @@ class DBObjectSearch extends DBSearch
}
}
- $aAliasTranslation = array();
+ $aAliasTranslation = [];
$oLeftFilter->RenameNestedQueriesAliasesInNameSpace($aRootClasses, $aAliasTranslation);
$oLeftFilter->MergeWith_InNamespace($oRightFilter, $aRootClasses, $aAliasTranslation);
$oRightFilter->RenameNestedQueriesAliasesInNameSpace($aRootClasses, $aAliasTranslation);
@@ -1275,32 +1166,24 @@ class DBObjectSearch extends DBSearch
*/
protected function MergeWith_InNamespace($oFilter, &$aClassAliases, &$aAliasTranslation)
{
- if ($this->GetFirstJoinedClass() != $oFilter->GetClass())
- {
+ if ($this->GetFirstJoinedClass() != $oFilter->GetClass()) {
throw new CoreException("Attempting to merge a filter of class '{$this->GetFirstJoinedClass()}' with a filter of class '{$oFilter->GetClass()}'");
}
// Translate search condition into our aliasing scheme
$aAliasTranslation[$oFilter->GetClassAlias()]['*'] = $this->GetFirstJoinedClassAlias();
- foreach($oFilter->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo)
- {
- foreach($aPointingTo as $iOperatorCode => $aFilter)
- {
- foreach($aFilter as $oExtFilter)
- {
+ foreach ($oFilter->m_aPointingTo as $sExtKeyAttCode => $aPointingTo) {
+ foreach ($aPointingTo as $iOperatorCode => $aFilter) {
+ foreach ($aFilter as $oExtFilter) {
$this->AddCondition_PointingTo_InNamespace($oExtFilter, $sExtKeyAttCode, $aClassAliases, $aAliasTranslation, $iOperatorCode);
}
}
}
- foreach($oFilter->m_aReferencedBy as $sForeignClass => $aReferences)
- {
- foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
- {
- foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
- {
- foreach ($aFilters as $oForeignFilter)
- {
+ foreach ($oFilter->m_aReferencedBy as $sForeignClass => $aReferences) {
+ foreach ($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) {
+ foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) {
+ foreach ($aFilters as $oForeignFilter) {
$this->AddCondition_ReferencedBy_InNamespace($oForeignFilter, $sForeignExtKeyAttCode, $aClassAliases, $aAliasTranslation, $iOperatorCode);
}
}
@@ -1308,15 +1191,22 @@ class DBObjectSearch extends DBSearch
}
}
- public function GetCriteria() {return $this->m_oSearchCondition;}
- public function GetCriteria_FullText() {throw new Exception("Removed GetCriteria_FullText");}
+ public function GetCriteria()
+ {
+ return $this->m_oSearchCondition;
+ }
+ public function GetCriteria_FullText()
+ {
+ throw new Exception("Removed GetCriteria_FullText");
+ }
public function GetCriteria_PointingTo($sKeyAttCode = "")
{
- if (empty($sKeyAttCode))
- {
+ if (empty($sKeyAttCode)) {
return $this->m_aPointingTo;
}
- if (!array_key_exists($sKeyAttCode, $this->m_aPointingTo)) return array();
+ if (!array_key_exists($sKeyAttCode, $this->m_aPointingTo)) {
+ return [];
+ }
return $this->m_aPointingTo[$sKeyAttCode];
}
@@ -1362,10 +1252,8 @@ class DBObjectSearch extends DBSearch
*/
public function AddInternalParam($sKey, $value, $bDoNotOverride = false)
{
- if ($bDoNotOverride)
- {
- if (array_key_exists($sKey, $this->m_aParams))
- {
+ if ($bDoNotOverride) {
+ if (array_key_exists($sKey, $this->m_aParams)) {
throw new CoreUnexpectedValue("The key $sKey already exists with value : ".$this->m_aParams[$sKey]);
}
}
@@ -1375,38 +1263,29 @@ class DBObjectSearch extends DBSearch
public function GetQueryParams()
{
- $aParams = array();
+ $aParams = [];
$this->m_oSearchCondition->RenderExpression(false, $aParams, true);
- $aRet = array();
+ $aRet = [];
// Make the list of acceptable arguments... could be factorized with run_query, into oSearch->GetQueryParams()
- $aNakedMagicArguments = array();
- foreach (MetaModel::PrepareQueryArguments(array(),array(), $this->GetExpectedArguments()) as $sArgName => $value)
- {
+ $aNakedMagicArguments = [];
+ foreach (MetaModel::PrepareQueryArguments([], [], $this->GetExpectedArguments()) as $sArgName => $value) {
$iPos = strpos($sArgName, '->object()');
- if ($iPos === false)
- {
+ if ($iPos === false) {
$aNakedMagicArguments[$sArgName] = $value;
- }
- else
- {
+ } else {
$aNakedMagicArguments[substr($sArgName, 0, $iPos)] = true;
}
}
- foreach ($aParams as $sParam => $foo)
- {
+ foreach ($aParams as $sParam => $foo) {
$iPos = strpos($sParam, '->');
- if ($iPos === false)
- {
+ if ($iPos === false) {
$sRefName = $sParam;
- }
- else
- {
+ } else {
$sRefName = substr($sParam, 0, $iPos);
}
- if (!array_key_exists($sRefName, $aNakedMagicArguments))
- {
+ if (!array_key_exists($sRefName, $aNakedMagicArguments)) {
$aRet[$sParam] = $foo;
}
}
@@ -1428,44 +1307,36 @@ class DBObjectSearch extends DBSearch
{
$this->m_oSearchCondition->ApplyParameters(array_merge($this->m_aParams, $aArgs));
}
-
+
public function ToOQL($bDevelopParams = false, $aContextParams = null, $bWithAllowAllFlag = false)
{
// Currently unused, but could be useful later
$bRetrofitParams = false;
- if ($bDevelopParams)
- {
- if (is_null($aContextParams))
- {
+ if ($bDevelopParams) {
+ if (is_null($aContextParams)) {
$aParams = array_merge($this->m_aParams);
- }
- else
- {
+ } else {
$aParams = array_merge($aContextParams, $this->m_aParams);
}
- $aParams = MetaModel::PrepareQueryArguments($aParams,array(), $this->GetExpectedArguments());
- }
- else
- {
+ $aParams = MetaModel::PrepareQueryArguments($aParams, [], $this->GetExpectedArguments());
+ } else {
// Leave it as is, the rendering will be made with parameters in clear
$aParams = null;
}
- $aSelectedAliases = array();
- foreach ($this->m_aSelectedClasses as $sAlias => $sClass)
- {
- $aSelectedAliases[] = '`' . $sAlias . '`';
+ $aSelectedAliases = [];
+ foreach ($this->m_aSelectedClasses as $sAlias => $sClass) {
+ $aSelectedAliases[] = '`'.$sAlias.'`';
}
$sSelectedClasses = implode(', ', $aSelectedAliases);
$sRes = 'SELECT '.$sSelectedClasses.' FROM';
- $sRes .= ' ' . $this->GetFirstJoinedClass() . ' AS `' . $this->GetFirstJoinedClassAlias() . '`';
+ $sRes .= ' '.$this->GetFirstJoinedClass().' AS `'.$this->GetFirstJoinedClassAlias().'`';
$sRes .= $this->ToOQL_Joins();
$sRes .= " WHERE ".$this->m_oSearchCondition->RenderExpression(false, $aParams, $bRetrofitParams);
- if ($bWithAllowAllFlag && $this->m_bAllowAllData)
- {
+ if ($bWithAllowAllFlag && $this->m_bAllowAllData) {
$sRes .= " ALLOW ALL DATA";
}
return $sRes;
@@ -1473,8 +1344,7 @@ class DBObjectSearch extends DBSearch
protected function OperatorCodeToOQL($iOperatorCode)
{
- switch($iOperatorCode)
- {
+ switch ($iOperatorCode) {
case TREE_OPERATOR_EQUALS:
$sOperator = ' = ';
break;
@@ -1518,28 +1388,21 @@ class DBObjectSearch extends DBSearch
protected function ToOQL_Joins()
{
$sRes = '';
- foreach($this->m_aPointingTo as $sExtKey => $aPointingTo)
- {
- foreach($aPointingTo as $iOperatorCode => $aFilter)
- {
+ foreach ($this->m_aPointingTo as $sExtKey => $aPointingTo) {
+ foreach ($aPointingTo as $iOperatorCode => $aFilter) {
$sOperator = $this->OperatorCodeToOQL($iOperatorCode);
- foreach($aFilter as $oFilter)
- {
- $sRes .= ' JOIN ' . $oFilter->GetFirstJoinedClass() . ' AS `' . $oFilter->GetFirstJoinedClassAlias() . '` ON `' . $this->GetFirstJoinedClassAlias() . '`.' . $sExtKey . $sOperator . '`' . $oFilter->GetFirstJoinedClassAlias() . '`.id';
- $sRes .= $oFilter->ToOQL_Joins();
+ foreach ($aFilter as $oFilter) {
+ $sRes .= ' JOIN '.$oFilter->GetFirstJoinedClass().' AS `'.$oFilter->GetFirstJoinedClassAlias().'` ON `'.$this->GetFirstJoinedClassAlias().'`.'.$sExtKey.$sOperator.'`'.$oFilter->GetFirstJoinedClassAlias().'`.id';
+ $sRes .= $oFilter->ToOQL_Joins();
}
}
}
- foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences)
- {
- foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
- {
- foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
- {
+ foreach ($this->m_aReferencedBy as $sForeignClass => $aReferences) {
+ foreach ($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) {
+ foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) {
$sOperator = $this->OperatorCodeToOQL($iOperatorCode);
- foreach ($aFilters as $oForeignFilter)
- {
- $sRes .= ' JOIN ' . $oForeignFilter->GetFirstJoinedClass() . ' AS `' . $oForeignFilter->GetFirstJoinedClassAlias() . '` ON `' . $oForeignFilter->GetFirstJoinedClassAlias() . '`.' . $sForeignExtKeyAttCode . $sOperator . '`' . $this->GetFirstJoinedClassAlias() . '`.id';
+ foreach ($aFilters as $oForeignFilter) {
+ $sRes .= ' JOIN '.$oForeignFilter->GetFirstJoinedClass().' AS `'.$oForeignFilter->GetFirstJoinedClassAlias().'` ON `'.$oForeignFilter->GetFirstJoinedClassAlias().'`.'.$sForeignExtKeyAttCode.$sOperator.'`'.$this->GetFirstJoinedClassAlias().'`.id';
$sRes .= $oForeignFilter->ToOQL_Joins();
}
}
@@ -1550,81 +1413,55 @@ class DBObjectSearch extends DBSearch
protected function OQLExpressionToCondition($sQuery, $oExpression, $aClassAliases)
{
- if ($oExpression instanceof BinaryOqlExpression)
- {
+ if ($oExpression instanceof BinaryOqlExpression) {
$sOperator = $oExpression->GetOperator();
$oLeft = $this->OQLExpressionToCondition($sQuery, $oExpression->GetLeftExpr(), $aClassAliases);
$oRight = $this->OQLExpressionToCondition($sQuery, $oExpression->GetRightExpr(), $aClassAliases);
return new BinaryExpression($oLeft, $sOperator, $oRight);
- }
- elseif ($oExpression instanceof MatchOqlExpression)
- {
+ } elseif ($oExpression instanceof MatchOqlExpression) {
$oLeft = $this->OQLExpressionToCondition($sQuery, $oExpression->GetLeftExpr(), $aClassAliases);
$oRight = $this->OQLExpressionToCondition($sQuery, $oExpression->GetRightExpr(), $aClassAliases);
return new MatchExpression($oLeft, $oRight);
- }
- elseif ($oExpression instanceof FieldOqlExpression)
- {
+ } elseif ($oExpression instanceof FieldOqlExpression) {
$sClassAlias = $oExpression->GetParent();
$sFltCode = $oExpression->GetName();
- if (empty($sClassAlias))
- {
+ if (empty($sClassAlias)) {
// Need to find the right alias
// Build an array of field => array of aliases
- $aFieldClasses = array();
- foreach($aClassAliases as $sAlias => $sReal)
- {
- foreach(MetaModel::GetFiltersList($sReal) as $sAnFltCode)
- {
+ $aFieldClasses = [];
+ foreach ($aClassAliases as $sAlias => $sReal) {
+ foreach (MetaModel::GetFiltersList($sReal) as $sAnFltCode) {
$aFieldClasses[$sAnFltCode][] = $sAlias;
}
}
$sClassAlias = $aFieldClasses[$sFltCode][0];
}
return new FieldExpression($sFltCode, $sClassAlias);
- }
- elseif ($oExpression instanceof VariableOqlExpression)
- {
+ } elseif ($oExpression instanceof VariableOqlExpression) {
return new VariableExpression($oExpression->GetName());
- }
- elseif ($oExpression instanceof TrueOqlExpression)
- {
- return new TrueExpression;
- }
- elseif ($oExpression instanceof ScalarOqlExpression)
- {
+ } elseif ($oExpression instanceof TrueOqlExpression) {
+ return new TrueExpression();
+ } elseif ($oExpression instanceof ScalarOqlExpression) {
return new ScalarExpression($oExpression->GetValue());
- }
- elseif ($oExpression instanceof ListOqlExpression)
- {
- $aItems = array();
- foreach ($oExpression->GetItems() as $oItemExpression)
- {
+ } elseif ($oExpression instanceof ListOqlExpression) {
+ $aItems = [];
+ foreach ($oExpression->GetItems() as $oItemExpression) {
$aItems[] = $this->OQLExpressionToCondition($sQuery, $oItemExpression, $aClassAliases);
}
return new ListExpression($aItems);
- }
- elseif ($oExpression instanceof FunctionOqlExpression)
- {
- $aArgs = array();
- foreach ($oExpression->GetArgs() as $oArgExpression)
- {
+ } elseif ($oExpression instanceof FunctionOqlExpression) {
+ $aArgs = [];
+ foreach ($oExpression->GetArgs() as $oArgExpression) {
$aArgs[] = $this->OQLExpressionToCondition($sQuery, $oArgExpression, $aClassAliases);
}
return new FunctionExpression($oExpression->GetVerb(), $aArgs);
- }
- elseif ($oExpression instanceof IntervalOqlExpression)
- {
+ } elseif ($oExpression instanceof IntervalOqlExpression) {
return new IntervalExpression($oExpression->GetValue(), $oExpression->GetUnit());
- }
- elseif ($oExpression instanceof NestedQueryOqlExpression)
- {
+ } elseif ($oExpression instanceof NestedQueryOqlExpression) {
return NestedQueryExpression::FromOQLObjectQuery($oExpression->GetOQLObjectQuery());
- }
- else
- {
- throw new CoreException('Unknown expression type', array('class'=>get_class($oExpression), 'query'=>$sQuery));
+ } else {
+ throw new CoreException('Unknown expression type', ['class' => get_class($oExpression), 'query' => $sQuery]);
}
}
@@ -1634,14 +1471,13 @@ class DBObjectSearch extends DBSearch
*/
public function ToJSON()
{
- $aRet = array('selects' => array(), 'joins' => array(), 'where' => array());
+ $aRet = ['selects' => [], 'joins' => [], 'where' => []];
$aParams = array_merge($this->m_aParams);
- $aParams = MetaModel::PrepareQueryArguments($aParams, array(), $this->GetExpectedArguments());
+ $aParams = MetaModel::PrepareQueryArguments($aParams, [], $this->GetExpectedArguments());
- foreach ($this->m_aSelectedClasses as $sAlias => $sClass)
- {
- $aRet['selects'][] = array('class' => $sClass, 'alias' => $sAlias);
+ foreach ($this->m_aSelectedClasses as $sAlias => $sClass) {
+ $aRet['selects'][] = ['class' => $sClass, 'alias' => $sAlias];
}
$this->JoinsToJSON($aRet);
@@ -1659,42 +1495,35 @@ class DBObjectSearch extends DBSearch
*/
protected function JoinsToJSON(&$aRet)
{
- foreach($this->m_aPointingTo as $sExtKey => $aPointingTo)
- {
- foreach($aPointingTo as $iOperatorCode => $aFilter)
- {
+ foreach ($this->m_aPointingTo as $sExtKey => $aPointingTo) {
+ foreach ($aPointingTo as $iOperatorCode => $aFilter) {
$sOperator = $this->OperatorCodeToOQL($iOperatorCode);
- foreach($aFilter as $oFilter)
- {
- $aRet['joins'][] = array(
+ foreach ($aFilter as $oFilter) {
+ $aRet['joins'][] = [
'src' => $this->GetFirstJoinedClass(),
'src_alias' => $this->GetFirstJoinedClassAlias(),
'target' => $oFilter->GetFirstJoinedClass(),
'target_alias' => $oFilter->GetFirstJoinedClassAlias(),
'foreign_key' => $sExtKey,
'operator' => $sOperator,
- );
+ ];
$oFilter->JoinsToJSON($aRet);
}
}
}
- foreach($this->m_aReferencedBy as $aReferences)
- {
- foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
- {
- foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
- {
+ foreach ($this->m_aReferencedBy as $aReferences) {
+ foreach ($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) {
+ foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) {
$sOperator = $this->OperatorCodeToOQL($iOperatorCode);
- foreach ($aFilters as $oForeignFilter)
- {
- $aRet['joins'][] = array(
+ foreach ($aFilters as $oForeignFilter) {
+ $aRet['joins'][] = [
'src' => $oForeignFilter->GetFirstJoinedClass(),
'src_alias' => $oForeignFilter->GetFirstJoinedClassAlias(),
'target' => $this->GetFirstJoinedClass(),
'target_alias' => $this->GetFirstJoinedClassAlias(),
'foreign_key' => $sForeignExtKeyAttCode,
'operator' => $sOperator,
- );
+ ];
$oForeignFilter->JoinsToJSON($aRet);
}
}
@@ -1715,18 +1544,15 @@ class DBObjectSearch extends DBSearch
$sClass = $oOqlQuery->GetClass($oModelReflection);
$sClassAlias = $oOqlQuery->GetClassAlias();
- $aAliases = array($sClassAlias => $sClass);
+ $aAliases = [$sClassAlias => $sClass];
// Note: the condition must be built here, it may be altered later on when optimizing some joins
$oConditionTree = $oOqlQuery->GetCondition();
- if ($oConditionTree instanceof Expression)
- {
- $aRawAliases = array($sClassAlias => $sClass);
+ if ($oConditionTree instanceof Expression) {
+ $aRawAliases = [$sClassAlias => $sClass];
$aJoinSpecs = $oOqlQuery->GetJoins();
- if (is_array($aJoinSpecs))
- {
- foreach ($aJoinSpecs as $oJoinSpec)
- {
+ if (is_array($aJoinSpecs)) {
+ foreach ($aJoinSpecs as $oJoinSpec) {
$aRawAliases[$oJoinSpec->GetClassAlias()] = $oJoinSpec->GetClass();
}
}
@@ -1736,18 +1562,15 @@ class DBObjectSearch extends DBSearch
// Maintain an array of filters, because the flat list is in fact referring to a tree
// And this will be an easy way to dispatch the conditions
// $this will be referenced by the other filters, or the other way around...
- $aJoinItems = array($sClassAlias => $this);
+ $aJoinItems = [$sClassAlias => $this];
$aJoinSpecs = $oOqlQuery->GetJoins();
- if (is_array($aJoinSpecs))
- {
- $aAliasTranslation = array();
- foreach ($aJoinSpecs as $oJoinSpec)
- {
+ if (is_array($aJoinSpecs)) {
+ $aAliasTranslation = [];
+ foreach ($aJoinSpecs as $oJoinSpec) {
$sJoinClass = $oJoinSpec->GetClass();
$sJoinClassAlias = $oJoinSpec->GetClassAlias();
- if (isset($aAliasTranslation[$sJoinClassAlias]['*']))
- {
+ if (isset($aAliasTranslation[$sJoinClassAlias]['*'])) {
$sJoinClassAlias = $aAliasTranslation[$sJoinClassAlias]['*'];
}
@@ -1755,16 +1578,14 @@ class DBObjectSearch extends DBSearch
// normalization should take care of this
$oLeftField = $oJoinSpec->GetLeftField();
$sFromClass = $oLeftField->GetParent();
- if (isset($aAliasTranslation[$sFromClass]['*']))
- {
+ if (isset($aAliasTranslation[$sFromClass]['*'])) {
$sFromClass = $aAliasTranslation[$sFromClass]['*'];
}
$sExtKeyAttCode = $oLeftField->GetName();
$oRightField = $oJoinSpec->GetRightField();
$sToClass = $oRightField->GetParent();
- if (isset($aAliasTranslation[$sToClass]['*']))
- {
+ if (isset($aAliasTranslation[$sToClass]['*'])) {
$sToClass = $aAliasTranslation[$sToClass]['*'];
}
@@ -1772,8 +1593,7 @@ class DBObjectSearch extends DBSearch
$aJoinItems[$sJoinClassAlias] = new DBObjectSearch($sJoinClass, $sJoinClassAlias);
$sOperator = $oJoinSpec->GetOperator();
- switch($sOperator)
- {
+ switch ($sOperator) {
case '=':
default:
$iOperatorCode = TREE_OPERATOR_EQUALS;
@@ -1804,14 +1624,11 @@ class DBObjectSearch extends DBSearch
break;
}
- if ($sFromClass == $sJoinClassAlias)
- {
+ if ($sFromClass == $sJoinClassAlias) {
$oReceiver = $aJoinItems[$sToClass];
$oNewComer = $aJoinItems[$sFromClass];
$oReceiver->AddCondition_ReferencedBy_InNameSpace($oNewComer, $sExtKeyAttCode, $oReceiver->m_aClasses, $aAliasTranslation, $iOperatorCode);
- }
- else
- {
+ } else {
$oReceiver = $aJoinItems[$sFromClass];
$oNewComer = $aJoinItems[$sToClass];
$oReceiver->AddCondition_PointingTo_InNameSpace($oNewComer, $sExtKeyAttCode, $oReceiver->m_aClasses, $aAliasTranslation, $iOperatorCode);
@@ -1821,12 +1638,10 @@ class DBObjectSearch extends DBSearch
}
// Check and prepare the select information
- $this->m_aSelectedClasses = array();
- foreach ($oOqlQuery->GetSelectedClasses() as $oClassDetails)
- {
+ $this->m_aSelectedClasses = [];
+ foreach ($oOqlQuery->GetSelectedClasses() as $oClassDetails) {
$sClassToSelect = $oClassDetails->GetValue();
- if (!array_key_exists($sClassToSelect, $aAliases))
- {
+ if (!array_key_exists($sClassToSelect, $aAliases)) {
throw new CoreException("$sClassToSelect is not a valid alias");
}
$this->m_aSelectedClasses[$sClassToSelect] = $aAliases[$sClassToSelect];
@@ -1840,7 +1655,7 @@ class DBObjectSearch extends DBSearch
//
////////////////////////////////////////////////////////////////////////////
- public function MakeDeleteQuery($aArgs = array())
+ public function MakeDeleteQuery($aArgs = [])
{
$oSQLObjectQueryBuilder = new SQLObjectQueryBuilder($this);
$oSQLQuery = $oSQLObjectQueryBuilder->MakeSQLObjectDeleteQuery();
@@ -1856,7 +1671,7 @@ class DBObjectSearch extends DBSearch
* @return string
* @throws \CoreException
*/
- public function MakeUpdateQuery($aValues, $aArgs = array())
+ public function MakeUpdateQuery($aValues, $aArgs = [])
{
$oSQLObjectQueryBuilder = new SQLObjectQueryBuilder($this);
$oSQLQuery = $oSQLObjectQueryBuilder->MakeSQLObjectUpdateQuery($aValues);
@@ -1875,7 +1690,7 @@ class DBObjectSearch extends DBSearch
* @return string
* @throws \CoreException
*/
- public function MakeInsertQuery($aValues, $aArgs = array())
+ public function MakeInsertQuery($aValues, $aArgs = [])
{
$oSQLObjectQueryBuilder = new SQLObjectQueryBuilder($this);
$oSQLQuery = $oSQLObjectQueryBuilder->MakeSQLObjectUpdateQuery($aValues);
@@ -1920,14 +1735,12 @@ class DBObjectSearch extends DBSearch
// Create a unique cache id
//
- $aContextData = array();
+ $aContextData = [];
$bCanCache = true;
- if (self::$m_bQueryCacheEnabled || self::$m_bTraceQueries)
- {
- if (isset($_SERVER['REQUEST_URI']))
- {
+ if (self::$m_bQueryCacheEnabled || self::$m_bTraceQueries) {
+ if (isset($_SERVER['REQUEST_URI'])) {
$aContextData['sRequestUri'] = $_SERVER['REQUEST_URI'];
- } else if (isset($_SERVER['SCRIPT_NAME'])) {
+ } elseif (isset($_SERVER['SCRIPT_NAME'])) {
$aContextData['sRequestUri'] = $_SERVER['SCRIPT_NAME'];
} else {
$aContextData['sRequestUri'] = '';
@@ -1980,19 +1793,15 @@ class DBObjectSearch extends DBSearch
$aContextData['bIsArchiveMode'] = $bIsArchiveMode;
$aContextData['bShowObsoleteData'] = $bShowObsoleteData;
$sOqlId = md5($sRawId);
- }
- else
- {
+ } else {
$sOqlQuery = "SELECTING... ".$oSearch->GetClass();
$sOqlId = "query id ? n/a";
}
-
// Query caching
//
$sOqlAPCCacheId = null;
- if (self::$m_bQueryCacheEnabled && $bCanCache)
- {
+ if (self::$m_bQueryCacheEnabled && $bCanCache) {
// Warning: using directly the query string as the key to the hash array can FAIL if the string
// is long and the differences are only near the end... so it's safer (but not bullet proof?)
// to use a hash (like md5) of the string as the key !
@@ -2003,15 +1812,12 @@ class DBObjectSearch extends DBSearch
// SELECT SLT JOIN lnkSLTToSLA AS L1 ON L1.slt_id=SLT.id JOIN SLA ON L1.sla_id = SLA.id JOIN lnkContractToSLA AS L2 ON L2.sla_id = SLA.id JOIN CustomerContract ON L2.contract_id = CustomerContract.id WHERE SLT.ticket_priority = 1 AND SLA.service_id = 3 AND SLT.metric = 'TTR' AND CustomerContract.customer_id = 2
// the only difference is R instead or O at position 285 (TTR instead of TTO)...
//
- if (array_key_exists($sOqlId, self::$m_aQueryStructCache))
- {
+ if (array_key_exists($sOqlId, self::$m_aQueryStructCache)) {
// hit!
$oSQLQuery = unserialize(serialize(self::$m_aQueryStructCache[$sOqlId]));
// Note: cloning is not enough because the subtree is made of objects
- }
- elseif (self::$m_bUseAPCCache)
- {
+ } elseif (self::$m_bUseAPCCache) {
// Note: For versions of APC older than 3.0.17, fetch() accepts only one parameter
//
$sOqlAPCCacheId = 'itop-'.MetaModel::GetEnvironmentId().'-query-cache-'.$sOqlId;
@@ -2019,25 +1825,21 @@ class DBObjectSearch extends DBSearch
$result = apc_fetch($sOqlAPCCacheId);
$oKPI->ComputeStats('Query APC (fetch)', $sOqlQuery);
- if (is_object($result))
- {
+ if (is_object($result)) {
$oSQLQuery = $result;
self::$m_aQueryStructCache[$sOqlId] = $oSQLQuery;
}
}
}
- if (!isset($oSQLQuery))
- {
+ if (!isset($oSQLQuery)) {
$oKPI = new ExecutionKPI();
$oSQLObjectQueryBuilder = new SQLObjectQueryBuilder($oSearch);
$oSQLQuery = $oSQLObjectQueryBuilder->BuildSQLQueryStruct($aAttToLoad, $bGetCount, $aModifierProperties, $aGroupByExpr, $aSelectedClasses, $aSelectExpr);
$oKPI->ComputeStats('BuildSQLQueryStruct', $sOqlQuery);
- if (self::$m_bQueryCacheEnabled)
- {
- if ($bCanCache && self::$m_bUseAPCCache)
- {
+ if (self::$m_bQueryCacheEnabled) {
+ if ($bCanCache && self::$m_bUseAPCCache) {
$oSQLQuery->m_aContextData = $aContextData;
$oKPI = new ExecutionKPI();
apc_store($sOqlAPCCacheId, $oSQLQuery, self::$m_iQueryCacheTTL);
@@ -2058,28 +1860,28 @@ class DBObjectSearch extends DBSearch
* @return \FunctionExpression|mixed|null
* @throws \CoreException
*/
- static public function GetPolymorphicExpression($sClass, $sAttCode)
+ public static function GetPolymorphicExpression($sClass, $sAttCode)
{
$oExpression = ExpressionCache::GetCachedExpression($sClass, $sAttCode);
- if (!empty($oExpression))
- {
+ if (!empty($oExpression)) {
return $oExpression;
}
// 1st step - get all of the required expressions (instantiable classes)
// and group them using their OQL representation
//
- $aExpressions = array(); // signature => array('expression' => oExp, 'classes' => array of classes)
- foreach (MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL) as $sSubClass)
- {
- if (($sSubClass != $sClass) && MetaModel::IsAbstract($sSubClass)) continue;
+ $aExpressions = []; // signature => array('expression' => oExp, 'classes' => array of classes)
+ foreach (MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL) as $sSubClass) {
+ if (($sSubClass != $sClass) && MetaModel::IsAbstract($sSubClass)) {
+ continue;
+ }
$oAttDef = MetaModel::GetAttributeDef($sSubClass, $sAttCode);
$oSubClassExp = $oAttDef->GetOQLExpression($sSubClass);
// 3rd step - position the attributes in the hierarchy of classes
//
- $oSubClassExp->Browse(function($oNode) use ($sSubClass) {
+ $oSubClassExp->Browse(function ($oNode) use ($sSubClass) {
if ($oNode instanceof FieldExpression) {
$sAttCode = $oNode->GetName();
$oAttDef = MetaModel::GetAttributeDef($sSubClass, $sAttCode);
@@ -2096,44 +1898,37 @@ class DBObjectSearch extends DBSearch
$sSignature = $oSubClassExp->RenderExpression();
if (!array_key_exists($sSignature, $aExpressions)) {
- $aExpressions[$sSignature] = array(
+ $aExpressions[$sSignature] = [
'expression' => $oSubClassExp,
- 'classes' => array(),
- );
+ 'classes' => [],
+ ];
}
$aExpressions[$sSignature]['classes'][] = $sSubClass;
}
// 2nd step - build the final name expression depending on the finalclass
//
- if (count($aExpressions) == 1)
- {
+ if (count($aExpressions) == 1) {
$aExpData = reset($aExpressions);
$oExpression = $aExpData['expression'];
- }
- else
- {
+ } else {
$oExpression = null;
- foreach ($aExpressions as $sSignature => $aExpData)
- {
+ foreach ($aExpressions as $sSignature => $aExpData) {
$oClassListExpr = ListExpression::FromScalars($aExpData['classes']);
$oClassExpr = new FieldExpression('finalclass', $sClass);
$oClassInList = new BinaryExpression($oClassExpr, 'IN', $oClassListExpr);
- if (is_null($oExpression))
- {
+ if (is_null($oExpression)) {
$oExpression = $aExpData['expression'];
- }
- else
- {
- $oExpression = new FunctionExpression('IF', array($oClassInList, $aExpData['expression'], $oExpression));
+ } else {
+ $oExpression = new FunctionExpression('IF', [$oClassInList, $aExpData['expression'], $oExpression]);
}
}
}
return $oExpression;
}
- function GetExpectedArguments(): array
+ public function GetExpectedArguments(): array
{
return $this->GetCriteria()->ListParameters();
}
diff --git a/core/dbsearch.class.php b/core/dbsearch.class.php
index 3aed95306..be26a5628 100644
--- a/core/dbsearch.class.php
+++ b/core/dbsearch.class.php
@@ -1,4 +1,5 @@
Init();
}
- /**
- * called by the constructor
- * @internal Set the obsolete and archive modes to the default ones
- */
+ /**
+ * called by the constructor
+ * @internal Set the obsolete and archive modes to the default ones
+ */
protected function Init()
{
$this->m_bArchiveMode = utils::IsArchiveMode();
@@ -86,104 +87,104 @@ abstract class DBSearch
$this->m_bArchiveMode = $bEnable;
}
- /**
- * @internal
- * @return bool
- */
+ /**
+ * @internal
+ * @return bool
+ */
public function GetArchiveMode()
{
return $this->m_bArchiveMode;
}
- /**
- * Should the obsolete data be fetched
- *
- * @internal
- * @param $bShow
- */
+ /**
+ * Should the obsolete data be fetched
+ *
+ * @internal
+ * @param $bShow
+ */
public function SetShowObsoleteData($bShow)
{
$this->m_bShowObsoleteData = $bShow;
}
- /**
- * @internal
- * @return bool
- */
+ /**
+ * @internal
+ * @return bool
+ */
public function GetShowObsoleteData()
{
- if ($this->m_bArchiveMode || $this->IsAllDataAllowed())
- {
+ if ($this->m_bArchiveMode || $this->IsAllDataAllowed()) {
// Enable obsolete data too!
$bRet = true;
- }
- else
- {
+ } else {
$bRet = $this->m_bShowObsoleteData;
}
return $bRet;
}
- /**
- * @internal
- */
- public function NoContextParameters() {$this->m_bNoContextParameters = true;}
+ /**
+ * @internal
+ */
+ public function NoContextParameters()
+ {
+ $this->m_bNoContextParameters = true;
+ }
- /**
- * @internal
- * @return bool
- */
- public function HasContextParameters() {return $this->m_bNoContextParameters;}
+ /**
+ * @internal
+ * @return bool
+ */
+ public function HasContextParameters()
+ {
+ return $this->m_bNoContextParameters;
+ }
- /**
- * @internal
- *
- * @param $sPluginClass
- * @param $sProperty
- * @param $value
- */
+ /**
+ * @internal
+ *
+ * @param $sPluginClass
+ * @param $sProperty
+ * @param $value
+ */
public function SetModifierProperty($sPluginClass, $sProperty, $value)
{
$this->m_aModifierProperties[$sPluginClass][$sProperty] = $value;
}
- /**
- * @internal
- *
- * @param $sPluginClass
- *
- * @return array|mixed
- */
+ /**
+ * @internal
+ *
+ * @param $sPluginClass
+ *
+ * @return array|mixed
+ */
public function GetModifierProperties($sPluginClass)
{
- if (array_key_exists($sPluginClass, $this->m_aModifierProperties))
- {
+ if (array_key_exists($sPluginClass, $this->m_aModifierProperties)) {
return $this->m_aModifierProperties[$sPluginClass];
- }
- else
- {
- return array();
+ } else {
+ return [];
}
}
- /**
- * @internal
- * @param $sAlias
- *
- * @return mixed
- */
+ /**
+ * @internal
+ * @param $sAlias
+ *
+ * @return mixed
+ */
abstract public function GetClassName($sAlias);
- /**
- * @internal
- * @return mixed
- */
+ /**
+ * @internal
+ * @return mixed
+ */
abstract public function GetClass();
- /**
- * @internal
- * @return mixed
- */
+ /**
+ * @internal
+ * @return mixed
+ */
abstract public function GetClassAlias();
/**
@@ -193,23 +194,23 @@ abstract class DBSearch
abstract public function GetFirstJoinedClass();
/**
- * Change the class
- *
- * Defaults to the first selected class (most of the time it is also the first joined class
- * only subclasses are supported as of now, because the conditions must fit the new class
- *
- * @internal
- */
+ * Change the class
+ *
+ * Defaults to the first selected class (most of the time it is also the first joined class
+ * only subclasses are supported as of now, because the conditions must fit the new class
+ *
+ * @internal
+ */
abstract public function ChangeClass($sNewClass, $sAlias = null);
- /**
- * @internal
- * @return mixed
- */
+ /**
+ * @internal
+ * @return mixed
+ */
abstract public function GetSelectedClasses();
/**
- * @internal
+ * @internal
* @param array $aSelectedClasses array of aliases
* @throws CoreException
*/
@@ -218,15 +219,15 @@ abstract class DBSearch
/**
* Change any alias of the query tree
*
- * @internal
- *
+ * @internal
+ *
* @param $sOldName
* @param $sNewName
* @return bool True if the alias has been found and changed
*/
abstract public function RenameAlias($sOldName, $sNewName);
- abstract public function RenameAliasesInNameSpace($aClassAliases, $aAliasTranslation = array());
+ abstract public function RenameAliasesInNameSpace($aClassAliases, $aAliasTranslation = []);
abstract public function TranslateConditions($aTranslationData, $bMatchAll = true, $bMarkFieldsAsResolved = true);
@@ -249,56 +250,56 @@ abstract class DBSearch
* @see DBSearch::AddConditionExpression()
*
* @param Expression $oExpression
- *
- * @return mixed
- */
+ *
+ * @return mixed
+ */
abstract public function MergeConditionExpression($oExpression);
- /**
- * add $oExpression as a AND
- *
- * @api
- * @see DBSearch::MergeConditionExpression()
- *
- * @param Expression $oExpression
- *
- * @return mixed
- */
+ /**
+ * add $oExpression as a AND
+ *
+ * @api
+ * @see DBSearch::MergeConditionExpression()
+ *
+ * @param Expression $oExpression
+ *
+ * @return mixed
+ */
abstract public function AddConditionExpression($oExpression);
- /**
- * Condition on the friendlyname
- *
- * Restrict the query to only the corresponding selected class' friendlyname
- *
- * @internal
- *
- * @param string $sName the desired friendlyname
- *
- * @return mixed
- */
- abstract public function AddNameCondition($sName);
+ /**
+ * Condition on the friendlyname
+ *
+ * Restrict the query to only the corresponding selected class' friendlyname
+ *
+ * @internal
+ *
+ * @param string $sName the desired friendlyname
+ *
+ * @return mixed
+ */
+ abstract public function AddNameCondition($sName);
- /**
- * Add a condition
- *
- * This is the simplest way to express a AND condition. For complex use cases, use MergeConditionExpression or AddConditionExpression instead
- *
- * @api
- *
- * @param string $sFilterCode
- * @param mixed $value
- * @param string $sOpCode operator to use : '=' (default), '!=', 'IN', 'NOT IN'
- *
- * @throws \CoreException
- *
- */
+ /**
+ * Add a condition
+ *
+ * This is the simplest way to express a AND condition. For complex use cases, use MergeConditionExpression or AddConditionExpression instead
+ *
+ * @api
+ *
+ * @param string $sFilterCode
+ * @param mixed $value
+ * @param string $sOpCode operator to use : '=' (default), '!=', 'IN', 'NOT IN'
+ *
+ * @throws \CoreException
+ *
+ */
abstract public function AddCondition($sFilterCode, $value, $sOpCode = null);
/**
* Specify a condition on external keys or link sets
- *
- * @internal
- *
+ *
+ * @internal
+ *
* @param string $sAttSpec Can be either an attribute code or extkey->[sAttSpec] or linkset->[sAttSpec] and so on, recursively
* Example: infra_list->ci_id->location_id->country
* @param mixed $value The value to match (can be an array => IN(val1, val2...)
@@ -306,50 +307,50 @@ abstract class DBSearch
*/
abstract public function AddConditionAdvanced($sAttSpec, $value);
- /**
- * @internal
- *
- * @param string $sFullText
- *
- * @return mixed
- */
+ /**
+ * @internal
+ *
+ * @param string $sFullText
+ *
+ * @return mixed
+ */
abstract public function AddCondition_FullText($sFullText);
abstract public function AddCondition_FullTextOnAttributes(array $aAttCodes, $sNeedle);
- /**
- * Perform a join, the remote class being matched by the mean of its primary key
- *
- * The join is performed
- * * from the searched class, based on the $sExtKeyAttCode attribute
- * * against the oFilter searched class, based on its primary key
- * Note : if several classes have already being joined (SELECT a join b ON...), the first joined class (a in the example) is considered as being the searched class.
- *
- * @api
- * @see AddCondition_ReferencedBy()
- *
+ /**
+ * Perform a join, the remote class being matched by the mean of its primary key
+ *
+ * The join is performed
+ * * from the searched class, based on the $sExtKeyAttCode attribute
+ * * against the oFilter searched class, based on its primary key
+ * Note : if several classes have already being joined (SELECT a join b ON...), the first joined class (a in the example) is considered as being the searched class.
+ *
+ * @api
+ * @see AddCondition_ReferencedBy()
+ *
* @param DBObjectSearch $oFilter
* @param string $sExtKeyAttCode
* @param int $iOperatorCode the comparison operator to use. For the list of all possible values, see the constant defined in core/oql/oqlquery.class.inc.php
* @param array|null $aRealiasingMap array of => , for each alias that has changed in the newly attached oFilter (in case of collisions between the two filters)
- *
+ *
* @throws CoreException
* @throws CoreWarning
*/
abstract public function AddCondition_PointingTo(DBObjectSearch $oFilter, $sExtKeyAttCode, $iOperatorCode = TREE_OPERATOR_EQUALS, &$aRealiasingMap = null);
/**
- * Inverse operation of AddCondition_PointingTo
- *
- * The join is performed
- * * from the olFilter searched class, based on the $sExtKeyAttCode attribute
- * * against the searched class, based on its primary key
- * Note : if several classes have already being joined (SELECT a join b ON...), the first joined class (a in the example) is considered as being the searched class.
- *
- *
- * @api
- * @see AddCondition_PointingTo()
- *
+ * Inverse operation of AddCondition_PointingTo
+ *
+ * The join is performed
+ * * from the olFilter searched class, based on the $sExtKeyAttCode attribute
+ * * against the searched class, based on its primary key
+ * Note : if several classes have already being joined (SELECT a join b ON...), the first joined class (a in the example) is considered as being the searched class.
+ *
+ *
+ * @api
+ * @see AddCondition_PointingTo()
+ *
* @param DBObjectSearch $oFilter
* @param $sForeignExtKeyAttCode
* @param int $iOperatorCode
@@ -373,62 +374,54 @@ abstract class DBSearch
abstract public function Filter($sClassAlias, DBSearch $oFilter);
/**
- * Filter the result
- *
- * The filter is performed by returning only the values in common with the given $oFilter
- * The impact on the resulting query performance/viability can be significant.
- * Only the first joined class can be filtered.
- *
- * @internal
- *
- * @param DBSearch $oFilter
- *
- * @return mixed
- */
+ * Filter the result
+ *
+ * The filter is performed by returning only the values in common with the given $oFilter
+ * The impact on the resulting query performance/viability can be significant.
+ * Only the first joined class can be filtered.
+ *
+ * @internal
+ *
+ * @param DBSearch $oFilter
+ *
+ * @return mixed
+ */
abstract public function Intersect(DBSearch $oFilter);
- /**
- * Perform a join
- *
- * The join is performed against $oFilter selected class using $sExtKeyAttCode of the current selected class
- *
- * @internal
- *
- * @param DBSearch $oFilter The join is performed against $oFilter selected class
- * @param integer $iDirection can be either DBSearch::JOIN_POINTING_TO or DBSearch::JOIN_REFERENCED_BY
- * @param string $sExtKeyAttCode The join is performed against $sExtKeyAttCode whether it is compared against the current DBSearch or $oFilter depend of $iDirection
- * @param integer $iOperatorCode See DBSearch::AddCondition_PointingTo()
- * @param array|null $aRealiasingMap Map of aliases from the attached query, that could have been renamed by the optimization process
- *
- * @return DBSearch
- * @throws CoreException
- * @throws CoreWarning
- */
+ /**
+ * Perform a join
+ *
+ * The join is performed against $oFilter selected class using $sExtKeyAttCode of the current selected class
+ *
+ * @internal
+ *
+ * @param DBSearch $oFilter The join is performed against $oFilter selected class
+ * @param integer $iDirection can be either DBSearch::JOIN_POINTING_TO or DBSearch::JOIN_REFERENCED_BY
+ * @param string $sExtKeyAttCode The join is performed against $sExtKeyAttCode whether it is compared against the current DBSearch or $oFilter depend of $iDirection
+ * @param integer $iOperatorCode See DBSearch::AddCondition_PointingTo()
+ * @param array|null $aRealiasingMap Map of aliases from the attached query, that could have been renamed by the optimization process
+ *
+ * @return DBSearch
+ * @throws CoreException
+ * @throws CoreWarning
+ */
public function Join(DBSearch $oFilter, $iDirection, $sExtKeyAttCode, $iOperatorCode = TREE_OPERATOR_EQUALS, &$aRealiasingMap = null)
{
$oSourceFilter = $this->DeepClone();
$oRet = null;
- if ($oFilter instanceof DBUnionSearch)
- {
- $aSearches = array();
- foreach ($oFilter->GetSearches() as $oSearch)
- {
+ if ($oFilter instanceof DBUnionSearch) {
+ $aSearches = [];
+ foreach ($oFilter->GetSearches() as $oSearch) {
$aSearches[] = $oSourceFilter->Join($oSearch, $iDirection, $sExtKeyAttCode, $iOperatorCode, $aRealiasingMap);
}
$oRet = new DBUnionSearch($aSearches);
- }
- else
- {
+ } else {
/** @var \DBObjectSearch $oFilter */
- if ($iDirection === static::JOIN_POINTING_TO)
- {
+ if ($iDirection === static::JOIN_POINTING_TO) {
$oSourceFilter->AddCondition_PointingTo($oFilter, $sExtKeyAttCode, $iOperatorCode, $aRealiasingMap);
- }
- else
- {
- if ($iOperatorCode !== TREE_OPERATOR_EQUALS)
- {
+ } else {
+ if ($iOperatorCode !== TREE_OPERATOR_EQUALS) {
throw new Exception('Only TREE_OPERATOR_EQUALS operator code is supported yet for AddCondition_ReferencedBy.');
}
$oSourceFilter->AddCondition_ReferencedBy($oFilter, $sExtKeyAttCode, TREE_OPERATOR_EQUALS, $aRealiasingMap);
@@ -439,99 +432,88 @@ abstract class DBSearch
return $oRet;
}
- /**
- * Set the internal params.
- *
- * If any params pre-existed, they are lost.
- *
- * @internal
- *
- * @param mixed[string] $aParams array of mixed params index by string name
- *
- * @return mixed
- */
+ /**
+ * Set the internal params.
+ *
+ * If any params pre-existed, they are lost.
+ *
+ * @internal
+ *
+ * @param mixed[string] $aParams array of mixed params index by string name
+ *
+ * @return mixed
+ */
abstract public function SetInternalParams($aParams);
- /**
- * @internal
- * @return mixed
- */
+ /**
+ * @internal
+ * @return mixed
+ */
abstract public function GetInternalParams();
- /**
- * @internal
- *
- * @return mixed
- */
+ /**
+ * @internal
+ *
+ * @return mixed
+ */
abstract public function GetQueryParams();
- /**
- * @internal
- * @return mixed
- */
+ /**
+ * @internal
+ * @return mixed
+ */
abstract public function ListConstantFields();
/**
- * Turn the parameters (:xxx) into scalar values
- *
- * The goal is to easily serialize a search
+ * Turn the parameters (:xxx) into scalar values
+ *
+ * The goal is to easily serialize a search
+ *
+ * @internal
*
- * @internal
- *
* @param array $aArgs
*
* @return string
*/
abstract public function ApplyParameters($aArgs);
- /**
- * Convert a query to a string representation
- *
- * This operation can be revert back to a DBSearch using DBSearch::unserialize()
- *
- * @api
- * @see DBSearch::unserialize()
- *
- * @param bool $bDevelopParams
- * @param array $aContextParams
- *
- * @return false|string
- * @throws ArchivedObjectException
- * @throws CoreException
- */
- public function serialize($bDevelopParams = false, $aContextParams = array())
+ /**
+ * Convert a query to a string representation
+ *
+ * This operation can be revert back to a DBSearch using DBSearch::unserialize()
+ *
+ * @api
+ * @see DBSearch::unserialize()
+ *
+ * @param bool $bDevelopParams
+ * @param array $aContextParams
+ *
+ * @return false|string
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ */
+ public function serialize($bDevelopParams = false, $aContextParams = [])
{
$aQueryParams = $this->GetQueryParams();
$aContextParams = array_merge($this->GetInternalParams(), $aContextParams);
- foreach($aQueryParams as $sParam => $sValue)
- {
- if (isset($aContextParams[$sParam]))
- {
+ foreach ($aQueryParams as $sParam => $sValue) {
+ if (isset($aContextParams[$sParam])) {
$aQueryParams[$sParam] = $aContextParams[$sParam];
- }
- elseif (($iPos = strpos($sParam, '->')) !== false)
- {
+ } elseif (($iPos = strpos($sParam, '->')) !== false) {
$sParamName = substr($sParam, 0, $iPos);
- if (isset($aContextParams[$sParamName.'->object()']) || isset($aContextParams[$sParamName]))
- {
+ if (isset($aContextParams[$sParamName.'->object()']) || isset($aContextParams[$sParamName])) {
$sAttCode = substr($sParam, $iPos + 2);
/** @var \DBObject $oObj */
$oObj = isset($aContextParams[$sParamName.'->object()']) ? $aContextParams[$sParamName.'->object()'] : $aContextParams[$sParamName];
- if ($oObj->IsModified())
- {
- if ($sAttCode == 'id')
- {
+ if ($oObj->IsModified()) {
+ if ($sAttCode == 'id') {
$aQueryParams[$sParam] = $oObj->GetKey();
- }
- else
- {
+ } else {
$aQueryParams[$sParam] = $oObj->Get($sAttCode);
}
- }
- else
- {
+ } else {
unset($aQueryParams[$sParam]);
// For database objects, serialize only class, key
$aQueryParams[$sParamName.'->id'] = $oObj->GetKey();
@@ -542,14 +524,14 @@ abstract class DBSearch
}
$sOql = $this->ToOql($bDevelopParams, $aContextParams);
- return urlencode(json_encode(array($sOql, $aQueryParams, $this->m_aModifierProperties)));
+ return urlencode(json_encode([$sOql, $aQueryParams, $this->m_aModifierProperties]));
}
/**
- * Convert a serialized query back to an instance of DBSearch
- *
- * @api
- *
+ * Convert a serialized query back to an instance of DBSearch
+ *
+ * @api
+ *
* @param string $sValue Serialized OQL query
*
* @return \DBSearch
@@ -557,23 +539,19 @@ abstract class DBSearch
* @throws \CoreException
* @throws \OQLException
*/
- static public function unserialize($sValue)
+ public static function unserialize($sValue)
{
$aData = json_decode(urldecode($sValue), true);
- if (is_null($aData))
- {
+ if (is_null($aData)) {
throw new CoreException("Invalid filter parameter");
}
$sOql = $aData[0];
$aParams = $aData[1];
- $aExtraParams = array();
- foreach($aParams as $sParam => $sValue)
- {
- if (($iPos = strpos($sParam, '->class')) !== false)
- {
+ $aExtraParams = [];
+ foreach ($aParams as $sParam => $sValue) {
+ if (($iPos = strpos($sParam, '->class')) !== false) {
$sParamName = substr($sParam, 0, $iPos);
- if (isset($aParams[$sParamName.'->id']))
- {
+ if (isset($aParams[$sParamName.'->id'])) {
$sClass = $aParams[$sParamName.'->class'];
$iKey = $aParams[$sParamName.'->id'];
$oObj = MetaModel::GetObject($sClass, $iKey);
@@ -590,65 +568,65 @@ abstract class DBSearch
return $oRetFilter;
}
- /**
- * Create a new DBObjectSearch from $oSearch with a new alias $sAlias
- *
- * @internal Note : This has not be tested with UNION queries.
- *
- * @param DBSearch $oSearch
- * @param string $sAlias
- *
- * @return DBObjectSearch
- * @throws CoreException
- */
- static public function CloneWithAlias(DBSearch $oSearch, $sAlias)
- {
- $oSearchWithAlias = new DBObjectSearch($oSearch->GetClass(), $sAlias);
- $oSearchWithAlias = $oSearchWithAlias->Intersect($oSearch);
- return $oSearchWithAlias;
- }
+ /**
+ * Create a new DBObjectSearch from $oSearch with a new alias $sAlias
+ *
+ * @internal Note : This has not be tested with UNION queries.
+ *
+ * @param DBSearch $oSearch
+ * @param string $sAlias
+ *
+ * @return DBObjectSearch
+ * @throws CoreException
+ */
+ public static function CloneWithAlias(DBSearch $oSearch, $sAlias)
+ {
+ $oSearchWithAlias = new DBObjectSearch($oSearch->GetClass(), $sAlias);
+ $oSearchWithAlias = $oSearchWithAlias->Intersect($oSearch);
+ return $oSearchWithAlias;
+ }
- /**
- * Convert the DBSearch to an OQL representation
- *
- * @api
- * @see DBSearch::FromOQL()
- *
- * @param bool $bDevelopParams
- * @param null $aContextParams
- * @param bool $bWithAllowAllFlag
- *
- * @return mixed
- */
- abstract public function ToOQL($bDevelopParams = false, $aContextParams = null, $bWithAllowAllFlag = false);
+ /**
+ * Convert the DBSearch to an OQL representation
+ *
+ * @api
+ * @see DBSearch::FromOQL()
+ *
+ * @param bool $bDevelopParams
+ * @param null $aContextParams
+ * @param bool $bWithAllowAllFlag
+ *
+ * @return mixed
+ */
+ abstract public function ToOQL($bDevelopParams = false, $aContextParams = null, $bWithAllowAllFlag = false);
- /**
- * Export the DBSearch as a structure (array of arrays...) suitable for a conversion to JSON
- *
- * @internal
- *
- * @return mixed[string]
- */
- abstract public function ToJSON();
+ /**
+ * Export the DBSearch as a structure (array of arrays...) suitable for a conversion to JSON
+ *
+ * @internal
+ *
+ * @return mixed[string]
+ */
+ abstract public function ToJSON();
- static protected $m_aOQLQueries = array();
+ protected static $m_aOQLQueries = [];
- /**
- * FromOQL with AllowAllData enabled
- *
- * The goal is to not filter out depending on user rights.
- * In particular when we are currently in the process of evaluating the user rights...
- *
- * @internal
- * @see DBSearch::FromOQL()
- *
- * @param string $sQuery
- * @param null $aParams
- *
- * @return DBSearch
- * @throws OQLException
- */
- static public function FromOQL_AllData($sQuery, $aParams = null)
+ /**
+ * FromOQL with AllowAllData enabled
+ *
+ * The goal is to not filter out depending on user rights.
+ * In particular when we are currently in the process of evaluating the user rights...
+ *
+ * @internal
+ * @see DBSearch::FromOQL()
+ *
+ * @param string $sQuery
+ * @param null $aParams
+ *
+ * @return DBSearch
+ * @throws OQLException
+ */
+ public static function FromOQL_AllData($sQuery, $aParams = null)
{
$oRes = self::FromOQL($sQuery, $aParams);
$oRes->AllowAllData();
@@ -656,41 +634,36 @@ abstract class DBSearch
}
/**
- * Create a new DBSearch from the given OQL.
- *
- * This is the simplest way to create a DBSearch.
- * For almost every cases, this is the easiest way.
- *
- * @api
- * @see DBSearch::ToOQL()
- *
+ * Create a new DBSearch from the given OQL.
+ *
+ * This is the simplest way to create a DBSearch.
+ * For almost every cases, this is the easiest way.
+ *
+ * @api
+ * @see DBSearch::ToOQL()
+ *
* @param string $sQuery The OQL to convert to a DBSearch
* @param array $aParams array of params index by name
* @param ModelReflection|null $oMetaModel The MetaModel to use when checking the consistency of the OQL
- *
+ *
* @return DBObjectSearch|DBUnionSearch
- *
+ *
* @throws OQLException
*/
- public static function FromOQL($sQuery, $aParams = null, ModelReflection $oMetaModel=null)
+ public static function FromOQL($sQuery, $aParams = null, ModelReflection $oMetaModel = null)
{
- if (empty($sQuery))
- {
+ if (empty($sQuery)) {
return null;
}
// Query caching
$sQueryId = md5($sQuery);
$bOQLCacheEnabled = true;
- if ($bOQLCacheEnabled)
- {
- if (array_key_exists($sQueryId, self::$m_aOQLQueries))
- {
+ if ($bOQLCacheEnabled) {
+ if (array_key_exists($sQueryId, self::$m_aOQLQueries)) {
// hit!
$oResultFilter = self::$m_aOQLQueries[$sQueryId]->DeepClone();
- }
- elseif (self::$m_bUseAPCCache)
- {
+ } elseif (self::$m_bUseAPCCache) {
// Note: For versions of APC older than 3.0.17, fetch() accepts only one parameter
//
$sAPCCacheId = 'itop-'.MetaModel::GetEnvironmentId().'-dbsearch-cache-'.$sQueryId;
@@ -698,8 +671,7 @@ abstract class DBSearch
$result = apc_fetch($sAPCCacheId);
$oKPI->ComputeStats('Search APC (fetch)', $sQuery);
- if (is_object($result))
- {
+ if (is_object($result)) {
$oResultFilter = $result;
self::$m_aOQLQueries[$sQueryId] = $oResultFilter->DeepClone();
}
@@ -707,15 +679,13 @@ abstract class DBSearch
}
/** @var DBObjectSearch | null $oResultFilter */
- if (!isset($oResultFilter))
- {
+ if (!isset($oResultFilter)) {
$oKPI = new ExecutionKPI();
$oOql = new OqlInterpreter($sQuery);
$oOqlQuery = $oOql->ParseQuery();
- if ($oMetaModel === null)
- {
+ if ($oMetaModel === null) {
$oMetaModel = new ModelReflectionRuntime();
}
$oOqlQuery->Check($oMetaModel, $sQuery); // Exceptions thrown in case of issue
@@ -724,12 +694,10 @@ abstract class DBSearch
$oKPI->ComputeStats('Parse OQL', $sQuery);
- if ($bOQLCacheEnabled)
- {
+ if ($bOQLCacheEnabled) {
self::$m_aOQLQueries[$sQueryId] = $oResultFilter->DeepClone();
- if (self::$m_bUseAPCCache)
- {
+ if (self::$m_bUseAPCCache) {
$oKPI = new ExecutionKPI();
apc_store($sAPCCacheId, $oResultFilter, self::$m_iQueryCacheTTL);
$oKPI->ComputeStats('Search APC (store)', $sQueryId);
@@ -737,8 +705,7 @@ abstract class DBSearch
}
}
- if (!is_null($aParams))
- {
+ if (!is_null($aParams)) {
$oResultFilter->SetInternalParams($aParams);
}
@@ -749,60 +716,54 @@ abstract class DBSearch
}
/**
- * Fetch the result has an array structure.
- *
+ * Fetch the result has an array structure.
+ *
* Alternative to object mapping: the data are transfered directly into an array
* This is 10 times faster than creating a set of objects, and makes sense when optimization is required
- * But this speed comes at the cost of not obtaining the easy to manipulates DBObject instances but simple array structure.
- *
- * @internal
+ * But this speed comes at the cost of not obtaining the easy to manipulates DBObject instances but simple array structure.
+ *
+ * @internal
*
* @param array $aColumns The columns you'd like to fetch.
* @param array $aOrderBy Array of '[.]attcode' => bAscending
* @param array $aArgs
*
* @return array|void
- *
+ *
* @throws \CoreException
* @throws \MissingQueryArgument
* @throws \MySQLException
* @throws \MySQLHasGoneAwayException
*/
- public function ToDataArray($aColumns = array(), $aOrderBy = array(), $aArgs = array())
+ public function ToDataArray($aColumns = [], $aOrderBy = [], $aArgs = [])
{
$sSQL = $this->MakeSelectQuery($aOrderBy, $aArgs);
$resQuery = CMDBSource::Query($sSQL);
- if (!$resQuery)
- {
+ if (!$resQuery) {
return;
}
- if (count($aColumns) == 0)
- {
- $aColumns = array_keys(MetaModel::ListAttributeDefs($this->GetClass()));
- // Add the standard id (as first column)
- array_unshift($aColumns, 'id');
+ if (count($aColumns) == 0) {
+ $aColumns = array_keys(MetaModel::ListAttributeDefs($this->GetClass()));
+ // Add the standard id (as first column)
+ array_unshift($aColumns, 'id');
}
$aQueryCols = CMDBSource::GetColumns($resQuery, $sSQL);
$sClassAlias = $this->GetClassAlias();
- $aColMap = array();
- foreach ($aColumns as $sAttCode)
- {
+ $aColMap = [];
+ foreach ($aColumns as $sAttCode) {
$sColName = $sClassAlias.$sAttCode;
- if (in_array($sColName, $aQueryCols))
- {
+ if (in_array($sColName, $aQueryCols)) {
$aColMap[$sAttCode] = $sColName;
}
}
- $aRes = array();
- while ($aRow = CMDBSource::FetchArray($resQuery))
- {
- $aMappedRow = array();
- foreach ($aColMap as $sAttCode => $sColName)
- {
+ $aRes = [];
+ while ($aRow = CMDBSource::FetchArray($resQuery)) {
+ $aMappedRow = [];
+ foreach ($aColMap as $sAttCode => $sColName) {
$aMappedRow[$sAttCode] = $aRow[$sColName];
}
$aRes[] = $aMappedRow;
@@ -811,68 +772,65 @@ abstract class DBSearch
return $aRes;
}
- /**
- * Selects a column ($sAttCode) from the specified class ($sClassAlias - default main class) of the DBsearch object and gives the result as an array
- * @param string $sAttCode
- * @param string|null $sClassAlias
- *
- * @return array
- * @throws ConfigException
- * @throws CoreException
- * @throws MissingQueryArgument
- * @throws MySQLException
- * @throws MySQLHasGoneAwayException
- */
- public function SelectAttributeToArray(string $sAttCode, ?string $sClassAlias = null):array
- {
- if(is_null($sClassAlias)) {
- $sClassAlias = $this->GetClassAlias();
- }
+ /**
+ * Selects a column ($sAttCode) from the specified class ($sClassAlias - default main class) of the DBsearch object and gives the result as an array
+ * @param string $sAttCode
+ * @param string|null $sClassAlias
+ *
+ * @return array
+ * @throws ConfigException
+ * @throws CoreException
+ * @throws MissingQueryArgument
+ * @throws MySQLException
+ * @throws MySQLHasGoneAwayException
+ */
+ public function SelectAttributeToArray(string $sAttCode, ?string $sClassAlias = null): array
+ {
+ if (is_null($sClassAlias)) {
+ $sClassAlias = $this->GetClassAlias();
+ }
- $sClass = $this->GetClass();
- if($sAttCode === 'id'){
- $aAttToLoad[$sClassAlias]=[];
- } else {
- $aAttToLoad[$sClassAlias][$sAttCode] = MetaModel::GetAttributeDef($sClass, $sAttCode);
- }
+ $sClass = $this->GetClass();
+ if ($sAttCode === 'id') {
+ $aAttToLoad[$sClassAlias] = [];
+ } else {
+ $aAttToLoad[$sClassAlias][$sAttCode] = MetaModel::GetAttributeDef($sClass, $sAttCode);
+ }
- $sSQL = $this->MakeSelectQuery([], [], $aAttToLoad);
- $resQuery = CMDBSource::Query($sSQL);
- if (!$resQuery)
- {
- return [];
- }
+ $sSQL = $this->MakeSelectQuery([], [], $aAttToLoad);
+ $resQuery = CMDBSource::Query($sSQL);
+ if (!$resQuery) {
+ return [];
+ }
- $sColName = $sClassAlias.$sAttCode;
+ $sColName = $sClassAlias.$sAttCode;
- $aRes = [];
- while ($aRow = CMDBSource::FetchArray($resQuery))
- {
- $aMappedRow = array();
- if($sAttCode === 'id') {
- $aMappedRow[$sAttCode] = $aRow[$sColName];
- } else {
- $aMappedRow[$sAttCode] = $aAttToLoad[$sClassAlias][$sAttCode]->FromSQLToValue($aRow, $sColName);
- }
- $aRes[] = $aMappedRow;
- }
- CMDBSource::FreeResult($resQuery);
- return $aRes;
- }
+ $aRes = [];
+ while ($aRow = CMDBSource::FetchArray($resQuery)) {
+ $aMappedRow = [];
+ if ($sAttCode === 'id') {
+ $aMappedRow[$sAttCode] = $aRow[$sColName];
+ } else {
+ $aMappedRow[$sAttCode] = $aAttToLoad[$sClassAlias][$sAttCode]->FromSQLToValue($aRow, $sColName);
+ }
+ $aRes[] = $aMappedRow;
+ }
+ CMDBSource::FreeResult($resQuery);
+ return $aRes;
+ }
////////////////////////////////////////////////////////////////////////////
//
// Construction of the SQL queries
//
////////////////////////////////////////////////////////////////////////////
- protected static $m_aQueryStructCache = array();
+ protected static $m_aQueryStructCache = [];
-
- /**
- * Generate a Group By SQL query from the current search
- *
- * @internal
- *
+ /**
+ * Generate a Group By SQL query from the current search
+ *
+ * @internal
+ *
* @param array $aArgs
* @param array $aGroupByExpr array('alias' => Expression)
* @param bool $bExcludeNullValues
@@ -880,76 +838,62 @@ abstract class DBSearch
* @param array $aOrderBy array('alias' => bool) true = ASC false = DESC
* @param int $iLimitCount
* @param int $iLimitStart
- *
+ *
* @return string SQL query generated
- *
+ *
* @throws Exception
*/
- public function MakeGroupByQuery($aArgs, $aGroupByExpr, $bExcludeNullValues = false, $aSelectExpr = array(), $aOrderBy = array(), $iLimitCount = 0, $iLimitStart = 0)
+ public function MakeGroupByQuery($aArgs, $aGroupByExpr, $bExcludeNullValues = false, $aSelectExpr = [], $aOrderBy = [], $iLimitCount = 0, $iLimitStart = 0)
{
// Sanity check
- foreach($aGroupByExpr as $sAlias => $oExpr)
- {
- if (!($oExpr instanceof Expression))
- {
+ foreach ($aGroupByExpr as $sAlias => $oExpr) {
+ if (!($oExpr instanceof Expression)) {
throw new CoreException("Wrong parameter for 'Group By' for [$sAlias] (an array('alias' => Expression) is awaited)");
}
}
- foreach($aSelectExpr as $sAlias => $oExpr)
- {
- if (array_key_exists($sAlias, $aGroupByExpr))
- {
+ foreach ($aSelectExpr as $sAlias => $oExpr) {
+ if (array_key_exists($sAlias, $aGroupByExpr)) {
throw new CoreException("Alias collision between 'Group By' and 'Select Expressions' [$sAlias]");
}
- if (!($oExpr instanceof Expression))
- {
+ if (!($oExpr instanceof Expression)) {
throw new CoreException("Wrong parameter for 'Select Expressions' for [$sAlias] (an array('alias' => Expression) is awaited)");
}
}
- foreach($aOrderBy as $sAlias => $bAscending)
- {
- if (!array_key_exists($sAlias, $aGroupByExpr) && !array_key_exists($sAlias, $aSelectExpr) && ($sAlias != '_itop_count_'))
- {
+ foreach ($aOrderBy as $sAlias => $bAscending) {
+ if (!array_key_exists($sAlias, $aGroupByExpr) && !array_key_exists($sAlias, $aSelectExpr) && ($sAlias != '_itop_count_')) {
$aAllowedAliases = array_keys($aSelectExpr);
- $aAllowedAliases = array_merge($aAllowedAliases, array_keys($aGroupByExpr));
+ $aAllowedAliases = array_merge($aAllowedAliases, array_keys($aGroupByExpr));
$aAllowedAliases[] = '_itop_count_';
throw new CoreException("Wrong alias [$sAlias] for 'Order By'. Allowed values are: ", null, implode(", ", $aAllowedAliases));
}
- if (!is_bool($bAscending))
- {
+ if (!is_bool($bAscending)) {
throw new CoreException("Wrong direction in ORDER BY spec, found '$bAscending' and expecting a boolean value for '$sAlias''");
}
}
- if ($bExcludeNullValues)
- {
+ if ($bExcludeNullValues) {
// Null values are not handled (though external keys set to 0 are allowed)
$oQueryFilter = $this->DeepClone();
- foreach ($aGroupByExpr as $oGroupByExp)
- {
- $oNull = new FunctionExpression('ISNULL', array($oGroupByExp));
+ foreach ($aGroupByExpr as $oGroupByExp) {
+ $oNull = new FunctionExpression('ISNULL', [$oGroupByExp]);
$oNotNull = new BinaryExpression($oNull, '!=', new TrueExpression());
$oQueryFilter->AddConditionExpression($oNotNull);
}
- }
- else
- {
+ } else {
$oQueryFilter = $this;
}
- $aAttToLoad = array();
- $oSQLQuery = $oQueryFilter->GetSQLQuery(array(), $aArgs, $aAttToLoad, null, 0, 0, false, $aGroupByExpr, $aSelectExpr);
+ $aAttToLoad = [];
+ $oSQLQuery = $oQueryFilter->GetSQLQuery([], $aArgs, $aAttToLoad, null, 0, 0, false, $aGroupByExpr, $aSelectExpr);
$aScalarArgs = MetaModel::PrepareQueryArguments($aArgs, $this->GetInternalParams(), $this->GetExpectedArguments());
- try
- {
+ try {
$bBeautifulSQL = self::$m_bTraceQueries || self::$m_bDebugQuery || self::$m_bIndentQueries;
$sRes = $oSQLQuery->RenderGroupBy($aScalarArgs, $bBeautifulSQL, $aOrderBy, $iLimitCount, $iLimitStart);
}
// Catch CoreException to add info before throwing again
// Other exceptions will be thrown directly
- catch (CoreException $e)
- {
+ catch (CoreException $e) {
// Add some information...
$e->addInfo('OQL', $this->ToOQL());
throw $e;
@@ -977,79 +921,62 @@ abstract class DBSearch
* @internal
*
*/
- public function MakeSelectQuery($aOrderBy = array(), $aArgs = array(), $aAttToLoad = null, $aExtendedDataSpec = null, $iLimitCount = 0, $iLimitStart = 0, $bGetCount = false, $bBeautifulSQL = true)
+ public function MakeSelectQuery($aOrderBy = [], $aArgs = [], $aAttToLoad = null, $aExtendedDataSpec = null, $iLimitCount = 0, $iLimitStart = 0, $bGetCount = false, $bBeautifulSQL = true)
{
// Check the order by specification, and prefix with the class alias
// and make sure that the ordering columns are going to be selected
//
$sClass = $this->GetClass();
$sClassAlias = $this->GetClassAlias();
- $aOrderSpec = array();
- foreach ($aOrderBy as $sFieldAlias => $bAscending)
- {
- if (!is_bool($bAscending))
- {
+ $aOrderSpec = [];
+ foreach ($aOrderBy as $sFieldAlias => $bAscending) {
+ if (!is_bool($bAscending)) {
throw new CoreException("Wrong direction in ORDER BY spec, found '$bAscending' and expecting a boolean value");
}
$iDotPos = strpos($sFieldAlias, '.');
- if ($iDotPos === false)
- {
+ if ($iDotPos === false) {
$sAttClass = $sClass;
$sAttClassAlias = $sClassAlias;
$sAttCode = $sFieldAlias;
- }
- else
- {
+ } else {
$sAttClassAlias = substr($sFieldAlias, 0, $iDotPos);
$sAttClass = $this->GetClassName($sAttClassAlias);
$sAttCode = substr($sFieldAlias, $iDotPos + 1);
}
- if ($sAttCode != 'id')
- {
+ if ($sAttCode != 'id') {
MyHelpers::CheckValueInArray('field name in ORDER BY spec', $sAttCode, MetaModel::GetAttributesList($sAttClass));
$oAttDef = MetaModel::GetAttributeDef($sAttClass, $sAttCode);
- foreach($oAttDef->GetOrderBySQLExpressions($sAttClassAlias) as $sSQLExpression)
- {
+ foreach ($oAttDef->GetOrderBySQLExpressions($sAttClassAlias) as $sSQLExpression) {
$aOrderSpec[$sSQLExpression] = $bAscending;
}
- // Make sure that the columns used for sorting are present in the loaded columns
- if (!is_null($aAttToLoad) && !isset($aAttToLoad[$sAttClassAlias][$sAttCode]))
- {
- $aAttToLoad[$sAttClassAlias][$sAttCode] = MetaModel::GetAttributeDef($sAttClass, $sAttCode);
- }
- }
- else
- {
+ // Make sure that the columns used for sorting are present in the loaded columns
+ if (!is_null($aAttToLoad) && !isset($aAttToLoad[$sAttClassAlias][$sAttCode])) {
+ $aAttToLoad[$sAttClassAlias][$sAttCode] = MetaModel::GetAttributeDef($sAttClass, $sAttCode);
+ }
+ } else {
$aOrderSpec['`'.$sAttClassAlias.$sAttCode.'`'] = $bAscending;
}
}
$oSQLQuery = $this->GetSQLQuery($aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount);
- if ($this->m_bNoContextParameters)
- {
+ if ($this->m_bNoContextParameters) {
// Only internal parameters
$aScalarArgs = $this->GetInternalParams();
- }
- else
- {
+ } else {
// The complete list of arguments will include magic arguments (e.g. current_user->attcode)
$aScalarArgs = MetaModel::PrepareQueryArguments($aArgs, $this->GetInternalParams(), $this->GetExpectedArguments());
}
- try
- {
+ try {
$sRes = $oSQLQuery->RenderSelect($aOrderSpec, $aScalarArgs, $iLimitCount, $iLimitStart, $bGetCount, $bBeautifulSQL);
- if ($sClassAlias == '_itop_')
- {
+ if ($sClassAlias == '_itop_') {
IssueLog::Info('SQL Query (_itop_): '.$sRes);
}
- }
- catch (MissingQueryArgument $e)
- {
+ } catch (MissingQueryArgument $e) {
// Add some information...
$e->addInfo('OQL', $this->ToOQL());
throw $e;
@@ -1071,39 +998,37 @@ abstract class DBSearch
*
* @since 2.7.0 N°2555
*/
- public function GetFirstResult($bMustHaveOneResultMax = true, $aOrderBy = array(), $aSearchParams = array())
+ public function GetFirstResult($bMustHaveOneResultMax = true, $aOrderBy = [], $aSearchParams = [])
{
- $oSet = new DBObjectSet($this, array(), $aSearchParams, null, 2);
+ $oSet = new DBObjectSet($this, [], $aSearchParams, null, 2);
$oFirstResult = $oSet->Fetch();
- if ($oFirstResult === null) // useless but here for readability ;)
- {
+ if ($oFirstResult === null) { // useless but here for readability ;)
return null;
}
- if ($bMustHaveOneResultMax)
- {
+ if ($bMustHaveOneResultMax) {
$oSecondResult = $oSet->Fetch();
- if ($oSecondResult !== null)
- {
+ if ($oSecondResult !== null) {
throw new CoreOqlMultipleResultsForbiddenException(
- 'Search returned multiple results, this is forbidden. Query was: '.$this->ToOQL());
+ 'Search returned multiple results, this is forbidden. Query was: '.$this->ToOQL()
+ );
}
}
return $oFirstResult;
}
- /**
- * @internal
- * @return mixed
- */
- protected abstract function IsDataFiltered();
+ /**
+ * @internal
+ * @return mixed
+ */
+ abstract protected function IsDataFiltered();
- /**
- * @internal
- * @return mixed
- */
- protected abstract function SetDataFiltered();
+ /**
+ * @internal
+ * @return mixed
+ */
+ abstract protected function SetDataFiltered();
/**
* @param $aOrderBy
@@ -1124,18 +1049,14 @@ abstract class DBSearch
protected function GetSQLQuery($aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount, $aGroupByExpr = null, $aSelectExpr = null)
{
$oSearch = $this;
- if (!$this->IsAllDataAllowed() && !$this->IsDataFiltered())
- {
- foreach ($this->GetSelectedClasses() as $sClassAlias => $sClass)
- {
+ if (!$this->IsAllDataAllowed() && !$this->IsDataFiltered()) {
+ foreach ($this->GetSelectedClasses() as $sClassAlias => $sClass) {
$oVisibleObjects = UserRights::GetSelectFilter($sClass, $this->GetModifierProperties('UserRightsGetSelectFilter'));
- if ($oVisibleObjects === false)
- {
+ if ($oVisibleObjects === false) {
// Make sure this is a valid search object, saying NO for all
$oVisibleObjects = DBObjectSearch::FromEmptySet($sClass);
}
- if (is_object($oVisibleObjects))
- {
+ if (is_object($oVisibleObjects)) {
$oVisibleObjects->AllowAllData();
$oSearch = $oSearch->Filter($sClassAlias, $oVisibleObjects);
$oSearch->SetDataFiltered();
@@ -1143,22 +1064,17 @@ abstract class DBSearch
}
}
- if (is_array($aGroupByExpr))
- {
- foreach($aGroupByExpr as $sAlias => $oGroupByExp)
- {
+ if (is_array($aGroupByExpr)) {
+ foreach ($aGroupByExpr as $sAlias => $oGroupByExp) {
/** @var \Expression $oGroupByExp */
$aFields = $oGroupByExp->ListRequiredFields();
- foreach($aFields as $sFieldAlias)
- {
- $aMatches = array();
- if (preg_match('/^([^.]+)\\.([^.]+)$/', $sFieldAlias, $aMatches))
- {
+ foreach ($aFields as $sFieldAlias) {
+ $aMatches = [];
+ if (preg_match('/^([^.]+)\\.([^.]+)$/', $sFieldAlias, $aMatches)) {
$sFieldClass = $this->GetClassName($aMatches[1]);
$oAttDef = MetaModel::GetAttributeDef($sFieldClass, $aMatches[2]);
- if ( $oAttDef instanceof iAttributeNoGroupBy)
- {
+ if ($oAttDef instanceof iAttributeNoGroupBy) {
throw new Exception("Grouping on '$sFieldClass' fields is not supported.");
}
}
@@ -1171,12 +1087,10 @@ abstract class DBSearch
// Join to an additional table, if required...
//
- if ($aExtendedDataSpec != null)
- {
+ if ($aExtendedDataSpec != null) {
$sTableAlias = '_extended_data_';
- $aExtendedFields = array();
- foreach($aExtendedDataSpec['fields'] as $sColumn)
- {
+ $aExtendedFields = [];
+ foreach ($aExtendedDataSpec['fields'] as $sColumn) {
$sColRef = $this->GetClassAlias().'_extdata_'.$sColumn;
$aExtendedFields[$sColRef] = new FieldExpressionResolved($sColumn, $sTableAlias);
}
@@ -1187,40 +1101,45 @@ abstract class DBSearch
return $oSQLQuery;
}
- /**
- * @internal
- *
- * @param $aAttToLoad
- * @param $bGetCount
- * @param null $aGroupByExpr
- * @param null $aSelectedClasses
- * @param null $aSelectExpr
- *
- * @return mixed
- */
- public abstract function GetSQLQueryStructure(
- $aAttToLoad, $bGetCount, $aGroupByExpr = null, $aSelectedClasses = null, $aSelectExpr = null
+ /**
+ * @internal
+ *
+ * @param $aAttToLoad
+ * @param $bGetCount
+ * @param null $aGroupByExpr
+ * @param null $aSelectedClasses
+ * @param null $aSelectExpr
+ *
+ * @return mixed
+ */
+ abstract public function GetSQLQueryStructure(
+ $aAttToLoad,
+ $bGetCount,
+ $aGroupByExpr = null,
+ $aSelectedClasses = null,
+ $aSelectExpr = null
);
- /**
- * Shortcut to add efficient IN condition
- *
- * @internal
- *
- * @param $sFilterCode
- * @param $aValues
- * @param bool $bPositiveMatch if true a `IN` is performed, if false, a `NOT IN` is performed
- *
- * @return mixed
- */
- public abstract function AddConditionForInOperatorUsingParam($sFilterCode, $aValues, $bPositiveMatch = true);
+ /**
+ * Shortcut to add efficient IN condition
+ *
+ * @internal
+ *
+ * @param $sFilterCode
+ * @param $aValues
+ * @param bool $bPositiveMatch if true a `IN` is performed, if false, a `NOT IN` is performed
+ *
+ * @return mixed
+ */
+ abstract public function AddConditionForInOperatorUsingParam($sFilterCode, $aValues, $bPositiveMatch = true);
/**
- * @internal
+ * @internal
* @return string a unique param name
*/
- protected function GenerateUniqueParamName() {
- return str_replace('.', '', 'param_'.microtime(true).rand(0,100));
+ protected function GenerateUniqueParamName()
+ {
+ return str_replace('.', '', 'param_'.microtime(true).rand(0, 100));
}
////////////////////////////////////////////////////////////////////////////
@@ -1229,7 +1148,7 @@ abstract class DBSearch
//
////////////////////////////////////////////////////////////////////////////
protected static $m_bDebugQuery = false;
- protected static $m_aQueriesLog = array();
+ protected static $m_aQueriesLog = [];
protected static $m_bQueryCacheEnabled = false;
protected static $m_bUseAPCCache = false;
protected static $m_iQueryCacheTTL = 3600;
@@ -1237,30 +1156,30 @@ abstract class DBSearch
protected static $m_bIndentQueries = false;
protected static $m_bOptimizeQueries = false;
- /**
- * @internal
- */
+ /**
+ * @internal
+ */
public static function StartDebugQuery()
{
$aBacktrace = debug_backtrace();
self::$m_bDebugQuery = true;
}
- /**
- * @internal
- */
+ /**
+ * @internal
+ */
public static function StopDebugQuery()
{
self::$m_bDebugQuery = false;
}
- /**
- * @internal
- *
- * @param bool $bEnabled
- * @param bool $bUseAPC
- * @param int $iTimeToLive
- */
+ /**
+ * @internal
+ *
+ * @param bool $bEnabled
+ * @param bool $bUseAPC
+ * @param int $iTimeToLive
+ */
public static function EnableQueryCache($bEnabled, $bUseAPC, $iTimeToLive = 3600)
{
self::$m_bQueryCacheEnabled = $bEnabled;
@@ -1268,28 +1187,28 @@ abstract class DBSearch
self::$m_iQueryCacheTTL = $iTimeToLive;
}
- /**
- * @internal
- * @param $bEnabled
- */
+ /**
+ * @internal
+ * @param $bEnabled
+ */
public static function EnableQueryTrace($bEnabled)
{
self::$m_bTraceQueries = $bEnabled;
}
- /**
- * @internal
- * @param $bEnabled
- */
+ /**
+ * @internal
+ * @param $bEnabled
+ */
public static function EnableQueryIndentation($bEnabled)
{
self::$m_bIndentQueries = $bEnabled;
}
- /**
- * @internal
- * @param $bEnabled
- */
+ /**
+ * @internal
+ * @param $bEnabled
+ */
public static function EnableOptimizeQuery($bEnabled)
{
self::$m_bOptimizeQueries = $bEnabled;
@@ -1313,46 +1232,39 @@ abstract class DBSearch
*/
protected function AddQueryTraceSelect($sOql, $aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount, $sSql)
{
- if (self::$m_bTraceQueries)
- {
- $aQueryData = array(
+ if (self::$m_bTraceQueries) {
+ $aQueryData = [
'type' => 'select',
'order_by' => $aOrderBy,
'att_to_load' => $aAttToLoad,
'limit_count' => $iLimitCount,
'limit_start' => $iLimitStart,
- 'is_count' => $bGetCount
- );
+ 'is_count' => $bGetCount,
+ ];
DBSearch::EnableQueryTrace(false);
$aQueryData['oql'] = $this->ToOQL(true, $aArgs);
DBSearch::EnableQueryTrace(true);
- if (!empty($aAttToLoad))
- {
- $aAttToLoadNames = array();
- foreach ($aAttToLoad as $sClass => $aAttributes)
- {
- $aAttToLoadNames[$sClass] = array();
- foreach ($aAttributes as $sAttCode => $oAttDef)
- {
+ if (!empty($aAttToLoad)) {
+ $aAttToLoadNames = [];
+ foreach ($aAttToLoad as $sClass => $aAttributes) {
+ $aAttToLoadNames[$sClass] = [];
+ foreach ($aAttributes as $sAttCode => $oAttDef) {
$aAttToLoadNames[$sClass][] = $sAttCode;
}
}
- }
- else
- {
+ } else {
$aAttToLoadNames = null;
}
$aQueryData['att_to_load'] = $aAttToLoadNames;
$hLogFile = @fopen(APPROOT.'log/oql_records.txt', 'a');
- if ($hLogFile !== false)
- {
- flock($hLogFile,LOCK_EX);
- fwrite($hLogFile,serialize($aQueryData)."\n");
+ if ($hLogFile !== false) {
+ flock($hLogFile, LOCK_EX);
+ fwrite($hLogFile, serialize($aQueryData)."\n");
fflush($hLogFile);
- flock($hLogFile,LOCK_UN);
+ flock($hLogFile, LOCK_UN);
fclose($hLogFile);
}
}
@@ -1376,9 +1288,8 @@ abstract class DBSearch
*/
protected function AddQueryTraceGroupBy($aArgs, $aGroupByExpr, $bExcludeNullValues, $aSelectExpr, $aOrderBy, $iLimitCount, $iLimitStart, $sSql)
{
- if (self::$m_bTraceQueries)
- {
- $aQueryData = array(
+ if (self::$m_bTraceQueries) {
+ $aQueryData = [
'type' => 'group_by',
'order_by' => $aOrderBy,
'group_by_expr' => $aGroupByExpr,
@@ -1386,89 +1297,77 @@ abstract class DBSearch
'select_expr' => $aSelectExpr,
'limit_count' => $iLimitCount,
'limit_start' => $iLimitStart,
- );
+ ];
$aQueryData['oql'] = $this->ToOQL(true, $aArgs);
$aQueryData['group_by_expr'] = Expression::ConvertArrayToOQL($aQueryData['group_by_expr'], $aArgs);
$aQueryData['select_expr'] = Expression::ConvertArrayToOQL($aQueryData['select_expr'], $aArgs);
$hLogFile = @fopen(APPROOT.'log/oql_group_by_records.txt', 'a');
- if ($hLogFile !== false)
- {
- flock($hLogFile,LOCK_EX);
- fwrite($hLogFile,serialize($aQueryData)."\n");
+ if ($hLogFile !== false) {
+ flock($hLogFile, LOCK_EX);
+ fwrite($hLogFile, serialize($aQueryData)."\n");
fflush($hLogFile);
- flock($hLogFile,LOCK_UN);
+ flock($hLogFile, LOCK_UN);
fclose($hLogFile);
}
}
}
- /**
- * @internal
- *
- * @param $aQueryData
- * @param $sOql
- * @param $sSql
- *
- * @throws MySQLException
- */
+ /**
+ * @internal
+ *
+ * @param $aQueryData
+ * @param $sOql
+ * @param $sSql
+ *
+ * @throws MySQLException
+ */
protected static function AddQueryTrace($aQueryData, $sOql, $sSql)
{
- if (self::$m_bTraceQueries)
- {
+ if (self::$m_bTraceQueries) {
$sQueryId = md5(serialize($aQueryData));
$sMySQLQueryId = md5($sSql);
- if(!isset(self::$m_aQueriesLog[$sQueryId]))
- {
+ if (!isset(self::$m_aQueriesLog[$sQueryId])) {
self::$m_aQueriesLog[$sQueryId]['data'] = serialize($aQueryData);
self::$m_aQueriesLog[$sQueryId]['oql'] = $sOql;
self::$m_aQueriesLog[$sQueryId]['hits'] = 1;
- }
- else
- {
+ } else {
self::$m_aQueriesLog[$sQueryId]['hits']++;
}
- if(!isset(self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]))
- {
+ if (!isset(self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId])) {
self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['sql'] = $sSql;
self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['count'] = 1;
$iTableCount = count(CMDBSource::ExplainQuery($sSql));
self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['table_count'] = $iTableCount;
- }
- else
- {
+ } else {
self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['count']++;
}
}
}
- /**
- * @internal
- */
+ /**
+ * @internal
+ */
public static function RecordQueryTrace()
{
- if (!self::$m_bTraceQueries)
- {
+ if (!self::$m_bTraceQueries) {
return;
}
$iOqlCount = count(self::$m_aQueriesLog);
$iSqlCount = 0;
- foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData)
- {
+ foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData) {
$iSqlCount += $aOqlData['hits'];
}
$sHtml = "Stats on SELECT queries: OQL=$iOqlCount, SQL=$iSqlCount \n";
- foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData)
- {
+ foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData) {
$sOql = $aOqlData['oql'];
$sHits = $aOqlData['hits'];
$sHtml .= "$sHits hits for OQL query: $sOql
\n";
$sHtml .= "\n";
- foreach($aOqlData['queries'] as $aSqlData)
- {
+ foreach ($aOqlData['queries'] as $aSqlData) {
$sQuery = $aSqlData['sql'];
$sSqlHits = $aSqlData['count'];
$iTableCount = $aSqlData['table_count'];
@@ -1485,60 +1384,49 @@ abstract class DBSearch
// Cumulate the queries
$sAllQueries = utils::GetDataPath().'queries.log';
- if (file_exists($sAllQueries))
- {
+ if (file_exists($sAllQueries)) {
// Merge the new queries into the existing log
include($sAllQueries);
- $aQueriesLog = array();
- foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData)
- {
- if (!array_key_exists($sQueryId, $aQueriesLog))
- {
+ $aQueriesLog = [];
+ foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData) {
+ if (!array_key_exists($sQueryId, $aQueriesLog)) {
$aQueriesLog[$sQueryId] = $aOqlData;
}
}
- }
- else
- {
+ } else {
$aQueriesLog = self::$m_aQueriesLog;
}
$sLog = "".$aBacktrace[1]["function"]."";
- if (is_object($value))
- {
+ if (is_object($value)) {
echo "$sIndent$sFunction:\n \n";
print_r($value);
echo " \n";
- }
- else
- {
+ } else {
echo "$sIndent$sFunction: $value \n";
}
}
@@ -1556,63 +1444,49 @@ abstract class DBSearch
public function DBBulkWriteArchiveFlag($bArchive)
{
$sClass = $this->GetClass();
- if (!MetaModel::IsArchivable($sClass))
- {
+ if (!MetaModel::IsArchivable($sClass)) {
throw new Exception($sClass.' is not an archivable class');
}
$iFlag = $bArchive ? 1 : 0;
$oSet = new DBObjectSet($this);
- if (MetaModel::IsStandaloneClass($sClass))
- {
- $oSet->OptimizeColumnLoad(array($this->GetClassAlias() => array()));
- $aIds = array($sClass => $oSet->GetColumnAsArray('id'));
- }
- else
- {
- $oSet->OptimizeColumnLoad(array($this->GetClassAlias() => array('finalclass')));
+ if (MetaModel::IsStandaloneClass($sClass)) {
+ $oSet->OptimizeColumnLoad([$this->GetClassAlias() => []]);
+ $aIds = [$sClass => $oSet->GetColumnAsArray('id')];
+ } else {
+ $oSet->OptimizeColumnLoad([$this->GetClassAlias() => ['finalclass']]);
$aTemp = $oSet->GetColumnAsArray('finalclass');
- $aIds = array();
- foreach ($aTemp as $iObjectId => $sObjectClass)
- {
+ $aIds = [];
+ foreach ($aTemp as $iObjectId => $sObjectClass) {
$aIds[$sObjectClass][$iObjectId] = $iObjectId;
}
}
- foreach ($aIds as $sFinalClass => $aObjectIds)
- {
+ foreach ($aIds as $sFinalClass => $aObjectIds) {
$sIds = implode(', ', $aObjectIds);
$sArchiveRoot = MetaModel::GetAttributeOrigin($sFinalClass, 'archive_flag');
$sRootTable = MetaModel::DBGetTable($sArchiveRoot);
$sRootKey = MetaModel::DBGetKey($sArchiveRoot);
- $aJoins = array("`$sRootTable`");
- $aUpdates = array();
- foreach (MetaModel::EnumParentClasses($sFinalClass, ENUM_PARENT_CLASSES_ALL) as $sParentClass)
- {
- if (!MetaModel::IsValidAttCode($sParentClass, 'archive_flag'))
- {
+ $aJoins = ["`$sRootTable`"];
+ $aUpdates = [];
+ foreach (MetaModel::EnumParentClasses($sFinalClass, ENUM_PARENT_CLASSES_ALL) as $sParentClass) {
+ if (!MetaModel::IsValidAttCode($sParentClass, 'archive_flag')) {
continue;
}
$sTable = MetaModel::DBGetTable($sParentClass);
$aUpdates[] = "`$sTable`.`archive_flag` = $iFlag";
- if ($sParentClass == $sArchiveRoot)
- {
- if ($bArchive)
- {
+ if ($sParentClass == $sArchiveRoot) {
+ if ($bArchive) {
// Set the date (do not change it)
$sDate = '"'.date(AttributeDate::GetSQLFormat()).'"';
$aUpdates[] = "`$sTable`.`archive_date` = coalesce(`$sTable`.`archive_date`, $sDate)";
- }
- else
- {
+ } else {
// Reset the date
$aUpdates[] = "`$sTable`.`archive_date` = null";
}
- }
- else
- {
+ } else {
$sKey = MetaModel::DBGetKey($sParentClass);
$aJoins[] = "`$sTable` ON `$sTable`.`$sKey` = `$sRootTable`.`$sRootKey`";
}
@@ -1624,9 +1498,9 @@ abstract class DBSearch
}
}
- /**
- * @internal
- */
+ /**
+ * @internal
+ */
public function UpdateContextFromUser()
{
$this->SetShowObsoleteData(utils::ShowObsoleteData());
@@ -1649,5 +1523,5 @@ abstract class DBSearch
*
* @return array{\VariableExpression}
*/
- abstract function GetExpectedArguments(): array;
+ abstract public function GetExpectedArguments(): array;
}
diff --git a/core/dbunionsearch.class.php b/core/dbunionsearch.class.php
index bd2336936..9d3836f0e 100644
--- a/core/dbunionsearch.class.php
+++ b/core/dbunionsearch.class.php
@@ -1,4 +1,5 @@
classes (lowest common ancestors) computed at construction
protected $aColumnToAliases;
- /**
- * DBUnionSearch constructor.
- *
- * @api
- *
- * @param $aSearches
- *
- * @throws CoreException
- */
+ /**
+ * DBUnionSearch constructor.
+ *
+ * @api
+ *
+ * @param $aSearches
+ *
+ * @throws CoreException
+ */
public function __construct($aSearches)
{
- if (count ($aSearches) == 0)
- {
+ if (count($aSearches) == 0) {
throw new CoreException('A DBUnionSearch must be made of at least one search');
}
- $this->aSearches = array();
- foreach ($aSearches as $oSearch)
- {
- if ($oSearch instanceof DBUnionSearch)
- {
- foreach ($oSearch->aSearches as $oSubSearch)
- {
+ $this->aSearches = [];
+ foreach ($aSearches as $oSearch) {
+ if ($oSearch instanceof DBUnionSearch) {
+ foreach ($oSearch->aSearches as $oSubSearch) {
$this->aSearches[] = $oSubSearch->DeepClone();
}
} else {
@@ -69,15 +66,16 @@ class DBUnionSearch extends DBSearch
public function IsAllDataAllowed()
{
foreach ($this->aSearches as $oSearch) {
- if ($oSearch->IsAllDataAllowed() === false) return false;
+ if ($oSearch->IsAllDataAllowed() === false) {
+ return false;
+ }
}
return true;
}
public function SetArchiveMode($bEnable)
{
- foreach ($this->aSearches as $oSearch)
- {
+ foreach ($this->aSearches as $oSearch) {
$oSearch->SetArchiveMode($bEnable);
}
parent::SetArchiveMode($bEnable);
@@ -85,8 +83,7 @@ class DBUnionSearch extends DBSearch
public function SetShowObsoleteData($bShow)
{
- foreach ($this->aSearches as $oSearch)
- {
+ foreach ($this->aSearches as $oSearch) {
$oSearch->SetShowObsoleteData($bShow);
}
parent::SetShowObsoleteData($bShow);
@@ -102,31 +99,25 @@ class DBUnionSearch extends DBSearch
// 1 - Collect all the column/classes
$aColumnToClasses = [];
$this->aColumnToAliases = [];
- foreach ($this->aSearches as $iPos => $oSearch)
- {
+ foreach ($this->aSearches as $iPos => $oSearch) {
$aSelected = array_values($oSearch->GetSelectedClasses());
- if ($iPos != 0)
- {
- if (count($aSelected) < count($aColumnToClasses))
- {
- throw new Exception('Too few selected classes in the subquery #'.($iPos+1));
+ if ($iPos != 0) {
+ if (count($aSelected) < count($aColumnToClasses)) {
+ throw new Exception('Too few selected classes in the subquery #'.($iPos + 1));
}
- if (count($aSelected) > count($aColumnToClasses))
- {
- throw new Exception('Too many selected classes in the subquery #'.($iPos+1));
+ if (count($aSelected) > count($aColumnToClasses)) {
+ throw new Exception('Too many selected classes in the subquery #'.($iPos + 1));
}
}
- foreach ($aSelected as $iColumn => $sClass)
- {
+ foreach ($aSelected as $iColumn => $sClass) {
$aColumnToClasses[$iColumn][$iPos] = $sClass;
}
// Store the aliases by column to map them later (the first query impose the aliases)
$aAliases = array_keys($oSearch->GetSelectedClasses());
- foreach ($aAliases as $iColumn => $sAlias)
- {
+ foreach ($aAliases as $iColumn => $sAlias) {
$this->aColumnToAliases[$iColumn][$iPos] = $sAlias;
}
}
@@ -137,13 +128,11 @@ class DBUnionSearch extends DBSearch
// 3 - Compute alias => lowest common ancestor
$this->aSelectedClasses = [];
- foreach ($aColumnToClasses as $iColumn => $aClasses)
- {
+ foreach ($aColumnToClasses as $iColumn => $aClasses) {
$sAlias = $aColumnToAlias[$iColumn];
$sAncestor = MetaModel::GetLowestCommonAncestor($aClasses);
- if (is_null($sAncestor))
- {
- throw new Exception('Could not find a common ancestor for the column '.($iColumn+1).' (Classes: '.implode(', ', $aClasses).')');
+ if (is_null($sAncestor)) {
+ throw new Exception('Could not find a common ancestor for the column '.($iColumn + 1).' (Classes: '.implode(', ', $aClasses).')');
}
$this->aSelectedClasses[$sAlias] = $sAncestor;
}
@@ -164,12 +153,9 @@ class DBUnionSearch extends DBSearch
*/
public function GetClassName($sAlias)
{
- if (array_key_exists($sAlias, $this->aSelectedClasses))
- {
+ if (array_key_exists($sAlias, $this->aSelectedClasses)) {
return $this->aSelectedClasses[$sAlias];
- }
- else
- {
+ } else {
throw new CoreException("Invalid class alias '$sAlias'");
}
}
@@ -185,20 +171,16 @@ class DBUnionSearch extends DBSearch
return key($this->aSelectedClasses);
}
-
/**
* Change the class (only subclasses are supported as of now, because the conditions must fit the new class)
* Defaults to the first selected class
* Only the selected classes can be changed
- */
+ */
public function ChangeClass($sNewClass, $sAlias = null)
{
- if (is_null($sAlias))
- {
+ if (is_null($sAlias)) {
$sAlias = $this->GetClassAlias();
- }
- elseif (!array_key_exists($sAlias, $this->aSelectedClasses))
- {
+ } elseif (!array_key_exists($sAlias, $this->aSelectedClasses)) {
// discard silently - necessary when recursing (??? copied from DBObjectSearch)
return;
}
@@ -207,8 +189,7 @@ class DBUnionSearch extends DBSearch
$iColumn = array_search($sAlias, array_keys($this->aSelectedClasses));
// 2 - change for each search
- foreach ($this->aSearches as $oSearch)
- {
+ foreach ($this->aSearches as $oSearch) {
$aSearchAliases = array_keys($oSearch->GetSelectedClasses());
$sSearchAlias = $aSearchAliases[$iColumn];
$oSearch->ChangeClass($sNewClass, $sSearchAlias);
@@ -279,38 +260,31 @@ class DBUnionSearch extends DBSearch
public function RenameAlias($sOldName, $sNewName)
{
$bRet = false;
- foreach ($this->aSearches as $oSearch)
- {
+ foreach ($this->aSearches as $oSearch) {
$bRet = $oSearch->RenameAlias($sOldName, $sNewName) || $bRet;
}
return $bRet;
}
- public function RenameAliasesInNameSpace($aClassAliases, $aAliasTranslation = array())
+ public function RenameAliasesInNameSpace($aClassAliases, $aAliasTranslation = [])
{
- foreach ($this->aSearches as $oSearch)
- {
+ foreach ($this->aSearches as $oSearch) {
$oSearch->RenameAliasesInNameSpace($aClassAliases, $aAliasTranslation);
}
}
public function TranslateConditions($aTranslationData, $bMatchAll = true, $bMarkFieldsAsResolved = true)
{
- foreach ($this->aSearches as $oSearch)
- {
+ foreach ($this->aSearches as $oSearch) {
$oSearch->TranslateConditions($aTranslationData, $bMatchAll, $bMarkFieldsAsResolved);
}
}
-
-
public function IsAny()
{
$bIsAny = true;
- foreach ($this->aSearches as $oSearch)
- {
- if (!$oSearch->IsAny())
- {
+ foreach ($this->aSearches as $oSearch) {
+ if (!$oSearch->IsAny()) {
$bIsAny = false;
break;
}
@@ -320,8 +294,7 @@ class DBUnionSearch extends DBSearch
public function ResetCondition()
{
- foreach ($this->aSearches as $oSearch)
- {
+ foreach ($this->aSearches as $oSearch) {
$oSearch->ResetCondition();
}
}
@@ -329,13 +302,10 @@ class DBUnionSearch extends DBSearch
public function MergeConditionExpression($oExpression)
{
$aAliases = array_keys($this->aSelectedClasses);
- foreach ($this->aSearches as $iSearchIndex => $oSearch)
- {
+ foreach ($this->aSearches as $iSearchIndex => $oSearch) {
$oClonedExpression = $oExpression->DeepClone();
- if ($iSearchIndex != 0)
- {
- foreach (array_keys($oSearch->GetSelectedClasses()) as $iColumn => $sSearchAlias)
- {
+ if ($iSearchIndex != 0) {
+ foreach (array_keys($oSearch->GetSelectedClasses()) as $iColumn => $sSearchAlias) {
$oClonedExpression->RenameAlias($aAliases[$iColumn], $sSearchAlias);
}
}
@@ -346,13 +316,10 @@ class DBUnionSearch extends DBSearch
public function AddConditionExpression($oExpression)
{
$aAliases = array_keys($this->aSelectedClasses);
- foreach ($this->aSearches as $iSearchIndex => $oSearch)
- {
+ foreach ($this->aSearches as $iSearchIndex => $oSearch) {
$oClonedExpression = $oExpression->DeepClone();
- if ($iSearchIndex != 0)
- {
- foreach (array_keys($oSearch->GetSelectedClasses()) as $iColumn => $sSearchAlias)
- {
+ if ($iSearchIndex != 0) {
+ foreach (array_keys($oSearch->GetSelectedClasses()) as $iColumn => $sSearchAlias) {
$oClonedExpression->RenameAlias($aAliases[$iColumn], $sSearchAlias);
}
}
@@ -360,18 +327,16 @@ class DBUnionSearch extends DBSearch
}
}
- public function AddNameCondition($sName)
+ public function AddNameCondition($sName)
{
- foreach ($this->aSearches as $oSearch)
- {
+ foreach ($this->aSearches as $oSearch) {
$oSearch->AddNameCondition($sName);
}
}
public function AddCondition($sFilterCode, $value, $sOpCode = null)
{
- foreach ($this->aSearches as $oSearch)
- {
+ foreach ($this->aSearches as $oSearch) {
$oSearch->AddCondition($sFilterCode, $value, $sOpCode);
}
}
@@ -379,35 +344,32 @@ class DBUnionSearch extends DBSearch
/**
* Specify a condition on external keys or link sets
* @param String sAttSpec Can be either an attribute code or extkey->[sAttSpec] or linkset->[sAttSpec] and so on, recursively
- * Example: infra_list->ci_id->location_id->country
+ * Example: infra_list->ci_id->location_id->country
* @param Object value The value to match (can be an array => IN(val1, val2...)
* @return void
*/
public function AddConditionAdvanced($sAttSpec, $value)
{
- foreach ($this->aSearches as $oSearch)
- {
+ foreach ($this->aSearches as $oSearch) {
$oSearch->AddConditionAdvanced($sAttSpec, $value);
}
}
public function AddCondition_FullText($sFullText)
{
- foreach ($this->aSearches as $oSearch)
- {
+ foreach ($this->aSearches as $oSearch) {
$oSearch->AddCondition_FullText($sFullText);
}
}
public function AddCondition_FullTextOnAttributes(array $aAttCodes, $sNeedle)
{
- foreach ($this->aSearches as $oSearch)
- {
+ foreach ($this->aSearches as $oSearch) {
$oSearch->AddCondition_FullTextOnAttributes($aAttCodes, $sNeedle);
}
}
- /**
+ /**
* @param DBObjectSearch $oFilter
* @param $sExtKeyAttCode
* @param int $iOperatorCode
@@ -415,8 +377,7 @@ class DBUnionSearch extends DBSearch
*/
public function AddCondition_PointingTo(DBObjectSearch $oFilter, $sExtKeyAttCode, $iOperatorCode = TREE_OPERATOR_EQUALS, &$aRealiasingMap = null)
{
- foreach ($this->aSearches as $oSearch)
- {
+ foreach ($this->aSearches as $oSearch) {
$oConditionFilter = $oFilter->DeepClone();
$oSearch->AddCondition_PointingTo($oConditionFilter, $sExtKeyAttCode, $iOperatorCode, $aRealiasingMap);
}
@@ -430,8 +391,7 @@ class DBUnionSearch extends DBSearch
*/
public function AddCondition_ReferencedBy(DBObjectSearch $oFilter, $sForeignExtKeyAttCode, $iOperatorCode = TREE_OPERATOR_EQUALS, &$aRealiasingMap = null)
{
- foreach ($this->aSearches as $oSearch)
- {
+ foreach ($this->aSearches as $oSearch) {
$oConditionFilter = $oFilter->DeepClone();
$oSearch->AddCondition_ReferencedBy($oConditionFilter, $sForeignExtKeyAttCode, $iOperatorCode, $aRealiasingMap);
}
@@ -439,9 +399,8 @@ class DBUnionSearch extends DBSearch
public function Filter($sClassAlias, DBSearch $oFilter)
{
- $aSearches = array();
- foreach ($this->aSearches as $oSearch)
- {
+ $aSearches = [];
+ foreach ($this->aSearches as $oSearch) {
if (!$oSearch->IsAllDataAllowed()) {
$aSearches[] = $oSearch->Filter($sClassAlias, $oFilter);
} else {
@@ -453,9 +412,8 @@ class DBUnionSearch extends DBSearch
public function Intersect(DBSearch $oFilter)
{
- $aSearches = array();
- foreach ($this->aSearches as $oSearch)
- {
+ $aSearches = [];
+ foreach ($this->aSearches as $oSearch) {
$aSearches[] = $oSearch->Intersect($oFilter);
}
return new DBUnionSearch($aSearches);
@@ -463,17 +421,15 @@ class DBUnionSearch extends DBSearch
public function SetInternalParams($aParams)
{
- foreach ($this->aSearches as $oSearch)
- {
+ foreach ($this->aSearches as $oSearch) {
$oSearch->SetInternalParams($aParams);
}
}
public function GetInternalParams()
{
- $aParams = array();
- foreach ($this->aSearches as $oSearch)
- {
+ $aParams = [];
+ foreach ($this->aSearches as $oSearch) {
$aParams = array_merge($oSearch->GetInternalParams(), $aParams);
}
return $aParams;
@@ -481,9 +437,8 @@ class DBUnionSearch extends DBSearch
public function GetQueryParams()
{
- $aParams = array();
- foreach ($this->aSearches as $oSearch)
- {
+ $aParams = [];
+ foreach ($this->aSearches as $oSearch) {
$aParams = array_merge($oSearch->GetQueryParams(), $aParams);
}
return $aParams;
@@ -492,7 +447,7 @@ class DBUnionSearch extends DBSearch
public function ListConstantFields()
{
// Somewhat complex to implement for unions, for a poor benefit
- return array();
+ return [];
}
/**
@@ -501,20 +456,18 @@ class DBUnionSearch extends DBSearch
*/
public function ApplyParameters($aArgs)
{
- foreach ($this->aSearches as $oSearch)
- {
+ foreach ($this->aSearches as $oSearch) {
$oSearch->ApplyParameters($aArgs);
}
}
/**
* Overloads for query building
- */
+ */
public function ToOQL($bDevelopParams = false, $aContextParams = null, $bWithAllowAllFlag = false)
{
- $aSubQueries = array();
- foreach ($this->aSearches as $oSearch)
- {
+ $aSubQueries = [];
+ foreach ($this->aSearches as $oSearch) {
$aSubQueries[] = $oSearch->ToOQL($bDevelopParams, $aContextParams, $bWithAllowAllFlag);
}
$sRet = implode(' UNION ', $aSubQueries);
@@ -527,9 +480,8 @@ class DBUnionSearch extends DBSearch
*/
public function ToJSON()
{
- $sRet = array('unions' => array());
- foreach ($this->aSearches as $oSearch)
- {
+ $sRet = ['unions' => []];
+ foreach ($this->aSearches as $oSearch) {
$sRet['unions'][] = $oSearch->ToJSON();
}
return $sRet;
@@ -543,21 +495,19 @@ class DBUnionSearch extends DBSearch
*/
public function RemoveDuplicateQueries()
{
- $aQueries = array();
- $aSearches = array();
+ $aQueries = [];
+ $aSearches = [];
- foreach ($this->GetSearches() as $oTmpSearch)
- {
+ foreach ($this->GetSearches() as $oTmpSearch) {
$sQuery = $oTmpSearch->ToOQL(true);
- if (!in_array($sQuery, $aQueries))
- {
+ if (!in_array($sQuery, $aQueries)) {
$aQueries[] = $sQuery;
$aSearches[] = $oTmpSearch;
}
}
$oNewSearch = new DBUnionSearch($aSearches);
-
+
return $oNewSearch;
}
@@ -567,60 +517,49 @@ class DBUnionSearch extends DBSearch
//
////////////////////////////////////////////////////////////////////////////
- public function MakeDeleteQuery($aArgs = array())
+ public function MakeDeleteQuery($aArgs = [])
{
throw new Exception('MakeDeleteQuery is not implemented for the unions!');
}
- public function MakeUpdateQuery($aValues, $aArgs = array())
+ public function MakeUpdateQuery($aValues, $aArgs = [])
{
throw new Exception('MakeUpdateQuery is not implemented for the unions!');
}
public function GetSQLQueryStructure($aAttToLoad, $bGetCount, $aGroupByExpr = null, $aSelectedClasses = null, $aSelectExpr = null)
{
- if (count($this->aSearches) == 1)
- {
+ if (count($this->aSearches) == 1) {
return $this->aSearches[0]->GetSQLQueryStructure($aAttToLoad, $bGetCount, $aGroupByExpr, $aSelectedClasses, $aSelectExpr);
}
- $aSQLQueries = array();
+ $aSQLQueries = [];
$aAliases = array_keys($this->aSelectedClasses);
$aQueryAttToLoad = null;
- $aUnionQuerySelectExpr = array();
- foreach ($this->aSearches as $iSearch => $oSearch)
- {
+ $aUnionQuerySelectExpr = [];
+ foreach ($this->aSearches as $iSearch => $oSearch) {
$aSearchAliases = array_keys($oSearch->GetSelectedClasses());
// The selected classes from the query build perspective are the lowest common ancestors amongst the various queries
// (used when it comes to determine which attributes must be selected)
- $aSearchSelectedClasses = array();
- foreach ($aSearchAliases as $iColumn => $sSearchAlias)
- {
+ $aSearchSelectedClasses = [];
+ foreach ($aSearchAliases as $iColumn => $sSearchAlias) {
$sAlias = $aAliases[$iColumn];
$aSearchSelectedClasses[$sSearchAlias] = $this->aSelectedClasses[$sAlias];
}
- if ($bGetCount)
- {
+ if ($bGetCount) {
// Select only ids for the count to allow optimization of joins
- foreach($aSearchAliases as $sSearchAlias)
- {
- $aQueryAttToLoad[$sSearchAlias] = array();
+ foreach ($aSearchAliases as $sSearchAlias) {
+ $aQueryAttToLoad[$sSearchAlias] = [];
}
- }
- else
- {
- if (is_null($aAttToLoad))
- {
+ } else {
+ if (is_null($aAttToLoad)) {
$aQueryAttToLoad = null;
- }
- else
- {
+ } else {
// (Eventually) Transform the aliases
- $aQueryAttToLoad = array();
- foreach($aAttToLoad as $sAlias => $aAttributes)
- {
+ $aQueryAttToLoad = [];
+ foreach ($aAttToLoad as $sAlias => $aAttributes) {
$iColumn = array_search($sAlias, $aAliases);
$sQueryAlias = ($iColumn === false) ? $sAlias : $aSearchAliases[$iColumn];
$aQueryAttToLoad[$sQueryAlias] = $aAttributes;
@@ -628,66 +567,51 @@ class DBUnionSearch extends DBSearch
}
}
- if (is_null($aGroupByExpr))
- {
+ if (is_null($aGroupByExpr)) {
$aQueryGroupByExpr = null;
- }
- else
- {
+ } else {
// Clone (and eventually transform) the group by expressions
- $aQueryGroupByExpr = array();
- $aTranslationData = array();
+ $aQueryGroupByExpr = [];
+ $aTranslationData = [];
$aQueryColumns = array_keys($oSearch->GetSelectedClasses());
- foreach ($aAliases as $iColumn => $sAlias)
- {
+ foreach ($aAliases as $iColumn => $sAlias) {
$sQueryAlias = $aQueryColumns[$iColumn];
$aTranslationData[$sAlias]['*'] = $sQueryAlias;
$aQueryGroupByExpr[$sAlias.'id'] = new FieldExpression('id', $sQueryAlias);
}
- foreach ($aGroupByExpr as $sExpressionAlias => $oExpression)
- {
+ foreach ($aGroupByExpr as $sExpressionAlias => $oExpression) {
$aQueryGroupByExpr[$sExpressionAlias] = $oExpression->Translate($aTranslationData, false, false);
}
}
- if (is_null($aSelectExpr))
- {
+ if (is_null($aSelectExpr)) {
$aQuerySelectExpr = null;
- }
- else
- {
- $aQuerySelectExpr = array();
- $aTranslationData = array();
+ } else {
+ $aQuerySelectExpr = [];
+ $aTranslationData = [];
$aQueryColumns = array_keys($oSearch->GetSelectedClasses());
- foreach($aAliases as $iColumn => $sAlias)
- {
+ foreach ($aAliases as $iColumn => $sAlias) {
$sQueryAlias = $aQueryColumns[$iColumn];
$aTranslationData[$sAlias]['*'] = $sQueryAlias;
}
- foreach($aSelectExpr as $sExpressionAlias => $oExpression)
- {
- $oExpression->Browse(function ($oNode) use (&$aQuerySelectExpr, &$aTranslationData)
- {
- if ($oNode instanceof FieldExpression)
- {
+ foreach ($aSelectExpr as $sExpressionAlias => $oExpression) {
+ $oExpression->Browse(function ($oNode) use (&$aQuerySelectExpr, &$aTranslationData) {
+ if ($oNode instanceof FieldExpression) {
$sAlias = $oNode->GetParent()."__".$oNode->GetName();
- if (!key_exists($sAlias, $aQuerySelectExpr))
- {
+ if (!key_exists($sAlias, $aQuerySelectExpr)) {
$aQuerySelectExpr[$sAlias] = $oNode->Translate($aTranslationData, false, false);
}
$aTranslationData[$oNode->GetParent()][$oNode->GetName()] = new FieldExpression($sAlias);
}
});
// Only done for the first select as aliases are named after the first query
- if (!array_key_exists($sExpressionAlias, $aUnionQuerySelectExpr))
- {
+ if (!array_key_exists($sExpressionAlias, $aUnionQuerySelectExpr)) {
$aUnionQuerySelectExpr[$sExpressionAlias] = $oExpression->Translate($aTranslationData, false, false);
}
}
}
$oSubQuery = $oSearch->GetSQLQueryStructure($aQueryAttToLoad, false, $aQueryGroupByExpr, $aSearchSelectedClasses, $aQuerySelectExpr);
- if (count($aSearchAliases) > 1)
- {
+ if (count($aSearchAliases) > 1) {
// Necessary to make sure that selected columns will match throughout all the queries
// (default order of selected fields depending on the order of JOINS)
$oSubQuery->SortSelectedFields();
@@ -698,17 +622,17 @@ class DBUnionSearch extends DBSearch
$oSQLQuery = new SQLUnionQuery($aSQLQueries, $aGroupByExpr, $aUnionQuerySelectExpr);
//MyHelpers::var_dump_html($oSQLQuery, true);
//MyHelpers::var_dump_html($oSQLQuery->RenderSelect(), true);
- if (self::$m_bDebugQuery) $oSQLQuery->DisplayHtml();
+ if (self::$m_bDebugQuery) {
+ $oSQLQuery->DisplayHtml();
+ }
return $oSQLQuery;
}
protected function IsDataFiltered()
{
$bIsAllDataFiltered = true;
- foreach ($this->aSearches as $oSearch)
- {
- if (!$oSearch->IsDataFiltered())
- {
+ foreach ($this->aSearches as $oSearch) {
+ if (!$oSearch->IsDataFiltered()) {
$bIsAllDataFiltered = false;
break;
}
@@ -718,19 +642,15 @@ class DBUnionSearch extends DBSearch
protected function SetDataFiltered()
{
- foreach ($this->aSearches as $oSearch)
- {
+ foreach ($this->aSearches as $oSearch) {
$oSearch->SetDataFiltered();
}
}
-
-
public function AddConditionForInOperatorUsingParam($sFilterCode, $aValues, $bPositiveMatch = true)
{
$sInParamName = $this->GenerateUniqueParamName();
- foreach ($this->aSearches as $iSearchIndex => $oSearch)
- {
+ foreach ($this->aSearches as $iSearchIndex => $oSearch) {
$oFieldExpression = new FieldExpression($sFilterCode, $oSearch->GetClassAlias());
$sOperator = $bPositiveMatch ? 'IN' : 'NOT IN';
@@ -738,17 +658,16 @@ class DBUnionSearch extends DBSearch
$oParamExpression = new VariableExpression($sInParamName);
$oSearch->GetInternalParamsByRef()[$sInParamName] = $aValues;
- $oListExpression = new ListExpression(array($oParamExpression));
+ $oListExpression = new ListExpression([$oParamExpression]);
$oInCondition = new BinaryExpression($oFieldExpression, $sOperator, $oListExpression);
$oSearch->AddConditionExpression($oInCondition);
}
}
- function GetExpectedArguments(): array
+ public function GetExpectedArguments(): array
{
- $aVariableCriteria = array();
- foreach ($this->aSearches as $oSearch)
- {
+ $aVariableCriteria = [];
+ foreach ($this->aSearches as $oSearch) {
$aVariableCriteria = array_merge($aVariableCriteria, $oSearch->GetExpectedArguments());
}
diff --git a/core/displayablegraph.class.inc.php b/core/displayablegraph.class.inc.php
index f454c030e..f1e378cdf 100644
--- a/core/displayablegraph.class.inc.php
+++ b/core/displayablegraph.class.inc.php
@@ -1,4 +1,5 @@
x - $oNode->x;
$dy = $this->y - $oNode->y;
- $d2 = $dx*$dx + $dy*$dy - $this->GetHeight()*$this->GetHeight();
- if ($d2 < 40)
- {
+ $d2 = $dx * $dx + $dy * $dy - $this->GetHeight() * $this->GetHeight();
+ if ($d2 < 40) {
$d2 = 40;
}
return $d2;
@@ -94,7 +94,7 @@ class DisplayableNode extends GraphNode
public function GetForRaphael($aContextDefs)
{
- $aNode = array();
+ $aNode = [];
$aNode['shape'] = 'icon';
$aNode['icon_url'] = $this->GetIconURL();
$aNode['width'] = 32;
@@ -103,19 +103,17 @@ class DisplayableNode extends GraphNode
$aNode['obj_key'] = $this->GetProperty('object')->GetKey();
$aNode['sink'] = ($this->GetProperty('sink') == true);
$aNode['x'] = $this->x;
- $aNode['y']= $this->y;
+ $aNode['y'] = $this->y;
$aNode['label'] = $this->GetLabel();
$aNode['id'] = $this->GetId();
$fOpacity = ($this->GetProperty('is_reached') ? 1 : 0.4);
- $aNode['icon_attr'] = array('opacity' => $fOpacity);
- $aNode['text_attr'] = array('opacity' => $fOpacity);
+ $aNode['icon_attr'] = ['opacity' => $fOpacity];
+ $aNode['text_attr'] = ['opacity' => $fOpacity];
$aNode['tooltip'] = $this->GetTooltip($aContextDefs);
- $aNode['context_icons'] = array();
+ $aNode['context_icons'] = [];
$aContextRootCauses = $this->GetProperty('context_root_causes');
- if (!is_null($aContextRootCauses))
- {
- foreach($aContextRootCauses as $key => $aObjects)
- {
+ if (!is_null($aContextRootCauses)) {
+ foreach ($aContextRootCauses as $key => $aObjects) {
$aNode['context_icons'][] = utils::GetAbsoluteUrlModulesRoot().$aContextDefs[$key]['icon'];
}
}
@@ -132,10 +130,10 @@ class DisplayableNode extends GraphNode
$sIconPath = str_replace(utils::GetAbsoluteUrlModulesRoot(), APPROOT.'env-'.utils::GetCurrentEnvironment().'/', $sIconUrl);
if ($this->GetProperty('source')) {
- $oPdf->SetLineStyle(array('width' => 2 * $fScale, 'cap' => 'round', 'join' => 'miter', 'dash' => 0, 'color' => array(204, 51, 51)));
+ $oPdf->SetLineStyle(['width' => 2 * $fScale, 'cap' => 'round', 'join' => 'miter', 'dash' => 0, 'color' => [204, 51, 51]]);
$oPdf->Circle($this->x * $fScale, $this->y * $fScale, 16 * 1.25 * $fScale, 0, 360, 'D');
- } else if ($this->GetProperty('sink')) {
- $oPdf->SetLineStyle(array('width' => 2 * $fScale, 'cap' => 'round', 'join' => 'miter', 'dash' => 0, 'color' => array(51, 51, 204)));
+ } elseif ($this->GetProperty('sink')) {
+ $oPdf->SetLineStyle(['width' => 2 * $fScale, 'cap' => 'round', 'join' => 'miter', 'dash' => 0, 'color' => [51, 51, 204]]);
$oPdf->Circle($this->x * $fScale, $this->y * $fScale, 16 * 1.25 * $fScale, 0, 360, 'D');
}
@@ -172,10 +170,10 @@ class DisplayableNode extends GraphNode
$oPdf->setAlpha(0.6 * $Alpha);
$oPdf->SetFillColor(255, 255, 255);
$oPdf->SetDrawColor(255, 255, 255);
- $oPdf->Rect($this->x*$fScale - $width/2, ($this->y + 18)*$fScale, $width, $height, 'DF');
+ $oPdf->Rect($this->x * $fScale - $width / 2, ($this->y + 18) * $fScale, $width, $height, 'DF');
$oPdf->setAlpha($Alpha);
$oPdf->SetTextColor(0, 0, 0);
- $oPdf->Text($this->x*$fScale - $width/2, ($this->y + 18)*$fScale, $this->GetProperty('label'));
+ $oPdf->Text($this->x * $fScale - $width / 2, ($this->y + 18) * $fScale, $this->GetProperty('label'));
}
/**
@@ -188,26 +186,22 @@ class DisplayableNode extends GraphNode
$aInfo = getimagesize($sIconFile);
$im = null;
- switch($aInfo['mime'])
- {
+ switch ($aInfo['mime']) {
case 'image/png':
- if (function_exists('imagecreatefrompng'))
- {
+ if (function_exists('imagecreatefrompng')) {
$im = imagecreatefrompng($sIconFile);
}
break;
case 'image/gif':
- if (function_exists('imagecreatefromgif'))
- {
+ if (function_exists('imagecreatefromgif')) {
$im = imagecreatefromgif($sIconFile);
}
break;
case 'image/jpeg':
case 'image/jpg':
- if (function_exists('imagecreatefromjpeg'))
- {
+ if (function_exists('imagecreatefromjpeg')) {
$im = imagecreatefromjpeg($sIconFile);
}
break;
@@ -216,16 +210,13 @@ class DisplayableNode extends GraphNode
return null;
}
- if($im && imagefilter($im, IMG_FILTER_COLORIZE, 255, 255, 255))
- {
+ if ($im && imagefilter($im, IMG_FILTER_COLORIZE, 255, 255, 255)) {
$sTempImageName = $oGraph->GetTempImageName();
imagesavealpha($im, true);
imagepng($im, $sTempImageName);
imagedestroy($im);
return $sTempImageName;
- }
- else
- {
+ } else {
return null;
}
}
@@ -243,24 +234,22 @@ class DisplayableNode extends GraphNode
protected function AddToStats($oNode, &$aNodesPerClass)
{
$sClass = $oNode->GetObjectClass();
- if (!array_key_exists($sClass, $aNodesPerClass))
- {
- $aNodesPerClass[$sClass] = array(
- 'reached' => array(
+ if (!array_key_exists($sClass, $aNodesPerClass)) {
+ $aNodesPerClass[$sClass] = [
+ 'reached' => [
'count' => 0,
- 'nodes' => array(),
+ 'nodes' => [],
'icon_url' => $oNode->GetProperty('icon_url'),
- ),
- 'not_reached' => array(
+ ],
+ 'not_reached' => [
'count' => 0,
- 'nodes' => array(),
+ 'nodes' => [],
'icon_url' => $oNode->GetProperty('icon_url'),
- )
- );
+ ],
+ ];
}
$sKey = $oNode->GetProperty('is_reached') ? 'reached' : 'not_reached';
- if (!array_key_exists($oNode->GetId(), $aNodesPerClass[$sClass][$sKey]['nodes']))
- {
+ if (!array_key_exists($oNode->GetId(), $aNodesPerClass[$sClass][$sKey]['nodes'])) {
$aNodesPerClass[$sClass][$sKey]['nodes'][$oNode->GetId()] = $oNode;
$aNodesPerClass[$sClass][$sKey]['count'] += $oNode->GetObjectCount();
}
@@ -273,18 +262,13 @@ class DisplayableNode extends GraphNode
*/
protected function GetNextNodes($bDirectionDown = true)
{
- $aNextNodes = array();
- if ($bDirectionDown)
- {
- foreach($this->GetOutgoingEdges() as $oEdge)
- {
+ $aNextNodes = [];
+ if ($bDirectionDown) {
+ foreach ($this->GetOutgoingEdges() as $oEdge) {
$aNextNodes[] = $oEdge->GetSinkNode();
}
- }
- else
- {
- foreach($this->GetIncomingEdges() as $oEdge)
- {
+ } else {
+ foreach ($this->GetIncomingEdges() as $oEdge) {
$aNextNodes[] = $oEdge->GetSourceNode();
}
}
@@ -302,76 +286,50 @@ class DisplayableNode extends GraphNode
protected function ReplaceNextNodeBy(DisplayableGraph $oGraph, DisplayableNode $oNextNode, DisplayableGroupNode $oNewNode, $bDirectionDown = true)
{
$sClass = $oNewNode->GetProperty('class');
- if ($bDirectionDown)
- {
- foreach($oNextNode->GetIncomingEdges() as $oEdge)
- {
- if ($oEdge->GetSourceNode()->GetId() !== $this->GetId())
- {
- try
- {
+ if ($bDirectionDown) {
+ foreach ($oNextNode->GetIncomingEdges() as $oEdge) {
+ if ($oEdge->GetSourceNode()->GetId() !== $this->GetId()) {
+ try {
$oNewEdge = new DisplayableEdge($oGraph, $oEdge->GetId().'::'.$sClass, $oEdge->GetSourceNode(), $oNewNode);
- }
- catch(Exception $e)
- {
+ } catch (Exception $e) {
// ignore this edge
}
}
}
- foreach($oNextNode->GetOutgoingEdges() as $oEdge)
- {
- try
- {
+ foreach ($oNextNode->GetOutgoingEdges() as $oEdge) {
+ try {
$oNewEdge = new DisplayableEdge($oGraph, $oEdge->GetId().'::'.$sClass, $oNewNode, $oEdge->GetSinkNode());
- }
- catch(Exception $e)
- {
+ } catch (Exception $e) {
// ignore this edge
}
}
- }
- else
- {
- foreach($oNextNode->GetOutgoingEdges() as $oEdge)
- {
- if ($oEdge->GetSinkNode()->GetId() !== $this->GetId())
- {
- try
- {
+ } else {
+ foreach ($oNextNode->GetOutgoingEdges() as $oEdge) {
+ if ($oEdge->GetSinkNode()->GetId() !== $this->GetId()) {
+ try {
$oNewEdge = new DisplayableEdge($oGraph, $oEdge->GetId().'::'.$sClass, $oNewNode, $oEdge->GetSinkNode());
- }
- catch(Exception $e)
- {
+ } catch (Exception $e) {
// ignore this edge
}
}
}
- foreach($oNextNode->GetIncomingEdges() as $oEdge)
- {
- try
- {
+ foreach ($oNextNode->GetIncomingEdges() as $oEdge) {
+ try {
$oNewEdge = new DisplayableEdge($oGraph, $oEdge->GetId().'::'.$sClass, $oEdge->GetSourceNode(), $oNewNode);
- }
- catch(Exception $e)
- {
+ } catch (Exception $e) {
// ignore this edge
}
}
}
- if ($oGraph->GetNode($oNextNode->GetId()))
- {
+ if ($oGraph->GetNode($oNextNode->GetId())) {
$oGraph->_RemoveNode($oNextNode);
- if ($oNextNode instanceof DisplayableGroupNode)
- {
+ if ($oNextNode instanceof DisplayableGroupNode) {
// Copy all the objects of the previous group into the new group
- foreach($oNextNode->GetObjects() as $oObj)
- {
+ foreach ($oNextNode->GetObjects() as $oObj) {
$oNewNode->AddObject($oObj);
}
- }
- else
- {
+ } else {
$oNewNode->AddObject($oNextNode->GetProperty('object'));
}
}
@@ -386,32 +344,26 @@ class DisplayableNode extends GraphNode
*/
public function GroupSimilarNeighbours(DisplayableGraph $oGraph, $iThresholdCount, $bDirectionUp = false, $bDirectionDown = true)
{
- if ($this->GetProperty('grouped') === true) return;
+ if ($this->GetProperty('grouped') === true) {
+ return;
+ }
$this->SetProperty('grouped', true);
- $aNodesPerClass = array();
- foreach($this->GetNextNodes($bDirectionDown) as $oNode)
- {
+ $aNodesPerClass = [];
+ foreach ($this->GetNextNodes($bDirectionDown) as $oNode) {
$sClass = $oNode->GetObjectClass();
- if ($sClass !== null)
- {
+ if ($sClass !== null) {
$this->AddToStats($oNode, $aNodesPerClass);
- }
- else
- {
+ } else {
$oNode->GroupSimilarNeighbours($oGraph, $iThresholdCount, $bDirectionUp, $bDirectionDown);
}
}
- foreach($aNodesPerClass as $sClass => $aDefs)
- {
- foreach($aDefs as $sStatus => $aGroupProps)
- {
- if (count($aGroupProps['nodes']) >= $iThresholdCount)
- {
- $sNewId = $this->GetId().'::'.$sClass.'/'.(($sStatus == 'reached') ? '_reached': '');
+ foreach ($aNodesPerClass as $sClass => $aDefs) {
+ foreach ($aDefs as $sStatus => $aGroupProps) {
+ if (count($aGroupProps['nodes']) >= $iThresholdCount) {
+ $sNewId = $this->GetId().'::'.$sClass.'/'.(($sStatus == 'reached') ? '_reached' : '');
$oNewNode = $oGraph->GetNode($sNewId);
- if ($oNewNode == null)
- {
+ if ($oNewNode == null) {
$oNewNode = new DisplayableGroupNode($oGraph, $sNewId);
$oNewNode->SetProperty('label', 'x'.$aGroupProps['count']);
$oNewNode->SetProperty('icon_url', MetaModel::GetClassIcon($sClass, false));
@@ -420,32 +372,22 @@ class DisplayableNode extends GraphNode
$oNewNode->SetProperty('count', $aGroupProps['count']);
}
- try
- {
- if ($bDirectionDown)
- {
+ try {
+ if ($bDirectionDown) {
$oIncomingEdge = new DisplayableEdge($oGraph, $this->GetId().'-'.$oNewNode->GetId(), $this, $oNewNode);
- }
- else
- {
+ } else {
$oOutgoingEdge = new DisplayableEdge($oGraph, $this->GetId().'-'.$oNewNode->GetId(), $oNewNode, $this);
}
- }
- catch(Exception $e)
- {
+ } catch (Exception $e) {
// Ignore this redundant egde
}
- foreach($aGroupProps['nodes'] as $oNextNode)
- {
+ foreach ($aGroupProps['nodes'] as $oNextNode) {
$this->ReplaceNextNodeBy($oGraph, $oNextNode, $oNewNode, $bDirectionDown);
}
$oNewNode->GroupSimilarNeighbours($oGraph, $iThresholdCount, $bDirectionUp, $bDirectionDown);
- }
- else
- {
- foreach($aGroupProps['nodes'] as $oNode)
- {
+ } else {
+ foreach ($aGroupProps['nodes'] as $oNode) {
$oNode->GroupSimilarNeighbours($oGraph, $iThresholdCount, $bDirectionUp, $bDirectionDown);
}
}
@@ -460,12 +402,10 @@ class DisplayableNode extends GraphNode
$sSubClass = get_class($oCurrObj);
$sHtml .= $oCurrObj->GetHyperlink()." ";
$aContextRootCauses = $this->GetProperty('context_root_causes');
- if (!is_null($aContextRootCauses))
- {
- foreach($aContextRootCauses as $key => $aObjects)
- {
+ if (!is_null($aContextRootCauses)) {
+ foreach ($aContextRootCauses as $key => $aObjects) {
$aContext = $aContextDefs[$key];
- $aRootCauses = array();
+ $aRootCauses = [];
foreach ($aObjects as $oRootCause) {
$aRootCauses[] = $oRootCause->GetHyperlink();
}
@@ -474,8 +414,7 @@ class DisplayableNode extends GraphNode
$sHtml .= ' ';
}
$sHtml .= '';
- foreach(MetaModel::GetZListItems($sSubClass, 'list') as $sAttCode)
- {
+ foreach (MetaModel::GetZListItems($sSubClass, 'list') as $sAttCode) {
$oAttDef = MetaModel::GetAttributeDef($sSubClass, $sAttCode);
$sHtml .= ''.$oAttDef->GetLabel().': '.$oCurrObj->GetAsHtml($sAttCode).' ';
}
@@ -492,14 +431,11 @@ class DisplayableNode extends GraphNode
public function GetDotAttributes($bNoLabel = false)
{
$sDot = '';
- if ($bNoLabel)
- {
+ if ($bNoLabel) {
// simulate a fake label with the approximate same size as the true label
$sLabel = str_repeat('x', mb_strlen($this->GetProperty('label', $this->GetId())));
$sDot = 'label="'.$sLabel.'"';
- }
- else
- {
+ } else {
// actual label
$sLabel = addslashes($this->GetProperty('label', $this->GetId()));
$sDot = 'label="'.$sLabel.'"';
@@ -517,20 +453,20 @@ class DisplayableRedundancyNode extends DisplayableNode
public function GetForRaphael($aContextDefs)
{
- $aNode = array();
+ $aNode = [];
$aNode['shape'] = 'disc';
$aNode['icon_url'] = $this->GetIconURL();
$aNode['source'] = ($this->GetProperty('source') == true);
$aNode['width'] = $this->GetWidth();
$aNode['x'] = $this->x;
- $aNode['y']= $this->y;
+ $aNode['y'] = $this->y;
$aNode['label'] = $this->GetLabel();
$aNode['id'] = $this->GetId();
$fDiscOpacity = ($this->GetProperty('is_reached') ? 1 : 0.2);
$sColor = ($this->GetProperty('is_reached_count') > $this->GetProperty('threshold')) ? '#c33' : '#999';
- $aNode['disc_attr'] = array('stroke-width' => 2, 'stroke' => '#000', 'fill' => $sColor, 'opacity' => $fDiscOpacity);
+ $aNode['disc_attr'] = ['stroke-width' => 2, 'stroke' => '#000', 'fill' => $sColor, 'opacity' => $fDiscOpacity];
$fTextOpacity = ($this->GetProperty('is_reached') ? 1 : 0.4);
- $aNode['text_attr'] = array('fill' => '#fff', 'opacity' => $fTextOpacity);
+ $aNode['text_attr'] = ['fill' => '#fff', 'opacity' => $fTextOpacity];
$aNode['tooltip'] = $this->GetTooltip($aContextDefs);
return $aNode;
}
@@ -538,28 +474,25 @@ class DisplayableRedundancyNode extends DisplayableNode
public function RenderAsPDF(iTopPDF $oPdf, DisplayableGraph $oGraph, $fScale, $aContextDefs)
{
$oPdf->SetAlpha(1);
- if($this->GetProperty('is_reached_count') > $this->GetProperty('threshold'))
- {
+ if ($this->GetProperty('is_reached_count') > $this->GetProperty('threshold')) {
$oPdf->SetFillColor(200, 0, 0);
- }
- else
- {
+ } else {
$oPdf->SetFillColor(144, 144, 144);
}
$oPdf->SetDrawColor(0, 0, 0);
- $oPdf->Circle($this->x*$fScale, $this->y*$fScale, 16*$fScale, 0, 360, 'DF');
+ $oPdf->Circle($this->x * $fScale, $this->y * $fScale, 16 * $fScale, 0, 360, 'DF');
$oPdf->SetTextColor(255, 255, 255);
$oPdf->SetFontParams('', 28 * $fScale, '', true);
$sLabel = (string)$this->GetProperty('label');
$width = $oPdf->GetStringWidth($sLabel, iTopPDF::GetPdfFont(), 'B', 24 * $fScale);
$height = $oPdf->GetStringHeight(1000, $sLabel);
- $xPos = (float)$this->x*$fScale - $width/2;
- $yPos = (float)$this->y*$fScale - $height/2;
+ $xPos = (float)$this->x * $fScale - $width / 2;
+ $yPos = (float)$this->y * $fScale - $height / 2;
- $oPdf->SetXY(($this->x - 16)*$fScale, ($this->y - 16)*$fScale);
+ $oPdf->SetXY(($this->x - 16) * $fScale, ($this->y - 16) * $fScale);
- $oPdf->Cell(32*$fScale, 32*$fScale, $sLabel, 0, 0, 'C', 0, '', 0, false, 'T', 'C');
+ $oPdf->Cell(32 * $fScale, 32 * $fScale, $sLabel, 0, 0, 'C', 0, '', 0, false, 'T', 'C');
}
/**
@@ -569,28 +502,20 @@ class DisplayableRedundancyNode extends DisplayableNode
{
parent::GroupSimilarNeighbours($oGraph, $iThresholdCount, $bDirectionUp, $bDirectionDown);
- if ($bDirectionUp)
- {
- $aNodesPerClass = array();
- foreach($this->GetIncomingEdges() as $oEdge)
- {
+ if ($bDirectionUp) {
+ $aNodesPerClass = [];
+ foreach ($this->GetIncomingEdges() as $oEdge) {
$oNode = $oEdge->GetSourceNode();
- if (($oNode->GetObjectClass() !== null) && (!$oNode->GetProperty('is_reached')))
- {
+ if (($oNode->GetObjectClass() !== null) && (!$oNode->GetProperty('is_reached'))) {
$this->AddToStats($oNode, $aNodesPerClass);
- }
- else
- {
+ } else {
//$oNode->GroupSimilarNeighbours($oGraph, $iThresholdCount, $bDirectionUp, $bDirectionDown);
}
}
- foreach($aNodesPerClass as $sClass => $aDefs)
- {
- foreach($aDefs as $sStatus => $aGroupProps)
- {
- if (count($aGroupProps['nodes']) >= $iThresholdCount)
- {
+ foreach ($aNodesPerClass as $sClass => $aDefs) {
+ foreach ($aDefs as $sStatus => $aGroupProps) {
+ if (count($aGroupProps['nodes']) >= $iThresholdCount) {
$oNewNode = new DisplayableGroupNode($oGraph, '-'.$this->GetId().'::'.$sClass.'/'.$sStatus);
$oNewNode->SetProperty('label', 'x'.count($aGroupProps['nodes']));
$oNewNode->SetProperty('icon_url', MetaModel::GetClassIcon($sClass, false));
@@ -598,11 +523,9 @@ class DisplayableRedundancyNode extends DisplayableNode
$oNewNode->SetProperty('class', $sClass);
$oNewNode->SetProperty('count', count($aGroupProps['nodes']));
-
- $sNewId = $this->GetId().'::'.$sClass.'/'.(($sStatus == 'reached') ? '_reached': '');
+ $sNewId = $this->GetId().'::'.$sClass.'/'.(($sStatus == 'reached') ? '_reached' : '');
$oNewNode = $oGraph->GetNode($sNewId);
- if ($oNewNode == null)
- {
+ if ($oNewNode == null) {
$oNewNode = new DisplayableGroupNode($oGraph, $sNewId);
$oNewNode->SetProperty('label', 'x'.$aGroupProps['count']);
$oNewNode->SetProperty('icon_url', $aGroupProps['icon_url']);
@@ -611,25 +534,18 @@ class DisplayableRedundancyNode extends DisplayableNode
$oNewNode->SetProperty('count', $aGroupProps['count']);
}
- try
- {
+ try {
$oOutgoingEdge = new DisplayableEdge($oGraph, '-'.$this->GetId().'-'.$oNewNode->GetId().'/'.$sStatus, $oNewNode, $this);
- }
- catch(Exception $e)
- {
+ } catch (Exception $e) {
// Ignore this redundant egde
}
- foreach($aGroupProps['nodes'] as $oNextNode)
- {
+ foreach ($aGroupProps['nodes'] as $oNextNode) {
$this->ReplaceNextNodeBy($oGraph, $oNextNode, $oNewNode, !$bDirectionUp);
}
//$oNewNode->GroupSimilarNeighbours($oGraph, $iThresholdCount, $bDirectionUp, $bDirectionDown);
- }
- else
- {
- foreach($aGroupProps['nodes'] as $oNode)
- {
+ } else {
+ foreach ($aGroupProps['nodes'] as $oNode) {
//$oNode->GroupSimilarNeighbours($oGraph, $iThresholdCount, $bDirectionUp, $bDirectionDown);
}
}
@@ -643,13 +559,12 @@ class DisplayableRedundancyNode extends DisplayableNode
$sHtml = '';
$sHtml .= Dict::S('UI:RelationTooltip:Redundancy')." ";
$sHtml .= '';
- $sHtml .= "".Dict::Format('UI:RelationTooltip:ImpactedItems_N_of_M' , $this->GetProperty('is_reached_count'), $this->GetProperty('min_up') + $this->GetProperty('threshold'))." ";
- $sHtml .= "".Dict::Format('UI:RelationTooltip:CriticalThreshold_N_of_M' , $this->GetProperty('threshold'), $this->GetProperty('min_up') + $this->GetProperty('threshold'))." ";
+ $sHtml .= "".Dict::Format('UI:RelationTooltip:ImpactedItems_N_of_M', $this->GetProperty('is_reached_count'), $this->GetProperty('min_up') + $this->GetProperty('threshold'))." ";
+ $sHtml .= "".Dict::Format('UI:RelationTooltip:CriticalThreshold_N_of_M', $this->GetProperty('threshold'), $this->GetProperty('min_up') + $this->GetProperty('threshold'))." ";
$sHtml .= '
';
return $sHtml;
}
-
public function GetObjectCount()
{
return 0;
@@ -666,16 +581,14 @@ class DisplayableEdge extends GraphEdge
public function RenderAsPDF(TCPDF $oPdf, DisplayableGraph $oGraph, $fScale, $aContextDefs)
{
$oSourceNode = $this->GetSourceNode();
- if (($oSourceNode->x == null) || ($oSourceNode->y == null))
- {
+ if (($oSourceNode->x == null) || ($oSourceNode->y == null)) {
return;
}
$xStart = $oSourceNode->x * $fScale;
$yStart = $oSourceNode->y * $fScale;
$oSinkNode = $this->GetSinkNode();
- if (($oSinkNode->x == null) || ($oSinkNode->y == null))
- {
+ if (($oSinkNode->x == null) || ($oSinkNode->y == null)) {
return;
}
$xEnd = $oSinkNode->x * $fScale;
@@ -684,32 +597,28 @@ class DisplayableEdge extends GraphEdge
$bReached = ($this->GetSourceNode()->GetProperty('is_reached') && $this->GetSinkNode()->GetProperty('is_reached'));
$oPdf->setAlpha(1);
- if ($bReached)
- {
- $aColor = array(100, 100, 100);
+ if ($bReached) {
+ $aColor = [100, 100, 100];
+ } else {
+ $aColor = [200, 200, 200];
}
- else
- {
- $aColor = array(200, 200, 200);
- }
- $oPdf->SetLineStyle(array('width' => 2*$fScale, 'cap' => 'round', 'join' => 'miter', 'dash' => 0, 'color' => $aColor));
+ $oPdf->SetLineStyle(['width' => 2 * $fScale, 'cap' => 'round', 'join' => 'miter', 'dash' => 0, 'color' => $aColor]);
$oPdf->Line($xStart, $yStart, $xEnd, $yEnd);
-
$vx = $xEnd - $xStart;
$vy = $yEnd - $yStart;
- $l = sqrt($vx*$vx + $vy*$vy);
+ $l = sqrt($vx * $vx + $vy * $vy);
$vx = $vx / $l;
$vy = $vy / $l;
$ux = -$vy;
$uy = $vx;
- $lPos = max($l/2, $l - 40*$fScale);
- $iArrowSize = 5*$fScale;
+ $lPos = max($l / 2, $l - 40 * $fScale);
+ $iArrowSize = 5 * $fScale;
$x = $xStart + $lPos * $vx;
$y = $yStart + $lPos * $vy;
- $oPdf->Line($x, $y, $x + $iArrowSize * ($ux-$vx), $y + $iArrowSize * ($uy-$vy));
- $oPdf->Line($x, $y, $x - $iArrowSize * ($ux+$vx), $y - $iArrowSize * ($uy+$vy));
+ $oPdf->Line($x, $y, $x + $iArrowSize * ($ux - $vx), $y + $iArrowSize * ($uy - $vy));
+ $oPdf->Line($x, $y, $x - $iArrowSize * ($ux + $vx), $y - $iArrowSize * ($uy + $vy));
}
}
@@ -720,16 +629,14 @@ class DisplayableGroupNode extends DisplayableNode
public function __construct(SimpleGraph $oGraph, $sId, $x = 0, $y = 0)
{
parent::__construct($oGraph, $sId, $x, $y);
- $this->aObjects = array();
+ $this->aObjects = [];
}
public function AddObject(DBObject $oObj = null)
{
- if (is_object($oObj))
- {
+ if (is_object($oObj)) {
$sPrevClass = $this->GetObjectClass();
- if (($sPrevClass !== null) && (get_class($oObj) !== $sPrevClass))
- {
+ if (($sPrevClass !== null) && (get_class($oObj) !== $sPrevClass)) {
throw new Exception("Error: adding an object of class '".get_class($oObj)."' to a group of '$sPrevClass' objects.");
}
$this->aObjects[$oObj->GetKey()] = $oObj;
@@ -748,21 +655,21 @@ class DisplayableGroupNode extends DisplayableNode
public function GetForRaphael($aContextDefs)
{
- $aNode = array();
+ $aNode = [];
$aNode['shape'] = 'group';
$aNode['icon_url'] = $this->GetIconURL();
$aNode['source'] = ($this->GetProperty('source') == true);
$aNode['width'] = $this->GetWidth();
$aNode['x'] = $this->x;
- $aNode['y']= $this->y;
+ $aNode['y'] = $this->y;
$aNode['label'] = $this->GetLabel();
$aNode['id'] = $this->GetId();
$aNode['group_index'] = $this->GetProperty('group_index'); // if supplied
$fDiscOpacity = ($this->GetProperty('is_reached') ? 1 : 0.2);
$fTextOpacity = ($this->GetProperty('is_reached') ? 1 : 0.4);
- $aNode['icon_attr'] = array('opacity' => $fTextOpacity);
- $aNode['disc_attr'] = array('stroke-width' => 2, 'stroke' => '#000', 'fill' => '#fff', 'opacity' => $fDiscOpacity);
- $aNode['text_attr'] = array('fill' => '#000', 'opacity' => $fTextOpacity);
+ $aNode['icon_attr'] = ['opacity' => $fTextOpacity];
+ $aNode['disc_attr'] = ['stroke-width' => 2, 'stroke' => '#000', 'fill' => '#fff', 'opacity' => $fDiscOpacity];
+ $aNode['text_attr'] = ['fill' => '#000', 'opacity' => $fTextOpacity];
$aNode['tooltip'] = $this->GetTooltip($aContextDefs);
return $aNode;
}
@@ -772,11 +679,11 @@ class DisplayableGroupNode extends DisplayableNode
$bReached = $this->GetProperty('is_reached');
$oPdf->SetFillColor(255, 255, 255);
if ($bReached) {
- $aBorderColor = array(100, 100, 100);
+ $aBorderColor = [100, 100, 100];
} else {
- $aBorderColor = array(200, 200, 200);
+ $aBorderColor = [200, 200, 200];
}
- $oPdf->SetLineStyle(array('width' => 2 * $fScale, 'cap' => 'round', 'join' => 'miter', 'dash' => 0, 'color' => $aBorderColor));
+ $oPdf->SetLineStyle(['width' => 2 * $fScale, 'cap' => 'round', 'join' => 'miter', 'dash' => 0, 'color' => $aBorderColor]);
$sIconUrl = $this->GetProperty('icon_url');
$sIconPath = str_replace(utils::GetAbsoluteUrlModulesRoot(), APPROOT.'env-'.utils::GetCurrentEnvironment().'/', $sIconUrl);
@@ -800,7 +707,7 @@ class DisplayableGroupNode extends DisplayableNode
public function GetTooltip($aContextDefs)
{
$iGroupIdx = $this->GetProperty('group_index');
- $sHtml = ''.Dict::Format('UI:RelationGroupNumber_N', (1+$iGroupIdx))." ";
+ $sHtml = ''.Dict::Format('UI:RelationGroupNumber_N', (1 + $iGroupIdx))." ";
$sHtml .= ' ';
$sHtml .= '';
$sHtml .= ''.MetaModel::GetName($this->GetObjectClass()).' ';
@@ -833,9 +740,9 @@ class DisplayableGraph extends SimpleGraph
public function __construct()
{
parent::__construct();
- $this->aTempImages = array();
- $this->aSourceObjects = array();
- $this->aSinkObjects = array();
+ $this->aTempImages = [];
+ $this->aSourceObjects = [];
+ $this->aSinkObjects = [];
}
public function GetTempImageName()
@@ -847,8 +754,7 @@ class DisplayableGraph extends SimpleGraph
public function __destruct()
{
- foreach($this->aTempImages as $sTempFile)
- {
+ foreach ($this->aTempImages as $sTempFile) {
@unlink($sTempFile);
}
}
@@ -880,14 +786,14 @@ class DisplayableGraph extends SimpleGraph
$sClass = get_class($oObj);
if ($oNode->GetProperty('source')) {
if (!array_key_exists($sClass, $oNewGraph->aSourceObjects)) {
- $oNewGraph->aSourceObjects[$sClass] = array();
+ $oNewGraph->aSourceObjects[$sClass] = [];
}
$oNewGraph->aSourceObjects[$sClass][] = $oObj->GetKey();
$oNewNode->SetProperty('source', true);
}
if ($oNode->GetProperty('sink')) {
if (!array_key_exists($sClass, $oNewGraph->aSinkObjects)) {
- $oNewGraph->aSinkObjects[$sClass] = array();
+ $oNewGraph->aSinkObjects[$sClass] = [];
}
$oNewGraph->aSinkObjects[$sClass][] = $oObj->GetKey();
$oNewNode->SetProperty('sink', true);
@@ -917,8 +823,7 @@ class DisplayableGraph extends SimpleGraph
}
}
$oEdgesIter = new RelationTypeIterator($oGraph, 'Edge');
- foreach($oEdgesIter as $oEdge)
- {
+ foreach ($oEdgesIter as $oEdge) {
set_time_limit(intval($iLoopTimeLimit));
$oSourceNode = $oNewGraph->GetNode($oEdge->GetSourceNode()->GetId());
$oSinkNode = $oNewGraph->GetNode($oEdge->GetSinkNode()->GetId());
@@ -927,60 +832,44 @@ class DisplayableGraph extends SimpleGraph
// Remove duplicate edges between two nodes
$oEdgesIter = new RelationTypeIterator($oNewGraph, 'Edge');
- $aEdgeKeys = array();
- foreach($oEdgesIter as $oEdge)
- {
+ $aEdgeKeys = [];
+ foreach ($oEdgesIter as $oEdge) {
set_time_limit(intval($iLoopTimeLimit));
$sSourceId = $oEdge->GetSourceNode()->GetId();
$sSinkId = $oEdge->GetSinkNode()->GetId();
- if ($sSourceId == $sSinkId)
- {
+ if ($sSourceId == $sSinkId) {
// Remove self referring edges
$oNewGraph->_RemoveEdge($oEdge);
- }
- else
- {
+ } else {
$sKey = $sSourceId.'//'.$sSinkId;
- if (array_key_exists($sKey, $aEdgeKeys))
- {
+ if (array_key_exists($sKey, $aEdgeKeys)) {
// Remove duplicate edges
$oNewGraph->_RemoveEdge($oEdge);
- }
- else
- {
+ } else {
$aEdgeKeys[$sKey] = true;
}
}
}
$oNodesIter = new RelationTypeIterator($oNewGraph, 'Node');
- foreach($oNodesIter as $oNode)
- {
+ foreach ($oNodesIter as $oNode) {
set_time_limit(intval($iLoopTimeLimit));
- if ($bDirectionDown && $oNode->GetProperty('source'))
- {
+ if ($bDirectionDown && $oNode->GetProperty('source')) {
$oNode->GroupSimilarNeighbours($oNewGraph, $iGroupingThreshold, true, $bDirectionDown);
- }
- else if (!$bDirectionDown && $oNode->GetProperty('sink'))
- {
+ } elseif (!$bDirectionDown && $oNode->GetProperty('sink')) {
$oNode->GroupSimilarNeighbours($oNewGraph, $iGroupingThreshold, true, $bDirectionDown);
}
}
// Groups numbering
$oIterator = new RelationTypeIterator($oNewGraph, 'Node');
$iGroupIdx = 0;
- foreach($oIterator as $oNode)
- {
+ foreach ($oIterator as $oNode) {
set_time_limit(intval($iLoopTimeLimit));
- if ($oNode instanceof DisplayableGroupNode)
- {
- if ($oNode->GetObjectCount() == 0)
- {
+ if ($oNode instanceof DisplayableGroupNode) {
+ if ($oNode->GetObjectCount() == 0) {
// Remove empty groups
$oNewGraph->_RemoveNode($oNode);
- }
- else
- {
+ } else {
$aGroups[] = $oNode->GetObjects();
$oNode->SetProperty('group_index', $iGroupIdx);
$iGroupIdx++;
@@ -990,27 +879,20 @@ class DisplayableGraph extends SimpleGraph
// Remove duplicate edges between two nodes
$oEdgesIter = new RelationTypeIterator($oNewGraph, 'Edge');
- $aEdgeKeys = array();
- foreach($oEdgesIter as $oEdge)
- {
+ $aEdgeKeys = [];
+ foreach ($oEdgesIter as $oEdge) {
set_time_limit(intval($iLoopTimeLimit));
$sSourceId = $oEdge->GetSourceNode()->GetId();
$sSinkId = $oEdge->GetSinkNode()->GetId();
- if ($sSourceId == $sSinkId)
- {
+ if ($sSourceId == $sSinkId) {
// Remove self referring edges
$oNewGraph->_RemoveEdge($oEdge);
- }
- else
- {
+ } else {
$sKey = $sSourceId.'//'.$sSinkId;
- if (array_key_exists($sKey, $aEdgeKeys))
- {
+ if (array_key_exists($sKey, $aEdgeKeys)) {
// Remove duplicate edges
$oNewGraph->_RemoveEdge($oEdge);
- }
- else
- {
+ } else {
$aEdgeKeys[$sKey] = true;
}
}
@@ -1028,28 +910,22 @@ class DisplayableGraph extends SimpleGraph
public function InitFromGraphviz()
{
$sDot = $this->DumpAsXDot();
- if (strpos($sDot, 'digraph') === false)
- {
+ if (strpos($sDot, 'digraph') === false) {
throw new Exception($sDot);
}
$aChunks = explode(";", $sDot);
- foreach($aChunks as $sChunk)
- {
- if(preg_match('/"([^"]+)".+pos="([0-9\\.]+),([0-9\\.]+)"/ms', $sChunk, $aMatches))
- {
+ foreach ($aChunks as $sChunk) {
+ if (preg_match('/"([^"]+)".+pos="([0-9\\.]+),([0-9\\.]+)"/ms', $sChunk, $aMatches)) {
$sId = $aMatches[1];
$xPos = $aMatches[2];
$yPos = $aMatches[3];
$oNode = $this->GetNode($sId);
- if ($oNode !== null)
- {
+ if ($oNode !== null) {
$oNode->x = (float)$xPos;
$oNode->y = (float)$yPos;
- }
- else
- {
+ } else {
IssueLog::Warning("??? Position of the non-existing node '$sId', x=$xPos, y=$yPos");
}
}
@@ -1063,17 +939,13 @@ class DisplayableGraph extends SimpleGraph
$yMin = null;
$yMax = null;
$oIterator = new RelationTypeIterator($this, 'Node');
- foreach($oIterator as $sId => $oNode)
- {
- if ($xMin === null) // First element in the loop
- {
+ foreach ($oIterator as $sId => $oNode) {
+ if ($xMin === null) { // First element in the loop
$xMin = $oNode->x - $oNode->GetWidth();
$xMax = $oNode->x + $oNode->GetWidth();
$yMin = $oNode->y - $oNode->GetHeight();
$yMax = $oNode->y + $oNode->GetHeight();
- }
- else
- {
+ } else {
$xMin = min($xMin, $oNode->x - $oNode->GetWidth() / 2);
$xMax = max($xMax, $oNode->x + $oNode->GetWidth() / 2);
$yMin = min($yMin, $oNode->y - $oNode->GetHeight() / 2);
@@ -1081,14 +953,13 @@ class DisplayableGraph extends SimpleGraph
}
}
- return array('xmin' => $xMin, 'xmax' => $xMax, 'ymin' => $yMin, 'ymax' => $yMax);
+ return ['xmin' => $xMin, 'xmax' => $xMax, 'ymin' => $yMin, 'ymax' => $yMax];
}
- function Translate($dx, $dy)
+ public function Translate($dx, $dy)
{
$oIterator = new RelationTypeIterator($this, 'Node');
- foreach($oIterator as $sId => $oNode)
- {
+ foreach ($oIterator as $sId => $oNode) {
$oNode->x += $dx;
$oNode->y += $dy;
}
@@ -1096,11 +967,9 @@ class DisplayableGraph extends SimpleGraph
public function UpdatePositions($aPositions)
{
- foreach($aPositions as $sNodeId => $aPos)
- {
+ foreach ($aPositions as $sNodeId => $aPos) {
$oNode = $this->GetNode($sNodeId);
- if ($oNode != null)
- {
+ if ($oNode != null) {
$oNode->x = $aPos['x'];
$oNode->y = $aPos['y'];
}
@@ -1110,17 +979,15 @@ class DisplayableGraph extends SimpleGraph
/**
* Renders as JSON string suitable for loading into the simple_graph widget
*/
- function GetAsJSON($sContextKey)
+ public function GetAsJSON($sContextKey)
{
$aContextDefs = static::GetContextDefinitions($sContextKey, false);
- $aData = array('nodes' => array(), 'edges' => array(), 'groups' => array(), 'lists' => array());
+ $aData = ['nodes' => [], 'edges' => [], 'groups' => [], 'lists' => []];
$iGroupIdx = 0;
$oIterator = new RelationTypeIterator($this, 'Node');
- foreach($oIterator as $sId => $oNode)
- {
- if ($oNode instanceof DisplayableGroupNode)
- {
+ foreach ($oIterator as $sId => $oNode) {
+ if ($oNode instanceof DisplayableGroupNode) {
// The contents of the "Groups" tab will be rendered
// using a separate ajax call, since the content of
// the page is made of a mix of HTML / CSS / JS which
@@ -1128,53 +995,45 @@ class DisplayableGraph extends SimpleGraph
// So we just pass a list of groups, each being defined by a class and a list of keys
// in order to avoid redoing the impact computation which is expensive
$aObjects = $oNode->GetObjects();
- $aKeys = array();
- foreach($aObjects as $oObj)
- {
+ $aKeys = [];
+ foreach ($aObjects as $oObj) {
$sClass = get_class($oObj);
$aKeys[] = $oObj->GetKey();
}
- $aData['groups'][$iGroupIdx] = array('class' => $sClass, 'keys' => $aKeys);
+ $aData['groups'][$iGroupIdx] = ['class' => $sClass, 'keys' => $aKeys];
$oNode->SetProperty('group_index', $iGroupIdx);
$iGroupIdx++;
- if ($oNode->GetProperty('is_reached'))
- {
+ if ($oNode->GetProperty('is_reached')) {
// Also add the objects from this group into the 'list' tab
- if (!array_key_exists($sClass, $aData['lists']))
- {
+ if (!array_key_exists($sClass, $aData['lists'])) {
$aData['lists'][$sClass] = $aKeys;
- }
- else
- {
+ } else {
$aData['lists'][$sClass] = array_merge($aData['lists'][$sClass], $aKeys);
}
}
}
- if (($oNode instanceof DisplayableNode) && $oNode->GetProperty('is_reached') && is_object($oNode->GetProperty('object')))
- {
+ if (($oNode instanceof DisplayableNode) && $oNode->GetProperty('is_reached') && is_object($oNode->GetProperty('object'))) {
$sObjClass = get_class($oNode->GetProperty('object'));
- if (!array_key_exists($sObjClass, $aData['lists']))
- {
- $aData['lists'][$sObjClass] = array();
+ if (!array_key_exists($sObjClass, $aData['lists'])) {
+ $aData['lists'][$sObjClass] = [];
}
$aData['lists'][$sObjClass][] = $oNode->GetProperty('object')->GetKey();
}
$aData['nodes'][] = $oNode->GetForRaphael($aContextDefs);
}
- uksort($aData['lists'], array(get_class($this), 'SortOnClassLabel')); // sort on the localized names of the classes to provide a consistent and stable order
+ uksort($aData['lists'], [get_class($this), 'SortOnClassLabel']); // sort on the localized names of the classes to provide a consistent and stable order
$oIterator = new RelationTypeIterator($this, 'Edge');
- foreach($oIterator as $sId => $oEdge)
- {
- $aEdge = array();
+ foreach ($oIterator as $sId => $oEdge) {
+ $aEdge = [];
$aEdge['id'] = $oEdge->GetId();
$aEdge['source_node_id'] = $oEdge->GetSourceNode()->GetId();
$aEdge['sink_node_id'] = $oEdge->GetSinkNode()->GetId();
$fOpacity = ($oEdge->GetSinkNode()->GetProperty('is_reached') && $oEdge->GetSourceNode()->GetProperty('is_reached') ? 1 : 0.2);
- $aEdge['attr'] = array('opacity' => $fOpacity, 'stroke' => '#000');
+ $aEdge['attr'] = ['opacity' => $fOpacity, 'stroke' => '#000'];
$aData['edges'][] = $aEdge;
}
@@ -1204,7 +1063,7 @@ class DisplayableGraph extends SimpleGraph
*
* @since 2.7.7 3.0.2 3.1.0 N°4985 $sComments param is no longer optional
*/
- function RenderAsPDF(PDFPage $oPage, $sComments, $sContextKey, $xMin = -1, $xMax = -1, $yMin = -1, $yMax = -1)
+ public function RenderAsPDF(PDFPage $oPage, $sComments, $sContextKey, $xMin = -1, $xMax = -1, $yMin = -1, $yMax = -1)
{
$aContextDefs = static::GetContextDefinitions($sContextKey, false); // No need to develop the parameters
$oPdf = $oPage->get_tcpdf();
@@ -1214,20 +1073,16 @@ class DisplayableGraph extends SimpleGraph
$aMargins = $oPdf->getMargins();
- if ($xMin == -1)
- {
+ if ($xMin == -1) {
$xMin = $aMargins['left'];
}
- if ($xMax == -1)
- {
+ if ($xMax == -1) {
$xMax = $oPdf->getPageWidth() - $aMargins['right'];
}
- if ($yMin == -1)
- {
+ if ($yMin == -1) {
$yMin = $aMargins['top'];
}
- if ($yMax == -1)
- {
+ if ($yMax == -1) {
$yMax = $oPdf->getPageHeight() - $aMargins['bottom'];
}
@@ -1251,19 +1106,17 @@ class DisplayableGraph extends SimpleGraph
$dx = ($fPageW - $fScale * $w) / 2;
$dy = ($fPageH - $fScale * $h) / 2;
- $this->Translate(($xMin + $dx)/$fScale, ($yMin + $dy)/$fScale);
+ $this->Translate(($xMin + $dx) / $fScale, ($yMin + $dy) / $fScale);
$oIterator = new RelationTypeIterator($this, 'Edge');
$iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
- foreach($oIterator as $sId => $oEdge)
- {
+ foreach ($oIterator as $sId => $oEdge) {
set_time_limit(intval($iLoopTimeLimit));
$oEdge->RenderAsPDF($oPdf, $this, $fScale, $aContextDefs);
}
$oIterator = new RelationTypeIterator($this, 'Node');
- foreach($oIterator as $sId => $oNode)
- {
+ foreach ($oIterator as $sId => $oNode) {
set_time_limit(intval($iLoopTimeLimit));
$oNode->RenderAsPDF($oPdf, $this, $fScale, $aContextDefs);
}
@@ -1292,17 +1145,14 @@ class DisplayableGraph extends SimpleGraph
$fPadding = 1; // in mm
$oIterator = new RelationTypeIterator($this, 'Node');
$fMaxWidth = max($oPdf->GetStringWidth(Dict::S('UI:Relation:Key')) - $fIconSize, $oPdf->GetStringWidth(Dict::S('UI:Relation:Comments')) - $fIconSize);
- $aClasses = array();
- $aIcons = array();
- $aContexts = array();
- $aContextIcons = array();
+ $aClasses = [];
+ $aIcons = [];
+ $aContexts = [];
+ $aContextIcons = [];
$oPdf->SetFontParams('', $fFontSize, '', true);
- foreach($oIterator as $sId => $oNode)
- {
- if ($sClass = $oNode->GetObjectClass())
- {
- if (!array_key_exists($sClass, $aClasses))
- {
+ foreach ($oIterator as $sId => $oNode) {
+ if ($sClass = $oNode->GetObjectClass()) {
+ if (!array_key_exists($sClass, $aClasses)) {
$sClassLabel = MetaModel::GetName($sClass);
$width = $oPdf->GetStringWidth($sClassLabel);
$fMaxWidth = max($width, $fMaxWidth);
@@ -1313,10 +1163,8 @@ class DisplayableGraph extends SimpleGraph
}
}
$aContextRootCauses = $oNode->GetProperty('context_root_causes');
- if (!is_null($aContextRootCauses))
- {
- foreach($aContextRootCauses as $key => $aObjects)
- {
+ if (!is_null($aContextRootCauses)) {
+ foreach ($aContextRootCauses as $key => $aObjects) {
$aContexts[$key] = Dict::S($aContextDefs[$key]['dict']);
$aContextIcons[$key] = APPROOT.'env-'.utils::GetCurrentEnvironment().'/'.$aContextDefs[$key]['icon'];
}
@@ -1339,7 +1187,7 @@ class DisplayableGraph extends SimpleGraph
$oPdf->AddImage($aContextIcons[$key], $xMin + 1 + $fIconSize * 0.125, $yPos + $fIconSize * 0.125, $fIconSize * 0.75, $fIconSize * 0.75);
$yPos += $fIconSize + 2 * $fPadding;
}
- $oPdf->Rect($xMin, $yMin, $fMaxWidth + $fIconSize + 3*$fPadding, $yMax - $yMin, 'D');
+ $oPdf->Rect($xMin, $yMin, $fMaxWidth + $fIconSize + 3 * $fPadding, $yMax - $yMin, 'D');
if ($sComments != '') {
// Draw the comment text (surrounded by a rectangle)
@@ -1355,7 +1203,7 @@ class DisplayableGraph extends SimpleGraph
$yMax = $yPos - $fPadding;
}
- return array('xmin' => $xMin + $fMaxWidth + $fIconSize + 4*$fPadding, 'xmax' => $xMax, 'ymin' => $yMin, 'ymax' => $yMax);
+ return ['xmin' => $xMin + $fMaxWidth + $fIconSize + 4 * $fPadding, 'xmax' => $xMax, 'ymin' => $yMin, 'ymax' => $yMax];
}
/**
@@ -1368,45 +1216,33 @@ class DisplayableGraph extends SimpleGraph
* @param array $aContextParams Arguments for the queries (via ToArgs()) if $bDevelopParams == true
* @return multitype:multitype:string
*/
- public static function GetContextDefinitions($sContextKey, $bDevelopParams = true, $aContextParams = array())
+ public static function GetContextDefinitions($sContextKey, $bDevelopParams = true, $aContextParams = [])
{
- $aContextDefs = array();
+ $aContextDefs = [];
$aLevels = explode('/', $sContextKey);
- if (count($aLevels) < 5)
- {
+ if (count($aLevels) < 5) {
IssueLog::Warning("GetContextDefinitions: invalid 'sContextKey' = '$sContextKey'. 5 levels of / are expected !");
- }
- else
- {
+ } else {
$sLeafClass = $aLevels[2];
- if (!MetaModel::IsValidClass($sLeafClass))
- {
+ if (!MetaModel::IsValidClass($sLeafClass)) {
IssueLog::Warning("GetContextDefinitions: invalid 'sLeafClass' = '$sLeafClass'. A valid class name is expected in 3rd position inside '$sContextKey' !");
- }
- else
- {
- $aRelationContext = MetaModel::GetConfig()->GetModuleSetting($aLevels[0], $aLevels[1], array());
- foreach(MetaModel::EnumParentClasses($sLeafClass, ENUM_PARENT_CLASSES_ALL) as $sClass)
- {
- if (isset($aRelationContext[$sClass][$aLevels[3]][$aLevels[4]]['items']))
- {
+ } else {
+ $aRelationContext = MetaModel::GetConfig()->GetModuleSetting($aLevels[0], $aLevels[1], []);
+ foreach (MetaModel::EnumParentClasses($sLeafClass, ENUM_PARENT_CLASSES_ALL) as $sClass) {
+ if (isset($aRelationContext[$sClass][$aLevels[3]][$aLevels[4]]['items'])) {
$aContextDefs = array_merge($aContextDefs, $aRelationContext[$sClass][$aLevels[3]][$aLevels[4]]['items']);
}
}
// Check if the queries are valid
- foreach($aContextDefs as $sKey => $sDefs)
- {
+ foreach ($aContextDefs as $sKey => $sDefs) {
$sOQL = $aContextDefs[$sKey]['oql'];
- try
- {
+ try {
// Expand the parameters. If anything goes wrong, then the query is considered as invalid and removed from the list
$oSearch = DBObjectSearch::FromOQL($sOQL);
$aContextDefs[$sKey]['oql'] = $oSearch->ToOQL($bDevelopParams, $aContextParams);
- }
- catch(Exception $e)
- {
+ } catch (Exception $e) {
IssueLog::Warning('Invalid OQL query: '.$sOQL.' in the parameter '.$sContextKey);
unset($aContextDefs[$sKey]);
}
@@ -1434,7 +1270,7 @@ class DisplayableGraph extends SimpleGraph
*
* @since 3.1.1 3.2.0 N°3767
*/
- function DisplayGraph(WebPage $oP, $sRelation, ApplicationContext $oAppContext, $aExcludedObjects, $sObjClass, $iObjKey, $sContextKey, $aContextParams = array(), bool $bLazyLoading = false): void
+ public function DisplayGraph(WebPage $oP, $sRelation, ApplicationContext $oAppContext, $aExcludedObjects, $sObjClass, $iObjKey, $sContextKey, $aContextParams = [], bool $bLazyLoading = false): void
{
list($aExcludedByClass, $aAdditionalContexts) = $this->GetFilteringData($sContextKey, $aContextParams, $aExcludedObjects);
@@ -1464,16 +1300,16 @@ class DisplayableGraph extends SimpleGraph
$oP->add_ready_script("$('.simple-graph').width(18/2.54*96).resizable({ stop: function() { $(window).trigger('resized'); }});"); // Default width about 18 cm, since most browsers assume 96 dpi
}
$oP->add('
');
- $aParams = array(
+ $aParams = [
'source_url' => $sLoadFromURL,
'sources' => ($this->bDirectionDown ? $this->aSourceObjects : $this->aSinkObjects),
'excluded' => $aExcludedByClass,
'grouping_threshold' => $iGroupingThreshold,
- 'export_as_pdf' => array('url' => $sExportAsPdfURL, 'label' => Dict::S('UI:Relation:ExportAsPDF')),
+ 'export_as_pdf' => ['url' => $sExportAsPdfURL, 'label' => Dict::S('UI:Relation:ExportAsPDF')],
'transaction_id' => utils::GetNewTransactionId(),
- 'export_as_attachment' => array('url' => $sExportAsDocumentURL, 'label' => Dict::S('UI:Relation:ExportAsAttachment'), 'obj_class' => $sObjClass, 'obj_key' => $iObjKey),
- 'drill_down' => array('url' => $sDrillDownURL, 'label' => Dict::S('UI:Relation:DrillDown')),
- 'labels' => array(
+ 'export_as_attachment' => ['url' => $sExportAsDocumentURL, 'label' => Dict::S('UI:Relation:ExportAsAttachment'), 'obj_class' => $sObjClass, 'obj_key' => $iObjKey],
+ 'drill_down' => ['url' => $sDrillDownURL, 'label' => Dict::S('UI:Relation:DrillDown')],
+ 'labels' => [
'export_pdf_title' => Dict::S('UI:Relation:PDFExportOptions'),
'export_as_attachment_title' => $sAttachmentExportTitle,
'export' => Dict::S('UI:Button:Export'),
@@ -1491,25 +1327,25 @@ class DisplayableGraph extends SimpleGraph
'additional_context_info' => Dict::S('UI:Relation:AdditionalContextInfo'),
'zoom' => Dict::S('UI:Relation:Zoom'),
'loading' => Dict::S('UI:Loading'),
- ),
- 'page_format' => array(
+ ],
+ 'page_format' => [
'label' => Dict::S('UI:Relation:PDFExportPageFormat'),
- 'values' => array(
+ 'values' => [
'A3' => Dict::S('UI:PageFormat_A3'),
'A4' => Dict::S('UI:PageFormat_A4'),
'Letter' => Dict::S('UI:PageFormat_Letter'),
- ),
- ),
- 'page_orientation' => array(
+ ],
+ ],
+ 'page_orientation' => [
'label' => Dict::S('UI:Relation:PDFExportPageOrientation'),
- 'values' => array(
+ 'values' => [
'P' => Dict::S('UI:PageOrientation_Portrait'),
'L' => Dict::S('UI:PageOrientation_Landscape'),
- ),
- ),
+ ],
+ ],
'additional_contexts' => $aAdditionalContexts,
'context_key' => $sContextKey,
- );
+ ];
if (!extension_loaded('gd')) {
// PDF export requires GD
unset($aParams['export_as_pdf']);
@@ -1524,8 +1360,7 @@ class DisplayableGraph extends SimpleGraph
$oP->add_script("function Load(){var aExcluded = []; $('input[name^=excluded]').each( function() {if (!$(this).prop('checked')) { aExcluded.push($(this).val()); }} ); var params= $.extend(".json_encode($aParams).", {excluded_classes: aExcluded}); $('#$sId').simple_graph(params);}");
$oP->add_ready_script("$('#graph').html('".utils::TextToHtml(Dict::S('Relation:impacts/NoFilteredData'))."');$('#impacted_objects_lists').html('".utils::TextToHtml(Dict::S('Relation:impacts/NoFilteredData'))."');$('#impacted_groups').html('".utils::TextToHtml(Dict::S('Relation:impacts/NoFilteredData'))."');");
}
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$oP->add(''.$e->getMessage().'
');
}
$oP->add_script(
@@ -1599,7 +1434,7 @@ EOF
} else {
$oP->add_ready_script("$('#dh_flash').addClass('closed');");
}
- $aSortedElements = array();
+ $aSortedElements = [];
foreach ($aResults as $sClassIdx => $aObjects) {
foreach ($aObjects as $oCurrObj) {
$sSubClass = get_class($oCurrObj);
@@ -1636,19 +1471,19 @@ EOF
public function GetFilteringData(string $sContextKey, array $aContextParams, array $aExcludedObjects): array
{
$aContextDefs = static::GetContextDefinitions($sContextKey, true, $aContextParams);
- $aExcludedByClass = array();
+ $aExcludedByClass = [];
foreach ($aExcludedObjects as $oObj) {
if (!array_key_exists(get_class($oObj), $aExcludedByClass)) {
- $aExcludedByClass[get_class($oObj)] = array();
+ $aExcludedByClass[get_class($oObj)] = [];
}
$aExcludedByClass[get_class($oObj)][] = $oObj->GetKey();
}
- $aAdditionalContexts = array();
+ $aAdditionalContexts = [];
foreach ($aContextDefs as $sKey => $aDefinition) {
- $aAdditionalContexts[] = array('key' => $sKey, 'label' => Dict::S($aDefinition['dict']), 'oql' => $aDefinition['oql'], 'default' => (array_key_exists('default', $aDefinition) && ($aDefinition['default'] == 'yes')));
+ $aAdditionalContexts[] = ['key' => $sKey, 'label' => Dict::S($aDefinition['dict']), 'oql' => $aDefinition['oql'], 'default' => (array_key_exists('default', $aDefinition) && ($aDefinition['default'] == 'yes'))];
}
- return array($aExcludedByClass, $aAdditionalContexts);
+ return [$aExcludedByClass, $aAdditionalContexts];
}
}
diff --git a/core/event.class.inc.php b/core/event.class.inc.php
index cca37deaf..d87a40e91 100644
--- a/core/event.class.inc.php
+++ b/core/event.class.inc.php
@@ -24,31 +24,31 @@ class Event extends DBObject implements iDisplay
{
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "core/cmdb,view_in_gui",
"key_type" => "autoincrement",
"name_attcode" => "",
"state_attcode" => "",
- "reconc_keys" => array(),
+ "reconc_keys" => [],
"db_table" => "priv_event",
"db_key_field" => "id",
"db_finalclass_field" => "realclass",
- "order_by_default" => array('date' => false)
- );
+ "order_by_default" => ['date' => false],
+ ];
MetaModel::Init_Params($aParams);
//MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeText("message", array("allowed_values"=>null, "sql"=>"message", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeDateTime("date", array("allowed_values"=>null, "sql"=>"date", "default_value"=>"NOW()", "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeString("userinfo", array("allowed_values"=>null, "sql"=>"userinfo", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
-// MetaModel::Init_AddAttribute(new AttributeString("userinfo", array("allowed_values"=>null, "sql"=>"userinfo", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeText("message", ["allowed_values" => null, "sql" => "message", "default_value" => null, "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeDateTime("date", ["allowed_values" => null, "sql" => "date", "default_value" => "NOW()", "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeString("userinfo", ["allowed_values" => null, "sql" => "userinfo", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ // MetaModel::Init_AddAttribute(new AttributeString("userinfo", array("allowed_values"=>null, "sql"=>"userinfo", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
// Display lists
- MetaModel::Init_SetZListItems('details', array('date', 'message', 'userinfo')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('date', 'finalclass', 'message')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['date', 'message', 'userinfo']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['date', 'finalclass', 'message']); // Attributes to be displayed for a list
// Search criteria
-// MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
-// MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
+ // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
+ // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
}
/**
@@ -58,12 +58,9 @@ class Event extends DBObject implements iDisplay
*/
public static function MapContextParam($sContextParam)
{
- if ($sContextParam == 'menu')
- {
+ if ($sContextParam == 'menu') {
return null;
- }
- else
- {
+ } else {
return $sContextParam;
}
}
@@ -79,7 +76,7 @@ class Event extends DBObject implements iDisplay
public function GetHilightClass()
{
// Possible return values are:
- // HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
+ // HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
return HILIGHT_CLASS_NONE; // Not hilighted by default
}
@@ -88,7 +85,7 @@ class Event extends DBObject implements iDisplay
return 'UI.php';
}
- function DisplayDetails(WebPage $oPage, $bEditMode = false)
+ public function DisplayDetails(WebPage $oPage, $bEditMode = false)
{
// Object's details
//$this->DisplayBareHeader($oPage, $bEditMode);
@@ -97,21 +94,23 @@ class Event extends DBObject implements iDisplay
$oPage->SetCurrentTab('UI:PropertiesTab');
$this->DisplayBareProperties($oPage, $bEditMode);
}
-
- function DisplayBareProperties(WebPage $oPage, $bEditMode = false, $sPrefix = '', $aExtraParams = array())
- {
- if ($bEditMode) return array(); // Not editable
- $aDetails = array();
+ public function DisplayBareProperties(WebPage $oPage, $bEditMode = false, $sPrefix = '', $aExtraParams = [])
+ {
+ if ($bEditMode) {
+ return [];
+ } // Not editable
+
+ $aDetails = [];
$sClass = get_class($this);
$aZList = MetaModel::FlattenZlist(MetaModel::GetZListItems($sClass, 'details'));
foreach ($aZList as $sAttCode) {
$sDisplayValue = $this->GetAsHTML($sAttCode);
- $aDetails[] = array('label' => ''.MetaModel::GetLabel($sClass, $sAttCode).' ', 'value' => $sDisplayValue);
+ $aDetails[] = ['label' => ''.MetaModel::GetLabel($sClass, $sAttCode).' ', 'value' => $sDisplayValue];
}
$oPage->Details($aDetails);
- return array();
+ return [];
}
}
@@ -119,35 +118,35 @@ class EventNotification extends Event
{
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "core/cmdb,view_in_gui",
"key_type" => "autoincrement",
"name_attcode" => "",
"state_attcode" => "",
- "reconc_keys" => array(),
+ "reconc_keys" => [],
"db_table" => "priv_event_notification",
"db_key_field" => "id",
"db_finalclass_field" => "",
- "order_by_default" => array('date' => false),
- 'indexes' => array(
- array( 'object_class', 'object_id'),
- )
- );
+ "order_by_default" => ['date' => false],
+ 'indexes' => [
+ [ 'object_class', 'object_id'],
+ ],
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeExternalKey("trigger_id", array("targetclass"=>"Trigger", "jointype"=> "", "allowed_values"=>null, "sql"=>"trigger_id", "is_null_allowed"=>false, "on_target_delete"=>DEL_AUTO, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeExternalKey("action_id", array("targetclass" => "Action", "jointype" => "", "allowed_values" => null, "sql" => "action_id", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => array())));
- MetaModel::Init_AddAttribute(new AttributeInteger("object_id", array("allowed_values" => null, "sql" => "object_id", "default_value" => 0, "is_null_allowed" => false, "depends_on" => array())));
- //@since 3.2.0
- MetaModel::Init_AddAttribute(new AttributeClass("object_class", array("class_category"=>"", "more_values"=>"", "sql"=>"object_class", "default_value"=>null, "is_null_allowed"=>true /*to avoid setting AbstractResource as default in database*/, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeExternalKey("trigger_id", ["targetclass" => "Trigger", "jointype" => "", "allowed_values" => null, "sql" => "trigger_id", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeExternalKey("action_id", ["targetclass" => "Action", "jointype" => "", "allowed_values" => null, "sql" => "action_id", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeInteger("object_id", ["allowed_values" => null, "sql" => "object_id", "default_value" => 0, "is_null_allowed" => false, "depends_on" => []]));
+ //@since 3.2.0
+ MetaModel::Init_AddAttribute(new AttributeClass("object_class", ["class_category" => "", "more_values" => "", "sql" => "object_class", "default_value" => null, "is_null_allowed" => true /*to avoid setting AbstractResource as default in database*/, "depends_on" => []]));
// Display lists
- MetaModel::Init_SetZListItems('details', array('date', 'message', 'userinfo', 'trigger_id', 'action_id', 'object_class', 'object_id')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('date', 'message')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['date', 'message', 'userinfo', 'trigger_id', 'action_id', 'object_class', 'object_id']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['date', 'message']); // Attributes to be displayed for a list
// Search criteria
-// MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
-// MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
+ // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
+ // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
}
}
@@ -155,35 +154,35 @@ class EventNotificationEmail extends EventNotification
{
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "core/cmdb,view_in_gui",
"key_type" => "autoincrement",
"name_attcode" => "",
"state_attcode" => "",
- "reconc_keys" => array(),
+ "reconc_keys" => [],
"db_table" => "priv_event_email",
"db_key_field" => "id",
"db_finalclass_field" => "",
- "order_by_default" => array('date' => false)
- );
+ "order_by_default" => ['date' => false],
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeText("to", array("allowed_values"=>null, "sql"=>"to", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeText("cc", array("allowed_values"=>null, "sql"=>"cc", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeText("bcc", array("allowed_values"=>null, "sql"=>"bcc", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeText("from", array("allowed_values"=>null, "sql"=>"from", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeText("subject", array("allowed_values"=>null, "sql"=>"subject", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeHTML("body", array("allowed_values"=>null, "sql"=>"body", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeTable("attachments", array("allowed_values"=>null, "sql"=>"attachments", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeText("to", ["allowed_values" => null, "sql" => "to", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeText("cc", ["allowed_values" => null, "sql" => "cc", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeText("bcc", ["allowed_values" => null, "sql" => "bcc", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeText("from", ["allowed_values" => null, "sql" => "from", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeText("subject", ["allowed_values" => null, "sql" => "subject", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeHTML("body", ["allowed_values" => null, "sql" => "body", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeTable("attachments", ["allowed_values" => null, "sql" => "attachments", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
// Display lists
- MetaModel::Init_SetZListItems('details', array('date', 'userinfo', 'message', 'trigger_id', 'action_id', 'object_class', 'object_id', 'to', 'cc', 'bcc', 'from', 'subject', 'body', 'attachments')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('date', 'message', 'to', 'subject', 'attachments')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['date', 'userinfo', 'message', 'trigger_id', 'action_id', 'object_class', 'object_id', 'to', 'cc', 'bcc', 'from', 'subject', 'body', 'attachments']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['date', 'message', 'to', 'subject', 'attachments']); // Attributes to be displayed for a list
// Search criteria
-// MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
-// MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
+ // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
+ // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
}
}
@@ -191,34 +190,34 @@ class EventIssue extends Event
{
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "core/cmdb,view_in_gui",
"key_type" => "autoincrement",
"name_attcode" => "",
"state_attcode" => "",
- "reconc_keys" => array(),
+ "reconc_keys" => [],
"db_table" => "priv_event_issue",
"db_key_field" => "id",
"db_finalclass_field" => "",
- "order_by_default" => array('date' => false)
- );
+ "order_by_default" => ['date' => false],
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeString("issue", array("allowed_values"=>null, "sql"=>"issue", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeString("impact", array("allowed_values"=>null, "sql"=>"impact", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeString("page", array("allowed_values"=>null, "sql"=>"page", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributePropertySet("arguments_post", array("allowed_values"=>null, "sql"=>"arguments_post", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributePropertySet("arguments_get", array("allowed_values"=>null, "sql"=>"arguments_get", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeTable("callstack", array("allowed_values"=>null, "sql"=>"callstack", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributePropertySet("data", array("allowed_values"=>null, "sql"=>"data", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeString("issue", ["allowed_values" => null, "sql" => "issue", "default_value" => null, "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeString("impact", ["allowed_values" => null, "sql" => "impact", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeString("page", ["allowed_values" => null, "sql" => "page", "default_value" => null, "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributePropertySet("arguments_post", ["allowed_values" => null, "sql" => "arguments_post", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributePropertySet("arguments_get", ["allowed_values" => null, "sql" => "arguments_get", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeTable("callstack", ["allowed_values" => null, "sql" => "callstack", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributePropertySet("data", ["allowed_values" => null, "sql" => "data", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
// Display lists
- MetaModel::Init_SetZListItems('details', array('date', 'message', 'userinfo', 'issue', 'impact', 'page', 'arguments_post', 'arguments_get', 'callstack', 'data')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('date', 'userinfo', 'issue', 'impact')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['date', 'message', 'userinfo', 'issue', 'impact', 'page', 'arguments_post', 'arguments_get', 'callstack', 'data']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['date', 'userinfo', 'issue', 'impact']); // Attributes to be displayed for a list
// Search criteria
-// MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
-// MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
+ // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
+ // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
}
protected function OnInsert()
@@ -231,20 +230,16 @@ class EventIssue extends Event
$this->Set('userinfo', UserRights::GetUserId());
}
- if (array_key_exists('_GET', $GLOBALS) && is_array($GLOBALS['_GET']))
- {
+ if (array_key_exists('_GET', $GLOBALS) && is_array($GLOBALS['_GET'])) {
$this->Set('arguments_get', $this->SanitizeRequestParams($GLOBALS['_GET']));
- }
- else
- {
- $this->Set('arguments_get', array());
+ } else {
+ $this->Set('arguments_get', []);
}
- if (array_key_exists('_POST', $GLOBALS) && is_array($GLOBALS['_POST']))
- {
+ if (array_key_exists('_POST', $GLOBALS) && is_array($GLOBALS['_POST'])) {
$this->Set('arguments_post', $this->SanitizeRequestParams($GLOBALS['_POST']));
} else {
- $this->Set('arguments_post', array());
+ $this->Set('arguments_post', []);
}
$sLength = mb_strlen($this->Get('issue'));
if ($sLength > 255) {
@@ -281,44 +276,42 @@ class EventIssue extends Event
}
}
-
return $aSanitizedParams;
}
}
-
class EventWebService extends Event
{
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "core/cmdb,view_in_gui",
"key_type" => "autoincrement",
"name_attcode" => "",
"state_attcode" => "",
- "reconc_keys" => array(),
+ "reconc_keys" => [],
"db_table" => "priv_event_webservice",
"db_key_field" => "id",
"db_finalclass_field" => "",
- "order_by_default" => array('date' => false)
- );
+ "order_by_default" => ['date' => false],
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeString("verb", array("allowed_values"=>null, "sql"=>"verb", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeString("verb", ["allowed_values" => null, "sql" => "verb", "default_value" => null, "is_null_allowed" => false, "depends_on" => []]));
//MetaModel::Init_AddAttribute(new AttributeStructure("arguments", array("allowed_values"=>null, "sql"=>"data", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeBoolean("result", array("allowed_values"=>null, "sql"=>"result", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeText("log_info", array("allowed_values"=>null, "sql"=>"log_info", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeText("log_warning", array("allowed_values"=>null, "sql"=>"log_warning", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeText("log_error", array("allowed_values"=>null, "sql"=>"log_error", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeText("data", array("allowed_values"=>null, "sql"=>"data", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeBoolean("result", ["allowed_values" => null, "sql" => "result", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeText("log_info", ["allowed_values" => null, "sql" => "log_info", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeText("log_warning", ["allowed_values" => null, "sql" => "log_warning", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeText("log_error", ["allowed_values" => null, "sql" => "log_error", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeText("data", ["allowed_values" => null, "sql" => "data", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
// Display lists
- MetaModel::Init_SetZListItems('details', array('date', 'userinfo', 'verb', 'result', 'log_info', 'log_warning', 'log_error', 'data')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('date', 'userinfo', 'verb', 'result')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['date', 'userinfo', 'verb', 'result', 'log_info', 'log_warning', 'log_error', 'data']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['date', 'userinfo', 'verb', 'result']); // Attributes to be displayed for a list
// Search criteria
-// MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
-// MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
+ // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
+ // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
}
}
@@ -326,34 +319,34 @@ class EventRestService extends Event
{
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "core/cmdb,view_in_gui",
"key_type" => "autoincrement",
"name_attcode" => "",
"state_attcode" => "",
- "reconc_keys" => array(),
+ "reconc_keys" => [],
"db_table" => "priv_event_restservice",
"db_key_field" => "id",
"db_finalclass_field" => "",
- "order_by_default" => array('date' => false)
- );
+ "order_by_default" => ['date' => false],
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeString("operation", array("allowed_values"=>null, "sql"=>"operation", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeString("version", array("allowed_values"=>null, "sql"=>"version", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeText("json_input", array("allowed_values"=>null, "sql"=>"json_input", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeString("operation", ["allowed_values" => null, "sql" => "operation", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeString("version", ["allowed_values" => null, "sql" => "version", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeText("json_input", ["allowed_values" => null, "sql" => "json_input", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
- MetaModel::Init_AddAttribute(new AttributeInteger("code", array("allowed_values"=>null, "sql"=>"code", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeText("json_output", array("allowed_values"=>null, "sql"=>"json_output", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeString("provider", array("allowed_values"=>null, "sql"=>"provider", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeInteger("code", ["allowed_values" => null, "sql" => "code", "default_value" => 0, "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeText("json_output", ["allowed_values" => null, "sql" => "json_output", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeString("provider", ["allowed_values" => null, "sql" => "provider", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
// Display lists
- MetaModel::Init_SetZListItems('details', array('date', 'userinfo', 'operation', 'version', 'json_input', 'message', 'code', 'json_output', 'provider')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('date', 'userinfo', 'operation', 'message')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['date', 'userinfo', 'operation', 'version', 'json_input', 'message', 'code', 'json_output', 'provider']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['date', 'userinfo', 'operation', 'message']); // Attributes to be displayed for a list
// Search criteria
-// MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
-// MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
+ // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
+ // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
}
}
@@ -361,66 +354,64 @@ class EventLoginUsage extends Event
{
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "core/cmdb,view_in_gui",
"key_type" => "autoincrement",
"name_attcode" => "",
"state_attcode" => "",
- "reconc_keys" => array(),
+ "reconc_keys" => [],
"db_table" => "priv_event_loginusage",
"db_key_field" => "id",
"db_finalclass_field" => "",
- "order_by_default" => array('date' => false)
- );
+ "order_by_default" => ['date' => false],
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeExternalKey("user_id", array("targetclass"=>"User", "jointype"=> "", "allowed_values"=>null, "sql"=>"user_id", "is_null_allowed"=>false, "on_target_delete"=>DEL_SILENT, "depends_on"=>array())));
- $aZList = array('date', 'user_id');
- if (MetaModel::IsValidAttCode('Contact', 'name'))
- {
- MetaModel::Init_AddAttribute(new AttributeExternalField("contact_name", array("allowed_values"=>null, "extkey_attcode"=>"user_id", "target_attcode"=>"contactid", "is_null_allowed"=>true, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeExternalKey("user_id", ["targetclass" => "User", "jointype" => "", "allowed_values" => null, "sql" => "user_id", "is_null_allowed" => false, "on_target_delete" => DEL_SILENT, "depends_on" => []]));
+ $aZList = ['date', 'user_id'];
+ if (MetaModel::IsValidAttCode('Contact', 'name')) {
+ MetaModel::Init_AddAttribute(new AttributeExternalField("contact_name", ["allowed_values" => null, "extkey_attcode" => "user_id", "target_attcode" => "contactid", "is_null_allowed" => true, "depends_on" => []]));
$aZList[] = 'contact_name';
}
- if (MetaModel::IsValidAttCode('Contact', 'email'))
- {
- MetaModel::Init_AddAttribute(new AttributeExternalField("contact_email", array("allowed_values"=>null, "extkey_attcode"=>"user_id", "target_attcode"=>"email", "is_null_allowed"=>true, "depends_on"=>array())));
+ if (MetaModel::IsValidAttCode('Contact', 'email')) {
+ MetaModel::Init_AddAttribute(new AttributeExternalField("contact_email", ["allowed_values" => null, "extkey_attcode" => "user_id", "target_attcode" => "email", "is_null_allowed" => true, "depends_on" => []]));
$aZList[] = 'contact_email';
}
// Display lists
- MetaModel::Init_SetZListItems('details', array_merge($aZList, array('userinfo', 'message'))); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array_merge($aZList, array('userinfo'))); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', array_merge($aZList, ['userinfo', 'message'])); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', array_merge($aZList, ['userinfo'])); // Attributes to be displayed for a list
// Search criteria
MetaModel::Init_SetZListItems('standard_search', $aZList); // Criteria of the std search form
-// MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
+ // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
}
}
class EventOnObject extends Event
{
- public static function Init()
- {
- $aParams = array
- (
- "category" => "core/cmdb,view_in_gui",
- "key_type" => "autoincrement",
- "name_attcode" => "",
- "state_attcode" => "",
- "reconc_keys" => array(),
- "db_table" => "priv_event_onobject",
- "db_key_field" => "id",
- "db_finalclass_field" => "",
- "display_template" => "",
- "order_by_default" => array('date' => false)
- );
- MetaModel::Init_Params($aParams);
- MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeString("obj_class", array("allowed_values"=>null, "sql"=>"obj_class", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeInteger("obj_key", array("allowed_values"=>null, "sql"=>"obj_key", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
+ public static function Init()
+ {
+ $aParams =
+ [
+ "category" => "core/cmdb,view_in_gui",
+ "key_type" => "autoincrement",
+ "name_attcode" => "",
+ "state_attcode" => "",
+ "reconc_keys" => [],
+ "db_table" => "priv_event_onobject",
+ "db_key_field" => "id",
+ "db_finalclass_field" => "",
+ "display_template" => "",
+ "order_by_default" => ['date' => false],
+ ];
+ MetaModel::Init_Params($aParams);
+ MetaModel::Init_InheritAttributes();
+ MetaModel::Init_AddAttribute(new AttributeString("obj_class", ["allowed_values" => null, "sql" => "obj_class", "default_value" => null, "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeInteger("obj_key", ["allowed_values" => null, "sql" => "obj_key", "default_value" => null, "is_null_allowed" => false, "depends_on" => []]));
- // Display lists
- MetaModel::Init_SetZListItems('details', array('date', 'userinfo', 'obj_class', 'obj_key', 'message')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('date', 'userinfo', 'obj_class', 'obj_key', 'message')); // Attributes to be displayed for a list
- }
+ // Display lists
+ MetaModel::Init_SetZListItems('details', ['date', 'userinfo', 'obj_class', 'obj_key', 'message']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['date', 'userinfo', 'obj_class', 'obj_key', 'message']); // Attributes to be displayed for a list
+ }
}
diff --git a/core/inlineimage.class.inc.php b/core/inlineimage.class.inc.php
index f14296681..b0cb500a8 100644
--- a/core/inlineimage.class.inc.php
+++ b/core/inlineimage.class.inc.php
@@ -1,4 +1,5 @@
'addon',
'key_type' => 'autoincrement',
- 'name_attcode' => array('item_class', 'temp_id'),
+ 'name_attcode' => ['item_class', 'temp_id'],
'state_attcode' => '',
- 'reconc_keys' => array(''),
+ 'reconc_keys' => [''],
'db_table' => 'inline_image',
'db_key_field' => 'id',
'db_finalclass_field' => '',
- 'indexes' => array(
- array('temp_id'),
- array('item_class', 'item_id'),
- array('item_org_id'),
- ),
- );
+ 'indexes' => [
+ ['temp_id'],
+ ['item_class', 'item_id'],
+ ['item_org_id'],
+ ],
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeDateTime("expire", array("allowed_values" => null, "sql" => 'expire', "default_value" => 'DATE_ADD(NOW(), INTERVAL 1 DAY)', "is_null_allowed" => false, "depends_on" => array(), "always_load_in_tables" => false)));
- MetaModel::Init_AddAttribute(new AttributeString("temp_id", array("allowed_values"=>null, "sql"=>'temp_id', "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array(), "always_load_in_tables"=>false)));
- MetaModel::Init_AddAttribute(new AttributeString("item_class", array("allowed_values"=>null, "sql"=>'item_class', "default_value"=>'', "is_null_allowed"=>false, "depends_on"=>array(), "always_load_in_tables"=>false)));
- MetaModel::Init_AddAttribute(new AttributeObjectKey("item_id", array("class_attcode"=>'item_class', "allowed_values"=>null, "sql"=>'item_id', "is_null_allowed"=>true, "depends_on"=>array(), "always_load_in_tables"=>false)));
- MetaModel::Init_AddAttribute(new AttributeInteger("item_org_id", array("allowed_values"=>null, "sql"=>'item_org_id', "default_value"=>'0', "is_null_allowed"=>true, "depends_on"=>array(), "always_load_in_tables"=>false)));
- MetaModel::Init_AddAttribute(new AttributeBlob("contents", array("is_null_allowed"=>false, "depends_on"=>array(), "always_load_in_tables"=>false)));
- MetaModel::Init_AddAttribute(new AttributeString("secret", array("allowed_values"=>null, "sql" => "secret", "default_value"=>'', "is_null_allowed"=>false, "depends_on"=>array(), "always_load_in_tables"=>false)));
+ MetaModel::Init_AddAttribute(new AttributeDateTime("expire", ["allowed_values" => null, "sql" => 'expire', "default_value" => 'DATE_ADD(NOW(), INTERVAL 1 DAY)', "is_null_allowed" => false, "depends_on" => [], "always_load_in_tables" => false]));
+ MetaModel::Init_AddAttribute(new AttributeString("temp_id", ["allowed_values" => null, "sql" => 'temp_id', "default_value" => '', "is_null_allowed" => true, "depends_on" => [], "always_load_in_tables" => false]));
+ MetaModel::Init_AddAttribute(new AttributeString("item_class", ["allowed_values" => null, "sql" => 'item_class', "default_value" => '', "is_null_allowed" => false, "depends_on" => [], "always_load_in_tables" => false]));
+ MetaModel::Init_AddAttribute(new AttributeObjectKey("item_id", ["class_attcode" => 'item_class', "allowed_values" => null, "sql" => 'item_id', "is_null_allowed" => true, "depends_on" => [], "always_load_in_tables" => false]));
+ MetaModel::Init_AddAttribute(new AttributeInteger("item_org_id", ["allowed_values" => null, "sql" => 'item_org_id', "default_value" => '0', "is_null_allowed" => true, "depends_on" => [], "always_load_in_tables" => false]));
+ MetaModel::Init_AddAttribute(new AttributeBlob("contents", ["is_null_allowed" => false, "depends_on" => [], "always_load_in_tables" => false]));
+ MetaModel::Init_AddAttribute(new AttributeString("secret", ["allowed_values" => null, "sql" => "secret", "default_value" => '', "is_null_allowed" => false, "depends_on" => [], "always_load_in_tables" => false]));
-
- MetaModel::Init_SetZListItems('details', array('temp_id', 'item_class', 'item_id', 'item_org_id'));
- MetaModel::Init_SetZListItems('standard_search', array('temp_id', 'item_class', 'item_id'));
- MetaModel::Init_SetZListItems('list', array('temp_id', 'item_class', 'item_id' ));
+ MetaModel::Init_SetZListItems('details', ['temp_id', 'item_class', 'item_id', 'item_org_id']);
+ MetaModel::Init_SetZListItems('standard_search', ['temp_id', 'item_class', 'item_id']);
+ MetaModel::Init_SetZListItems('list', ['temp_id', 'item_class', 'item_id' ]);
}
-
/**
* Maps the given context parameter name to the appropriate filter/search code for this class
*
@@ -77,12 +76,9 @@ class InlineImage extends DBObject
*/
public static function MapContextParam($sContextParam)
{
- if ($sContextParam == 'org_id')
- {
+ if ($sContextParam == 'org_id') {
return 'item_org_id';
- }
- else
- {
+ } else {
return null;
}
}
@@ -104,23 +100,18 @@ class InlineImage extends DBObject
$sClass = get_class($oItem);
$iItemId = $oItem->GetKey();
- $this->Set('item_class', $sClass);
- $this->Set('item_id', $iItemId);
+ $this->Set('item_class', $sClass);
+ $this->Set('item_id', $iItemId);
- $aCallSpec = array($sClass, 'MapContextParam');
- if (is_callable($aCallSpec))
- {
+ $aCallSpec = [$sClass, 'MapContextParam'];
+ if (is_callable($aCallSpec)) {
$sAttCode = call_user_func($aCallSpec, 'org_id'); // Returns null when there is no mapping for this parameter
- if (MetaModel::IsValidAttCode($sClass, $sAttCode))
- {
+ if (MetaModel::IsValidAttCode($sClass, $sAttCode)) {
$iOrgId = $oItem->Get($sAttCode);
- if ($iOrgId > 0)
- {
- if ($iOrgId != $this->Get('item_org_id'))
- {
+ if ($iOrgId > 0) {
+ if ($iOrgId != $this->Get('item_org_id')) {
$this->Set('item_org_id', $iOrgId);
- if ($bUpdateOnChange)
- {
+ if ($bUpdateOnChange) {
$this->DBUpdate();
}
}
@@ -143,29 +134,23 @@ class InlineImage extends DBObject
// First check that the organization CAN be fetched from the target class
//
$sClass = $this->Get('item_class');
- $aCallSpec = array($sClass, 'MapContextParam');
- if (is_callable($aCallSpec))
- {
+ $aCallSpec = [$sClass, 'MapContextParam'];
+ if (is_callable($aCallSpec)) {
$sAttCode = call_user_func($aCallSpec, 'org_id'); // Returns null when there is no mapping for this parameter
- if (MetaModel::IsValidAttCode($sClass, $sAttCode))
- {
+ if (MetaModel::IsValidAttCode($sClass, $sAttCode)) {
// Second: check that the organization CAN be fetched from the current user
//
- if (MetaModel::IsValidClass('Person'))
- {
- $aCallSpec = array($sClass, 'MapContextParam');
- if (is_callable($aCallSpec))
- {
+ if (MetaModel::IsValidClass('Person')) {
+ $aCallSpec = [$sClass, 'MapContextParam'];
+ if (is_callable($aCallSpec)) {
$sAttCode = call_user_func($aCallSpec, 'org_id'); // Returns null when there is no mapping for this parameter
- if (MetaModel::IsValidAttCode($sClass, $sAttCode))
- {
+ if (MetaModel::IsValidAttCode($sClass, $sAttCode)) {
// OK - try it
//
$oCurrentPerson = MetaModel::GetObject('Person', UserRights::GetContactId(), false);
- if ($oCurrentPerson)
- {
- $this->Set('item_org_id', $oCurrentPerson->Get($sAttCode));
- }
+ if ($oCurrentPerson) {
+ $this->Set('item_org_id', $oCurrentPerson->Get($sAttCode));
+ }
}
}
}
@@ -189,39 +174,37 @@ class InlineImage extends DBObject
public static function FinalizeInlineImages(DBObject $oObject)
{
$iTransactionId = utils::ReadParam('transaction_id', null, false, 'transaction_id');
- if (!is_null($iTransactionId))
- {
+ if (!is_null($iTransactionId)) {
// Attach new (temporary) inline images
$sTempId = utils::GetUploadTempId($iTransactionId);
// The object is being created from a form, check if there are pending inline images for this object
$sOQL = 'SELECT InlineImage WHERE temp_id = :temp_id';
$oSearch = DBObjectSearch::FromOQL($sOQL);
- $oSet = new DBObjectSet($oSearch, array(), array('temp_id' => $sTempId));
- $aInlineImagesId = array();
+ $oSet = new DBObjectSet($oSearch, [], ['temp_id' => $sTempId]);
+ $aInlineImagesId = [];
while ($oInlineImage = $oSet->Fetch()) {
$aInlineImagesId[] = $oInlineImage->GetKey();
$oInlineImage->SetItem($oObject);
$oInlineImage->Set('temp_id', '');
$oInlineImage->DBUpdate();
}
- IssueLog::Trace('FinalizeInlineImages (see $aInlineImagesId for the id list)', LogChannels::INLINE_IMAGE, array(
+ IssueLog::Trace('FinalizeInlineImages (see $aInlineImagesId for the id list)', LogChannels::INLINE_IMAGE, [
'$sObjectClass' => get_class($oObject),
'$sTransactionId' => $iTransactionId,
'$sTempId' => $sTempId,
'$aInlineImagesId' => $aInlineImagesId,
'$sUser' => UserRights::GetUser(),
'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'],
- ));
+ ]);
+ } else {
+ IssueLog::Trace('FinalizeInlineImages "error" $iTransactionId is null', LogChannels::INLINE_IMAGE, [
+ '$sObjectClass' => get_class($oObject),
+ '$sTransactionId' => $iTransactionId,
+ '$sUser' => UserRights::GetUser(),
+ 'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'],
+ ]);
}
- else {
- IssueLog::Trace('FinalizeInlineImages "error" $iTransactionId is null', LogChannels::INLINE_IMAGE, array(
- '$sObjectClass' => get_class($oObject),
- '$sTransactionId' => $iTransactionId,
- '$sUser' => UserRights::GetUser(),
- 'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'],
- ));
- }
}
/**
@@ -243,11 +226,11 @@ class InlineImage extends DBObject
{
// Protection against unfortunate massive delete of inline images when a null temp ID is passed
if (utils::IsNullOrEmptyString($sTempId)) {
- IssueLog::Trace('OnFormCancel "error" $sTempId is null or empty', LogChannels::INLINE_IMAGE, array(
+ IssueLog::Trace('OnFormCancel "error" $sTempId is null or empty', LogChannels::INLINE_IMAGE, [
'$sTempId' => $sTempId,
'$sUser' => UserRights::GetUser(),
'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'],
- ));
+ ]);
return false;
}
@@ -255,19 +238,18 @@ class InlineImage extends DBObject
// Delete all "pending" InlineImages for this form
$sOQL = 'SELECT InlineImage WHERE temp_id = :temp_id';
$oSearch = DBObjectSearch::FromOQL($sOQL);
- $oSet = new DBObjectSet($oSearch, array(), array('temp_id' => $sTempId));
- $aInlineImagesId = array();
- while($oInlineImage = $oSet->Fetch())
- {
- $aInlineImagesId[] = $oInlineImage->GetKey();
+ $oSet = new DBObjectSet($oSearch, [], ['temp_id' => $sTempId]);
+ $aInlineImagesId = [];
+ while ($oInlineImage = $oSet->Fetch()) {
+ $aInlineImagesId[] = $oInlineImage->GetKey();
$oInlineImage->DBDelete();
}
- IssueLog::Trace('OnFormCancel', LogChannels::INLINE_IMAGE, array(
+ IssueLog::Trace('OnFormCancel', LogChannels::INLINE_IMAGE, [
'$sTempId' => $sTempId,
'$aInlineImagesId' => $aInlineImagesId,
'$sUser' => UserRights::GetUser(),
'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'],
- ));
+ ]);
return true;
}
@@ -284,15 +266,17 @@ class InlineImage extends DBObject
*/
public static function FixUrls($sHtml)
{
- $aNeedles = array();
- $aReplacements = array();
+ $aNeedles = [];
+ $aReplacements = [];
// Find img tags with an attribute data-img-id
- if (preg_match_all('/ ]*)'.self::DOM_ATTR_ID.'="([0-9]+)"([^>]*)>/i',
- $sHtml, $aMatches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE))
- {
+ if (preg_match_all(
+ '/ ]*)'.self::DOM_ATTR_ID.'="([0-9]+)"([^>]*)>/i',
+ $sHtml,
+ $aMatches,
+ PREG_SET_ORDER | PREG_OFFSET_CAPTURE
+ )) {
$sUrl = utils::GetAbsoluteUrlAppRoot().INLINEIMAGE_DOWNLOAD_URL;
- foreach($aMatches as $aImgInfo)
- {
+ foreach ($aMatches as $aImgInfo) {
$sImgTag = $aImgInfo[0][0];
$sSecret = '';
if (preg_match('/data-img-secret="([0-9a-f]+)"/', $sImgTag, $aSecretMatches)) {
@@ -321,11 +305,10 @@ class InlineImage extends DBObject
public static function ProcessImageTag(DOMElement $oElement)
{
$sSrc = $oElement->getAttribute('src');
- $sDownloadUrl = str_replace(array('.', '?'), array('\.', '\?'), INLINEIMAGE_DOWNLOAD_URL); // Escape . and ?
+ $sDownloadUrl = str_replace(['.', '?'], ['\.', '\?'], INLINEIMAGE_DOWNLOAD_URL); // Escape . and ?
$sUrlPattern = '|'.$sDownloadUrl.'([0-9]+)&s=([0-9a-f]+)|';
$bIsInlineImage = preg_match($sUrlPattern, $sSrc, $aMatches);
- if (!$bIsInlineImage)
- {
+ if (!$bIsInlineImage) {
return;
}
$iInlineImageId = $aMatches[1];
@@ -334,8 +317,7 @@ class InlineImage extends DBObject
$sAppRoot = utils::GetAbsoluteUrlAppRoot();
$sAppRootPattern = '/^'.preg_quote($sAppRoot, '/').'/';
$bIsSameItop = preg_match($sAppRootPattern, $sSrc);
- if (!$bIsSameItop)
- {
+ if (!$bIsSameItop) {
// @see N°1921
// image from another iTop should be treated as external images
$oElement->removeAttribute(self::DOM_ATTR_ID);
@@ -357,8 +339,7 @@ class InlineImage extends DBObject
{
$iMaxWidth = (int)MetaModel::GetConfig()->Get('inline_image_max_display_width', 0);
$sJS = '';
- if ($iMaxWidth != 0)
- {
+ if ($iMaxWidth != 0) {
$sJS =
<< 1024*1024*1024)
- {
- $sRet = Dict::Format('Attachment:Max_Go', sprintf('%0.2f', $iMaxUpload/(1024*1024*1024)));
- }
- else if ($iMaxUpload > 1024*1024)
- {
- $sRet = Dict::Format('Attachment:Max_Mo', sprintf('%0.2f', $iMaxUpload/(1024*1024)));
- }
- else
- {
- $sRet = Dict::Format('Attachment:Max_Ko', sprintf('%0.2f', $iMaxUpload/(1024)));
+ if ($iMaxUpload > 1024 * 1024 * 1024) {
+ $sRet = Dict::Format('Attachment:Max_Go', sprintf('%0.2f', $iMaxUpload / (1024 * 1024 * 1024)));
+ } elseif ($iMaxUpload > 1024 * 1024) {
+ $sRet = Dict::Format('Attachment:Max_Mo', sprintf('%0.2f', $iMaxUpload / (1024 * 1024)));
+ } else {
+ $sRet = Dict::Format('Attachment:Max_Ko', sprintf('%0.2f', $iMaxUpload / (1024)));
}
}
return $sRet;
@@ -469,73 +443,71 @@ JS
JS;
}
+ /**
+ * @inheritDoc
+ */
+ protected function AfterInsert()
+ {
+ IssueLog::Trace(__METHOD__, LogChannels::INLINE_IMAGE, [
+ 'id' => $this->GetKey(),
+ 'expire' => $this->Get('expire'),
+ 'temp_id' => $this->Get('temp_id'),
+ 'item_class' => $this->Get('item_class'),
+ 'item_id' => $this->Get('item_id'),
+ 'item_org_id' => $this->Get('item_org_id'),
+ 'secret' => $this->Get('secret'),
+ 'user' => $sUser = UserRights::GetUser(),
+ 'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'],
+ 'REQUEST_URI' => @$_SERVER['REQUEST_URI'],
+ ]);
+
+ parent::AfterInsert();
+ }
/**
* @inheritDoc
*/
- protected function AfterInsert()
- {
- IssueLog::Trace(__METHOD__, LogChannels::INLINE_IMAGE, array(
- 'id' => $this->GetKey(),
- 'expire' => $this->Get('expire'),
- 'temp_id' => $this->Get('temp_id'),
- 'item_class' => $this->Get('item_class'),
- 'item_id' => $this->Get('item_id'),
- 'item_org_id' => $this->Get('item_org_id'),
- 'secret' => $this->Get('secret'),
- 'user' => $sUser = UserRights::GetUser(),
- 'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'],
- 'REQUEST_URI' => @$_SERVER['REQUEST_URI'],
- ));
+ protected function AfterUpdate()
+ {
+ IssueLog::Trace(__METHOD__, LogChannels::INLINE_IMAGE, [
+ 'id' => $this->GetKey(),
+ 'expire' => $this->Get('expire'),
+ 'temp_id' => $this->Get('temp_id'),
+ 'item_class' => $this->Get('item_class'),
+ 'item_id' => $this->Get('item_id'),
+ 'item_org_id' => $this->Get('item_org_id'),
+ 'secret' => $this->Get('secret'),
+ 'user' => $sUser = UserRights::GetUser(),
+ 'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'],
+ 'REQUEST_URI' => @$_SERVER['REQUEST_URI'],
+ ]);
- parent::AfterInsert();
- }
-
- /**
- * @inheritDoc
- */
- protected function AfterUpdate()
- {
- IssueLog::Trace(__METHOD__, LogChannels::INLINE_IMAGE, array(
- 'id' => $this->GetKey(),
- 'expire' => $this->Get('expire'),
- 'temp_id' => $this->Get('temp_id'),
- 'item_class' => $this->Get('item_class'),
- 'item_id' => $this->Get('item_id'),
- 'item_org_id' => $this->Get('item_org_id'),
- 'secret' => $this->Get('secret'),
- 'user' => $sUser = UserRights::GetUser(),
- 'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'],
- 'REQUEST_URI' => @$_SERVER['REQUEST_URI'],
- ));
-
- parent::AfterUpdate();
- }
+ parent::AfterUpdate();
+ }
/**
* @inheritDoc
*/
protected function AfterDelete()
- {
- IssueLog::Trace(__METHOD__, LogChannels::INLINE_IMAGE, array(
- 'id' => $this->GetKey(),
- 'expire' => $this->Get('expire'),
- 'temp_id' => $this->Get('temp_id'),
- 'item_class' => $this->Get('item_class'),
- 'item_id' => $this->Get('item_id'),
- 'item_org_id' => $this->Get('item_org_id'),
- 'secret' => $this->Get('secret'),
- 'user' => $sUser = UserRights::GetUser(),
- 'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'],
- 'REQUEST_URI' => @$_SERVER['REQUEST_URI'],
- ));
+ {
+ IssueLog::Trace(__METHOD__, LogChannels::INLINE_IMAGE, [
+ 'id' => $this->GetKey(),
+ 'expire' => $this->Get('expire'),
+ 'temp_id' => $this->Get('temp_id'),
+ 'item_class' => $this->Get('item_class'),
+ 'item_id' => $this->Get('item_id'),
+ 'item_org_id' => $this->Get('item_org_id'),
+ 'secret' => $this->Get('secret'),
+ 'user' => $sUser = UserRights::GetUser(),
+ 'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'],
+ 'REQUEST_URI' => @$_SERVER['REQUEST_URI'],
+ ]);
- parent::AfterDelete();
- }
+ parent::AfterDelete();
+ }
}
-
/**
* Garbage collector for cleaning "old" temporary InlineImages (and Attachments).
*/
@@ -545,9 +517,9 @@ class InlineImageGC implements iBackgroundProcess
* @inheritDoc
*/
public function GetPeriodicity()
- {
- return 1;
- }
+ {
+ return 1;
+ }
/**
* @inheritDoc
@@ -556,13 +528,11 @@ class InlineImageGC implements iBackgroundProcess
{
$sDateLimit = date(AttributeDateTime::GetSQLFormat(), time()); // Every temporary InlineImage/Attachment expired will be deleted
- $aResults = array();
- $aClasses = array('InlineImage', 'Attachment');
- foreach($aClasses as $sClass)
- {
+ $aResults = [];
+ $aClasses = ['InlineImage', 'Attachment'];
+ foreach ($aClasses as $sClass) {
$iProcessed = 0;
- if(class_exists($sClass))
- {
+ if (class_exists($sClass)) {
$iProcessed = $this->DeleteExpiredDocuments($sClass, $iTimeLimit, $sDateLimit);
}
$aResults[] = "$iProcessed old temporary $sClass(s)";
@@ -591,11 +561,15 @@ class InlineImageGC implements iBackgroundProcess
$iProcessed = 0;
$sOQL = "SELECT $sClass WHERE (item_id = 0) AND (expire < '$sDateLimit')";
// Next one ?
- $oSet = new CMDBObjectSet(DBObjectSearch::FromOQL($sOQL), array('expire' => true) /* order by*/, array(), null,
- 1 /* limit count */);
- $oSet->OptimizeColumnLoad(array());
- while ((time() < $iTimeLimit) && ($oResult = $oSet->Fetch()))
- {
+ $oSet = new CMDBObjectSet(
+ DBObjectSearch::FromOQL($sOQL),
+ ['expire' => true] /* order by*/,
+ [],
+ null,
+ 1 /* limit count */
+ );
+ $oSet->OptimizeColumnLoad([]);
+ while ((time() < $iTimeLimit) && ($oResult = $oSet->Fetch())) {
/** @var \ormDocument $oDocument */
$oDocument = $oResult->Get('contents');
IssueLog::Info($sClass.' GC: Removed temp. file '.$oDocument->GetFileName().' on "'.$oResult->Get('item_class').'" #'.$oResult->Get('item_id').' as it has expired.');
@@ -605,4 +579,4 @@ class InlineImageGC implements iBackgroundProcess
return $iProcessed;
}
-}
\ No newline at end of file
+}
diff --git a/core/kpi.class.inc.php b/core/kpi.class.inc.php
index 86a1d2671..fd6f83feb 100644
--- a/core/kpi.class.inc.php
+++ b/core/kpi.class.inc.php
@@ -1,4 +1,5 @@
0) {
self::$m_bEnabled_Duration = true;
@@ -47,7 +47,7 @@ class ExecutionKPI
}
}
- static public function EnableMemory($iLevel)
+ public static function EnableMemory($iLevel)
{
if ($iLevel > 0) {
self::$m_bEnabled_Memory = true;
@@ -57,91 +57,94 @@ class ExecutionKPI
}
/**
- * @param string sUser A user login or * for all users
- */
- static public function SetAllowedUser($sUser)
+ * @param string sUser A user login or * for all users
+ */
+ public static function SetAllowedUser($sUser)
{
self::$m_sAllowedUser = $sUser;
}
- static public function IsEnabled()
+ public static function IsEnabled()
{
- if (self::$m_bEnabled_Duration || self::$m_bEnabled_Memory)
- {
- if ((self::$m_sAllowedUser == '*') || (UserRights::GetUser() == trim(self::$m_sAllowedUser)))
- {
+ if (self::$m_bEnabled_Duration || self::$m_bEnabled_Memory) {
+ if ((self::$m_sAllowedUser == '*') || (UserRights::GetUser() == trim(self::$m_sAllowedUser))) {
return true;
}
}
return false;
}
- static public function SetGenerateLegacyReport($bReportExtensionsOnly)
- {
- self::$m_bGenerateLegacyReport = $bReportExtensionsOnly;
- }
-
- static public function SetSlowQueries($fSlowQueries)
- {
- self::$m_fSlowQueries = $fSlowQueries;
- }
-
- static public function GetDescription()
+ public static function SetGenerateLegacyReport($bReportExtensionsOnly)
{
- $aFeatures = array();
- if (self::$m_bEnabled_Duration) $aFeatures[] = 'Duration';
- if (self::$m_bEnabled_Memory) $aFeatures[] = 'Memory usage';
- $sFeatures = 'Measures: '.implode(', ', $aFeatures);
- $sFor = self::$m_sAllowedUser == '*' ? 'EVERYBODY' : "'".trim(self::$m_sAllowedUser)."'";
- $sSlowQueries = '';
- if (self::$m_fSlowQueries > 0) {
- $sSlowQueries = ". Slow Queries: ".self::$m_fSlowQueries."s";
- }
-
- $aExtensions = [];
- /** @var \iKPILoggerExtension $oExtensionInstance */
- foreach (MetaModel::EnumPlugins('iKPILoggerExtension') as $oExtensionInstance) {
- $aExtensions[] = ModuleService::GetInstance()->GetModuleNameFromObject($oExtensionInstance);
- }
- $sExtensions = '';
- if (count($aExtensions) > 0) {
- $sExtensions = '. KPI Extensions: ['.implode(', ', $aExtensions).']';
- }
-
- return "KPI logging is active for $sFor. $sFeatures$sSlowQueries$sExtensions";
+ self::$m_bGenerateLegacyReport = $bReportExtensionsOnly;
}
- static public function ReportStats()
+ public static function SetSlowQueries($fSlowQueries)
{
- if (!self::IsEnabled()) return;
+ self::$m_fSlowQueries = $fSlowQueries;
+ }
+
+ public static function GetDescription()
+ {
+ $aFeatures = [];
+ if (self::$m_bEnabled_Duration) {
+ $aFeatures[] = 'Duration';
+ }
+ if (self::$m_bEnabled_Memory) {
+ $aFeatures[] = 'Memory usage';
+ }
+ $sFeatures = 'Measures: '.implode(', ', $aFeatures);
+ $sFor = self::$m_sAllowedUser == '*' ? 'EVERYBODY' : "'".trim(self::$m_sAllowedUser)."'";
+ $sSlowQueries = '';
+ if (self::$m_fSlowQueries > 0) {
+ $sSlowQueries = ". Slow Queries: ".self::$m_fSlowQueries."s";
+ }
+
+ $aExtensions = [];
+ /** @var \iKPILoggerExtension $oExtensionInstance */
+ foreach (MetaModel::EnumPlugins('iKPILoggerExtension') as $oExtensionInstance) {
+ $aExtensions[] = ModuleService::GetInstance()->GetModuleNameFromObject($oExtensionInstance);
+ }
+ $sExtensions = '';
+ if (count($aExtensions) > 0) {
+ $sExtensions = '. KPI Extensions: ['.implode(', ', $aExtensions).']';
+ }
+
+ return "KPI logging is active for $sFor. $sFeatures$sSlowQueries$sExtensions";
+ }
+
+ public static function ReportStats()
+ {
+ if (!self::IsEnabled()) {
+ return;
+ }
global $fItopStarted;
- global $iItopInitialMemory;
+ global $iItopInitialMemory;
$sExecId = microtime(); // id to differentiate the hrefs!
- $sRequest = $_SERVER['REQUEST_URI'].' ('.$_SERVER['REQUEST_METHOD'].')';
- if (isset($_POST['operation'])) {
- $sRequest .= ' operation: '.$_POST['operation'];
- }
+ $sRequest = $_SERVER['REQUEST_URI'].' ('.$_SERVER['REQUEST_METHOD'].')';
+ if (isset($_POST['operation'])) {
+ $sRequest .= ' operation: '.$_POST['operation'];
+ }
- $fStop = MyHelpers::getmicrotime();
- if (($fStop - $fItopStarted) > self::$m_fSlowQueries) {
- // Invoke extensions to log the KPI operation
- /** @var \iKPILoggerExtension $oExtensionInstance */
- $iCurrentMemory = self::memory_get_usage();
- $iPeakMemory = self::memory_get_peak_usage();
- foreach (MetaModel::EnumPlugins('iKPILoggerExtension') as $oExtensionInstance) {
- $oKPILogData = new KpiLogData(KpiLogData::TYPE_REQUEST, 'Page', $sRequest, $fItopStarted, $fStop, '', $iItopInitialMemory, $iCurrentMemory, $iPeakMemory);
- $oExtensionInstance->LogOperation($oKPILogData);
- }
- }
+ $fStop = MyHelpers::getmicrotime();
+ if (($fStop - $fItopStarted) > self::$m_fSlowQueries) {
+ // Invoke extensions to log the KPI operation
+ /** @var \iKPILoggerExtension $oExtensionInstance */
+ $iCurrentMemory = self::memory_get_usage();
+ $iPeakMemory = self::memory_get_peak_usage();
+ foreach (MetaModel::EnumPlugins('iKPILoggerExtension') as $oExtensionInstance) {
+ $oKPILogData = new KpiLogData(KpiLogData::TYPE_REQUEST, 'Page', $sRequest, $fItopStarted, $fStop, '', $iItopInitialMemory, $iCurrentMemory, $iPeakMemory);
+ $oExtensionInstance->LogOperation($oKPILogData);
+ }
+ }
- if (!self::$m_bGenerateLegacyReport) {
- return;
- }
+ if (!self::$m_bGenerateLegacyReport) {
+ return;
+ }
- $aBeginTimes = array();
- foreach (self::$m_aExecData as $aOpStats)
- {
+ $aBeginTimes = [];
+ foreach (self::$m_aExecData as $aOpStats) {
$aBeginTimes[] = $aOpStats['time_begin'];
}
array_multisort($aBeginTimes, self::$m_aExecData);
@@ -150,7 +153,7 @@ class ExecutionKPI
$sHtml = " ";
$sHtml .= "";
- $sHtml .= "
KPIs - $sRequest";
+ $sHtml .= "
KPIs - $sRequest";
$oStarted = DateTime::createFromFormat('U.u', $fItopStarted);
$sHtml .= '
'.$oStarted->format('Y-m-d H:i:s.u').'
';
$sHtml .= "
log_kpi_user_id: ".UserRights::GetUserId()."
";
@@ -159,8 +162,7 @@ class ExecutionKPI
$sHtml .= "
";
$sHtml .= " Operation Begin End Duration Memory start Memory end Memory peak ";
$sHtml .= " ";
- foreach (self::$m_aExecData as $aOpStats)
- {
+ foreach (self::$m_aExecData as $aOpStats) {
$sOperation = $aOpStats['op'];
$sBegin = round($aOpStats['time_begin'], 3);
$sEnd = round($aOpStats['time_end'], 3);
@@ -170,12 +172,10 @@ class ExecutionKPI
$sMemBegin = 'n/a';
$sMemEnd = 'n/a';
$sMemPeak = 'n/a';
- if (isset($aOpStats['mem_begin']))
- {
+ if (isset($aOpStats['mem_begin'])) {
$sMemBegin = self::MemStr($aOpStats['mem_begin']);
$sMemEnd = self::MemStr($aOpStats['mem_end']);
- if (isset($aOpStats['mem_peak']))
- {
+ if (isset($aOpStats['mem_peak'])) {
$sMemPeak = self::MemStr($aOpStats['mem_peak']);
}
}
@@ -187,38 +187,34 @@ class ExecutionKPI
$sHtml .= "
";
$sHtml .= "";
- $aConsolidatedStats = array();
- foreach (self::$m_aStats as $sOperation => $aOpStats)
- {
+ $aConsolidatedStats = [];
+ foreach (self::$m_aStats as $sOperation => $aOpStats) {
$fTotalOp = 0;
$iTotalOp = 0;
$fMinOp = null;
$fMaxOp = 0;
$sMaxOpArguments = null;
- foreach ($aOpStats as $sArguments => $aEvents)
- {
- foreach ($aEvents as $aEventData)
- {
+ foreach ($aOpStats as $sArguments => $aEvents) {
+ foreach ($aEvents as $aEventData) {
$fDuration = $aEventData['time'];
$fTotalOp += $fDuration;
$iTotalOp++;
$fMinOp = is_null($fMinOp) ? $fDuration : min($fMinOp, $fDuration);
- if ($fDuration > $fMaxOp)
- {
+ if ($fDuration > $fMaxOp) {
$sMaxOpArguments = $sArguments;
$fMaxOp = $fDuration;
}
}
}
- $aConsolidatedStats[$sOperation] = array(
+ $aConsolidatedStats[$sOperation] = [
'count' => $iTotalOp,
'duration' => $fTotalOp,
'min' => $fMinOp,
'max' => $fMaxOp,
'avg' => $fTotalOp / $iTotalOp,
- 'max_args' => $sMaxOpArguments
- );
+ 'max_args' => $sMaxOpArguments,
+ ];
}
$sHtml .= "";
@@ -226,8 +222,7 @@ class ExecutionKPI
$sHtml .= "
";
$sHtml .= " Operation Count Duration Min Max Avg ";
$sHtml .= " ";
- foreach ($aConsolidatedStats as $sOperation => $aOpStats)
- {
+ foreach ($aConsolidatedStats as $sOperation => $aOpStats) {
$sOperation = '
'.$sOperation.' ';
$sCount = $aOpStats['count'];
$sDuration = round($aOpStats['duration'], 3);
@@ -250,25 +245,20 @@ class ExecutionKPI
self::Report($sHtml);
// Report operation details
- foreach (self::$m_aStats as $sOperation => $aOpStats)
- {
+ foreach (self::$m_aStats as $sOperation => $aOpStats) {
$sHtml = '';
$bDisplayHeader = true;
- foreach ($aOpStats as $sArguments => $aEvents)
- {
+ foreach ($aOpStats as $sArguments => $aEvents) {
$sHtmlArguments = '
'.$sArguments.'
';
- if ($aConsolidatedStats[$sOperation]['max_args'] == $sArguments)
- {
+ if ($aConsolidatedStats[$sOperation]['max_args'] == $sArguments) {
$sHtmlArguments = '
'.$sHtmlArguments.' ';
}
- if (isset($aEvents[0]['callers']))
- {
+ if (isset($aEvents[0]['callers'])) {
$sHtmlArguments .= '
';
$sHtmlArguments .= '
';
$sHtmlArguments .= 'Call stack for the FIRST caller ';
- foreach ($aEvents[0]['callers'] as $aCall)
- {
+ foreach ($aEvents[0]['callers'] as $aCall) {
$sHtmlArguments .= '';
$sHtmlArguments .= ''.$aCall['Function'].' ';
$sHtmlArguments .= ''.$aCall['File'].':'.$aCall['Line'].' ';
@@ -281,8 +271,7 @@ class ExecutionKPI
$fTotalInter = 0;
$fMinInter = null;
$fMaxInter = 0;
- foreach ($aEvents as $aEventData)
- {
+ foreach ($aEvents as $aEventData) {
$fDuration = $aEventData['time'];
$fTotalInter += $fDuration;
$fMinInter = is_null($fMinInter) ? $fDuration : min($fMinInter, $fDuration);
@@ -293,10 +282,8 @@ class ExecutionKPI
$sTotalInter = round($fTotalInter, 3);
$sMinInter = round($fMinInter, 3);
$sMaxInter = round($fMaxInter, 3);
- if (($fTotalInter >= self::$m_fSlowQueries))
- {
- if ($bDisplayHeader)
- {
+ if (($fTotalInter >= self::$m_fSlowQueries)) {
+ if ($bDisplayHeader) {
$sOperationHtml = ''.$sOperation.' ';
$sHtml .= "$sOperationHtml ";
$sHtml .= "";
@@ -310,8 +297,7 @@ class ExecutionKPI
$sHtml .= "";
}
}
- if (!$bDisplayHeader)
- {
+ if (!$bDisplayHeader) {
$sHtml .= "
";
$sHtml .= "Back to page stats
";
}
@@ -321,19 +307,19 @@ class ExecutionKPI
self::Report($sHtml);
}
- public static function InitStats()
- {
- // Invoke extensions to initialize the KPI statistics
- /** @var \iKPILoggerExtension $oExtensionInstance */
- foreach (MetaModel::EnumPlugins('iKPILoggerExtension') as $oExtensionInstance) {
- $oExtensionInstance->InitStats();
- }
- }
+ public static function InitStats()
+ {
+ // Invoke extensions to initialize the KPI statistics
+ /** @var \iKPILoggerExtension $oExtensionInstance */
+ foreach (MetaModel::EnumPlugins('iKPILoggerExtension') as $oExtensionInstance) {
+ $oExtensionInstance->InitStats();
+ }
+ }
public function __construct()
{
$this->ResetCounters();
- }
+ }
// Get the duration since startup, and reset the counter for the next measure
//
@@ -341,65 +327,62 @@ class ExecutionKPI
{
global $fItopStarted;
- if (!self::IsEnabled()) {
- return;
- }
+ if (!self::IsEnabled()) {
+ return;
+ }
$aNewEntry = null;
- $fStarted = $this->m_fStarted;
- $fStopped = $this->m_fStarted;
- if (self::$m_bEnabled_Duration) {
+ $fStarted = $this->m_fStarted;
+ $fStopped = $this->m_fStarted;
+ if (self::$m_bEnabled_Duration) {
$fStopped = MyHelpers::getmicrotime();
- $aNewEntry = array(
+ $aNewEntry = [
'op' => $sOperationDesc,
'time_begin' => $this->m_fStarted - $fItopStarted,
'time_end' => $fStopped - $fItopStarted,
- );
+ ];
// Reset for the next operation (if the object is recycled)
$this->m_fStarted = $fStopped;
}
- $iInitialMemory = is_null($this->m_iInitialMemory) ? 0 : $this->m_iInitialMemory;
- $iCurrentMemory = 0;
- $iPeakMemory = 0;
- if (self::$m_bEnabled_Memory)
- {
+ $iInitialMemory = is_null($this->m_iInitialMemory) ? 0 : $this->m_iInitialMemory;
+ $iCurrentMemory = 0;
+ $iPeakMemory = 0;
+ if (self::$m_bEnabled_Memory) {
$iCurrentMemory = self::memory_get_usage();
- if (is_null($aNewEntry))
- {
- $aNewEntry = array('op' => $sOperationDesc);
+ if (is_null($aNewEntry)) {
+ $aNewEntry = ['op' => $sOperationDesc];
}
$aNewEntry['mem_begin'] = $this->m_iInitialMemory;
$aNewEntry['mem_end'] = $iCurrentMemory;
- $iPeakMemory = self::memory_get_peak_usage();
- $aNewEntry['mem_peak'] = $iPeakMemory;
+ $iPeakMemory = self::memory_get_peak_usage();
+ $aNewEntry['mem_peak'] = $iPeakMemory;
// Reset for the next operation (if the object is recycled)
$this->m_iInitialMemory = $iCurrentMemory;
}
- if (self::$m_bEnabled_Duration || self::$m_bEnabled_Memory) {
- // Invoke extensions to log the KPI operation
- /** @var \iKPILoggerExtension $oExtensionInstance */
- foreach(MetaModel::EnumPlugins('iKPILoggerExtension') as $oExtensionInstance)
- {
- $sExtension = ModuleService::GetInstance()->GetModuleNameFromCallStack(1);
- $oKPILogData = new KpiLogData(
- KpiLogData::TYPE_REPORT,
- 'Step',
- $sOperationDesc,
- $fStarted,
- $fStopped,
- $sExtension,
- $iInitialMemory,
- $iCurrentMemory,
- $iPeakMemory);
- $oExtensionInstance->LogOperation($oKPILogData);
- }
- }
+ if (self::$m_bEnabled_Duration || self::$m_bEnabled_Memory) {
+ // Invoke extensions to log the KPI operation
+ /** @var \iKPILoggerExtension $oExtensionInstance */
+ foreach (MetaModel::EnumPlugins('iKPILoggerExtension') as $oExtensionInstance) {
+ $sExtension = ModuleService::GetInstance()->GetModuleNameFromCallStack(1);
+ $oKPILogData = new KpiLogData(
+ KpiLogData::TYPE_REPORT,
+ 'Step',
+ $sOperationDesc,
+ $fStarted,
+ $fStopped,
+ $sExtension,
+ $iInitialMemory,
+ $iCurrentMemory,
+ $iPeakMemory
+ );
+ $oExtensionInstance->LogOperation($oKPILogData);
+ }
+ }
- if (!is_null($aNewEntry) && self::$m_bGenerateLegacyReport)
- {
+ if (!is_null($aNewEntry) && self::$m_bGenerateLegacyReport) {
self::$m_aExecData[] = $aNewEntry;
}
$this->ResetCounters();
@@ -417,20 +400,20 @@ class ExecutionKPI
* @throws \ReflectionException
*/
public function ComputeStatsForExtension($object, string $sMethod, string $sMessage = ''): bool
- {
- if (!self::IsEnabled()) {
- return true;
- }
+ {
+ if (!self::IsEnabled()) {
+ return true;
+ }
- $sSignature = ModuleService::GetInstance()->GetModuleMethodSignature($object, $sMethod);
- if (utils::StartsWith($sSignature, '[')) {
- $this->ComputeStats('Extension', "$sSignature $sMessage");
+ $sSignature = ModuleService::GetInstance()->GetModuleMethodSignature($object, $sMethod);
+ if (utils::StartsWith($sSignature, '[')) {
+ $this->ComputeStats('Extension', "$sSignature $sMessage");
return true;
- }
+ }
return false;
- }
+ }
public function ComputeStats($sOperation, $sArguments)
{
@@ -442,85 +425,82 @@ class ExecutionKPI
if (self::$m_bEnabled_Duration) {
$fStopped = MyHelpers::getmicrotime();
$fDuration = $fStopped - $this->m_fStarted;
- $aCallstack = [];
- if (self::$m_bGenerateLegacyReport) {
- if (self::$m_bBlameCaller) {
- $aCallstack = MyHelpers::get_callstack(1);
- self::$m_aStats[$sOperation][$sArguments][] = [
- 'time' => $fDuration,
- 'callers' => $aCallstack,
- ];
- } else {
- self::$m_aStats[$sOperation][$sArguments][] = [
- 'time' => $fDuration
- ];
- }
- }
+ $aCallstack = [];
+ if (self::$m_bGenerateLegacyReport) {
+ if (self::$m_bBlameCaller) {
+ $aCallstack = MyHelpers::get_callstack(1);
+ self::$m_aStats[$sOperation][$sArguments][] = [
+ 'time' => $fDuration,
+ 'callers' => $aCallstack,
+ ];
+ } else {
+ self::$m_aStats[$sOperation][$sArguments][] = [
+ 'time' => $fDuration,
+ ];
+ }
+ }
- $iInitialMemory = is_null($this->m_iInitialMemory) ? 0 : $this->m_iInitialMemory;
- $iCurrentMemory = 0;
- $iPeakMemory = 0;
- if (self::$m_bEnabled_Memory)
- {
- $iCurrentMemory = self::memory_get_usage();
- $iPeakMemory = self::memory_get_peak_usage();
- }
+ $iInitialMemory = is_null($this->m_iInitialMemory) ? 0 : $this->m_iInitialMemory;
+ $iCurrentMemory = 0;
+ $iPeakMemory = 0;
+ if (self::$m_bEnabled_Memory) {
+ $iCurrentMemory = self::memory_get_usage();
+ $iPeakMemory = self::memory_get_peak_usage();
+ }
- // Invoke extensions to log the KPI operation
- /** @var \iKPILoggerExtension $oExtensionInstance */
- foreach (MetaModel::EnumPlugins('iKPILoggerExtension') as $oExtensionInstance) {
- //$sExtension = ModuleService::GetInstance()->GetModuleNameFromCallStack(1);
- $sExtension = '';
- $oKPILogData = new KpiLogData(
- KpiLogData::TYPE_STATS,
- $sOperation,
- $sArguments,
- $this->m_fStarted,
- $fStopped,
- $sExtension,
- $iInitialMemory,
- $iCurrentMemory,
- $iPeakMemory,
- $aCallstack);
- $oExtensionInstance->LogOperation($oKPILogData);
- }
- }
+ // Invoke extensions to log the KPI operation
+ /** @var \iKPILoggerExtension $oExtensionInstance */
+ foreach (MetaModel::EnumPlugins('iKPILoggerExtension') as $oExtensionInstance) {
+ //$sExtension = ModuleService::GetInstance()->GetModuleNameFromCallStack(1);
+ $sExtension = '';
+ $oKPILogData = new KpiLogData(
+ KpiLogData::TYPE_STATS,
+ $sOperation,
+ $sArguments,
+ $this->m_fStarted,
+ $fStopped,
+ $sExtension,
+ $iInitialMemory,
+ $iCurrentMemory,
+ $iPeakMemory,
+ $aCallstack
+ );
+ $oExtensionInstance->LogOperation($oKPILogData);
+ }
+ }
}
protected function ResetCounters()
{
- if (self::$m_bEnabled_Duration)
- {
+ if (self::$m_bEnabled_Duration) {
$this->m_fStarted = microtime(true);
}
- if (self::$m_bEnabled_Memory)
- {
+ if (self::$m_bEnabled_Memory) {
$this->m_iInitialMemory = self::memory_get_usage();
}
}
- const HTML_REPORT_FILE = 'log/kpi.html';
+ public const HTML_REPORT_FILE = 'log/kpi.html';
- static protected function Report($sText)
+ protected static function Report($sText)
{
file_put_contents(APPROOT.self::HTML_REPORT_FILE, "$sText\n", FILE_APPEND | LOCK_EX);
}
- static protected function MemStr($iMemory)
+ protected static function MemStr($iMemory)
{
return round($iMemory / 1024).' Kb';
}
- static protected function memory_get_usage()
+ protected static function memory_get_usage()
{
- return memory_get_usage(true);
+ return memory_get_usage(true);
}
- static public function memory_get_peak_usage($bRealUsage = false)
+ public static function memory_get_peak_usage($bRealUsage = false)
{
- if (function_exists('memory_get_peak_usage'))
- {
+ if (function_exists('memory_get_peak_usage')) {
return memory_get_peak_usage($bRealUsage);
}
// PHP > 5.2.1 - this verb depends on a compilation option
diff --git a/core/metamodel.class.php b/core/metamodel.class.php
index 3375e991d..c5d6ae1be 100644
--- a/core/metamodel.class.php
+++ b/core/metamodel.class.php
@@ -1,4 +1,5 @@
"rootclass"
*
* @var array
*/
- private static $m_aRootClasses = array();
+ private static $m_aRootClasses = [];
/**
* array of ("classname" => array of "parentclass")
*
* @var array
*/
- private static $m_aParentClasses = array();
+ private static $m_aParentClasses = [];
/**
* array of ("classname" => array of "childclass")
*
* @var array
*/
- private static $m_aChildClasses = array();
+ private static $m_aChildClasses = [];
/**
* array of ("classname" => array of class information)
*
* @var array
*/
- private static $m_aClassParams = array();
+ private static $m_aClassParams = [];
/**
* array of ("classname" => array of highlightscale information)
*
* @var array
*/
- private static $m_aHighlightScales = array();
+ private static $m_aHighlightScales = [];
/**
* @param string $sRefClass
@@ -641,47 +637,37 @@ abstract class MetaModel
*/
final public static function GetUniquenessRules($sClass, $bClassDefinitionOnly = false)
{
- if (!isset(self::$m_aClassParams[$sClass]))
- {
- return array();
+ if (!isset(self::$m_aClassParams[$sClass])) {
+ return [];
}
- $aCurrentUniquenessRules = array();
+ $aCurrentUniquenessRules = [];
- if (array_key_exists('uniqueness_rules', self::$m_aClassParams[$sClass]))
- {
+ if (array_key_exists('uniqueness_rules', self::$m_aClassParams[$sClass])) {
$aCurrentUniquenessRules = self::$m_aClassParams[$sClass]['uniqueness_rules'];
}
- if ($bClassDefinitionOnly)
- {
+ if ($bClassDefinitionOnly) {
return $aCurrentUniquenessRules;
}
$sParentClass = self::GetParentClass($sClass);
- if ($sParentClass)
- {
+ if ($sParentClass) {
$aParentUniquenessRules = self::GetUniquenessRules($sParentClass);
- foreach ($aParentUniquenessRules as $sUniquenessRuleId => $aParentUniquenessRuleProperties)
- {
+ foreach ($aParentUniquenessRules as $sUniquenessRuleId => $aParentUniquenessRuleProperties) {
$bCopyDisabledKey = true;
$bCurrentDisabledValue = null;
- if (array_key_exists($sUniquenessRuleId, $aCurrentUniquenessRules))
- {
- if (self::IsUniquenessRuleContainingOnlyDisabledKey($aCurrentUniquenessRules[$sUniquenessRuleId]))
- {
+ if (array_key_exists($sUniquenessRuleId, $aCurrentUniquenessRules)) {
+ if (self::IsUniquenessRuleContainingOnlyDisabledKey($aCurrentUniquenessRules[$sUniquenessRuleId])) {
$bCopyDisabledKey = false;
- }
- else
- {
+ } else {
continue;
}
}
$aMergedUniquenessProperties = $aParentUniquenessRuleProperties;
- if (!$bCopyDisabledKey)
- {
+ if (!$bCopyDisabledKey) {
$aMergedUniquenessProperties['disabled'] = $aCurrentUniquenessRules[$sUniquenessRuleId]['disabled'];
}
$aCurrentUniquenessRules[$sUniquenessRuleId] = $aMergedUniquenessProperties;
@@ -701,8 +687,7 @@ abstract class MetaModel
*/
private static function SetUniquenessRuleRootClass($sRootClass, $sRuleId)
{
- foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_ALL) as $sClass)
- {
+ foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_ALL) as $sClass) {
self::$m_aClassParams[$sClass]['uniqueness_rules'][$sRuleId]['root_class'] = $sClass;
}
}
@@ -716,17 +701,14 @@ abstract class MetaModel
final public static function GetRootClassForUniquenessRule($sRuleId, $sLeafClassName)
{
$sFirstClassWithRuleId = null;
- if (isset(self::$m_aClassParams[$sLeafClassName]['uniqueness_rules'][$sRuleId]))
- {
+ if (isset(self::$m_aClassParams[$sLeafClassName]['uniqueness_rules'][$sRuleId])) {
$sFirstClassWithRuleId = $sLeafClassName;
}
$sParentClass = self::GetParentClass($sLeafClassName);
- if ($sParentClass)
- {
+ if ($sParentClass) {
$sParentClassWithRuleId = self::GetRootClassForUniquenessRule($sRuleId, $sParentClass);
- if (!is_null($sParentClassWithRuleId))
- {
+ if (!is_null($sParentClassWithRuleId)) {
$sFirstClassWithRuleId = $sParentClassWithRuleId;
}
}
@@ -745,29 +727,22 @@ abstract class MetaModel
*/
final public static function GetChildClassesWithDisabledUniquenessRule($sRootClass, $sRuleId)
{
- $aClassesWithDisabledRule = array();
- foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_EXCLUDETOP) as $sChildClass)
- {
- if (array_key_exists($sChildClass, $aClassesWithDisabledRule))
- {
+ $aClassesWithDisabledRule = [];
+ foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_EXCLUDETOP) as $sChildClass) {
+ if (array_key_exists($sChildClass, $aClassesWithDisabledRule)) {
continue;
}
- if (!array_key_exists('uniqueness_rules', self::$m_aClassParams[$sChildClass]))
- {
+ if (!array_key_exists('uniqueness_rules', self::$m_aClassParams[$sChildClass])) {
continue;
}
- if (!array_key_exists($sRuleId, self::$m_aClassParams[$sChildClass]['uniqueness_rules']))
- {
+ if (!array_key_exists($sRuleId, self::$m_aClassParams[$sChildClass]['uniqueness_rules'])) {
continue;
}
- if (self::$m_aClassParams[$sChildClass]['uniqueness_rules'][$sRuleId]['disabled'] === true)
- {
+ if (self::$m_aClassParams[$sChildClass]['uniqueness_rules'][$sRuleId]['disabled'] === true) {
$aDisabledClassChildren = self::EnumChildClasses($sChildClass, ENUM_CHILD_CLASSES_ALL);
- foreach ($aDisabledClassChildren as $sDisabledClassChild)
- {
- if (!self::IsAbstract($sDisabledClassChild))
- {
+ foreach ($aDisabledClassChildren as $sDisabledClassChild) {
+ if (!self::IsAbstract($sDisabledClassChild)) {
$aClassesWithDisabledRule[] = $sDisabledClassChild;
}
}
@@ -792,7 +767,6 @@ abstract class MetaModel
return ((count($aNonNullRuleProperties) == 1) && (array_key_exists('disabled', $aNonNullRuleProperties)));
}
-
/**
* @param string $sClass
* @param string $sType {@see \Combodo\iTop\Core\MetaModel\FriendlyNameType}
@@ -957,7 +931,7 @@ abstract class MetaModel
$aAttributes = $aNameSpec[1];
$aPieces = preg_split('/%([0-9])\\$s/', $sFormat, -1, PREG_SPLIT_DELIM_CAPTURE);
- $aExpressions = array();
+ $aExpressions = [];
foreach ($aPieces as $i => $sPiece) {
if ($i & 1) {
// $i is ODD - sPiece is a delimiter
@@ -968,12 +942,10 @@ abstract class MetaModel
$sAttCode = $aAttributes[$iReplacement];
$aExpressions[] = new FieldExpression($sAttCode);
}
- } else
- {
+ } else {
// $i is EVEN - sPiece is a literal
//
- if (strlen($sPiece) > 0)
- {
+ if (strlen($sPiece) > 0) {
$aExpressions[] = new ScalarExpression($sPiece);
}
}
@@ -1132,8 +1104,10 @@ abstract class MetaModel
final public static function GetOrderByDefault($sClass, $bOnlyDeclared = false)
{
self::_check_subclass($sClass);
- $aOrderBy = array_key_exists("order_by_default",
- self::$m_aClassParams[$sClass]) ? self::$m_aClassParams[$sClass]["order_by_default"] : array();
+ $aOrderBy = array_key_exists(
+ "order_by_default",
+ self::$m_aClassParams[$sClass]
+ ) ? self::$m_aClassParams[$sClass]["order_by_default"] : [];
if ($bOnlyDeclared) {
// Used to reverse engineer the declaration of the data model
return $aOrderBy;
@@ -1188,7 +1162,7 @@ abstract class MetaModel
*/
final public static function GetDependentAttributes($sClass, $sAttCode)
{
- $aResults = array();
+ $aResults = [];
self::_check_subclass($sClass);
foreach (self::ListAttributeDefs($sClass) as $sDependentAttCode => $void) {
$aPrerequisites = self::GetPrerequisiteAttributes($sClass, $sDependentAttCode);
@@ -1244,7 +1218,7 @@ abstract class MetaModel
// This API does not rely on our capability to query the DB and retrieve
// the list of existing tables
// Rather, it uses the list of expected tables, corresponding to the data model
- $aTables = array();
+ $aTables = [];
foreach (self::GetClasses() as $sClass) {
if (!self::HasTable($sClass)) {
continue;
@@ -1253,7 +1227,7 @@ abstract class MetaModel
// Could be completed later with all the classes that are using a given table
if (!array_key_exists($sTable, $aTables)) {
- $aTables[$sTable] = array();
+ $aTables[$sTable] = [];
}
$aTables[$sTable][] = $sClass;
}
@@ -1273,13 +1247,12 @@ abstract class MetaModel
if (isset(self::$m_aClassParams[$sClass]['indexes'])) {
$aRet = self::$m_aClassParams[$sClass]['indexes'];
} else {
- $aRet = array();
+ $aRet = [];
}
return $aRet;
}
-
/**
* @param $sClass
* @param $aColumns
@@ -1290,15 +1263,12 @@ abstract class MetaModel
*/
private static function DBGetIndexesLength($sClass, $aColumns, $aTableInfo)
{
- $aLength = array();
+ $aLength = [];
$aAttDefs = self::ListAttributeDefs($sClass);
- foreach($aColumns as $sAttSqlCode)
- {
+ foreach ($aColumns as $sAttSqlCode) {
$iLength = null;
- foreach($aAttDefs as $sAttCode => $oAttDef)
- {
- if (($sAttCode == $sAttSqlCode) || ($oAttDef->IsParam('sql') && ($oAttDef->Get('sql') == $sAttSqlCode)))
- {
+ foreach ($aAttDefs as $sAttCode => $oAttDef) {
+ if (($sAttCode == $sAttSqlCode) || ($oAttDef->IsParam('sql') && ($oAttDef->Get('sql') == $sAttSqlCode))) {
$iLength = $oAttDef->GetIndexLength();
break;
}
@@ -1430,25 +1400,25 @@ abstract class MetaModel
*
* @var \AttributeDefinition[][]
*/
- private static $m_aAttribDefs = array();
+ private static $m_aAttribDefs = [];
/**
* array of ("classname" => array of ("attcode"=>"sourceclass"))
*
* @var array
*/
- private static $m_aAttribOrigins = array();
+ private static $m_aAttribOrigins = [];
/**
* array of ("classname" => array of ("attcode"))
*
* @var array
*/
- private static $m_aIgnoredAttributes = array();
+ private static $m_aIgnoredAttributes = [];
/**
* array of ("classname" => array of ("attcode" => array of ("metaattcode" => oMetaAttDef))
*
* @var array
*/
- private static $m_aEnumToMeta = array();
+ private static $m_aEnumToMeta = [];
/**
* @param string $sClass
@@ -1529,7 +1499,7 @@ abstract class MetaModel
}
if (array_key_exists($sClass, self::$m_aMagicFields)) {
// Add the magic fields
- $aFilterList = array_merge($aFilterList,self::$m_aMagicFields[$sClass]);
+ $aFilterList = array_merge($aFilterList, self::$m_aMagicFields[$sClass]);
}
$aFilterList[] = 'id';
return $aFilterList;
@@ -1544,11 +1514,9 @@ abstract class MetaModel
final public static function GetKeysList($sClass)
{
self::_check_subclass($sClass);
- $aExtKeys = array();
- foreach(self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef)
- {
- if ($oAttDef->IsExternalKey())
- {
+ $aExtKeys = [];
+ foreach (self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef) {
+ if ($oAttDef->IsExternalKey()) {
$aExtKeys[] = $sAttCode;
}
}
@@ -1606,9 +1574,7 @@ abstract class MetaModel
$bRes = false;
}
}
- }
- else
- {
+ } else {
$bRes = array_key_exists($sAttCode, self::$m_aAttribDefs[$sClass]);
}
@@ -1667,8 +1633,7 @@ abstract class MetaModel
*/
public static function IsValidObject($oObject)
{
- if (!is_object($oObject))
- {
+ if (!is_object($oObject)) {
return false;
}
return (self::IsValidClass(get_class($oObject)));
@@ -1704,9 +1669,7 @@ abstract class MetaModel
$oKeyAttDef = self::GetAttributeDef($sClass, $sExtKeyAttCode);
$sRemoteClass = $oKeyAttDef->GetTargetClass();
return self::GetAttributeDef($sRemoteClass, $sRemoteAttCode);
- }
- else
- {
+ } else {
throw new Exception("Unknown attribute $sAttCode from class $sClass");
}
}
@@ -1719,7 +1682,7 @@ abstract class MetaModel
*/
final public static function GetExternalKeys($sClass)
{
- $aExtKeys = array();
+ $aExtKeys = [];
foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt) {
if ($oAtt->IsExternalKey()) {
$aExtKeys[$sAttCode] = $oAtt;
@@ -1737,7 +1700,7 @@ abstract class MetaModel
*/
final public static function GetLinkedSets($sClass)
{
- $aLinkedSets = array();
+ $aLinkedSets = [];
foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt) {
// Note: Careful, this will only return SUB-classes, which does NOT include AttributeLinkedset itself! We might want to use "is_a()" instead.
if (is_subclass_of($oAtt, 'AttributeLinkedSet')) {
@@ -1757,9 +1720,9 @@ abstract class MetaModel
*/
final public static function GetExternalFields($sClass, $sKeyAttCode)
{
- static $aExtFields = array();
+ static $aExtFields = [];
if (!isset($aExtFields[$sClass][$sKeyAttCode])) {
- $aExtFields[$sClass][$sKeyAttCode] = array();
+ $aExtFields[$sClass][$sKeyAttCode] = [];
foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt) {
if ($oAtt->IsExternalField() && ($oAtt->GetKeyAttCode() == $sKeyAttCode)) {
$aExtFields[$sClass][$sKeyAttCode][$oAtt->GetExtAttCode()] = $oAtt;
@@ -1811,7 +1774,7 @@ abstract class MetaModel
}
/** @var array */
- protected static $m_aTrackForwardCache = array();
+ protected static $m_aTrackForwardCache = [];
/**
* List external keys for which there is a LinkSet (direct or indirect) on the other end
@@ -1827,20 +1790,17 @@ abstract class MetaModel
final public static function GetTrackForwardExternalKeys($sClass)
{
if (!isset(self::$m_aTrackForwardCache[$sClass])) {
- $aRes = array();
+ $aRes = [];
foreach (MetaModel::GetExternalKeys($sClass) as $sAttCode => $oAttDef) {
$sRemoteClass = $oAttDef->GetTargetClass();
foreach (MetaModel::ListAttributeDefs($sRemoteClass) as $sRemoteAttCode => $oRemoteAttDef) {
- if (!$oRemoteAttDef->IsLinkSet())
- {
+ if (!$oRemoteAttDef->IsLinkSet()) {
continue;
}
- if (!is_subclass_of($sClass, $oRemoteAttDef->GetLinkedClass()) && $oRemoteAttDef->GetLinkedClass() != $sClass)
- {
+ if (!is_subclass_of($sClass, $oRemoteAttDef->GetLinkedClass()) && $oRemoteAttDef->GetLinkedClass() != $sClass) {
continue;
}
- if ($oRemoteAttDef->GetExtKeyToMe() != $sAttCode)
- {
+ if ($oRemoteAttDef->GetExtKeyToMe() != $sAttCode) {
continue;
}
$aRes[$sAttCode] = $oRemoteAttDef;
@@ -1863,7 +1823,7 @@ abstract class MetaModel
if (isset(self::$m_aEnumToMeta[$sClass][$sAttCode])) {
$aRet = self::$m_aEnumToMeta[$sClass][$sAttCode];
} else {
- $aRet = array();
+ $aRet = [];
}
return $aRet;
@@ -1882,21 +1842,15 @@ abstract class MetaModel
*/
public static function GetLabel($sClass, $sAttCodeEx, $bShowMandatory = false)
{
- if (($iPos = strpos($sAttCodeEx, '->')) === false)
- {
- if ($sAttCodeEx == 'id')
- {
+ if (($iPos = strpos($sAttCodeEx, '->')) === false) {
+ if ($sAttCodeEx == 'id') {
$sLabel = Dict::S('UI:CSVImport:idField');
- }
- else
- {
+ } else {
$oAttDef = self::GetAttributeDef($sClass, $sAttCodeEx);
$sMandatory = ($bShowMandatory && !$oAttDef->IsNullAllowed()) ? '*' : '';
$sLabel = $oAttDef->GetLabel().$sMandatory;
}
- }
- else
- {
+ } else {
$sExtKeyAttCode = substr($sAttCodeEx, 0, $iPos);
$sRemoteAttCode = substr($sAttCodeEx, $iPos + 2);
$oKeyAttDef = MetaModel::GetAttributeDef($sClass, $sExtKeyAttCode);
@@ -1938,7 +1892,7 @@ abstract class MetaModel
/**
* @var array array of ("listcode" => various info on the list, common to every classes)
*/
- private static $m_aListInfos = array();
+ private static $m_aListInfos = [];
/**
* array of ("classname" => array of "listcode" => list)
* list may be an array of attcode / fltcode
@@ -1946,7 +1900,7 @@ abstract class MetaModel
*
* @var array
*/
- private static $m_aListData = array();
+ private static $m_aListData = [];
/**
* @return array
@@ -1961,7 +1915,7 @@ abstract class MetaModel
*
* @return mixed
*/
- final static public function GetZListInfo($sListCode)
+ final public static function GetZListInfo($sListCode)
{
return self::$m_aListInfos[$sListCode];
}
@@ -1974,17 +1928,14 @@ abstract class MetaModel
*/
public static function GetZListItems($sClass, $sListCode)
{
- if (array_key_exists($sClass, self::$m_aListData))
- {
- if (array_key_exists($sListCode, self::$m_aListData[$sClass]))
- {
+ if (array_key_exists($sClass, self::$m_aListData)) {
+ if (array_key_exists($sListCode, self::$m_aListData[$sClass])) {
return self::$m_aListData[$sClass][$sListCode];
}
}
$sParentClass = self::GetParentPersistentClass($sClass);
- if (empty($sParentClass))
- {
- return array();
+ if (empty($sParentClass)) {
+ return [];
} // nothing for the mother of all classes
// Dig recursively
return self::GetZListItems($sParentClass, $sListCode);
@@ -2037,28 +1988,23 @@ abstract class MetaModel
$sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
$sDefaultState = MetaModel::GetDefaultState($sClass);
- foreach (MetaModel::FlattenZList(MetaModel::GetZListItems($sLinkedClass, 'list')) as $sLnkAttCode)
- {
+ foreach (MetaModel::FlattenZList(MetaModel::GetZListItems($sLinkedClass, 'list')) as $sLnkAttCode) {
$oLnkAttDef = MetaModel::GetAttributeDef($sLinkedClass, $sLnkAttCode);
- if ($sStateAttCode == $sLnkAttCode)
- {
+ if ($sStateAttCode == $sLnkAttCode) {
// State attribute is always hidden from the UI
continue;
}
if (($sLnkAttCode == $sExtKeyToMe)
|| ($sLnkAttCode == $sExtKeyToRemote)
- || ($sLnkAttCode == 'finalclass'))
- {
+ || ($sLnkAttCode == 'finalclass')) {
continue;
}
- if (!($oLnkAttDef->IsWritable()))
- {
+ if (!($oLnkAttDef->IsWritable())) {
continue;
}
$iFlags = MetaModel::GetAttributeFlags($sLinkedClass, $sDefaultState, $sLnkAttCode);
- if (!($iFlags & OPT_ATT_HIDDEN) && !($iFlags & OPT_ATT_READONLY))
- {
+ if (!($iFlags & OPT_ATT_HIDDEN) && !($iFlags & OPT_ATT_READONLY)) {
$aAttCodesToPrint[] = $oLnkAttDef;
}
}
@@ -2078,7 +2024,7 @@ abstract class MetaModel
* @since 3.0.0 N°2334 added code for n-n relations in {@see BlockIndirectLinkSetViewTable::GetAttCodesToDisplay}
* @since 3.1.0 N°3200 method creation so that it can be used elsewhere
*/
- public static function GetAttributeLinkedSetIndirectDatatableAttCodesToDisplay(string $sObjectClass, string $sObjectLinkedSetIndirectAttCode, string $sRemoteClass, string $sLnkExternalKeyToRemoteClassAttCode):array
+ public static function GetAttributeLinkedSetIndirectDatatableAttCodesToDisplay(string $sObjectClass, string $sObjectLinkedSetIndirectAttCode, string $sRemoteClass, string $sLnkExternalKeyToRemoteClassAttCode): array
{
$aLnkAttDefsToDisplay = MetaModel::GetZListAttDefsFilteredForIndirectLinkClass($sObjectClass, $sObjectLinkedSetIndirectAttCode);
$aRemoteAttDefsToDisplay = MetaModel::GetZListAttDefsFilteredForIndirectRemoteClass($sRemoteClass);
@@ -2114,8 +2060,7 @@ abstract class MetaModel
public static function IsAttributeInZList($sClass, $sListCode, $sAttCodeOrFltCode, $sGroup = null)
{
$aZList = self::FlattenZlist(self::GetZListItems($sClass, $sListCode));
- if (!$sGroup)
- {
+ if (!$sGroup) {
return (in_array($sAttCodeOrFltCode, $aZList));
}
return (in_array($sAttCodeOrFltCode, $aZList[$sGroup]));
@@ -2129,7 +2074,7 @@ abstract class MetaModel
*
* @var array
*/
- private static $m_aRelationInfos = array();
+ private static $m_aRelationInfos = [];
/**
* @param string $sClass
@@ -2144,18 +2089,15 @@ abstract class MetaModel
$aRelationInfo = array_keys(self::$m_aRelationInfos);
// Return only the relations that have a meaning (i.e. for which at least one query is defined)
// for the specified class
- $aClassRelations = array();
- foreach($aRelationInfo as $sRelCode)
- {
+ $aClassRelations = [];
+ foreach ($aRelationInfo as $sRelCode) {
$aQueriesDown = self::EnumRelationQueries($sClass, $sRelCode, true /* Down */);
- if (count($aQueriesDown) > 0)
- {
+ if (count($aQueriesDown) > 0) {
$aClassRelations[$sRelCode]['down'] = self::GetRelationLabel($sRelCode, true);
}
$aQueriesUp = self::EnumRelationQueries($sClass, $sRelCode, false /* Up */);
- if (count($aQueriesUp) > 0)
- {
+ if (count($aQueriesUp) > 0) {
$aClassRelations[$sRelCode]['up'] = self::GetRelationLabel($sRelCode, false);
}
}
@@ -2170,18 +2112,15 @@ abstract class MetaModel
* @return string
* @throws \DictExceptionMissingString
*/
- final static public function GetRelationDescription($sRelCode, $bDown = true)
+ final public static function GetRelationDescription($sRelCode, $bDown = true)
{
// Legacy convention had only one description describing the relation.
// Now, as the relation is bidirectional, we have a description for each directions.
$sLegacy = Dict::S("Relation:$sRelCode/Description");
- if($bDown)
- {
+ if ($bDown) {
$sKey = "Relation:$sRelCode/DownStream+";
- }
- else
- {
+ } else {
$sKey = "Relation:$sRelCode/UpStream+";
}
$sRet = Dict::S($sKey, $sLegacy);
@@ -2204,8 +2143,7 @@ abstract class MetaModel
// Now, the relation from A to B says that something is transmitted from A to B, thus going DOWNstream as described in a petri net.
$sKey = "Relation:$sRelCode/DownStream";
$sLegacy = Dict::S("Relation:$sRelCode/VerbUp", $sKey);
- } else
- {
+ } else {
$sKey = "Relation:$sRelCode/UpStream";
$sLegacy = Dict::S("Relation:$sRelCode/VerbDown", $sKey);
}
@@ -2223,23 +2161,19 @@ abstract class MetaModel
*/
protected static function ComputeRelationQueries($sRelCode)
{
- $aQueries = array();
- foreach(self::GetClasses() as $sClass)
- {
- $aQueries[$sClass]['down'] = array();
- if (!array_key_exists('up', $aQueries[$sClass]))
- {
- $aQueries[$sClass]['up'] = array();
+ $aQueries = [];
+ foreach (self::GetClasses() as $sClass) {
+ $aQueries[$sClass]['down'] = [];
+ if (!array_key_exists('up', $aQueries[$sClass])) {
+ $aQueries[$sClass]['up'] = [];
}
- $aNeighboursDown = call_user_func_array(array($sClass, 'GetRelationQueriesEx'), array($sRelCode));
+ $aNeighboursDown = call_user_func_array([$sClass, 'GetRelationQueriesEx'], [$sRelCode]);
// Translate attributes into queries (new style of spec only)
- foreach($aNeighboursDown as $sNeighbourId => $aNeighbourData)
- {
+ foreach ($aNeighboursDown as $sNeighbourId => $aNeighbourData) {
$aNeighbourData['sFromClass'] = $aNeighbourData['sDefinedInClass'];
- try
- {
+ try {
if (Utils::StrLen($aNeighbourData['sQueryDown']) == 0) {
$oAttDef = self::GetAttributeDef($sClass, $aNeighbourData['sAttribute']);
if ($oAttDef instanceof AttributeExternalKey) {
@@ -2247,12 +2181,10 @@ abstract class MetaModel
$aNeighbourData['sToClass'] = $sTargetClass;
$aNeighbourData['sQueryDown'] = 'SELECT '.$sTargetClass.' AS o WHERE o.id = :this->'.$aNeighbourData['sAttribute'];
$aNeighbourData['sQueryUp'] = 'SELECT '.$aNeighbourData['sFromClass'].' AS o WHERE o.'.$aNeighbourData['sAttribute'].' = :this->id';
- } elseif ($oAttDef instanceof AttributeLinkedSet)
- {
+ } elseif ($oAttDef instanceof AttributeLinkedSet) {
$sLinkedClass = $oAttDef->GetLinkedClass();
$sExtKeyToMe = $oAttDef->GetExtKeyToMe();
- if ($oAttDef->IsIndirect())
- {
+ if ($oAttDef->IsIndirect()) {
$sExtKeyToRemote = $oAttDef->GetExtKeyToRemote();
$oRemoteAttDef = self::GetAttributeDef($sLinkedClass, $sExtKeyToRemote);
$sRemoteClass = $oRemoteAttDef->GetTargetClass();
@@ -2260,32 +2192,23 @@ abstract class MetaModel
$aNeighbourData['sToClass'] = $sRemoteClass;
$aNeighbourData['sQueryDown'] = "SELECT $sRemoteClass AS o JOIN $sLinkedClass AS lnk ON lnk.$sExtKeyToRemote = o.id WHERE lnk.$sExtKeyToMe = :this->id";
$aNeighbourData['sQueryUp'] = "SELECT ".$aNeighbourData['sFromClass']." AS o JOIN $sLinkedClass AS lnk ON lnk.$sExtKeyToMe = o.id WHERE lnk.$sExtKeyToRemote = :this->id";
- }
- else
- {
+ } else {
$aNeighbourData['sToClass'] = $sLinkedClass;
$aNeighbourData['sQueryDown'] = "SELECT $sLinkedClass AS o WHERE o.$sExtKeyToMe = :this->id";
$aNeighbourData['sQueryUp'] = "SELECT ".$aNeighbourData['sFromClass']." AS o WHERE o.id = :this->$sExtKeyToMe";
}
- }
- else
- {
+ } else {
throw new Exception("Unexpected attribute type for '{$aNeighbourData['sAttribute']}'. Expecting a link set or external key.");
}
- }
- else
- {
+ } else {
$oSearch = DBObjectSearch::FromOQL($aNeighbourData['sQueryDown']);
$aNeighbourData['sToClass'] = $oSearch->GetClass();
}
- }
- catch (Exception $e)
- {
+ } catch (Exception $e) {
throw new Exception("Wrong definition for the relation $sRelCode/{$aNeighbourData['sDefinedInClass']}/{$aNeighbourData['sNeighbour']}: ".$e->getMessage());
}
- if ($aNeighbourData['sDirection'] == 'down')
- {
+ if ($aNeighbourData['sDirection'] == 'down') {
$aNeighbourData['sQueryUp'] = null;
}
@@ -2293,13 +2216,10 @@ abstract class MetaModel
$aQueries[$sClass]['down'][$sArrowId] = $aNeighbourData;
// Compute the reverse index
- if ($aNeighbourData['sDefinedInClass'] == $sClass)
- {
- if ($aNeighbourData['sDirection'] == 'both')
- {
+ if ($aNeighbourData['sDefinedInClass'] == $sClass) {
+ if ($aNeighbourData['sDirection'] == 'both') {
$sToClass = $aNeighbourData['sToClass'];
- foreach(self::EnumChildClasses($sToClass, ENUM_CHILD_CLASSES_ALL) as $sSubClass)
- {
+ foreach (self::EnumChildClasses($sToClass, ENUM_CHILD_CLASSES_ALL) as $sSubClass) {
$aQueries[$sSubClass]['up'][$sArrowId] = $aNeighbourData;
}
}
@@ -2322,19 +2242,15 @@ abstract class MetaModel
*/
public static function EnumRelationQueries($sClass, $sRelCode, $bDown = true)
{
- static $aQueries = array();
- if (!isset($aQueries[$sRelCode]))
- {
+ static $aQueries = [];
+ if (!isset($aQueries[$sRelCode])) {
$aQueries[$sRelCode] = self::ComputeRelationQueries($sRelCode);
}
$sDirection = $bDown ? 'down' : 'up';
- if (isset($aQueries[$sRelCode][$sClass][$sDirection]))
- {
+ if (isset($aQueries[$sRelCode][$sClass][$sDirection])) {
return $aQueries[$sRelCode][$sClass][$sDirection];
- }
- else
- {
- return array();
+ } else {
+ return [];
}
}
@@ -2352,9 +2268,13 @@ abstract class MetaModel
* @throws \Exception
*/
public static function GetRelatedObjectsDown(
- $sRelCode, $aSourceObjects, $iMaxDepth = 99, $bEnableRedundancy = true, $aUnreachable = array(), $aContexts = array()
- )
- {
+ $sRelCode,
+ $aSourceObjects,
+ $iMaxDepth = 99,
+ $bEnableRedundancy = true,
+ $aUnreachable = [],
+ $aContexts = []
+ ) {
$oGraph = new RelationGraph();
foreach ($aSourceObjects as $oObject) {
$oGraph->AddSourceObject($oObject);
@@ -2378,7 +2298,7 @@ abstract class MetaModel
* @return RelationGraph The graph of all the related objects
* @throws \Exception
*/
- public static function GetRelatedObjectsUp($sRelCode, $aSourceObjects, $iMaxDepth = 99, $bEnableRedundancy = true, $aContexts = array())
+ public static function GetRelatedObjectsUp($sRelCode, $aSourceObjects, $iMaxDepth = 99, $bEnableRedundancy = true, $aContexts = [])
{
$oGraph = new RelationGraph();
foreach ($aSourceObjects as $oObject) {
@@ -2399,19 +2319,19 @@ abstract class MetaModel
*
* @var array
*/
- private static $m_aStates = array();
+ private static $m_aStates = [];
/**
* array of ("classname" => array of ("stimuluscode"=>array('label'=>...)))
*
* @var array
*/
- private static $m_aStimuli = array();
+ private static $m_aStimuli = [];
/**
* array of ("classname" => array of ("statcode_from"=>array of ("stimuluscode" => array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD)))
*
* @var array
*/
- private static $m_aTransitions = array();
+ private static $m_aTransitions = [];
/**
* @param string $sClass
@@ -2420,18 +2340,14 @@ abstract class MetaModel
*/
public static function EnumStates($sClass)
{
- if (array_key_exists($sClass, self::$m_aStates))
- {
+ if (array_key_exists($sClass, self::$m_aStates)) {
return self::$m_aStates[$sClass];
- }
- elseif (self::HasStateAttributeCode($sClass))
- {
+ } elseif (self::HasStateAttributeCode($sClass)) {
$sStateAttCode = self::GetStateAttributeCode($sClass);
$oAttDef = self::GetAttributeDef($sClass, $sStateAttCode);
$aStates = [];
- foreach($oAttDef->GetAllowedValues() as $sStateCode => $sStateLabel)
- {
+ foreach ($oAttDef->GetAllowedValues() as $sStateCode => $sStateLabel) {
$aStates[$sStateCode] = [
'attribute_inherit' => '',
'attribute_list' => [],
@@ -2439,10 +2355,8 @@ abstract class MetaModel
}
return $aStates;
- }
- else
- {
- return array();
+ } else {
+ return [];
}
}
@@ -2455,28 +2369,22 @@ abstract class MetaModel
*/
public static function EnumInitialStates($sClass)
{
- if (array_key_exists($sClass, self::$m_aStates))
- {
- $aRet = array();
+ if (array_key_exists($sClass, self::$m_aStates)) {
+ $aRet = [];
// Add the states for which the flag 'is_initial_state' is set to
- foreach(self::$m_aStates[$sClass] as $aStateCode => $aProps)
- {
- if (isset($aProps['initial_state_path']))
- {
+ foreach (self::$m_aStates[$sClass] as $aStateCode => $aProps) {
+ if (isset($aProps['initial_state_path'])) {
$aRet[$aStateCode] = $aProps['initial_state_path'];
}
}
// Add the default initial state
$sMainInitialState = self::GetDefaultState($sClass);
- if (!isset($aRet[$sMainInitialState]))
- {
- $aRet[$sMainInitialState] = array();
+ if (!isset($aRet[$sMainInitialState])) {
+ $aRet[$sMainInitialState] = [];
}
return $aRet;
- }
- else
- {
- return array();
+ } else {
+ return [];
}
}
@@ -2487,13 +2395,10 @@ abstract class MetaModel
*/
public static function EnumStimuli($sClass)
{
- if (array_key_exists($sClass, self::$m_aStimuli))
- {
+ if (array_key_exists($sClass, self::$m_aStimuli)) {
return self::$m_aStimuli[$sClass];
- }
- else
- {
- return array();
+ } else {
+ return [];
}
}
@@ -2550,14 +2455,12 @@ abstract class MetaModel
*/
public static function EnumTransitions($sClass, $sStateCode)
{
- if (array_key_exists($sClass, self::$m_aTransitions))
- {
- if (array_key_exists($sStateCode, self::$m_aTransitions[$sClass]))
- {
+ if (array_key_exists($sClass, self::$m_aTransitions)) {
+ if (array_key_exists($sStateCode, self::$m_aTransitions[$sClass])) {
return self::$m_aTransitions[$sClass][$sStateCode];
}
}
- return array();
+ return [];
}
/**
@@ -2575,15 +2478,15 @@ abstract class MetaModel
*/
public static function EnumPossibleAttributeFlags()
{
- return $aPossibleAttFlags = array(
+ return $aPossibleAttFlags = [
'normal' => OPT_ATT_NORMAL,
'hidden' => OPT_ATT_HIDDEN,
'read_only' => OPT_ATT_READONLY,
'mandatory' => OPT_ATT_MANDATORY,
'must_change' => OPT_ATT_MUSTCHANGE,
'must_prompt' => OPT_ATT_MUSTPROMPT,
- 'slave' => OPT_ATT_SLAVE
- );
+ 'slave' => OPT_ATT_SLAVE,
+ ];
}
/**
@@ -2651,7 +2554,7 @@ abstract class MetaModel
*/
public static function GetTransitionAttributes($sClass, $sStimulus, $sOriginState)
{
- $aAttributes = array();
+ $aAttributes = [];
// Retrieving target state
$aTransitions = MetaModel::EnumTransitions($sClass, $sOriginState);
@@ -2663,19 +2566,15 @@ abstract class MetaModel
$aTargetState = $aStates[$sTargetState];
$aTargetStateAttributes = $aTargetState['attribute_list'];
// - Merging with results (only MUST_XXX and MANDATORY)
- foreach($aTargetStateAttributes as $sTargetStateAttCode => $iTargetStateAttFlags)
- {
+ foreach ($aTargetStateAttributes as $sTargetStateAttCode => $iTargetStateAttFlags) {
$iTmpAttFlags = OPT_ATT_NORMAL;
- if ($iTargetStateAttFlags & OPT_ATT_MUSTPROMPT)
- {
+ if ($iTargetStateAttFlags & OPT_ATT_MUSTPROMPT) {
$iTmpAttFlags = $iTmpAttFlags | OPT_ATT_MUSTPROMPT;
}
- if ($iTargetStateAttFlags & OPT_ATT_MUSTCHANGE)
- {
+ if ($iTargetStateAttFlags & OPT_ATT_MUSTCHANGE) {
$iTmpAttFlags = $iTmpAttFlags | OPT_ATT_MUSTCHANGE;
}
- if ($iTargetStateAttFlags & OPT_ATT_MANDATORY)
- {
+ if ($iTargetStateAttFlags & OPT_ATT_MANDATORY) {
$iTmpAttFlags = $iTmpAttFlags | OPT_ATT_MANDATORY;
}
@@ -2685,14 +2584,10 @@ abstract class MetaModel
// Retrieving attributes from transition
$aTransitionAttributes = $aTransition['attribute_list'];
// - Merging with results
- foreach($aTransitionAttributes as $sAttCode => $iAttributeFlags)
- {
- if (array_key_exists($sAttCode, $aAttributes))
- {
+ foreach ($aTransitionAttributes as $sAttCode => $iAttributeFlags) {
+ if (array_key_exists($sAttCode, $aAttributes)) {
$aAttributes[$sAttCode] = $aAttributes[$sAttCode] | $iAttributeFlags;
- }
- else
- {
+ } else {
$aAttributes[$sAttCode] = $iAttributeFlags;
}
}
@@ -2717,7 +2612,7 @@ abstract class MetaModel
if (array_key_exists($sState, $aStates)) {
$bReadOnly = (($iFlags & OPT_ATT_READONLY) == OPT_ATT_READONLY);
$bHidden = (($iFlags & OPT_ATT_HIDDEN) == OPT_ATT_HIDDEN);
- foreach($aStates[$sState] as $sPrevState) {
+ foreach ($aStates[$sState] as $sPrevState) {
$iPrevFlags = self::GetAttributeFlags($sClass, $sPrevState, $sAttCode);
if (($iPrevFlags & OPT_ATT_HIDDEN) != OPT_ATT_HIDDEN) {
$bReadOnly = $bReadOnly && (($iPrevFlags & OPT_ATT_READONLY) == OPT_ATT_READONLY); // if it is/was not readonly => then it's not
@@ -2727,15 +2622,13 @@ abstract class MetaModel
if ($bReadOnly) {
$iFlags = $iFlags | OPT_ATT_READONLY;
- }
- else {
+ } else {
$iFlags = $iFlags & ~OPT_ATT_READONLY;
}
if ($bHidden) {
$iFlags = $iFlags | OPT_ATT_HIDDEN;
- }
- else {
+ } else {
$iFlags = $iFlags & ~OPT_ATT_HIDDEN;
}
}
@@ -2752,7 +2645,7 @@ abstract class MetaModel
* @return mixed
* @throws \Exception
*/
- public static function GetAllowedValues_att($sClass, $sAttCode, $aArgs = array(), $sContains = '')
+ public static function GetAllowedValues_att($sClass, $sAttCode, $aArgs = [], $sContains = '')
{
$oAttDef = self::GetAttributeDef($sClass, $sAttCode);
return $oAttDef->GetAllowedValues($aArgs, $sContains);
@@ -2768,7 +2661,7 @@ abstract class MetaModel
* @return mixed
* @throws \Exception
*/
- public static function GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs = array(), $sContains = '', $iAdditionalValue = null)
+ public static function GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs = [], $sContains = '', $iAdditionalValue = null)
{
/** @var \AttributeExternalKey $oAttDef */
$oAttDef = self::GetAttributeDef($sClass, $sAttCode);
@@ -2776,8 +2669,6 @@ abstract class MetaModel
return $oAttDef->GetAllowedValuesAsObjectSet($aArgs, $sContains, $iAdditionalValue);
}
-
-
//
// Business model declaration verbs (should be static)
//
@@ -2790,14 +2681,12 @@ abstract class MetaModel
public static function RegisterZList($sListCode, $aListInfo)
{
// Check mandatory params
- $aMandatParams = array(
+ $aMandatParams = [
"description" => "detailed (though one line) description of the list",
"type" => "attributes | filters",
- );
- foreach($aMandatParams as $sParamName => $sParamDesc)
- {
- if (!array_key_exists($sParamName, $aListInfo))
- {
+ ];
+ foreach ($aMandatParams as $sParamName => $sParamDesc) {
+ if (!array_key_exists($sParamName, $aListInfo)) {
throw new CoreException("Declaration of list $sListCode - missing parameter $sParamName");
}
}
@@ -2842,8 +2731,7 @@ abstract class MetaModel
*/
public static function InitClasses($sTablePrefix)
{
- if (count(self::GetClasses()) > 0)
- {
+ if (count(self::GetClasses()) > 0) {
throw new CoreException("InitClasses should not be called more than once -skipped");
}
@@ -2852,54 +2740,43 @@ abstract class MetaModel
// Initialize the classes (declared attributes, etc.)
//
- $aObsoletableRootClasses = array();
- foreach(get_declared_classes() as $sPHPClass)
- {
- if (is_subclass_of($sPHPClass, 'DBObject'))
- {
+ $aObsoletableRootClasses = [];
+ foreach (get_declared_classes() as $sPHPClass) {
+ if (is_subclass_of($sPHPClass, 'DBObject')) {
$sParent = self::GetParentPersistentClass($sPHPClass);
- if (array_key_exists($sParent, self::$m_aIgnoredAttributes))
- {
+ if (array_key_exists($sParent, self::$m_aIgnoredAttributes)) {
// Inherit info about attributes to ignore
self::$m_aIgnoredAttributes[$sPHPClass] = self::$m_aIgnoredAttributes[$sParent];
}
- try
- {
+ try {
$oMethod = new ReflectionMethod($sPHPClass, 'Init');
- if ($oMethod->getDeclaringClass()->name == $sPHPClass)
- {
- call_user_func(array($sPHPClass, 'Init'));
+ if ($oMethod->getDeclaringClass()->name == $sPHPClass) {
+ call_user_func([$sPHPClass, 'Init']);
// Inherit archive flag
$bParentArchivable = isset(self::$m_aClassParams[$sParent]['archive']) ? self::$m_aClassParams[$sParent]['archive'] : false;
$bArchivable = isset(self::$m_aClassParams[$sPHPClass]['archive']) ? self::$m_aClassParams[$sPHPClass]['archive'] : null;
- if (!$bParentArchivable && $bArchivable && !self::IsRootClass($sPHPClass))
- {
+ if (!$bParentArchivable && $bArchivable && !self::IsRootClass($sPHPClass)) {
throw new Exception("Archivability must be declared on top of the class hierarchy above $sPHPClass (consistency throughout the whole class tree is a must)");
}
- if ($bParentArchivable && ($bArchivable === false))
- {
+ if ($bParentArchivable && ($bArchivable === false)) {
throw new Exception("$sPHPClass must be archivable (consistency throughout the whole class tree is a must)");
}
$bReallyArchivable = $bParentArchivable || $bArchivable;
self::$m_aClassParams[$sPHPClass]['archive'] = $bReallyArchivable;
$bArchiveRoot = $bReallyArchivable && !$bParentArchivable;
self::$m_aClassParams[$sPHPClass]['archive_root'] = $bArchiveRoot;
- if ($bReallyArchivable)
- {
+ if ($bReallyArchivable) {
self::$m_aClassParams[$sPHPClass]['archive_root_class'] = $bArchiveRoot ? $sPHPClass : self::$m_aClassParams[$sParent]['archive_root_class'];
}
// Inherit obsolescence expression
$sObsolescence = null;
- if (isset(self::$m_aClassParams[$sPHPClass]['obsolescence_expression']))
- {
+ if (isset(self::$m_aClassParams[$sPHPClass]['obsolescence_expression'])) {
// Defined or overloaded
$sObsolescence = self::$m_aClassParams[$sPHPClass]['obsolescence_expression'];
$aObsoletableRootClasses[self::$m_aRootClasses[$sPHPClass]] = true;
- }
- elseif (isset(self::$m_aClassParams[$sParent]['obsolescence_expression']))
- {
+ } elseif (isset(self::$m_aClassParams[$sParent]['obsolescence_expression'])) {
// Inherited
$sObsolescence = self::$m_aClassParams[$sParent]['obsolescence_expression'];
}
@@ -2909,7 +2786,7 @@ abstract class MetaModel
// - State attribute
$bParentHasStateAttribute = (isset(self::$m_aClassParams[$sParent]['state_attcode']) && !empty(self::$m_aClassParams[$sParent]['state_attcode']));
$bHasStateAttribute = (isset(self::$m_aClassParams[$sPHPClass]['state_attcode']) && !empty(self::$m_aClassParams[$sPHPClass]['state_attcode']));
- if($bParentHasStateAttribute && !$bHasStateAttribute) {
+ if ($bParentHasStateAttribute && !$bHasStateAttribute) {
// Set attribute code
self::$m_aClassParams[$sPHPClass]['state_attcode'] = self::$m_aClassParams[$sParent]['state_attcode'];
@@ -2918,43 +2795,34 @@ abstract class MetaModel
// - Image attribute
$bParentHasImageAttribute = (isset(self::$m_aClassParams[$sParent]['image_attcode']) && !empty(self::$m_aClassParams[$sParent]['image_attcode']));
$bHasImageAttribute = (isset(self::$m_aClassParams[$sPHPClass]['image_attcode']) && !empty(self::$m_aClassParams[$sPHPClass]['image_attcode']));
- if($bParentHasImageAttribute && !$bHasImageAttribute) {
+ if ($bParentHasImageAttribute && !$bHasImageAttribute) {
// Set attribute code
self::$m_aClassParams[$sPHPClass]['image_attcode'] = self::$m_aClassParams[$sParent]['image_attcode'];
}
- foreach(MetaModel::EnumPlugins('iOnClassInitialization') as $sPluginClass => $oClassInit)
- {
+ foreach (MetaModel::EnumPlugins('iOnClassInitialization') as $sPluginClass => $oClassInit) {
$oClassInit->OnAfterClassInitialization($sPHPClass);
}
}
$aCurrentClassUniquenessRules = MetaModel::GetUniquenessRules($sPHPClass, true);
- if (!empty($aCurrentClassUniquenessRules))
- {
+ if (!empty($aCurrentClassUniquenessRules)) {
$aClassFields = self::GetAttributesList($sPHPClass);
- foreach ($aCurrentClassUniquenessRules as $sUniquenessRuleId => $aUniquenessRuleProperties)
- {
+ foreach ($aCurrentClassUniquenessRules as $sUniquenessRuleId => $aUniquenessRuleProperties) {
$bIsRuleOverride = self::HasSameUniquenessRuleInParent($sPHPClass, $sUniquenessRuleId);
- try
- {
+ try {
self::CheckUniquenessRuleValidity($aUniquenessRuleProperties, $bIsRuleOverride, $aClassFields);
- }
- catch (CoreUnexpectedValue $e)
- {
+ } catch (CoreUnexpectedValue $e) {
throw new Exception("Invalid uniqueness rule declaration : class={$sPHPClass}, rule=$sUniquenessRuleId, reason={$e->getMessage()}");
}
- if (!$bIsRuleOverride)
- {
+ if (!$bIsRuleOverride) {
self::SetUniquenessRuleRootClass($sPHPClass, $sUniquenessRuleId);
}
}
}
- }
- catch (ReflectionException $e)
- {
+ } catch (ReflectionException $e) {
// This class is only implementing methods, ignore it from the MetaModel perspective
}
}
@@ -2962,25 +2830,22 @@ abstract class MetaModel
// Add a 'class' attribute/filter to the root classes and their children
//
- foreach(self::EnumRootClasses() as $sRootClass)
- {
- if (self::IsStandaloneClass($sRootClass))
- {
+ foreach (self::EnumRootClasses() as $sRootClass) {
+ if (self::IsStandaloneClass($sRootClass)) {
continue;
}
$sDbFinalClassField = self::DBGetClassField($sRootClass);
- if (strlen($sDbFinalClassField) == 0)
- {
+ if (strlen($sDbFinalClassField) == 0) {
$sDbFinalClassField = 'finalclass';
self::$m_aClassParams[$sRootClass]["db_finalclass_field"] = 'finalclass';
}
- $oClassAtt = new AttributeFinalClass('finalclass', array(
+ $oClassAtt = new AttributeFinalClass('finalclass', [
"sql" => $sDbFinalClassField,
"default_value" => $sRootClass,
"is_null_allowed" => false,
- "depends_on" => array(),
- ));
+ "depends_on" => [],
+ ]);
self::AddMagicAttribute($oClassAtt, $sRootClass);
$bObsoletable = array_key_exists($sRootClass, $aObsoletableRootClasses);
@@ -2988,7 +2853,6 @@ abstract class MetaModel
self::$m_aClassParams[$sRootClass]['obsolescence_expression'] = '0';
}
-
foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_EXCLUDETOP) as $sChildClass) {
if (array_key_exists('finalclass', self::$m_aAttribDefs[$sChildClass])) {
throw new CoreException("Class $sChildClass, 'finalclass' is a reserved keyword, it cannot be used as an attribute code");
@@ -3017,7 +2881,7 @@ abstract class MetaModel
$oArchiveFlag = new AttributeArchiveFlag('archive_flag');
self::AddMagicAttribute($oArchiveFlag, $sClass);
- $oArchiveDate = new AttributeArchiveDate('archive_date', array('magic' => true, "allowed_values" => null, "sql" => 'archive_date', "default_value" => '', "is_null_allowed" => true, "depends_on" => array()));
+ $oArchiveDate = new AttributeArchiveDate('archive_date', ['magic' => true, "allowed_values" => null, "sql" => 'archive_date', "default_value" => '', "is_null_allowed" => true, "depends_on" => []]);
self::AddMagicAttribute($oArchiveDate, $sClass);
} elseif (self::$m_aClassParams[$sClass]["archive"]) {
$sArchiveRoot = self::$m_aClassParams[$sClass]['archive_root_class'];
@@ -3038,7 +2902,7 @@ abstract class MetaModel
self::AddMagicAttribute($oObsolescenceFlag, $sClass);
if (self::$m_aRootClasses[$sClass] == $sClass) {
- $oObsolescenceDate = new AttributeObsolescenceDate('obsolescence_date', array('magic' => true, "allowed_values" => null, "sql" => 'obsolescence_date', "default_value" => '', "is_null_allowed" => true, "depends_on" => array()));
+ $oObsolescenceDate = new AttributeObsolescenceDate('obsolescence_date', ['magic' => true, "allowed_values" => null, "sql" => 'obsolescence_date', "default_value" => '', "is_null_allowed" => true, "depends_on" => []]);
self::AddMagicAttribute($oObsolescenceDate, $sClass);
} else {
$oObsolescenceDate = clone self::$m_aAttribDefs[$sRootClass]['obsolescence_date'];
@@ -3057,13 +2921,13 @@ abstract class MetaModel
// Compute the filter codes
//
foreach ($oAttDef->GetMagicFields() as $sCode) {
- if(!array_key_exists($sClass, self::$m_aMagicFields)) {
+ if (!array_key_exists($sClass, self::$m_aMagicFields)) {
self::$m_aMagicFields[] = $sClass;
}
self::$m_aMagicFields[$sClass][] = $sCode;
}
- if(!$oAttDef->IsSearchable()){
- if(!array_key_exists($sClass, self::$m_aFilterForbiddenAttributes)) {
+ if (!$oAttDef->IsSearchable()) {
+ if (!array_key_exists($sClass, self::$m_aFilterForbiddenAttributes)) {
self::$m_aFilterForbiddenAttributes[] = $sClass;
}
self::$m_aFilterForbiddenAttributes[$sClass][] = $sAttCode;
@@ -3084,41 +2948,37 @@ abstract class MetaModel
$sKeyAttCode = $oAttDef->GetKeyAttCode();
$sRemoteAttCode = $oAttDef->GetExtAttCode()."_friendlyname";
$sFriendlyNameAttCode = $sAttCode.'_friendlyname';
- $oFriendlyName = new AttributeExternalField($sFriendlyNameAttCode, array("allowed_values" => null, "extkey_attcode" => $sKeyAttCode, "target_attcode" => $sRemoteAttCode, "depends_on" => array()));
+ $oFriendlyName = new AttributeExternalField($sFriendlyNameAttCode, ["allowed_values" => null, "extkey_attcode" => $sKeyAttCode, "target_attcode" => $sRemoteAttCode, "depends_on" => []]);
self::AddMagicAttribute($oFriendlyName, $sClass, self::$m_aAttribOrigins[$sClass][$sKeyAttCode]);
} else {
// Create the friendly name attribute
$sFriendlyNameAttCode = $sAttCode.'_friendlyname';
- $oFriendlyName = new AttributeExternalField($sFriendlyNameAttCode, array('allowed_values' => null, 'extkey_attcode' => $sAttCode, "target_attcode" => 'friendlyname', 'depends_on' => array()));
+ $oFriendlyName = new AttributeExternalField($sFriendlyNameAttCode, ['allowed_values' => null, 'extkey_attcode' => $sAttCode, "target_attcode" => 'friendlyname', 'depends_on' => []]);
self::AddMagicAttribute($oFriendlyName, $sClass, self::$m_aAttribOrigins[$sClass][$sAttCode]);
if (self::HasChildrenClasses($sRemoteClass)) {
// First, create an external field attribute, that gets the final class
$sClassRecallAttCode = $sAttCode.'_finalclass_recall';
- $oClassRecall = new AttributeExternalField($sClassRecallAttCode, array(
+ $oClassRecall = new AttributeExternalField($sClassRecallAttCode, [
"allowed_values" => null,
"extkey_attcode" => $sAttCode,
"target_attcode" => "finalclass",
"is_null_allowed" => true,
- "depends_on" => array(),
- ));
+ "depends_on" => [],
+ ]);
self::AddMagicAttribute($oClassRecall, $sClass, self::$m_aAttribOrigins[$sClass][$sAttCode]);
// Add it to the ZLists where the external key is present
//foreach(self::$m_aListData[$sClass] as $sListCode => $aAttributes)
$sListCode = 'list';
- if (isset(self::$m_aListData[$sClass][$sListCode]))
- {
+ if (isset(self::$m_aListData[$sClass][$sListCode])) {
$aAttributes = self::$m_aListData[$sClass][$sListCode];
// temporary.... no loop
{
- if (in_array($sAttCode, $aAttributes))
- {
- $aNewList = array();
- foreach($aAttributes as $iPos => $sAttToDisplay)
- {
- if (is_string($sAttToDisplay) && ($sAttToDisplay == $sAttCode))
- {
+ if (in_array($sAttCode, $aAttributes)) {
+ $aNewList = [];
+ foreach ($aAttributes as $iPos => $sAttToDisplay) {
+ if (is_string($sAttToDisplay) && ($sAttToDisplay == $sAttCode)) {
// Insert the final class right before
$aNewList[] = $sClassRecallAttCode;
}
@@ -3142,7 +3002,7 @@ abstract class MetaModel
$sKeyAttCode = $sAttCode;
$sRemoteAttCode = 'archive_flag';
}
- $oMagic = new AttributeExternalField($sCode, array("allowed_values" => null, "extkey_attcode" => $sKeyAttCode, "target_attcode" => $sRemoteAttCode, "depends_on" => array()));
+ $oMagic = new AttributeExternalField($sCode, ["allowed_values" => null, "extkey_attcode" => $sKeyAttCode, "target_attcode" => $sRemoteAttCode, "depends_on" => []]);
self::AddMagicAttribute($oMagic, $sClass, self::$m_aAttribOrigins[$sClass][$sKeyAttCode]);
}
@@ -3157,7 +3017,7 @@ abstract class MetaModel
$sKeyAttCode = $sAttCode;
$sRemoteAttCode = 'obsolescence_flag';
}
- $oMagic = new AttributeExternalField($sCode, array("allowed_values" => null, "extkey_attcode" => $sKeyAttCode, "target_attcode" => $sRemoteAttCode, "depends_on" => array()));
+ $oMagic = new AttributeExternalField($sCode, ["allowed_values" => null, "extkey_attcode" => $sKeyAttCode, "target_attcode" => $sRemoteAttCode, "depends_on" => []]);
self::AddMagicAttribute($oMagic, $sClass, self::$m_aAttribOrigins[$sClass][$sKeyAttCode]);
}
}
@@ -3188,14 +3048,12 @@ abstract class MetaModel
private static function HasSameUniquenessRuleInParent($sClassName, $sUniquenessRuleId)
{
$sParentClass = self::GetParentClass($sClassName);
- if (empty($sParentClass))
- {
+ if (empty($sParentClass)) {
return false;
}
$aParentClassUniquenessRules = self::GetUniquenessRules($sParentClass);
- if (array_key_exists($sUniquenessRuleId, $aParentClassUniquenessRules))
- {
+ if (array_key_exists($sUniquenessRuleId, $aParentClassUniquenessRules)) {
return true;
}
@@ -3213,9 +3071,9 @@ abstract class MetaModel
* @since 2.6.0 N°659 uniqueness constraint
* @since 2.6.1 N°1968 (joli mois de mai...) disallow overrides of 'attributes' properties
*/
- public static function CheckUniquenessRuleValidity($aUniquenessRuleProperties, $bRuleOverride = true, $aExistingClassFields = array())
+ public static function CheckUniquenessRuleValidity($aUniquenessRuleProperties, $bRuleOverride = true, $aExistingClassFields = [])
{
- $MANDATORY_ATTRIBUTES = array('attributes');
+ $MANDATORY_ATTRIBUTES = ['attributes'];
$UNIQUENESS_MANDATORY_KEYS_NB = count($MANDATORY_ATTRIBUTES);
$bHasMissingMandatoryKey = true;
@@ -3224,18 +3082,14 @@ abstract class MetaModel
$bHasNonDisabledKeys = false;
$bDisabledKeyValue = null;
- foreach ($aUniquenessRuleProperties as $sUniquenessRuleKey => $aUniquenessRuleProperty)
- {
- if ($sUniquenessRuleKey === 'disabled')
- {
+ foreach ($aUniquenessRuleProperties as $sUniquenessRuleKey => $aUniquenessRuleProperty) {
+ if ($sUniquenessRuleKey === 'disabled') {
$bDisabledKeyValue = $aUniquenessRuleProperty;
- if (!is_null($aUniquenessRuleProperty))
- {
+ if (!is_null($aUniquenessRuleProperty)) {
continue;
}
}
- if (is_null($aUniquenessRuleProperty))
- {
+ if (is_null($aUniquenessRuleProperty)) {
continue;
}
@@ -3245,14 +3099,10 @@ abstract class MetaModel
$iMissingMandatoryKeysNb--;
}
- if ($sUniquenessRuleKey === 'attributes')
- {
- if (!empty($aExistingClassFields))
- {
- foreach ($aUniquenessRuleProperties[$sUniquenessRuleKey] as $sRuleAttribute)
- {
- if (!in_array($sRuleAttribute, $aExistingClassFields, true))
- {
+ if ($sUniquenessRuleKey === 'attributes') {
+ if (!empty($aExistingClassFields)) {
+ foreach ($aUniquenessRuleProperties[$sUniquenessRuleKey] as $sRuleAttribute) {
+ if (!in_array($sRuleAttribute, $aExistingClassFields, true)) {
throw new CoreUnexpectedValue("Uniqueness rule : non existing field '$sRuleAttribute'");
}
}
@@ -3260,21 +3110,17 @@ abstract class MetaModel
}
}
- if ($iMissingMandatoryKeysNb === 0)
- {
+ if ($iMissingMandatoryKeysNb === 0) {
$bHasMissingMandatoryKey = false;
}
- if ($bRuleOverride && $bHasNonDisabledKeys)
- {
+ if ($bRuleOverride && $bHasNonDisabledKeys) {
throw new CoreUnexpectedValue('Uniqueness rule : only the \'disabled\' key can be overridden');
}
- if ($bRuleOverride && is_null($bDisabledKeyValue))
- {
+ if ($bRuleOverride && is_null($bDisabledKeyValue)) {
throw new CoreUnexpectedValue('Uniqueness rule : when overriding a rule, value must be set for the \'disabled\' key');
}
- if (!$bRuleOverride && $bHasMissingMandatoryKey)
- {
+ if (!$bRuleOverride && $bHasMissingMandatoryKey) {
throw new CoreUnexpectedValue('Uniqueness rule : missing mandatory property');
}
}
@@ -3287,7 +3133,6 @@ abstract class MetaModel
// In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation)
}
-
/**
* @param array $aParams
*
@@ -3297,7 +3142,7 @@ abstract class MetaModel
{
// Check mandatory params
// Warning: Do not put image_attcode as a mandatory attribute or it will break all PHP datamodel classes
- $aMandatParams = array(
+ $aMandatParams = [
"category" => "group classes by modules defining their visibility in the UI",
"key_type" => "autoincrement | string",
"name_attcode" => "define which attribute is the class name, may be an array of attributes (format specified in the dictionary as 'Class:myclass/Name' => '%1\$s %2\$s...'",
@@ -3306,34 +3151,30 @@ abstract class MetaModel
"db_table" => "database table",
"db_key_field" => "database field which is the key",
"db_finalclass_field" => "database field wich is the reference to the actual class of the object, considering that this will be a compound class",
- );
+ ];
$sClass = self::GetCallersPHPClass("Init", self::$m_bTraceSourceFiles);
- foreach($aMandatParams as $sParamName => $sParamDesc)
- {
- if (!array_key_exists($sParamName, $aParams))
- {
+ foreach ($aMandatParams as $sParamName => $sParamDesc) {
+ if (!array_key_exists($sParamName, $aParams)) {
throw new CoreException("Declaration of class $sClass - missing parameter $sParamName");
}
}
$aCategories = explode(',', $aParams['category']);
- foreach($aCategories as $sCategory)
- {
+ foreach ($aCategories as $sCategory) {
self::$m_Category2Class[$sCategory][] = $sClass;
}
self::$m_Category2Class[''][] = $sClass; // all categories, include this one
-
self::$m_aRootClasses[$sClass] = $sClass; // first, let consider that I am the root... updated on inheritance
- self::$m_aParentClasses[$sClass] = array();
- self::$m_aChildClasses[$sClass] = array();
+ self::$m_aParentClasses[$sClass] = [];
+ self::$m_aChildClasses[$sClass] = [];
self::$m_aClassParams[$sClass] = $aParams;
- self::$m_aAttribDefs[$sClass] = array();
- self::$m_aAttribOrigins[$sClass] = array();
+ self::$m_aAttribDefs[$sClass] = [];
+ self::$m_aAttribOrigins[$sClass] = [];
}
/**
@@ -3344,13 +3185,11 @@ abstract class MetaModel
*/
protected static function object_array_mergeclone($aSource1, $aSource2)
{
- $aRes = array();
- foreach($aSource1 as $key => $object)
- {
+ $aRes = [];
+ foreach ($aSource1 as $key => $object) {
$aRes[$key] = clone $object;
}
- foreach($aSource2 as $key => $object)
- {
+ foreach ($aSource2 as $key => $object) {
$aRes[$key] = clone $object;
}
@@ -3372,8 +3211,8 @@ abstract class MetaModel
}
if (isset(self::$m_aAttribDefs[$sSourceClass])) {
if (!isset(self::$m_aAttribDefs[$sTargetClass])) {
- self::$m_aAttribDefs[$sTargetClass] = array();
- self::$m_aAttribOrigins[$sTargetClass] = array();
+ self::$m_aAttribDefs[$sTargetClass] = [];
+ self::$m_aAttribOrigins[$sTargetClass] = [];
}
self::$m_aAttribDefs[$sTargetClass] = self::object_array_mergeclone(self::$m_aAttribDefs[$sTargetClass], self::$m_aAttribDefs[$sSourceClass]);
foreach (self::$m_aAttribDefs[$sTargetClass] as $sAttCode => $oAttDef) {
@@ -3382,13 +3221,10 @@ abstract class MetaModel
self::$m_aAttribOrigins[$sTargetClass] = array_merge(self::$m_aAttribOrigins[$sTargetClass], self::$m_aAttribOrigins[$sSourceClass]);
}
// Build root class information
- if (array_key_exists($sSourceClass, self::$m_aRootClasses))
- {
+ if (array_key_exists($sSourceClass, self::$m_aRootClasses)) {
// Inherit...
self::$m_aRootClasses[$sTargetClass] = self::$m_aRootClasses[$sSourceClass];
- }
- else
- {
+ } else {
// This class will be the root class
self::$m_aRootClasses[$sSourceClass] = $sSourceClass;
self::$m_aRootClasses[$sTargetClass] = $sSourceClass;
@@ -3396,8 +3232,7 @@ abstract class MetaModel
self::$m_aParentClasses[$sTargetClass] += self::$m_aParentClasses[$sSourceClass];
self::$m_aParentClasses[$sTargetClass][] = $sSourceClass;
// I am the child of each and every parent...
- foreach(self::$m_aParentClasses[$sTargetClass] as $sAncestorClass)
- {
+ foreach (self::$m_aParentClasses[$sTargetClass] as $sAncestorClass) {
self::$m_aChildClasses[$sAncestorClass][] = $sTargetClass;
}
}
@@ -3411,12 +3246,10 @@ abstract class MetaModel
{
// Differs from self::IsValidClass()
// because it is being called before all the classes have been initialized
- if (!class_exists($sClass))
- {
+ if (!class_exists($sClass)) {
return false;
}
- if (!is_subclass_of($sClass, 'DBObject'))
- {
+ if (!is_subclass_of($sClass, 'DBObject')) {
return false;
}
@@ -3454,29 +3287,21 @@ abstract class MetaModel
// declared in a module which is currently not installed/active
// We simply discard those attributes
//
- if ($oAtt->IsLinkSet())
- {
+ if ($oAtt->IsLinkSet()) {
$sRemoteClass = $oAtt->GetLinkedClass();
- if (!self::Init_IsKnownClass($sRemoteClass))
- {
+ if (!self::Init_IsKnownClass($sRemoteClass)) {
self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = $sRemoteClass;
return;
}
- }
- elseif ($oAtt->IsExternalKey())
- {
+ } elseif ($oAtt->IsExternalKey()) {
$sRemoteClass = $oAtt->GetTargetClass();
- if (!self::Init_IsKnownClass($sRemoteClass))
- {
+ if (!self::Init_IsKnownClass($sRemoteClass)) {
self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = $sRemoteClass;
return;
}
- }
- elseif ($oAtt->IsExternalField())
- {
+ } elseif ($oAtt->IsExternalField()) {
$sExtKeyAttCode = $oAtt->GetKeyAttCode();
- if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode]))
- {
+ if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode])) {
// The corresponding external key has already been ignored
self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode];
@@ -3518,22 +3343,16 @@ abstract class MetaModel
*/
protected static function Init_CheckZListItems(&$aItems, $sTargetClass)
{
- foreach($aItems as $iFoo => $attCode)
- {
- if (is_array($attCode))
- {
+ foreach ($aItems as $iFoo => $attCode) {
+ if (is_array($attCode)) {
// Note: to make sure that the values will be updated recursively,
// do not pass $attCode, but $aItems[$iFoo] instead
self::Init_CheckZListItems($aItems[$iFoo], $sTargetClass);
- if (count($aItems[$iFoo]) == 0)
- {
+ if (count($aItems[$iFoo]) == 0) {
unset($aItems[$iFoo]);
}
- }
- else
- {
- if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$attCode]))
- {
+ } else {
+ if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$attCode])) {
unset($aItems[$iFoo]);
}
}
@@ -3547,15 +3366,11 @@ abstract class MetaModel
*/
public static function FlattenZList($aList)
{
- $aResult = array();
- foreach($aList as $value)
- {
- if (!is_array($value))
- {
+ $aResult = [];
+ foreach ($aList as $value) {
+ if (!is_array($value)) {
$aResult[] = $value;
- }
- else
- {
+ } else {
$aResult = array_merge($aResult, self::FlattenZList($value));
}
}
@@ -3570,22 +3385,19 @@ abstract class MetaModel
public static function Init_DefineState($sStateCode, $aStateDef)
{
$sTargetClass = self::GetCallersPHPClass("Init");
- if (is_null($aStateDef['attribute_list']))
- {
- $aStateDef['attribute_list'] = array();
+ if (is_null($aStateDef['attribute_list'])) {
+ $aStateDef['attribute_list'] = [];
}
$sParentState = $aStateDef['attribute_inherit'];
- if (!empty($sParentState))
- {
+ if (!empty($sParentState)) {
// Inherit from the given state (must be defined !)
//
$aToInherit = self::$m_aStates[$sTargetClass][$sParentState];
// Reset the constraint when it was mandatory to set the value at the previous state
//
- foreach($aToInherit['attribute_list'] as $sState => $iFlags)
- {
+ foreach ($aToInherit['attribute_list'] as $sState => $iFlags) {
$iFlags = $iFlags & ~OPT_ATT_MUSTPROMPT;
$iFlags = $iFlags & ~OPT_ATT_MUSTCHANGE;
$aToInherit['attribute_list'][$sState] = $iFlags;
@@ -3595,10 +3407,8 @@ abstract class MetaModel
$aStateDef['attribute_list'] = array_merge($aToInherit['attribute_list'], $aStateDef['attribute_list']);
}
- foreach($aStateDef['attribute_list'] as $sAttCode => $iFlags)
- {
- if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sAttCode]))
- {
+ foreach ($aStateDef['attribute_list'] as $sAttCode => $iFlags) {
+ if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sAttCode])) {
unset($aStateDef['attribute_list'][$sAttCode]);
}
}
@@ -3606,7 +3416,7 @@ abstract class MetaModel
self::$m_aStates[$sTargetClass][$sStateCode] = $aStateDef;
// by default, create an empty set of transitions associated to that state
- self::$m_aTransitions[$sTargetClass][$sStateCode] = array();
+ self::$m_aTransitions[$sTargetClass][$sStateCode] = [];
}
/**
@@ -3646,16 +3456,14 @@ abstract class MetaModel
*/
public static function GetHighlightScale($sTargetClass)
{
- $aScale = array();
- $aParentScale = array();
+ $aScale = [];
+ $aParentScale = [];
$sParentClass = self::GetParentPersistentClass($sTargetClass);
- if (!empty($sParentClass))
- {
+ if (!empty($sParentClass)) {
// inherit the scale from the parent class
$aParentScale = self::GetHighlightScale($sParentClass);
}
- if (array_key_exists($sTargetClass, self::$m_aHighlightScales))
- {
+ if (array_key_exists($sTargetClass, self::$m_aHighlightScales)) {
$aScale = self::$m_aHighlightScales[$sTargetClass];
}
return array_merge($aParentScale, $aScale); // Merge both arrays, the values from the last one have precedence
@@ -3672,16 +3480,12 @@ abstract class MetaModel
$sCode = '';
if (array_key_exists($sTargetClass, self::$m_aStates)
&& array_key_exists($sStateCode, self::$m_aStates[$sTargetClass])
- && array_key_exists('highlight', self::$m_aStates[$sTargetClass][$sStateCode]))
- {
+ && array_key_exists('highlight', self::$m_aStates[$sTargetClass][$sStateCode])) {
$sCode = self::$m_aStates[$sTargetClass][$sStateCode]['highlight']['code'];
- }
- else
- {
+ } else {
// Check the parent's definition
$sParentClass = self::GetParentPersistentClass($sTargetClass);
- if (!empty($sParentClass))
- {
+ if (!empty($sParentClass)) {
$sCode = self::GetHighlightCode($sParentClass, $sStateCode);
}
}
@@ -3722,9 +3526,8 @@ abstract class MetaModel
public static function Init_DefineTransition($sStateCode, $sStimulusCode, $aTransitionDef)
{
$sTargetClass = self::GetCallersPHPClass("Init");
- if (is_null($aTransitionDef['actions']))
- {
- $aTransitionDef['actions'] = array();
+ if (is_null($aTransitionDef['actions'])) {
+ $aTransitionDef['actions'] = [];
}
self::$m_aTransitions[$sTargetClass][$sStateCode][$sStimulusCode] = $aTransitionDef;
}
@@ -3735,12 +3538,10 @@ abstract class MetaModel
public static function Init_InheritLifecycle($sSourceClass = '')
{
$sTargetClass = self::GetCallersPHPClass("Init");
- if (empty($sSourceClass))
- {
+ if (empty($sSourceClass)) {
// Default: inherit from parent class
$sSourceClass = self::GetParentPersistentClass($sTargetClass);
- if (empty($sSourceClass))
- {
+ if (empty($sSourceClass)) {
return;
} // no attributes for the mother of all classes
}
@@ -3787,12 +3588,9 @@ abstract class MetaModel
*/
public static function GetParentClass($sClass)
{
- if (count(self::$m_aParentClasses[$sClass]) == 0)
- {
+ if (count(self::$m_aParentClasses[$sClass]) == 0) {
return null;
- }
- else
- {
+ } else {
return end(self::$m_aParentClasses[$sClass]);
}
}
@@ -3806,24 +3604,16 @@ abstract class MetaModel
public static function GetLowestCommonAncestor($aClasses)
{
$sAncestor = null;
- foreach($aClasses as $sClass)
- {
- if (is_null($sAncestor))
- {
+ foreach ($aClasses as $sClass) {
+ if (is_null($sAncestor)) {
// first loop
$sAncestor = $sClass;
- }
- elseif ($sClass == $sAncestor)
- {
+ } elseif ($sClass == $sAncestor) {
// remains the same
- }
- elseif (self::GetRootClass($sClass) != self::GetRootClass($sAncestor))
- {
+ } elseif (self::GetRootClass($sClass) != self::GetRootClass($sAncestor)) {
$sAncestor = null;
break;
- }
- else
- {
+ } else {
$sAncestor = self::LowestCommonAncestor($sAncestor, $sClass);
}
}
@@ -3840,20 +3630,13 @@ abstract class MetaModel
*/
protected static function LowestCommonAncestor($sClassA, $sClassB)
{
- if ($sClassA == $sClassB)
- {
+ if ($sClassA == $sClassB) {
$sRet = $sClassA;
- }
- elseif (is_subclass_of($sClassA, $sClassB))
- {
+ } elseif (is_subclass_of($sClassA, $sClassB)) {
$sRet = $sClassB;
- }
- elseif (is_subclass_of($sClassB, $sClassA))
- {
+ } elseif (is_subclass_of($sClassB, $sClassA)) {
$sRet = $sClassA;
- }
- else
- {
+ } else {
// Recurse
$sRet = self::LowestCommonAncestor($sClassA, self::GetParentClass($sClassB));
}
@@ -3871,10 +3654,8 @@ abstract class MetaModel
public static function IsHierarchicalClass($sClass)
{
$sHierarchicalKeyCode = false;
- foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
- {
- if ($oAtt->IsHierarchicalKey())
- {
+ foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt) {
+ if ($oAtt->IsHierarchicalKey()) {
$sHierarchicalKeyCode = $sAttCode; // Found the hierarchical key, no need to continue
break;
}
@@ -3901,23 +3682,16 @@ abstract class MetaModel
public static function EnumParentClasses($sClass, $iOption = ENUM_PARENT_CLASSES_EXCLUDELEAF, $bRootFirst = true)
{
self::_check_subclass($sClass);
- if ($bRootFirst)
- {
+ if ($bRootFirst) {
$aRes = self::$m_aParentClasses[$sClass];
- }
- else
- {
+ } else {
$aRes = array_reverse(self::$m_aParentClasses[$sClass], true);
}
- if ($iOption != ENUM_PARENT_CLASSES_EXCLUDELEAF)
- {
- if ($bRootFirst)
- {
+ if ($iOption != ENUM_PARENT_CLASSES_EXCLUDELEAF) {
+ if ($bRootFirst) {
// Leaf class at the end
$aRes[] = $sClass;
- }
- else
- {
+ } else {
// Leaf class on top
array_unshift($aRes, $sClass);
}
@@ -3940,8 +3714,7 @@ abstract class MetaModel
self::_check_subclass($sClass);
$aRes = self::$m_aChildClasses[$sClass];
- if ($iOption != ENUM_CHILD_CLASSES_EXCLUDETOP)
- {
+ if ($iOption != ENUM_CHILD_CLASSES_EXCLUDETOP) {
if ($bRootFirst) {
// Root class on top
array_unshift($aRes, $sClass);
@@ -3960,11 +3733,9 @@ abstract class MetaModel
*/
public static function EnumArchivableClasses()
{
- $aRes = array();
- foreach(self::GetClasses() as $sClass)
- {
- if (self::IsArchivable($sClass))
- {
+ $aRes = [];
+ foreach (self::GetClasses() as $sClass) {
+ if (self::IsArchivable($sClass)) {
$aRes[] = $sClass;
}
}
@@ -3980,13 +3751,10 @@ abstract class MetaModel
*/
public static function EnumObsoletableClasses($bRootClassesOnly = true)
{
- $aRes = array();
- foreach(self::GetClasses() as $sClass)
- {
- if (self::IsObsoletable($sClass))
- {
- if ($bRootClassesOnly && !static::IsRootClass($sClass))
- {
+ $aRes = [];
+ foreach (self::GetClasses() as $sClass) {
+ if (self::IsObsoletable($sClass)) {
+ if ($bRootClassesOnly && !static::IsRootClass($sClass)) {
continue;
}
$aRes[] = $sClass;
@@ -4024,11 +3792,9 @@ abstract class MetaModel
public static function GetSubclasses($sClass)
{
self::_check_subclass($sClass);
- $aSubClasses = array();
- foreach(self::$m_aClassParams as $sSubClass => $foo)
- {
- if (is_subclass_of($sSubClass, $sClass))
- {
+ $aSubClasses = [];
+ foreach (self::$m_aClassParams as $sSubClass => $foo) {
+ if (is_subclass_of($sSubClass, $sClass)) {
$aSubClasses[] = $sSubClass;
}
}
@@ -4046,21 +3812,16 @@ abstract class MetaModel
public static function GetClasses($sCategories = '', $bStrict = false)
{
$aCategories = explode(',', $sCategories);
- $aClasses = array();
- foreach($aCategories as $sCategory)
- {
+ $aClasses = [];
+ foreach ($aCategories as $sCategory) {
$sCategory = trim($sCategory);
- if (strlen($sCategory) == 0)
- {
+ if (strlen($sCategory) == 0) {
return array_keys(self::$m_aClassParams);
}
- if (array_key_exists($sCategory, self::$m_Category2Class))
- {
+ if (array_key_exists($sCategory, self::$m_Category2Class)) {
$aClasses = array_merge($aClasses, self::$m_Category2Class[$sCategory]);
- }
- elseif ($bStrict)
- {
+ } elseif ($bStrict) {
throw new CoreException("unkown class category '$sCategory', expecting a value in {".implode(', ', array_keys(self::$m_Category2Class))."}");
}
}
@@ -4076,8 +3837,7 @@ abstract class MetaModel
*/
public static function HasTable($sClass)
{
- if (strlen(self::DBGetTable($sClass)) == 0)
- {
+ if (strlen(self::DBGetTable($sClass)) == 0) {
return false;
}
return true;
@@ -4106,13 +3866,11 @@ abstract class MetaModel
*
* @return array
*/
- public static function PrepareQueryArguments($aArgs, $aMoreArgs = array(), $aExpectedArgs = null)
+ public static function PrepareQueryArguments($aArgs, $aMoreArgs = [], $aExpectedArgs = null)
{
- $aScalarArgs = array();
- if (is_null($aExpectedArgs) || count($aExpectedArgs) > 0 || count($aMoreArgs)>0)
- {
- foreach (array_merge($aArgs, $aMoreArgs) as $sArgName => $value)
- {
+ $aScalarArgs = [];
+ if (is_null($aExpectedArgs) || count($aExpectedArgs) > 0 || count($aMoreArgs) > 0) {
+ foreach (array_merge($aArgs, $aMoreArgs) as $sArgName => $value) {
if (self::IsValidObject($value)) {
if (strpos($sArgName, '->object()') === false) {
// Normalize object arguments
@@ -4132,10 +3890,8 @@ abstract class MetaModel
}
}
return static::AddMagicPlaceholders($aScalarArgs, $aExpectedArgs);
- }
- else
- {
- return array();
+ } else {
+ return [];
}
}
@@ -4148,33 +3904,27 @@ abstract class MetaModel
{
// Add standard magic arguments
//
- if (is_null($aExpectedArgs))
- {
+ if (is_null($aExpectedArgs)) {
$aPlaceholders['current_contact_id'] = UserRights::GetContactId(); // legacy
$oUser = UserRights::GetUserObject();
- if (!is_null($oUser))
- {
+ if (!is_null($oUser)) {
$aPlaceholders['current_user->object()'] = $oUser;
$oContact = UserRights::GetContactObject();
- if (!is_null($oContact))
- {
+ if (!is_null($oContact)) {
$aPlaceholders['current_contact->object()'] = $oContact;
}
}
- }
- else
- {
+ } else {
$aCurrentUser = [];
$aCurrentContact = [];
- foreach ($aExpectedArgs as $expression)
- {
+ foreach ($aExpectedArgs as $expression) {
$aName = explode('->', $expression->GetName());
if ($aName[0] == 'current_contact_id') {
$aPlaceholders['current_contact_id'] = UserRights::GetContactId();
- } else if ($aName[0] == 'current_user') {
+ } elseif ($aName[0] == 'current_user') {
array_push($aCurrentUser, $aName[1]);
- } else if ($aName[0] == 'current_contact') {
+ } elseif ($aName[0] == 'current_contact') {
array_push($aCurrentContact, $aName[1]);
}
}
@@ -4199,35 +3949,42 @@ abstract class MetaModel
* @return void
*
*/
- private static function FillObjectPlaceholders(array &$aPlaceholders, string $sPlaceHolderPrefix, ?\DBObject $oObject, array $aCurrentUser) : void {
+ private static function FillObjectPlaceholders(array &$aPlaceholders, string $sPlaceHolderPrefix, ?\DBObject $oObject, array $aCurrentUser): void
+ {
$sPlaceHolderKey = $sPlaceHolderPrefix."->object()";
- if (is_null($oObject)){
+ if (is_null($oObject)) {
$aContext = [
"current_user_id" => UserRights::GetUserId(),
"null object type" => $sPlaceHolderPrefix,
"fields" => $aCurrentUser,
];
- IssueLog::Warning("Unresolved placeholders due to null object in current context", null,
- $aContext);
+ IssueLog::Warning(
+ "Unresolved placeholders due to null object in current context",
+ null,
+ $aContext
+ );
$aPlaceholders[$sPlaceHolderKey] = Dict::Format("Core:Placeholder:CannotBeResolved", $sPlaceHolderKey);
foreach ($aCurrentUser as $sField) {
- $sPlaceHolderKey = $sPlaceHolderPrefix . "->$sField";
+ $sPlaceHolderKey = $sPlaceHolderPrefix."->$sField";
$aPlaceholders[$sPlaceHolderKey] = Dict::Format("Core:Placeholder:CannotBeResolved", $sPlaceHolderKey);
}
} else {
$aPlaceholders[$sPlaceHolderKey] = $oObject;
foreach ($aCurrentUser as $sField) {
- $sPlaceHolderKey = $sPlaceHolderPrefix . "->$sField";
+ $sPlaceHolderKey = $sPlaceHolderPrefix."->$sField";
// Mind that the "id" is not viewed as a valid att. code by \MetaModel::IsValidAttCode() so we have to test it manually
- if ($sField !== "id" && false === MetaModel::IsValidAttCode(get_class($oObject), $sField)){
+ if ($sField !== "id" && false === MetaModel::IsValidAttCode(get_class($oObject), $sField)) {
$aContext = [
"current_user_id" => UserRights::GetUserId(),
"obj_class" => get_class($oObject),
"placeholder" => $sPlaceHolderKey,
"invalid_field" => $sField,
];
- IssueLog::Warning("Unresolved placeholder due to invalid attribute", null,
- $aContext);
+ IssueLog::Warning(
+ "Unresolved placeholder due to invalid attribute",
+ null,
+ $aContext
+ );
$aPlaceholders[$sPlaceHolderKey] = Dict::Format("Core:Placeholder:CannotBeResolved", $sPlaceHolderKey);
continue;
}
@@ -4246,29 +4003,25 @@ abstract class MetaModel
{
// Compute query modifiers properties (can be set in the search itself, by the context, etc.)
//
- $aModifierProperties = array();
+ $aModifierProperties = [];
/**
* @var string $sPluginClass
* @var iQueryModifier $oQueryModifier
*/
- foreach(MetaModel::EnumPlugins('iQueryModifier') as $sPluginClass => $oQueryModifier)
- {
+ foreach (MetaModel::EnumPlugins('iQueryModifier') as $sPluginClass => $oQueryModifier) {
// Lowest precedence: the application context
$aPluginProps = ApplicationContext::GetPluginProperties($sPluginClass);
// Highest precedence: programmatically specified (or OQL)
- foreach($oFilter->GetModifierProperties($sPluginClass) as $sProp => $value)
- {
+ foreach ($oFilter->GetModifierProperties($sPluginClass) as $sProp => $value) {
$aPluginProps[$sProp] = $value;
}
- if (count($aPluginProps) > 0)
- {
+ if (count($aPluginProps) > 0) {
$aModifierProperties[$sPluginClass] = $aPluginProps;
}
}
return $aModifierProperties;
}
-
/**
* Special processing for the hierarchical keys stored as nested sets
*
@@ -4281,22 +4034,16 @@ abstract class MetaModel
public static function HKInsertChildUnder($iId, $oAttDef, $sTable)
{
// Get the parent id.right value
- if ($iId == 0)
- {
+ if ($iId == 0) {
// No parent, insert completely at the right of the tree
$sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
$aRes = CMDBSource::QueryToArray($sSQL);
- if (count($aRes) == 0)
- {
+ if (count($aRes) == 0) {
$iMyRight = 1;
- }
- else
- {
+ } else {
$iMyRight = $aRes[0]['max'] + 1;
}
- }
- else
- {
+ } else {
$sSQL = "SELECT `".$oAttDef->GetSQLRight()."` FROM `$sTable` WHERE id=".$iId;
$iMyRight = CMDBSource::QueryToScalar($sSQL);
$sSQLUpdateRight = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` + 2 WHERE `".$oAttDef->GetSQLRight()."` >= $iMyRight";
@@ -4304,7 +4051,7 @@ abstract class MetaModel
$sSQLUpdateLeft = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` + 2 WHERE `".$oAttDef->GetSQLLeft()."` > $iMyRight";
CMDBSource::Query($sSQLUpdateLeft);
}
- return array($oAttDef->GetSQLRight() => $iMyRight + 1, $oAttDef->GetSQLLeft() => $iMyRight);
+ return [$oAttDef->GetSQLRight() => $iMyRight + 1, $oAttDef->GetSQLLeft() => $iMyRight];
}
/**
@@ -4366,26 +4113,20 @@ abstract class MetaModel
public static function CheckHKeys(bool $bDiagnosticsOnly = false, bool $bVerbose = false, bool $bForceComputation = false)
{
$bChangeNeeded = false;
- foreach(self::GetClasses() as $sClass)
- {
- if (!self::HasTable($sClass))
- {
+ foreach (self::GetClasses() as $sClass) {
+ if (!self::HasTable($sClass)) {
continue;
}
- foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
- {
+ foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) {
// Check (once) all the attributes that are hierarchical keys
- if ((self::GetAttributeOrigin($sClass, $sAttCode) == $sClass) && $oAttDef->IsHierarchicalKey())
- {
- if ($bVerbose)
- {
+ if ((self::GetAttributeOrigin($sClass, $sAttCode) == $sClass) && $oAttDef->IsHierarchicalKey()) {
+ if ($bVerbose) {
echo "The attribute $sAttCode from $sClass is a hierarchical key.\n";
}
$bResult = self::HKInit($sClass, $sAttCode, $bDiagnosticsOnly, $bVerbose, $bForceComputation);
$bChangeNeeded |= $bResult;
- if ($bVerbose && !$bResult)
- {
+ if ($bVerbose && !$bResult) {
echo "Ok, the attribute $sAttCode from class $sClass seems up to date.\n";
}
}
@@ -4416,40 +4157,31 @@ abstract class MetaModel
$bUpdateNeeded = $bForceComputation;
$oAttDef = self::GetAttributeDef($sClass, $sAttCode);
$sTable = self::DBGetTable($sClass, $sAttCode);
- if ($oAttDef->IsHierarchicalKey())
- {
+ if ($oAttDef->IsHierarchicalKey()) {
// Check if some values already exist in the table for the _right value, if so, do nothing
$sRight = $oAttDef->GetSQLRight();
$sSQL = "SELECT MAX(`$sRight`) AS MaxRight FROM `$sTable`";
$iMaxRight = CMDBSource::QueryToScalar($sSQL);
$sSQL = "SELECT COUNT(*) AS Count FROM `$sTable`"; // Note: COUNT(field) returns zero if the given field contains only NULLs
$iCount = CMDBSource::QueryToScalar($sSQL);
- if (!$bForceComputation && ($iCount != 0) && ($iMaxRight == 0))
- {
+ if (!$bForceComputation && ($iCount != 0) && ($iMaxRight == 0)) {
$bUpdateNeeded = true;
- if ($bVerbose)
- {
+ if ($bVerbose) {
echo "The table '$sTable' must be updated to compute the fields $sRight and ".$oAttDef->GetSQLLeft()."\n";
}
}
- if ($bForceComputation && !$bDiagnosticsOnly)
- {
+ if ($bForceComputation && !$bDiagnosticsOnly) {
echo "Rebuilding the fields $sRight and ".$oAttDef->GetSQLLeft()." from table '$sTable'...\n";
}
- if ($bUpdateNeeded && !$bDiagnosticsOnly)
- {
- try
- {
+ if ($bUpdateNeeded && !$bDiagnosticsOnly) {
+ try {
CMDBSource::Query('START TRANSACTION');
self::HKInitChildren($sTable, $sAttCode, $oAttDef, 0, $idx);
CMDBSource::Query('COMMIT');
- if ($bVerbose)
- {
+ if ($bVerbose) {
echo "Ok, table '$sTable' successfully updated.\n";
}
- }
- catch (Exception $e)
- {
+ } catch (Exception $e) {
CMDBSource::Query('ROLLBACK');
throw new Exception("An error occured (".$e->getMessage().") while initializing the hierarchy for ($sClass, $sAttCode). The database was not modified.");
}
@@ -4476,8 +4208,7 @@ abstract class MetaModel
$aRes = CMDBSource::QueryToArray($sSQL);
$sLeft = $oAttDef->GetSQLLeft();
$sRight = $oAttDef->GetSQLRight();
- foreach($aRes as $aValues)
- {
+ foreach ($aRes as $aValues) {
$iChildId = $aValues['id'];
$iLeft = $iCurrIndex++;
self::HKInitChildren($sTable, $sAttCode, $oAttDef, $iChildId, $iCurrIndex);
@@ -4499,49 +4230,33 @@ abstract class MetaModel
*/
public static function RebuildMetaEnums($bVerbose = false)
{
- foreach(self::GetClasses() as $sClass)
- {
- if (!self::HasTable($sClass))
- {
+ foreach (self::GetClasses() as $sClass) {
+ if (!self::HasTable($sClass)) {
continue;
}
- foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
- {
+ foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) {
// Check (once) all the attributes that are hierarchical keys
- if ((self::GetAttributeOrigin($sClass, $sAttCode) == $sClass) && $oAttDef instanceof AttributeEnum)
- {
- if (isset(self::$m_aEnumToMeta[$sClass][$sAttCode]))
- {
- foreach(self::$m_aEnumToMeta[$sClass][$sAttCode] as $sMetaAttCode => $oMetaAttDef)
- {
- $aMetaValues = array(); // array of (metavalue => array of values)
- foreach($oAttDef->GetAllowedValues() as $sCode => $sLabel)
- {
+ if ((self::GetAttributeOrigin($sClass, $sAttCode) == $sClass) && $oAttDef instanceof AttributeEnum) {
+ if (isset(self::$m_aEnumToMeta[$sClass][$sAttCode])) {
+ foreach (self::$m_aEnumToMeta[$sClass][$sAttCode] as $sMetaAttCode => $oMetaAttDef) {
+ $aMetaValues = []; // array of (metavalue => array of values)
+ foreach ($oAttDef->GetAllowedValues() as $sCode => $sLabel) {
$aMappingData = $oMetaAttDef->GetMapRule($sClass);
- if ($aMappingData == null)
- {
+ if ($aMappingData == null) {
$sMetaValue = $oMetaAttDef->GetDefaultValue();
- }
- else
- {
- if (array_key_exists($sCode, $aMappingData['values']))
- {
+ } else {
+ if (array_key_exists($sCode, $aMappingData['values'])) {
$sMetaValue = $aMappingData['values'][$sCode];
- }
- elseif ($oMetaAttDef->GetDefaultValue() != '')
- {
+ } elseif ($oMetaAttDef->GetDefaultValue() != '') {
$sMetaValue = $oMetaAttDef->GetDefaultValue();
- }
- else
- {
+ } else {
throw new Exception('MetaModel::RebuildMetaEnums(): mapping not found for value "'.$sCode.'"" in '.$sClass.', on attribute '.self::GetAttributeOrigin($sClass, $oMetaAttDef->GetCode()).'::'.$oMetaAttDef->GetCode());
}
}
$aMetaValues[$sMetaValue][] = $sCode;
}
- foreach($aMetaValues as $sMetaValue => $aEnumValues)
- {
+ foreach ($aMetaValues as $sMetaValue => $aEnumValues) {
$sMetaTable = self::DBGetTable($sClass, $sMetaAttCode);
$sEnumTable = self::DBGetTable($sClass);
$aColumns = array_keys($oMetaAttDef->GetSQLColumns());
@@ -4550,8 +4265,7 @@ abstract class MetaModel
$sEnumColumn = reset($aColumns);
$sValueList = implode(', ', CMDBSource::Quote($aEnumValues));
$sSql = "UPDATE `$sMetaTable` JOIN `$sEnumTable` ON `$sEnumTable`.id = `$sMetaTable`.id SET `$sMetaTable`.`$sMetaColumn` = '$sMetaValue' WHERE `$sEnumTable`.`$sEnumColumn` IN ($sValueList) AND `$sMetaTable`.`$sMetaColumn` != '$sMetaValue'";
- if ($bVerbose)
- {
+ if ($bVerbose) {
echo "Executing query: $sSql\n";
}
CMDBSource::Query($sSql);
@@ -4563,7 +4277,6 @@ abstract class MetaModel
}
}
-
/**
* @param boolean $bDiagnostics
* @param boolean $bVerbose
@@ -4576,20 +4289,16 @@ abstract class MetaModel
$sOQL = 'SELECT SynchroDataSource';
$oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL));
$bFixNeeded = false;
- if ($bVerbose && $oSet->Count() == 0)
- {
+ if ($bVerbose && $oSet->Count() == 0) {
echo "There are no Data Sources in the database.\n";
}
- while ($oSource = $oSet->Fetch())
- {
- if ($bVerbose)
- {
+ while ($oSource = $oSet->Fetch()) {
+ if ($bVerbose) {
echo "Checking Data Source '".$oSource->GetName()."'...\n";
$bFixNeeded = $bFixNeeded | $oSource->CheckDBConsistency($bDiagnostics, $bVerbose);
}
}
- if (!$bFixNeeded && $bVerbose)
- {
+ if (!$bFixNeeded && $bVerbose) {
echo "Ok.\n";
}
@@ -4606,23 +4315,20 @@ abstract class MetaModel
*/
public static function GenerateUniqueAlias(&$aAliases, $sNewName, $sRealName)
{
- if (!array_key_exists($sNewName, $aAliases))
- {
+ if (!array_key_exists($sNewName, $aAliases)) {
$aAliases[$sNewName] = $sRealName;
return $sNewName;
}
- for($i = 1; $i < 100; $i++)
- {
+ for ($i = 1; $i < 100; $i++) {
$sAnAlias = $sNewName.$i;
- if (!array_key_exists($sAnAlias, $aAliases))
- {
+ if (!array_key_exists($sAnAlias, $aAliases)) {
// Create that new alias
$aAliases[$sAnAlias] = $sRealName;
return $sAnAlias;
}
}
- throw new CoreException('Failed to create an alias', array('aliases' => $aAliases, 'new' => $sNewName));
+ throw new CoreException('Failed to create an alias', ['aliases' => $aAliases, 'new' => $sNewName]);
}
/**
@@ -4634,106 +4340,76 @@ abstract class MetaModel
*/
public static function CheckDefinitions($bExitOnError = true)
{
- if (count(self::GetClasses()) == 0)
- {
+ if (count(self::GetClasses()) == 0) {
throw new CoreException("MetaModel::InitClasses() has not been called, or no class has been declared ?!?!");
}
- $aErrors = array();
- $aSugFix = array();
- foreach(self::GetClasses() as $sClass)
- {
+ $aErrors = [];
+ $aSugFix = [];
+ foreach (self::GetClasses() as $sClass) {
$sTable = self::DBGetTable($sClass);
$sTableLowercase = strtolower($sTable);
- if ($sTableLowercase != $sTable)
- {
+ if ($sTableLowercase != $sTable) {
$aErrors[$sClass][] = "Table name '".$sTable."' has upper case characters. You might encounter issues when moving your installation between Linux and Windows.";
$aSugFix[$sClass][] = "Use '$sTableLowercase' instead. Step 1: If already installed, then rename manually in the DB: RENAME TABLE `$sTable` TO `{$sTableLowercase}_tempname`, `{$sTableLowercase}_tempname` TO `$sTableLowercase`; Step 2: Rename the table in the datamodel and compile the application. Note: the MySQL statement provided in step 1 has been designed to be compatible with Windows or Linux.";
}
$aNameSpec = self::GetNameSpec($sClass);
- foreach($aNameSpec[1] as $i => $sAttCode)
- {
- if (!self::IsValidAttCode($sClass, $sAttCode))
- {
+ foreach ($aNameSpec[1] as $i => $sAttCode) {
+ if (!self::IsValidAttCode($sClass, $sAttCode)) {
$aErrors[$sClass][] = "Unknown attribute code '".$sAttCode."' for the name definition";
$aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
}
}
- foreach(self::GetReconcKeys($sClass) as $sReconcKeyAttCode)
- {
- if (!empty($sReconcKeyAttCode) && !self::IsValidAttCode($sClass, $sReconcKeyAttCode))
- {
+ foreach (self::GetReconcKeys($sClass) as $sReconcKeyAttCode) {
+ if (!empty($sReconcKeyAttCode) && !self::IsValidAttCode($sClass, $sReconcKeyAttCode)) {
$aErrors[$sClass][] = "Unknown attribute code '".$sReconcKeyAttCode."' in the list of reconciliation keys";
$aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
}
}
$bHasWritableAttribute = false;
- foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
- {
+ foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) {
// It makes no sense to check the attributes again and again in the subclasses
- if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass)
- {
+ if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) {
continue;
}
- if ($oAttDef->IsExternalKey())
- {
- if (!self::IsValidClass($oAttDef->GetTargetClass()))
- {
+ if ($oAttDef->IsExternalKey()) {
+ if (!self::IsValidClass($oAttDef->GetTargetClass())) {
$aErrors[$sClass][] = "Unknown class '".$oAttDef->GetTargetClass()."' for the external key '$sAttCode'";
$aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetClasses())."}";
}
- }
- elseif ($oAttDef->IsExternalField())
- {
+ } elseif ($oAttDef->IsExternalField()) {
$sKeyAttCode = $oAttDef->GetKeyAttCode();
- if (!self::IsValidAttCode($sClass, $sKeyAttCode) || !self::IsValidKeyAttCode($sClass, $sKeyAttCode))
- {
+ if (!self::IsValidAttCode($sClass, $sKeyAttCode) || !self::IsValidKeyAttCode($sClass, $sKeyAttCode)) {
$aErrors[$sClass][] = "Unknown key attribute code '".$sKeyAttCode."' for the external field $sAttCode";
$aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sClass))."}";
- }
- else
- {
+ } else {
$oKeyAttDef = self::GetAttributeDef($sClass, $sKeyAttCode);
$sTargetClass = $oKeyAttDef->GetTargetClass();
$sExtAttCode = $oAttDef->GetExtAttCode();
- if (!self::IsValidAttCode($sTargetClass, $sExtAttCode))
- {
+ if (!self::IsValidAttCode($sTargetClass, $sExtAttCode)) {
$aErrors[$sClass][] = "Unknown key attribute code '".$sExtAttCode."' for the external field $sAttCode";
$aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sTargetClass))."}";
}
}
- }
- else
- {
- if ($oAttDef->IsLinkSet())
- {
+ } else {
+ if ($oAttDef->IsLinkSet()) {
// Do nothing...
- }
- else
- {
- if ($oAttDef instanceof AttributeStopWatch)
- {
+ } else {
+ if ($oAttDef instanceof AttributeStopWatch) {
$aThresholds = $oAttDef->ListThresholds();
- if (is_array($aThresholds))
- {
- foreach($aThresholds as $iPercent => $aDef)
- {
- if (array_key_exists('highlight', $aDef))
- {
- if (!array_key_exists('code', $aDef['highlight']))
- {
+ if (is_array($aThresholds)) {
+ foreach ($aThresholds as $iPercent => $aDef) {
+ if (array_key_exists('highlight', $aDef)) {
+ if (!array_key_exists('code', $aDef['highlight'])) {
$aErrors[$sClass][] = "The 'code' element is missing for the 'highlight' property of the $iPercent% threshold in the attribute: '$sAttCode'.";
$aSugFix[$sClass][] = "Add a 'code' entry specifying the value of the highlight code for this threshold.";
- }
- else
- {
+ } else {
$aScale = self::GetHighlightScale($sClass);
- if (!array_key_exists($aDef['highlight']['code'], $aScale))
- {
+ if (!array_key_exists($aDef['highlight']['code'], $aScale)) {
$aErrors[$sClass][] = "'{$aDef['highlight']['code']}' is not a valid value for the 'code' element of the $iPercent% threshold in the attribute: '$sAttCode'.";
$aSugFix[$sClass][] = "The possible highlight codes for this class are: ".implode(', ', array_keys($aScale)).".";
}
@@ -4741,25 +4417,18 @@ abstract class MetaModel
}
}
}
- }
- else // standard attributes
- {
+ } else { // standard attributes
// Check that the default values definition is a valid object!
$oValSetDef = $oAttDef->GetValuesDef();
- if (!is_null($oValSetDef) && !$oValSetDef instanceof ValueSetDefinition)
- {
+ if (!is_null($oValSetDef) && !$oValSetDef instanceof ValueSetDefinition) {
$aErrors[$sClass][] = "Allowed values for attribute $sAttCode is not of the relevant type";
$aSugFix[$sClass][] = "Please set it as an instance of a ValueSetDefinition object.";
- }
- else
- {
+ } else {
// Default value must be listed in the allowed values (if defined)
$aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
- if (!is_null($aAllowedValues))
- {
+ if (!is_null($aAllowedValues)) {
$sDefaultValue = $oAttDef->GetDefaultValue();
- if (is_string($sDefaultValue) && !array_key_exists($sDefaultValue, $aAllowedValues))
- {
+ if (is_string($sDefaultValue) && !array_key_exists($sDefaultValue, $aAllowedValues)) {
$aErrors[$sClass][] = "Default value '".$sDefaultValue."' for attribute $sAttCode is not an allowed value";
$aSugFix[$sClass][] = "Please pickup the default value out of {'".implode(", ", array_keys($aAllowedValues))."'}";
}
@@ -4769,13 +4438,10 @@ abstract class MetaModel
}
}
// Check dependencies
- if ($oAttDef->IsWritable())
- {
+ if ($oAttDef->IsWritable()) {
$bHasWritableAttribute = true;
- foreach($oAttDef->GetPrerequisiteAttributes() as $sDependOnAttCode)
- {
- if (!self::IsValidAttCode($sClass, $sDependOnAttCode))
- {
+ foreach ($oAttDef->GetPrerequisiteAttributes() as $sDependOnAttCode) {
+ if (!self::IsValidAttCode($sClass, $sDependOnAttCode)) {
$aErrors[$sClass][] = "Unknown attribute code '".$sDependOnAttCode."' in the list of prerequisite attributes";
$aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
}
@@ -4786,43 +4452,32 @@ abstract class MetaModel
// Lifecycle
//
$sStateAttCode = self::GetStateAttributeCode($sClass);
- if (strlen($sStateAttCode) > 0)
- {
+ if (strlen($sStateAttCode) > 0) {
// Lifecycle - check that the state attribute does exist as an attribute
- if (!self::IsValidAttCode($sClass, $sStateAttCode))
- {
+ if (!self::IsValidAttCode($sClass, $sStateAttCode)) {
$aErrors[$sClass][] = "Unknown attribute code '".$sStateAttCode."' for the state definition";
$aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
- }
- else
- {
+ } else {
// Lifecycle - check that there is a value set constraint on the state attribute
$aAllowedValuesRaw = self::GetAllowedValues_att($sClass, $sStateAttCode);
$aStates = array_keys(self::EnumStates($sClass));
- if (is_null($aAllowedValuesRaw))
- {
+ if (is_null($aAllowedValuesRaw)) {
$aErrors[$sClass][] = "Attribute '".$sStateAttCode."' will reflect the state of the object. It must be restricted to a set of values";
$aSugFix[$sClass][] = "Please define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')]";
- }
- else
- {
+ } else {
$aAllowedValues = array_keys($aAllowedValuesRaw);
// Lifecycle - check the the state attribute allowed values are defined states
- foreach($aAllowedValues as $sValue)
- {
- if (!in_array($sValue, $aStates))
- {
+ foreach ($aAllowedValues as $sValue) {
+ if (!in_array($sValue, $aStates)) {
$aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has an allowed value ($sValue) which is not a known state";
$aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
}
}
// Lifecycle - check that defined states are allowed values
- foreach($aStates as $sStateValue)
- {
- if (!in_array($sStateValue, $aAllowedValues))
- {
+ foreach ($aStates as $sStateValue) {
+ if (!in_array($sStateValue, $aAllowedValues)) {
$aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has a state ($sStateValue) which is not an allowed value";
$aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
}
@@ -4830,43 +4485,30 @@ abstract class MetaModel
}
// Lifecycle - check that the action handlers are defined
- foreach(self::EnumStates($sClass) as $sStateCode => $aStateDef)
- {
- foreach(self::EnumTransitions($sClass, $sStateCode) as $sStimulusCode => $aTransitionDef)
- {
- foreach($aTransitionDef['actions'] as $actionHandler)
- {
- if (is_string($actionHandler))
- {
- if (!method_exists($sClass, $actionHandler))
- {
+ foreach (self::EnumStates($sClass) as $sStateCode => $aStateDef) {
+ foreach (self::EnumTransitions($sClass, $sStateCode) as $sStimulusCode => $aTransitionDef) {
+ foreach ($aTransitionDef['actions'] as $actionHandler) {
+ if (is_string($actionHandler)) {
+ if (!method_exists($sClass, $actionHandler)) {
$aErrors[$sClass][] = "Unknown function '$actionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'";
$aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $actionHandler(\$sStimulusCode){return true;}]";
}
- }
- else // if(is_array($actionHandler))
- {
+ } else { // if(is_array($actionHandler))
$sActionHandler = $actionHandler['verb'];
- if (!method_exists($sClass, $sActionHandler))
- {
+ if (!method_exists($sClass, $sActionHandler)) {
$aErrors[$sClass][] = "Unknown function '$sActionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'";
$aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $sActionHandler(...){return true;}]";
}
}
}
}
- if (array_key_exists('highlight', $aStateDef))
- {
- if (!array_key_exists('code', $aStateDef['highlight']))
- {
+ if (array_key_exists('highlight', $aStateDef)) {
+ if (!array_key_exists('code', $aStateDef['highlight'])) {
$aErrors[$sClass][] = "The 'code' element is missing for the 'highlight' property of state: '$sStateCode'.";
$aSugFix[$sClass][] = "Add a 'code' entry specifying the value of the highlight code for this state.";
- }
- else
- {
+ } else {
$aScale = self::GetHighlightScale($sClass);
- if (!array_key_exists($aStateDef['highlight']['code'], $aScale))
- {
+ if (!array_key_exists($aStateDef['highlight']['code'], $aScale)) {
$aErrors[$sClass][] = "'{$aStateDef['highlight']['code']}' is not a valid value for the 'code' element in the 'highlight' property of state: '$sStateCode'.";
$aSugFix[$sClass][] = "The possible highlight codes for this class are: ".implode(', ', array_keys($aScale)).".";
}
@@ -4876,24 +4518,18 @@ abstract class MetaModel
}
}
- if ($bHasWritableAttribute)
- {
- if (!self::HasTable($sClass))
- {
+ if ($bHasWritableAttribute) {
+ if (!self::HasTable($sClass)) {
$aErrors[$sClass][] = "No table has been defined for this class";
$aSugFix[$sClass][] = "Either define a table name or move the attributes elsewhere";
}
}
-
// ZList
//
- foreach(self::EnumZLists() as $sListCode)
- {
- foreach(self::FlattenZList(self::GetZListItems($sClass, $sListCode)) as $sMyAttCode)
- {
- if (!self::IsValidAttCode($sClass, $sMyAttCode))
- {
+ foreach (self::EnumZLists() as $sListCode) {
+ foreach (self::FlattenZList(self::GetZListItems($sClass, $sListCode)) as $sMyAttCode) {
+ if (!self::IsValidAttCode($sClass, $sMyAttCode)) {
$aErrors[$sClass][] = "Unknown attribute code '".$sMyAttCode."' from ZList '$sListCode'";
$aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
}
@@ -4902,30 +4538,23 @@ abstract class MetaModel
// Check SQL columns uniqueness
//
- if (self::HasTable($sClass))
- {
- $aTableColumns = array(); // array of column => attcode (the column is used by this attribute)
+ if (self::HasTable($sClass)) {
+ $aTableColumns = []; // array of column => attcode (the column is used by this attribute)
$aTableColumns[self::DBGetKey($sClass)] = 'id';
// Check that SQL columns are declared only once
//
- foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
- {
+ foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) {
// Skip this attribute if not originally defined in this class
- if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass)
- {
+ if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) {
continue;
}
- foreach($oAttDef->GetSQLColumns() as $sField => $sDBFieldType)
- {
- if (array_key_exists($sField, $aTableColumns))
- {
+ foreach ($oAttDef->GetSQLColumns() as $sField => $sDBFieldType) {
+ if (array_key_exists($sField, $aTableColumns)) {
$aErrors[$sClass][] = "Column '$sField' declared for attribute $sAttCode, but already used for attribute ".$aTableColumns[$sField];
$aSugFix[$sClass][] = "Please find another name for the SQL column";
- }
- else
- {
+ } else {
$aTableColumns[$sField] = $sAttCode;
}
}
@@ -4933,30 +4562,25 @@ abstract class MetaModel
}
} // foreach class
- if (count($aErrors) > 0)
- {
+ if (count($aErrors) > 0) {
echo "";
echo "
Business model inconsistencies have been found \n";
// #@# later -> this is the responsibility of the caller to format the output
- foreach($aErrors as $sClass => $aMessages)
- {
+ foreach ($aErrors as $sClass => $aMessages) {
echo "
Wrong declaration for class $sClass
\n";
echo "
\n";
$i = 0;
- foreach($aMessages as $sMsg)
- {
+ foreach ($aMessages as $sMsg) {
echo "$sMsg ({$aSugFix[$sClass][$i]}) \n";
$i++;
}
echo " \n";
}
- if ($bExitOnError)
- {
+ if ($bExitOnError) {
echo "
Aborting...
\n";
}
echo "
\n";
- if ($bExitOnError)
- {
+ if ($bExitOnError) {
exit;
}
}
@@ -4974,7 +4598,7 @@ abstract class MetaModel
}
// By design, some queries might be blank, we have to ignore them
- $aCleanFixes = array();
+ $aCleanFixes = [];
foreach ($aSQLFixes as $sSQLFix) {
if (!empty($sSQLFix)) {
$aCleanFixes[] = $sSQLFix;
@@ -4999,40 +4623,29 @@ abstract class MetaModel
*/
public static function DBExists($bMustBeComplete = true)
{
- if (!CMDBSource::IsDB(self::$m_sDBName))
- {
+ if (!CMDBSource::IsDB(self::$m_sDBName)) {
return false;
}
CMDBSource::SelectDB(self::$m_sDBName);
- $aFound = array();
- $aMissing = array();
- foreach(self::DBEnumTables() as $sTable => $aClasses)
- {
- if (CMDBSource::IsTable($sTable))
- {
+ $aFound = [];
+ $aMissing = [];
+ foreach (self::DBEnumTables() as $sTable => $aClasses) {
+ if (CMDBSource::IsTable($sTable)) {
$aFound[] = $sTable;
- }
- else
- {
+ } else {
$aMissing[] = $sTable;
}
}
- if (count($aFound) == 0)
- {
+ if (count($aFound) == 0) {
// no expected table has been found
return false;
- }
- else
- {
- if (count($aMissing) == 0)
- {
+ } else {
+ if (count($aMissing) == 0) {
// the database is complete (still, could be some fields missing!)
return true;
- }
- else
- {
+ } else {
// not all the tables, could be an older version
return !$bMustBeComplete;
}
@@ -5047,30 +4660,23 @@ abstract class MetaModel
{
$bDropEntireDB = true;
- if (!empty(self::$m_sTablePrefix))
- {
- foreach(self::DBEnumTables() as $sTable)
- {
+ if (!empty(self::$m_sTablePrefix)) {
+ foreach (self::DBEnumTables() as $sTable) {
// perform a case-insensitive test because on Windows the table names become lowercase :-(
- if (strtolower(substr($sTable, 0, strlen(self::$m_sTablePrefix))) == strtolower(self::$m_sTablePrefix))
- {
+ if (strtolower(substr($sTable, 0, strlen(self::$m_sTablePrefix))) == strtolower(self::$m_sTablePrefix)) {
CMDBSource::DropTable($sTable);
- }
- else
- {
+ } else {
// There is at least one table which is out of the scope of the current application
$bDropEntireDB = false;
}
}
}
- if ($bDropEntireDB)
- {
+ if ($bDropEntireDB) {
CMDBSource::DropDB(self::$m_sDBName);
}
}
-
/**
* @param callable $aCallback
*
@@ -5083,8 +4689,7 @@ abstract class MetaModel
{
// Note: we have to check if the DB does exist, because we may share the DB
// with other applications (in which case the DB does exist, not the tables with the given prefix)
- if (!CMDBSource::IsDB(self::$m_sDBName))
- {
+ if (!CMDBSource::IsDB(self::$m_sDBName)) {
CMDBSource::CreateDB(self::$m_sDBName);
}
self::DBCreateTables($aCallback);
@@ -5101,13 +4706,11 @@ abstract class MetaModel
[$aErrors, $aSugFix, $aCondensedQueries] = self::DBCheckFormat();
//$sSQL = implode('; ', $aCondensedQueries); Does not work - multiple queries not allowed
- foreach($aCondensedQueries as $sQuery)
- {
+ foreach ($aCondensedQueries as $sQuery) {
$fStart = microtime(true);
CMDBSource::CreateTable($sQuery);
$fDuration = microtime(true) - $fStart;
- if ($aCallback != null)
- {
+ if ($aCallback != null) {
call_user_func($aCallback, $sQuery, $fDuration);
}
}
@@ -5122,14 +4725,10 @@ abstract class MetaModel
{
[$aErrors, $aSugFix] = self::DBCleanLegacyViews();
- foreach($aSugFix as $sClass => $aTarget)
- {
- foreach($aTarget as $aQueries)
- {
- foreach($aQueries as $sQuery)
- {
- if (!empty($sQuery))
- {
+ foreach ($aSugFix as $sClass => $aTarget) {
+ foreach ($aTarget as $aQueries) {
+ foreach ($aQueries as $sQuery) {
+ if (!empty($sQuery)) {
// forces a refresh of cached information
CMDBSource::CreateTable($sQuery);
}
@@ -5145,9 +4744,8 @@ abstract class MetaModel
*/
public static function DBDump()
{
- $aDataDump = array();
- foreach(self::DBEnumTables() as $sTable => $aClasses)
- {
+ $aDataDump = [];
+ foreach (self::DBEnumTables() as $sTable => $aClasses) {
$aRows = CMDBSource::DumpTable($sTable);
$aDataDump[$sTable] = $aRows;
}
@@ -5163,16 +4761,12 @@ abstract class MetaModel
{
// Improvement: check the mySQL variable -> Read-only
- if (utils::IsArchiveMode())
- {
+ if (utils::IsArchiveMode()) {
return true;
}
- if (UserRights::IsAdministrator())
- {
+ if (UserRights::IsAdministrator()) {
return (!self::DBHasAccess(ACCESS_ADMIN_WRITE));
- }
- else
- {
+ } else {
return (!self::DBHasAccess(ACCESS_USER_WRITE));
}
}
@@ -5185,8 +4779,7 @@ abstract class MetaModel
public static function DBHasAccess($iRequested = ACCESS_FULL)
{
$iMode = self::$m_oConfig->Get('access_mode');
- if (($iMode & $iRequested) == 0)
- {
+ if (($iMode & $iRequested) == 0) {
return false;
}
@@ -5205,12 +4798,10 @@ abstract class MetaModel
protected static function MakeDictEntry($sKey, $sValueFromOldSystem, $sDefaultValue, &$bNotInDico)
{
$sValue = Dict::S($sKey, 'x-no-nothing');
- if ($sValue == 'x-no-nothing')
- {
+ if ($sValue == 'x-no-nothing') {
$bNotInDico = true;
$sValue = $sValueFromOldSystem;
- if (strlen($sValue) == 0)
- {
+ if (strlen($sValue) == 0) {
$sValue = $sDefaultValue;
}
}
@@ -5244,7 +4835,7 @@ abstract class MetaModel
// Note: I did not use EnumCategories(), because a given class maybe found in several categories
// Need to invent the "module", to characterize the origins of a class
if (strlen($sModules) == 0) {
- $aModules = array('bizmodel', 'core/cmdb', 'gui', 'application', 'addon/userrights');
+ $aModules = ['bizmodel', 'core/cmdb', 'gui', 'application', 'addon/userrights'];
} else {
$aModules = explode(', ', $sModules);
}
@@ -5273,54 +4864,39 @@ abstract class MetaModel
$sClassRes .= "Dict::Add('EN US', 'English', 'English', array(\n";
$sClassRes .= self::MakeDictEntry("Class:$sClass", self::GetName_Obsolete($sClass), $sClass, $bNotInDico);
$sClassRes .= self::MakeDictEntry("Class:$sClass+", self::GetClassDescription_Obsolete($sClass), '', $bNotInDico);
- foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
- {
+ foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) {
// Skip this attribute if not originally defined in this class
- if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass)
- {
+ if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) {
continue;
}
$sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode", $oAttDef->GetLabel_Obsolete(), $sAttCode, $bNotInDico);
$sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode+", $oAttDef->GetDescription_Obsolete(), '', $bNotInDico);
- if ($oAttDef instanceof AttributeEnum)
- {
- if (self::GetStateAttributeCode($sClass) == $sAttCode)
- {
- foreach(self::EnumStates($sClass) as $sStateCode => $aStateData)
- {
- if (array_key_exists('label', $aStateData))
- {
+ if ($oAttDef instanceof AttributeEnum) {
+ if (self::GetStateAttributeCode($sClass) == $sAttCode) {
+ foreach (self::EnumStates($sClass) as $sStateCode => $aStateData) {
+ if (array_key_exists('label', $aStateData)) {
$sValue = $aStateData['label'];
- }
- else
- {
+ } else {
$sValue = MetaModel::GetStateLabel($sClass, $sStateCode);
}
- if (array_key_exists('description', $aStateData))
- {
+ if (array_key_exists('description', $aStateData)) {
$sValuePlus = $aStateData['description'];
- }
- else
- {
+ } else {
$sValuePlus = MetaModel::GetStateDescription($sClass, $sStateCode);
}
$sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode", $sValue, '', $bNotInDico);
$sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode+", $sValuePlus, '', $bNotInDico);
}
- }
- else
- {
- foreach($oAttDef->GetAllowedValues() as $sKey => $value)
- {
+ } else {
+ foreach ($oAttDef->GetAllowedValues() as $sKey => $value) {
$sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey", $value, '', $bNotInDico);
$sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey+", $value, '', $bNotInDico);
}
}
}
}
- foreach(self::EnumStimuli($sClass) as $sStimulusCode => $oStimulus)
- {
+ foreach (self::EnumStimuli($sClass) as $sStimulusCode => $oStimulus) {
$sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode", $oStimulus->GetLabel_Obsolete(), '', $bNotInDico);
$sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode+", $oStimulus->GetDescription_Obsolete(), '', $bNotInDico);
}
@@ -5328,8 +4904,7 @@ abstract class MetaModel
$sClassRes .= "));\n";
$sClassRes .= "\n";
- if ($bNotInDico || ($sOutputFilter != 'NotInDictionary'))
- {
+ if ($bNotInDico || ($sOutputFilter != 'NotInDictionary')) {
$sRes .= $sClassRes;
}
}
@@ -5338,7 +4913,6 @@ abstract class MetaModel
return $sRes;
}
-
/**
* @return array
* @throws \CoreException
@@ -5346,29 +4920,27 @@ abstract class MetaModel
*/
public static function DBCheckFormat()
{
- $aErrors = array();
- $aSugFix = array();
+ $aErrors = [];
+ $aSugFix = [];
$sAlterDBMetaData = CMDBSource::DBCheckCharsetAndCollation();
// A new way of representing things to be done - quicker to execute !
- $aCreateTable = array(); // array of =>
- $aCreateTableItems = array(); // array of => array of
- $aAlterTableMetaData = array();
- $aAlterTableItems = array(); // array of =>
- $aPostTableAlteration = array(); // array of => post alteration queries
+ $aCreateTable = []; // array of =>
+ $aCreateTableItems = []; // array of => array of
+ $aAlterTableMetaData = [];
+ $aAlterTableItems = []; // array of =>
+ $aPostTableAlteration = []; // array of => post alteration queries
- foreach(self::GetClasses() as $sClass)
- {
- if (!self::HasTable($sClass))
- {
+ foreach (self::GetClasses() as $sClass) {
+ if (!self::HasTable($sClass)) {
continue;
}
// Check that the table exists
//
$sTable = self::DBGetTable($sClass);
- $aSugFix[$sClass]['*First'] = array();
+ $aSugFix[$sClass]['*First'] = [];
$aTableInfo = CMDBSource::GetTableInfo($sTable);
@@ -5379,8 +4951,7 @@ abstract class MetaModel
$sAutoIncrement = (self::IsAutoIncrementKey($sClass) ? "AUTO_INCREMENT" : "");
$sKeyFieldDefinition = "`$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY";
$aTableInfo['Indexes']['PRIMARY']['used'] = true;
- if (!CMDBSource::IsTable($sTable))
- {
+ if (!CMDBSource::IsTable($sTable)) {
$bTableToCreate = true;
$aErrors[$sClass]['*'][] = "table '$sTable' could not be found in the DB";
$aSugFix[$sClass]['*'][] = "CREATE TABLE `$sTable` ($sKeyFieldDefinition) ENGINE = ".MYSQL_ENGINE." CHARACTER SET $sDbCharset COLLATE $sDbCollation";
@@ -5389,44 +4960,34 @@ abstract class MetaModel
}
// Check that the key field exists
//
- elseif (!CMDBSource::IsField($sTable, $sKeyField))
- {
+ elseif (!CMDBSource::IsField($sTable, $sKeyField)) {
$aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) could not be found";
$aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` ADD $sKeyFieldDefinition";
- if (!$bTableToCreate)
- {
+ if (!$bTableToCreate) {
$aAlterTableItems[$sTable]['field'][$sKeyField] = "ADD $sKeyFieldDefinition";
}
- }
- else
- {
+ } else {
// Check the key field properties
//
- if (!CMDBSource::IsKey($sTable, $sKeyField))
- {
+ if (!CMDBSource::IsKey($sTable, $sKeyField)) {
$aErrors[$sClass]['id'][] = "key '$sKeyField' is not a key for table '$sTable'";
$aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable`, DROP PRIMARY KEY, ADD PRIMARY key(`$sKeyField`)";
- if (!$bTableToCreate)
- {
+ if (!$bTableToCreate) {
$aAlterTableItems[$sTable]['field'][$sKeyField] = "CHANGE `$sKeyField` $sKeyFieldDefinition";
}
}
- if (self::IsAutoIncrementKey($sClass) && !CMDBSource::IsAutoIncrement($sTable, $sKeyField))
- {
+ if (self::IsAutoIncrementKey($sClass) && !CMDBSource::IsAutoIncrement($sTable, $sKeyField)) {
$aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) is not automatically incremented";
$aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` CHANGE `$sKeyField` $sKeyFieldDefinition";
- if (!$bTableToCreate)
- {
+ if (!$bTableToCreate) {
$aAlterTableItems[$sTable]['field'][$sKeyField] = "CHANGE `$sKeyField` $sKeyFieldDefinition";
}
}
}
- if (!$bTableToCreate)
- {
+ if (!$bTableToCreate) {
$sAlterTableMetaDataQuery = CMDBSource::DBCheckTableCharsetAndCollation($sTable);
- if (!empty($sAlterTableMetaDataQuery))
- {
+ if (!empty($sAlterTableMetaDataQuery)) {
$aAlterTableMetaData[$sTable] = $sAlterTableMetaDataQuery;
}
}
@@ -5435,135 +4996,101 @@ abstract class MetaModel
//
$aTableInfo['Fields'][$sKeyField]['used'] = true;
$aFriendlynameAttcodes = self::GetFriendlyNameAttributeCodeList($sClass);
- foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
- {
- if (!$oAttDef->CopyOnAllTables())
- {
+ foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) {
+ if (!$oAttDef->CopyOnAllTables()) {
// Skip this attribute if not originally defined in this class
- if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass)
- {
+ if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) {
continue;
}
}
- foreach($oAttDef->GetSQLColumns(true) as $sField => $sDBFieldSpec)
- {
+ foreach ($oAttDef->GetSQLColumns(true) as $sField => $sDBFieldSpec) {
// Keep track of columns used by iTop
$aTableInfo['Fields'][$sField]['used'] = true;
$bIndexNeeded = $oAttDef->RequiresIndex();
$bFullTextIndexNeeded = false;
- if (!$bIndexNeeded)
- {
+ if (!$bIndexNeeded) {
// Add an index on the columns of the friendlyname
- if (in_array($sField, $aFriendlynameAttcodes))
- {
+ if (in_array($sField, $aFriendlynameAttcodes)) {
$bIndexNeeded = true;
}
- }
- else
- {
- if ($oAttDef->RequiresFullTextIndex())
- {
+ } else {
+ if ($oAttDef->RequiresFullTextIndex()) {
$bFullTextIndexNeeded = true;
}
}
$sFieldDefinition = "`$sField` $sDBFieldSpec";
- if (!CMDBSource::IsField($sTable, $sField))
- {
+ if (!CMDBSource::IsField($sTable, $sField)) {
$aErrors[$sClass][$sAttCode][] = "field '$sField' could not be found in table '$sTable'";
$aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD $sFieldDefinition";
- if ($bTableToCreate)
- {
+ if ($bTableToCreate) {
$aCreateTableItems[$sTable][$sField] = $sFieldDefinition;
- }
- else
- {
+ } else {
$aAlterTableItems[$sTable]['field'][$sField] = "ADD $sFieldDefinition";
$aAdditionalRequests = self::GetAdditionalRequestAfterAlter($sClass, $sTable, $sField);
- if (!empty($aAdditionalRequests))
- {
- foreach ($aAdditionalRequests as $sAdditionalRequest)
- {
+ if (!empty($aAdditionalRequests)) {
+ foreach ($aAdditionalRequests as $sAdditionalRequest) {
$aPostTableAlteration[$sTable][] = $sAdditionalRequest;
}
}
}
- if ($bIndexNeeded)
- {
+ if ($bIndexNeeded) {
$aTableInfo['Indexes'][$sField]['used'] = true;
$sIndexName = $sField;
$sColumns = '`'.$sField.'`';
- if ($bFullTextIndexNeeded)
- {
+ if ($bFullTextIndexNeeded) {
$sIndexType = 'FULLTEXT INDEX';
- }
- else
- {
+ } else {
$sIndexType = 'INDEX';
- $aColumns = array($sField);
+ $aColumns = [$sField];
$aLength = self::DBGetIndexesLength($sClass, $aColumns, $aTableInfo);
- if (!is_null($aLength[0]))
- {
+ if (!is_null($aLength[0])) {
$sColumns .= ' ('.$aLength[0].')';
}
}
$sSugFix = "ALTER TABLE `$sTable` ADD $sIndexType `$sIndexName` ($sColumns)";
$aSugFix[$sClass][$sAttCode][] = $sSugFix;
- if ($bFullTextIndexNeeded)
- {
+ if ($bFullTextIndexNeeded) {
// MySQL does not support multi fulltext index creation in a single query (mysql_errno = 1795)
$aPostTableAlteration[$sTable][] = $sSugFix;
- }
- elseif ($bTableToCreate)
- {
+ } elseif ($bTableToCreate) {
$aCreateTableItems[$sTable][] = "$sIndexType `$sIndexName` ($sColumns)";
- }
- else
- {
+ } else {
$aAlterTableItems[$sTable]['index'][] = "ADD $sIndexType `$sIndexName` ($sColumns)";
}
}
- }
- else
- {
+ } else {
// Create indexes (external keys only... so far)
// (drop before change, add after change)
$sSugFixAfterChange = '';
$sAlterTableItemsAfterChange = '';
- if ($bIndexNeeded)
- {
+ if ($bIndexNeeded) {
$aTableInfo['Indexes'][$sField]['used'] = true;
- if ($bFullTextIndexNeeded)
- {
+ if ($bFullTextIndexNeeded) {
$sIndexType = 'FULLTEXT INDEX';
$aColumns = null;
$aLength = null;
- }
- else
- {
+ } else {
$sIndexType = 'INDEX';
- $aColumns = array($sField);
+ $aColumns = [$sField];
$aLength = self::DBGetIndexesLength($sClass, $aColumns, $aTableInfo);
}
- if (!CMDBSource::HasIndex($sTable, $sField, $aColumns, $aLength))
- {
+ if (!CMDBSource::HasIndex($sTable, $sField, $aColumns, $aLength)) {
$sIndexName = $sField;
$sColumns = '`'.$sField.'`';
- if (isset($aLength[0]))
- {
+ if (isset($aLength[0])) {
$sColumns .= ' ('.$aLength[0].')';
}
$aErrors[$sClass][$sAttCode][] = "Foreign key '$sField' in table '$sTable' should have an index";
- if (CMDBSource::HasIndex($sTable, $sField))
- {
+ if (CMDBSource::HasIndex($sTable, $sField)) {
$aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` DROP INDEX `$sIndexName`";
$aAlterTableItems[$sTable]['index'][] = "DROP INDEX `$sIndexName`";
}
@@ -5575,8 +5102,7 @@ abstract class MetaModel
// The field already exists, does it have the relevant properties?
//
$sActualFieldSpec = CMDBSource::GetFieldSpec($sTable, $sField);
- if (!CMDBSource::IsSameFieldTypes($sDBFieldSpec, $sActualFieldSpec))
- {
+ if (!CMDBSource::IsSameFieldTypes($sDBFieldSpec, $sActualFieldSpec)) {
$aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' has a wrong type: found $sActualFieldSpec while expecting $sDBFieldSpec";
$aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` $sFieldDefinition";
$aAlterTableItems[$sTable]['field'][$sField] = "CHANGE `$sField` $sFieldDefinition";
@@ -5584,16 +5110,12 @@ abstract class MetaModel
// Create indexes (external keys only... so far)
//
- if (!empty($sSugFixAfterChange))
- {
+ if (!empty($sSugFixAfterChange)) {
$aSugFix[$sClass][$sAttCode][] = $sSugFixAfterChange;
- if ($bFullTextIndexNeeded)
- {
+ if ($bFullTextIndexNeeded) {
// MySQL does not support multi fulltext index creation in a single query (mysql_errno = 1795)
$aPostTableAlteration[$sTable][] = $sSugFixAfterChange;
- }
- else
- {
+ } else {
$aAlterTableItems[$sTable]['index'][] = $sAlterTableItemsAfterChange;
}
}
@@ -5602,60 +5124,45 @@ abstract class MetaModel
}
// Check indexes
- foreach(self::DBGetIndexes($sClass) as $aColumns)
- {
+ foreach (self::DBGetIndexes($sClass) as $aColumns) {
$sIndexId = implode('_', $aColumns);
- if (isset($aTableInfo['Indexes'][$sIndexId]['used']) && $aTableInfo['Indexes'][$sIndexId]['used'])
- {
+ if (isset($aTableInfo['Indexes'][$sIndexId]['used']) && $aTableInfo['Indexes'][$sIndexId]['used']) {
continue;
}
$aLength = self::DBGetIndexesLength($sClass, $aColumns, $aTableInfo);
$aTableInfo['Indexes'][$sIndexId]['used'] = true;
- if (!CMDBSource::HasIndex($sTable, $sIndexId, $aColumns, $aLength))
- {
+ if (!CMDBSource::HasIndex($sTable, $sIndexId, $aColumns, $aLength)) {
$sColumns = '';
- for ($i = 0; $i < count($aColumns); $i++)
- {
- if (!empty($sColumns))
- {
+ for ($i = 0; $i < count($aColumns); $i++) {
+ if (!empty($sColumns)) {
$sColumns .= ', ';
}
$sColumns .= '`'.$aColumns[$i].'`';
- if (!is_null($aLength[$i]))
- {
+ if (!is_null($aLength[$i])) {
$sColumns .= ' ('.$aLength[$i].')';
}
}
- if (CMDBSource::HasIndex($sTable, $sIndexId))
- {
+ if (CMDBSource::HasIndex($sTable, $sIndexId)) {
$aErrors[$sClass]['*'][] = "Wrong index '$sIndexId' ($sColumns) in table '$sTable'";
$aSugFix[$sClass]['*First'][] = "ALTER TABLE `$sTable` DROP INDEX `$sIndexId`";
$aSugFix[$sClass]['*'][] = "ALTER TABLE `$sTable` ADD INDEX `$sIndexId` ($sColumns)";
- }
- else
- {
+ } else {
$aErrors[$sClass]['*'][] = "Missing index '$sIndexId' ($sColumns) in table '$sTable'";
$aSugFix[$sClass]['*'][] = "ALTER TABLE `$sTable` ADD INDEX `$sIndexId` ($sColumns)";
}
- if ($bTableToCreate)
- {
+ if ($bTableToCreate) {
$aCreateTableItems[$sTable][] = "INDEX `$sIndexId` ($sColumns)";
- }
- else
- {
- if (CMDBSource::HasIndex($sTable, $sIndexId))
- {
+ } else {
+ if (CMDBSource::HasIndex($sTable, $sIndexId)) {
// Add the drop before CHARSET alteration
- if (!isset($aAlterTableItems[$sTable]))
- {
- $aAlterTableItems[$sTable] = array();
+ if (!isset($aAlterTableItems[$sTable])) {
+ $aAlterTableItems[$sTable] = [];
}
- if (isset($aAlterTableItems[$sTable]['index']))
- {
+ if (isset($aAlterTableItems[$sTable]['index'])) {
array_unshift($aAlterTableItems[$sTable]['index'], "DROP INDEX `$sIndexId`");
}
}
@@ -5666,13 +5173,10 @@ abstract class MetaModel
// Find out unused columns
//
- foreach($aTableInfo['Fields'] as $sField => $aFieldData)
- {
- if (!isset($aFieldData['used']) || !$aFieldData['used'])
- {
+ foreach ($aTableInfo['Fields'] as $sField => $aFieldData) {
+ if (!isset($aFieldData['used']) || !$aFieldData['used']) {
$aErrors[$sClass]['*'][] = "Column '$sField' in table '$sTable' is not used";
- if (!CMDBSource::IsNullAllowed($sTable, $sField))
- {
+ if (!CMDBSource::IsNullAllowed($sTable, $sField)) {
// Allow null values so that new record can be inserted
// without specifying the value of this unknown column
$sFieldDefinition = "`$sField` ".CMDBSource::GetFieldType($sTable, $sField).' NULL';
@@ -5685,86 +5189,71 @@ abstract class MetaModel
// Find out unused indexes
//
- foreach($aTableInfo['Indexes'] as $sIndexId => $aIndexData)
- {
- if (!isset($aIndexData['used']) || !$aIndexData['used'])
- {
+ foreach ($aTableInfo['Indexes'] as $sIndexId => $aIndexData) {
+ if (!isset($aIndexData['used']) || !$aIndexData['used']) {
$aErrors[$sClass]['*'][] = "Index '$sIndexId' in table '$sTable' is not used and will be removed";
$aSugFix[$sClass]['*First'][] = "ALTER TABLE `$sTable` DROP INDEX `$sIndexId`";
// Add the drop before CHARSET alteration
- if (!isset($aAlterTableItems[$sTable]))
- {
- $aAlterTableItems[$sTable] = array();
+ if (!isset($aAlterTableItems[$sTable])) {
+ $aAlterTableItems[$sTable] = [];
}
- if (isset($aAlterTableItems[$sTable]['index']))
- {
+ if (isset($aAlterTableItems[$sTable]['index'])) {
array_unshift($aAlterTableItems[$sTable]['index'], "DROP INDEX `$sIndexId`");
}
}
}
- if (empty($aSugFix[$sClass]['*First'])) unset($aSugFix[$sClass]['*First']);
+ if (empty($aSugFix[$sClass]['*First'])) {
+ unset($aSugFix[$sClass]['*First']);
+ }
}
- $aCondensedQueries = array();
- if (!empty($sAlterDBMetaData))
- {
+ $aCondensedQueries = [];
+ if (!empty($sAlterDBMetaData)) {
$aCondensedQueries[] = $sAlterDBMetaData;
}
- foreach($aCreateTable as $sTable => $sTableOptions)
- {
+ foreach ($aCreateTable as $sTable => $sTableOptions) {
$sTableItems = implode(', ', $aCreateTableItems[$sTable]);
$aCondensedQueries[] = "CREATE TABLE `$sTable` ($sTableItems) $sTableOptions";
// Add request right after the CREATE TABLE
- if (isset($aPostTableAlteration[$sTable]))
- {
- foreach ($aPostTableAlteration[$sTable] as $sQuery)
- {
+ if (isset($aPostTableAlteration[$sTable])) {
+ foreach ($aPostTableAlteration[$sTable] as $sQuery) {
$aCondensedQueries[] = $sQuery;
}
unset($aPostTableAlteration[$sTable]);
}
}
- foreach ($aAlterTableMetaData as $sTableAlterQuery)
- {
+ foreach ($aAlterTableMetaData as $sTableAlterQuery) {
$aCondensedQueries[] = $sTableAlterQuery;
}
- foreach ($aAlterTableItems as $sTable => $aChangeList)
- {
- if (isset($aAlterTableItems[$sTable]['field']))
- {
+ foreach ($aAlterTableItems as $sTable => $aChangeList) {
+ if (isset($aAlterTableItems[$sTable]['field'])) {
$sChangeList = implode(', ', $aChangeList['field']);
$aCondensedQueries[] = "ALTER TABLE `$sTable` $sChangeList";
}
- if (isset($aAlterTableItems[$sTable]['index']))
- {
+ if (isset($aAlterTableItems[$sTable]['index'])) {
$sChangeList = implode(', ', $aChangeList['index']);
$aCondensedQueries[] = "ALTER TABLE `$sTable` $sChangeList";
}
// Add request right after the ALTER TABLE
- if (isset($aPostTableAlteration[$sTable]))
- {
- foreach ($aPostTableAlteration[$sTable] as $sQuery)
- {
+ if (isset($aPostTableAlteration[$sTable])) {
+ foreach ($aPostTableAlteration[$sTable] as $sQuery) {
$aCondensedQueries[] = $sQuery;
}
unset($aPostTableAlteration[$sTable]);
- }
+ }
}
// Add alterations not yet managed
- foreach ($aPostTableAlteration as $aQueries)
- {
- foreach ($aQueries as $sQuery)
- {
+ foreach ($aPostTableAlteration as $aQueries) {
+ foreach ($aQueries as $sQuery) {
$aCondensedQueries[] = $sQuery;
}
}
- return array($aErrors, $aSugFix, $aCondensedQueries);
+ return [$aErrors, $aSugFix, $aCondensedQueries];
}
-
/**
* @internal
* @deprecated will be remove when 2.7 will not be supported anymore
@@ -5781,11 +5270,9 @@ abstract class MetaModel
// Reporting views (must be created after any other table)
//
- foreach(self::GetClasses() as $sClass)
- {
+ foreach (self::GetClasses() as $sClass) {
$sView = self::DBGetView($sClass);
- if (CMDBSource::IsTable($sView))
- {
+ if (CMDBSource::IsTable($sView)) {
// Remove deprecated views
$aErrors[$sClass]['*'][] = "Remove view '$sView' (deprecated, consider installing combodo-views if needed)";
$aSugFix[$sClass]['*'][] = "DROP VIEW `$sView`";
@@ -5812,31 +5299,24 @@ abstract class MetaModel
$sTable = self::DBGetTable($sClass);
$sKeyField = self::DBGetKey($sClass);
- if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
- {
+ if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0) {
$sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
}
$aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
- if (count($aWrongRecords) == 0)
- {
+ if (count($aWrongRecords) == 0) {
return;
}
- if (!array_key_exists($sRootClass, $aErrorsAndFixes))
- {
- $aErrorsAndFixes[$sRootClass] = array();
+ if (!array_key_exists($sRootClass, $aErrorsAndFixes)) {
+ $aErrorsAndFixes[$sRootClass] = [];
}
- if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass]))
- {
- $aErrorsAndFixes[$sRootClass][$sTable] = array();
+ if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) {
+ $aErrorsAndFixes[$sRootClass][$sTable] = [];
}
- foreach($aWrongRecords as $iRecordId)
- {
- if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
- {
- switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
- {
+ foreach ($aWrongRecords as $iRecordId) {
+ if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable])) {
+ switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action']) {
case 'Delete':
// Already planned for a deletion
// Let's concatenate the errors description together
@@ -5847,48 +5327,46 @@ abstract class MetaModel
// Let's plan a deletion
break;
}
- }
- else
- {
+ } else {
$aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
}
- if (!$bProcessingFriends)
- {
- if (!array_key_exists($sTable, $aPlannedDel) || !in_array($iRecordId, $aPlannedDel[$sTable]))
- {
+ if (!$bProcessingFriends) {
+ if (!array_key_exists($sTable, $aPlannedDel) || !in_array($iRecordId, $aPlannedDel[$sTable])) {
// Something new to be deleted...
$iNewDelCount++;
}
}
$aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Delete';
- $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array();
+ $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = [];
$aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
$aPlannedDel[$sTable][] = $iRecordId;
}
// Now make sure that we would delete the records of the other tables for that class
//
- if (!$bProcessingFriends)
- {
+ if (!$bProcessingFriends) {
$sDeleteKeys = "'".implode("', '", $aWrongRecords)."'";
- foreach(self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_ALL) as $sFriendClass)
- {
+ foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_ALL) as $sFriendClass) {
$sFriendTable = self::DBGetTable($sFriendClass);
$sFriendKey = self::DBGetKey($sFriendClass);
// skip the current table
- if ($sFriendTable == $sTable)
- {
+ if ($sFriendTable == $sTable) {
continue;
}
$sFindRelatedRec = "SELECT DISTINCT maintable.`$sFriendKey` AS id FROM `$sFriendTable` AS maintable WHERE maintable.`$sFriendKey` IN ($sDeleteKeys)";
- self::DBCheckIntegrity_Check2Delete($sFindRelatedRec,
- "Cascading deletion of record in friend table `$sTable `", $sFriendClass, $aErrorsAndFixes,
- $iNewDelCount, $aPlannedDel,
- true);
+ self::DBCheckIntegrity_Check2Delete(
+ $sFindRelatedRec,
+ "Cascading deletion of record in friend table `$sTable `",
+ $sFriendClass,
+ $aErrorsAndFixes,
+ $iNewDelCount,
+ $aPlannedDel,
+ true
+ );
}
}
}
@@ -5911,63 +5389,51 @@ abstract class MetaModel
$sTable = self::DBGetTable($sClass);
$sKeyField = self::DBGetKey($sClass);
- if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
- {
+ if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0) {
$sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
}
$aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
- if (count($aWrongRecords) == 0)
- {
+ if (count($aWrongRecords) == 0) {
return;
}
- if (!array_key_exists($sRootClass, $aErrorsAndFixes))
- {
- $aErrorsAndFixes[$sRootClass] = array();
+ if (!array_key_exists($sRootClass, $aErrorsAndFixes)) {
+ $aErrorsAndFixes[$sRootClass] = [];
}
- if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass]))
- {
- $aErrorsAndFixes[$sRootClass][$sTable] = array();
+ if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) {
+ $aErrorsAndFixes[$sRootClass][$sTable] = [];
}
- foreach($aWrongRecords as $iRecordId)
- {
- if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
- {
+ foreach ($aWrongRecords as $iRecordId) {
+ if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable])) {
$sAction = $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'];
//if ($sAction == 'Delete')
//{
- // No need to update, the record will be deleted!
+ // No need to update, the record will be deleted!
//}
- if ($sAction == 'Update')
- {
+ if ($sAction == 'Update') {
// Already planned for an update
// Add this new update spec to the list
$bFoundSameSpec = false;
- foreach ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] as $aUpdateSpec)
- {
- if (($sColumn == $aUpdateSpec['column']) && ($sNewValue == $aUpdateSpec['newvalue']))
- {
+ foreach ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] as $aUpdateSpec) {
+ if (($sColumn == $aUpdateSpec['column']) && ($sNewValue == $aUpdateSpec['newvalue'])) {
$bFoundSameSpec = true;
}
}
- if (!$bFoundSameSpec)
- {
- $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'][] = (array(
+ if (!$bFoundSameSpec) {
+ $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'][] = ([
'column' => $sColumn,
- 'newvalue' => $sNewValue
- ));
+ 'newvalue' => $sNewValue,
+ ]);
$aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
}
}
- }
- else
- {
+ } else {
$aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
$aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Update';
- $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array(array('column' => $sColumn, 'newvalue' => $sNewValue));
+ $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = [['column' => $sColumn, 'newvalue' => $sNewValue]];
$aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
}
@@ -5984,20 +5450,16 @@ abstract class MetaModel
*/
public static function DBCheckIntegrity_SinglePass(&$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
{
- foreach(self::GetClasses() as $sClass)
- {
- if (!self::HasTable($sClass))
- {
+ foreach (self::GetClasses() as $sClass) {
+ if (!self::HasTable($sClass)) {
continue;
}
$sRootClass = self::GetRootClass($sClass);
$sTable = self::DBGetTable($sClass);
$sKeyField = self::DBGetKey($sClass);
- if (!self::IsStandaloneClass($sClass))
- {
- if (self::IsRootClass($sClass))
- {
+ if (!self::IsStandaloneClass($sClass)) {
+ if (self::IsRootClass($sClass)) {
// Check that the final class field contains the name of a class which inherited from the current class
//
$sFinalClassField = self::DBGetClassField($sClass);
@@ -6007,9 +5469,7 @@ abstract class MetaModel
$sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE `$sFinalClassField` NOT IN ($sAllowedValues)";
self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "final class (field `$sFinalClassField `) is wrong (expected a value in {".$sAllowedValues."})", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
- }
- else
- {
+ } else {
$sRootTable = self::DBGetTable($sRootClass);
$sRootKey = self::DBGetKey($sRootClass);
$sFinalClassField = self::DBGetClassField($sRootClass);
@@ -6031,16 +5491,13 @@ abstract class MetaModel
}
}
- foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
- {
+ foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) {
// Skip this attribute if not defined in this table
- if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass)
- {
+ if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) {
continue;
}
- if ($oAttDef->IsExternalKey())
- {
+ if ($oAttDef->IsExternalKey()) {
// Check that any external field is pointing to an existing object
//
$sRemoteClass = $oAttDef->GetTargetClass();
@@ -6054,46 +5511,35 @@ abstract class MetaModel
$sSelBase = "SELECT DISTINCT maintable.`$sKeyField` AS id, maintable.`$sExtKeyField` AS extkey FROM `$sTable` AS maintable LEFT JOIN `$sRemoteTable` ON maintable.`$sExtKeyField` = `$sRemoteTable`.`$sRemoteKey`";
$sSelWrongRecs = $sSelBase." WHERE `$sRemoteTable`.`$sRemoteKey` IS NULL";
- if ($oAttDef->IsNullAllowed())
- {
+ if ($oAttDef->IsNullAllowed()) {
// Exclude the records pointing to 0/null from the errors
$sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
$sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '$sAttCode ') non existing objects", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
- }
- else
- {
+ } else {
self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '$sAttCode ') non existing objects", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
}
// Do almost the same, taking into account the records planned for deletion
- if (array_key_exists($sRemoteTable, $aPlannedDel) && count($aPlannedDel[$sRemoteTable]) > 0)
- {
+ if (array_key_exists($sRemoteTable, $aPlannedDel) && count($aPlannedDel[$sRemoteTable]) > 0) {
// This could be done by the mean of a 'OR ... IN (aIgnoreRecords)
// but in that case you won't be able to track the root cause (cascading)
$sSelWrongRecs = $sSelBase." WHERE maintable.`$sExtKeyField` IN ('".implode("', '", $aPlannedDel[$sRemoteTable])."')";
- if ($oAttDef->IsNullAllowed())
- {
+ if ($oAttDef->IsNullAllowed()) {
// Exclude the records pointing to 0/null from the errors
$sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
$sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '$sAttCode ') a record planned for deletion", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
- }
- else
- {
+ } else {
self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '$sAttCode ') a record planned for deletion", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
}
}
- }
- else
- {
- if ($oAttDef->IsBasedOnDBColumns())
- {
+ } else {
+ if ($oAttDef->IsBasedOnDBColumns()) {
// Check that the values fit the allowed values
//
$aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
- if (!is_null($aAllowedValues) && count($aAllowedValues) > 0)
- {
+ if (!is_null($aAllowedValues) && count($aAllowedValues) > 0) {
$sExpectedValues = implode(",", CMDBSource::Quote(array_keys($aAllowedValues), true));
$aCols = $oAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
@@ -6120,11 +5566,11 @@ abstract class MetaModel
{
// Records in error, and action to be taken: delete or update
// by RootClass/Table/Record
- $aErrorsAndFixes = array();
+ $aErrorsAndFixes = [];
// Records to be ignored in the current/next pass
// by Table = array of RecordId
- $aPlannedDel = array();
+ $aPlannedDel = [];
// Count of errors in the next pass: no error means that we can leave...
$iErrorCount = 0;
@@ -6132,8 +5578,7 @@ abstract class MetaModel
$iLoopCount = 0;
$iNewDelCount = 1; // startup...
- while ($iNewDelCount > 0)
- {
+ while ($iNewDelCount > 0) {
$iNewDelCount = 0;
self::DBCheckIntegrity_SinglePass($aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
$iErrorCount += $iNewDelCount;
@@ -6142,20 +5587,17 @@ abstract class MetaModel
//
$iMaxDel = 1000;
$iPlannedDel = 0;
- foreach($aPlannedDel as $sTable => $aPlannedDelOnTable)
- {
+ foreach ($aPlannedDel as $sTable => $aPlannedDelOnTable) {
$iPlannedDel += count($aPlannedDelOnTable);
}
- if ($iPlannedDel > $iMaxDel)
- {
+ if ($iPlannedDel > $iMaxDel) {
throw new CoreWarning("DB Integrity Check safety net - Exceeding the limit of $iMaxDel planned record deletion");
}
// Safety net #2 - limit the iterations
//
$iLoopCount++;
$iMaxLoops = 10;
- if ($iLoopCount > $iMaxLoops)
- {
+ if ($iLoopCount > $iMaxLoops) {
throw new CoreWarning("DB Integrity Check safety net - Reached the limit of $iMaxLoops loops");
}
}
@@ -6163,29 +5605,24 @@ abstract class MetaModel
// Display the results
//
$iIssueCount = 0;
- $aFixesDelete = array();
- $aFixesUpdate = array();
+ $aFixesDelete = [];
+ $aFixesUpdate = [];
- foreach($aErrorsAndFixes as $sRootClass => $aTables)
- {
- foreach($aTables as $sTable => $aRecords)
- {
- foreach($aRecords as $iRecord => $aError)
- {
+ foreach ($aErrorsAndFixes as $sRootClass => $aTables) {
+ foreach ($aTables as $sTable => $aRecords) {
+ foreach ($aRecords as $iRecord => $aError) {
$sAction = $aError['Action'];
$sReason = $aError['Reason'];
- switch ($sAction)
- {
+ switch ($sAction) {
case 'Delete':
$sActionDetails = "";
$aFixesDelete[$sTable][] = $iRecord;
break;
case 'Update':
- $aUpdateDesc = array();
- foreach($aError['Action_Details'] as $aUpdateSpec)
- {
+ $aUpdateDesc = [];
+ foreach ($aError['Action_Details'] as $aUpdateSpec) {
$aUpdateDesc[] = $aUpdateSpec['column']." -> ".$aUpdateSpec['newvalue'];
$aFixesUpdate[$sTable][$aUpdateSpec['column']][$aUpdateSpec['newvalue']][] = $iRecord;
}
@@ -6202,17 +5639,14 @@ abstract class MetaModel
}
}
- if ($iIssueCount > 0)
- {
+ if ($iIssueCount > 0) {
// Build the queries to fix in the database
//
// First step, be able to get class data out of the table name
// Could be optimized, because we've made the job earlier... but few benefits, so...
- $aTable2ClassProp = array();
- foreach(self::GetClasses() as $sClass)
- {
- if (!self::HasTable($sClass))
- {
+ $aTable2ClassProp = [];
+ foreach (self::GetClasses() as $sClass) {
+ if (!self::HasTable($sClass)) {
continue;
}
@@ -6220,18 +5654,15 @@ abstract class MetaModel
$sTable = self::DBGetTable($sClass);
$sKeyField = self::DBGetKey($sClass);
- $aErrorsAndFixes[$sRootClass][$sTable] = array();
- $aTable2ClassProp[$sTable] = array('rootclass' => $sRootClass, 'class' => $sClass, 'keyfield' => $sKeyField);
+ $aErrorsAndFixes[$sRootClass][$sTable] = [];
+ $aTable2ClassProp[$sTable] = ['rootclass' => $sRootClass, 'class' => $sClass, 'keyfield' => $sKeyField];
}
// Second step, build a flat list of SQL queries
- $aSQLFixes = array();
+ $aSQLFixes = [];
$iPlannedUpdate = 0;
- foreach($aFixesUpdate as $sTable => $aColumns)
- {
- foreach($aColumns as $sColumn => $aNewValues)
- {
- foreach($aNewValues as $sNewValue => $aRecords)
- {
+ foreach ($aFixesUpdate as $sTable => $aColumns) {
+ foreach ($aColumns as $sColumn => $aNewValues) {
+ foreach ($aNewValues as $sNewValue => $aRecords) {
$iPlannedUpdate += count($aRecords);
$sWrongRecords = "'".implode("', '", $aRecords)."'";
$sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
@@ -6241,8 +5672,7 @@ abstract class MetaModel
}
}
$iPlannedDel = 0;
- foreach($aFixesDelete as $sTable => $aRecords)
- {
+ foreach ($aFixesDelete as $sTable => $aRecords) {
$iPlannedDel += count($aRecords);
$sWrongRecords = "'".implode("', '", $aRecords)."'";
$sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
@@ -6256,8 +5686,7 @@ abstract class MetaModel
echo "Database corruption error(s): $iErrorCount issues have been encountered. $iPlannedDel records will be deleted, $iPlannedUpdate records will be updated: \n";
// #@# later -> this is the responsibility of the caller to format the output
echo "\n";
- foreach($aIssues as $sIssueDesc)
- {
+ foreach ($aIssues as $sIssueDesc) {
echo "$sIssueDesc \n";
}
echo " \n";
@@ -6316,8 +5745,7 @@ abstract class MetaModel
}
ExpressionCache::Warmup();
- }
- finally {
+ } finally {
// Event service must be initialized after the MetaModel startup, otherwise it cannot discover classes implementing the iEventServiceSetup interface
EventService::InitService();
EventService::FireEvent(new EventData(ApplicationEvents::APPLICATION_EVENT_METAMODEL_STARTED));
@@ -6344,8 +5772,7 @@ abstract class MetaModel
utils::SetConfig($oConfiguration);
// Set log ASAP
- if (self::$m_oConfig->GetLogGlobal())
- {
+ if (self::$m_oConfig->GetLogGlobal()) {
if (self::$m_oConfig->GetLogIssue()) {
self::$m_bLogIssue = true;
IssueLog::Enable(APPROOT.'log/error.log');
@@ -6357,9 +5784,7 @@ abstract class MetaModel
DeadLockLog::Enable();
DeprecatedCallsLog::Enable();
ExceptionLog::Enable();
- }
- else
- {
+ } else {
self::$m_bLogIssue = false;
self::$m_bLogNotification = false;
self::$m_bLogWebService = false;
@@ -6367,9 +5792,9 @@ abstract class MetaModel
ExecutionKPI::EnableDuration(self::$m_oConfig->Get('log_kpi_duration'));
ExecutionKPI::EnableMemory(self::$m_oConfig->Get('log_kpi_memory'));
- ExecutionKPI::SetAllowedUser(self::$m_oConfig->Get('log_kpi_user_id'));
- ExecutionKPI::SetGenerateLegacyReport(self::$m_oConfig->Get('log_kpi_generate_legacy_report'));
- ExecutionKPI::SetSlowQueries(self::$m_oConfig->Get('log_kpi_slow_queries'));
+ ExecutionKPI::SetAllowedUser(self::$m_oConfig->Get('log_kpi_user_id'));
+ ExecutionKPI::SetGenerateLegacyReport(self::$m_oConfig->Get('log_kpi_generate_legacy_report'));
+ ExecutionKPI::SetSlowQueries(self::$m_oConfig->Get('log_kpi_slow_queries'));
self::$m_bSkipCheckToWrite = self::$m_oConfig->Get('skip_check_to_write');
self::$m_bSkipCheckExtKeys = self::$m_oConfig->Get('skip_check_ext_keys');
@@ -6387,8 +5812,7 @@ abstract class MetaModel
// Note: load the dictionary as soon as possible, because it might be
// needed when some error occur
$sAppIdentity = 'itop-'.MetaModel::GetEnvironmentId();
- if (self::$m_bUseAPCCache)
- {
+ if (self::$m_bUseAPCCache) {
Dict::EnableCache($sAppIdentity);
}
require_once(APPROOT.'env-'.self::$m_sEnvironment.'/dictionaries/languages.php');
@@ -6447,8 +5871,7 @@ abstract class MetaModel
$oKPI->ComputeAndReport('Metamodel APC (fetch + read)');
}
- if (count(self::$m_aAttribDefs) == 0)
- {
+ if (count(self::$m_aAttribDefs) == 0) {
// The includes have been included, let's browse the existing classes and
// develop some data based on the proposed model
$oKPI = new ExecutionKPI();
@@ -6456,11 +5879,10 @@ abstract class MetaModel
self::InitClasses($sTablePrefix);
$oKPI->ComputeAndReport('Initialization of Data model structures');
- if (self::$m_bUseAPCCache)
- {
+ if (self::$m_bUseAPCCache) {
$oKPI = new ExecutionKPI();
- $aCache = array();
+ $aCache = [];
$aCache['m_aExtensionClassNames'] = self::$m_aExtensionClassNames;
$aCache['m_Category2Class'] = self::$m_Category2Class;
$aCache['m_aRootClasses'] = self::$m_aRootClasses; // array of "classname" => "rootclass"
@@ -6490,7 +5912,7 @@ abstract class MetaModel
CMDBSource::InitFromConfig(self::$m_oConfig);
// Later when timezone implementation is correctly done: CMDBSource::SetTimezone($sDBTimezone);
- ExecutionKPI::InitStats();
+ ExecutionKPI::InitStats();
}
/**
@@ -6515,8 +5937,7 @@ abstract class MetaModel
public static function GetModuleParameter($sModule, $sProperty, $defaultvalue = null)
{
$value = $defaultvalue;
- if (!self::$m_aModulesParameters[$sModule] == null)
- {
+ if (!self::$m_aModulesParameters[$sModule] == null) {
$value = self::$m_aModulesParameters[$sModule]->Get($sProperty, $defaultvalue);
}
return $value;
@@ -6559,8 +5980,8 @@ abstract class MetaModel
return md5(APPROOT).'-'.self::$m_sEnvironment;
}
- /** @var array */
- protected static $m_aExtensionClassNames = [];
+ /** @var array */
+ protected static $m_aExtensionClassNames = [];
/**
* @param string $sToInclude
@@ -6572,42 +5993,29 @@ abstract class MetaModel
{
$sFirstChar = substr($sToInclude, 0, 1);
$sSecondChar = substr($sToInclude, 1, 1);
- if (($sFirstChar != '/') && ($sFirstChar != '\\') && ($sSecondChar != ':'))
- {
+ if (($sFirstChar != '/') && ($sFirstChar != '\\') && ($sSecondChar != ':')) {
// It is a relative path, prepend APPROOT
- if (substr($sToInclude, 0, 3) == '../')
- {
+ if (substr($sToInclude, 0, 3) == '../') {
// Preserve compatibility with config files written before 1.0.1
// Replace '../' by '/'
$sFile = APPROOT.'/'.substr($sToInclude, 3);
- }
- else
- {
+ } else {
$sFile = APPROOT.'/'.$sToInclude;
}
- }
- else
- {
+ } else {
// Leave as is - should be an absolute path
$sFile = $sToInclude;
}
- if (!file_exists($sFile))
- {
+ if (!file_exists($sFile)) {
$sConfigFile = self::$m_oConfig->GetLoadedFile();
- if ($sModuleType == null)
- {
+ if ($sModuleType == null) {
throw new CoreException("Include: unable to load the file '$sFile'");
- }
- else
- {
- if (strlen($sConfigFile) > 0)
- {
- throw new CoreException('Include: wrong file name in configuration file', array('config file' => $sConfigFile, 'section' => $sModuleType, 'filename' => $sFile));
- }
- else
- {
+ } else {
+ if (strlen($sConfigFile) > 0) {
+ throw new CoreException('Include: wrong file name in configuration file', ['config file' => $sConfigFile, 'section' => $sModuleType, 'filename' => $sFile]);
+ } else {
// The configuration is in memory only
- throw new CoreException('Include: wrong file name in configuration file (in memory)', array('section' => $sModuleType, 'filename' => $sFile));
+ throw new CoreException('Include: wrong file name in configuration file (in memory)', ['section' => $sModuleType, 'filename' => $sFile]);
}
}
}
@@ -6620,10 +6028,8 @@ abstract class MetaModel
ob_start();
require_once($sFile);
$sPreviousContent = ob_get_clean();
- if (self::$m_oConfig->Get('debug_report_spurious_chars'))
- {
- if ($sPreviousContent != '')
- {
+ if (self::$m_oConfig->Get('debug_report_spurious_chars')) {
+ if ($sPreviousContent != '') {
IssueLog::Error("Spurious characters injected by '$sFile'");
}
}
@@ -6633,19 +6039,18 @@ abstract class MetaModel
//
//
/** @var array */
- private static $aQueryCacheGetObject = array();
+ private static $aQueryCacheGetObject = [];
/** @var array */
- private static $aQueryCacheGetObjectHits = array();
+ private static $aQueryCacheGetObjectHits = [];
/**
* @return string
*/
public static function GetQueryCacheStatus()
{
- $aRes = array();
+ $aRes = [];
$iTotalHits = 0;
- foreach(self::$aQueryCacheGetObjectHits as $sClassSign => $iHits)
- {
+ foreach (self::$aQueryCacheGetObjectHits as $sClassSign => $iHits) {
$aRes[] = "$sClassSign: $iHits";
$iTotalHits += $iHits;
}
@@ -6670,20 +6075,17 @@ abstract class MetaModel
// Build the query cache signature
//
$sQuerySign = $sClass;
- if ($bAllowAllData)
- {
+ if ($bAllowAllData) {
$sQuerySign .= '_all_';
}
- if (is_array($aModifierProperties) && (count($aModifierProperties) > 0))
- {
+ if (is_array($aModifierProperties) && (count($aModifierProperties) > 0)) {
array_multisort($aModifierProperties);
$sModifierProperties = json_encode($aModifierProperties);
$sQuerySign .= '_all_'.md5($sModifierProperties);
}
$sQuerySign .= utils::IsArchiveMode() ? '_arch_' : '';
- if (!array_key_exists($sQuerySign, self::$aQueryCacheGetObject))
- {
+ if (!array_key_exists($sQuerySign, self::$aQueryCacheGetObject)) {
// NOTE: Quick and VERY dirty caching mechanism which relies on
// the fact that the string '987654321' will never appear in the
// standard query
@@ -6691,27 +6093,21 @@ abstract class MetaModel
// but this would slow down -by how much time?- the application
$oFilter = new DBObjectSearch($sClass);
$oFilter->AddCondition('id', 987654321, '=');
- if ($aModifierProperties)
- {
- foreach($aModifierProperties as $sPluginClass => $aProperties)
- {
- foreach($aProperties as $sProperty => $value)
- {
+ if ($aModifierProperties) {
+ foreach ($aModifierProperties as $sPluginClass => $aProperties) {
+ foreach ($aProperties as $sProperty => $value) {
$oFilter->SetModifierProperty($sPluginClass, $sProperty, $value);
}
}
}
- if ($bAllowAllData)
- {
+ if ($bAllowAllData) {
$oFilter->AllowAllData();
}
$oFilter->NoContextParameters();
$sSQL = $oFilter->MakeSelectQuery();
self::$aQueryCacheGetObject[$sQuerySign] = $sSQL;
self::$aQueryCacheGetObjectHits[$sQuerySign] = 0;
- }
- else
- {
+ } else {
$sSQL = self::$aQueryCacheGetObject[$sQuerySign];
self::$aQueryCacheGetObjectHits[$sQuerySign] += 1;
}
@@ -6721,8 +6117,7 @@ abstract class MetaModel
$aRow = CMDBSource::FetchArray($res);
CMDBSource::FreeResult($res);
- if ($bMustBeFound && empty($aRow))
- {
+ if ($bMustBeFound && empty($aRow)) {
$sNotFoundErrorMessage = "No result for the single row query";
IssueLog::Info($sNotFoundErrorMessage, LogChannels::CMDB_SOURCE, [
'class' => $sClass,
@@ -6752,40 +6147,31 @@ abstract class MetaModel
{
self::_check_subclass($sClass);
- if (strlen($sClassAlias) == 0)
- {
+ if (strlen($sClassAlias) == 0) {
$sClassAlias = $sClass;
}
// Compound objects: if available, get the final object class
//
- if (!array_key_exists($sClassAlias."finalclass", $aRow))
- {
+ if (!array_key_exists($sClassAlias."finalclass", $aRow)) {
// Either this is a bug (forgot to specify a root class with a finalclass field
// Or this is the expected behavior, because the object is not made of several tables
- if (self::IsAbstract($sClass))
- {
+ if (self::IsAbstract($sClass)) {
throw new CoreUnexpectedValue("Querying the abstract '$sClass' class without finalClass attribute");
}
- if (self::HasChildrenClasses($sClass))
- {
+ if (self::HasChildrenClasses($sClass)) {
throw new CoreUnexpectedValue("Querying the '$sClass' class without the finalClass attribute, whereas this class has children");
}
- }
- elseif (empty($aRow[$sClassAlias."finalclass"]))
- {
+ } elseif (empty($aRow[$sClassAlias."finalclass"])) {
// The data is missing in the DB
// @#@ possible improvement: check that the class is valid !
$sRootClass = self::GetRootClass($sClass);
$sFinalClassField = self::DBGetClassField($sRootClass);
throw new CoreException("Empty class name for object $sClass::{$aRow["id"]} (root class '$sRootClass', field '{$sFinalClassField}' is empty)");
- }
- else
- {
+ } else {
// do the job for the real target class
- if (!class_exists($aRow[$sClassAlias."finalclass"]))
- {
- throw new CoreException("Class {$aRow[$sClassAlias."finalclass"]} derived from $sClass does not exist anymore, please remove corresponding tables in the database", array('row' => $aRow));
+ if (!class_exists($aRow[$sClassAlias."finalclass"])) {
+ throw new CoreException("Class {$aRow[$sClassAlias."finalclass"]} derived from $sClass does not exist anymore, please remove corresponding tables in the database", ['row' => $aRow]);
}
$sClass = $aRow[$sClassAlias."finalclass"];
}
@@ -6902,23 +6288,17 @@ abstract class MetaModel
self::_check_subclass($sClass);
utils::PushArchiveMode(true);
- try
- {
+ try {
$aRow = self::MakeSingleRow($sClass, $iKey, $bMustBeFound, $bAllowAllData, $aModifierProperties);
- }
- catch(Exception $e)
- {
+ } catch (Exception $e) {
// In the finally block we will pop the pushed archived mode
// otherwise the application stays in ArchiveMode true which has caused hazardious behavior!
throw $e;
- }
- finally
- {
+ } finally {
utils::PopArchiveMode();
}
- if (empty($aRow))
- {
+ if (empty($aRow)) {
return null;
}
@@ -6940,11 +6320,9 @@ abstract class MetaModel
$oObjSearch = new DBObjectSearch($sClass);
$oObjSearch->AddNameCondition($sName);
$oSet = new DBObjectSet($oObjSearch);
- if ($oSet->Count() != 1)
- {
- if ($bMustBeFound)
- {
- throw new CoreException('Failed to get an object by its name', array('class' => $sClass, 'name' => $sName));
+ if ($oSet->Count() != 1) {
+ if ($bMustBeFound) {
+ throw new CoreException('Failed to get an object by its name', ['class' => $sClass, 'name' => $sName]);
}
return null;
}
@@ -6953,7 +6331,7 @@ abstract class MetaModel
}
/** @var array */
- static protected $m_aCacheObjectByColumn = array();
+ protected static $m_aCacheObjectByColumn = [];
/**
* @param string $sClass
@@ -6982,15 +6360,11 @@ abstract class MetaModel
$oObjSearch->AllowAllData($bAllowAllData);
$oObjSearch->AddCondition($sAttCode, $value, '=');
$oSet = new DBObjectSet($oObjSearch);
- if ($oSet->Count() == 1)
- {
+ if ($oSet->Count() == 1) {
self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value] = $oSet->fetch();
- }
- else
- {
- if ($bMustBeFoundUnique)
- {
- throw new CoreException('Failed to get an object by column', array('class' => $sClass, 'attcode' => $sAttCode, 'value' => $value, 'matches' => $oSet->Count()));
+ } else {
+ if ($bMustBeFoundUnique) {
+ throw new CoreException('Failed to get an object by column', ['class' => $sClass, 'attcode' => $sAttCode, 'value' => $value, 'matches' => $oSet->Count()]);
}
self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value] = null;
}
@@ -7010,8 +6384,7 @@ abstract class MetaModel
public static function GetObjectFromOQL($sQuery, $aParams = null, $bAllowAllData = false)
{
$oFilter = DBObjectSearch::FromOQL($sQuery, $aParams);
- if ($bAllowAllData)
- {
+ if ($bAllowAllData) {
$oFilter->AllowAllData();
}
$oSet = new DBObjectSet($oFilter);
@@ -7035,11 +6408,11 @@ abstract class MetaModel
if ($iKey < 0) {
return "$sTargetClass: $iKey (invalid value)";
}
- $oObj = self::GetObject($sTargetClass, $iKey, false);
+ $oObj = self::GetObject($sTargetClass, $iKey, false);
if (is_null($oObj)) {
// Whatever we are looking for, the root class is the key to search for
$sRootClass = self::GetRootClass($sTargetClass);
- $oSearch = DBObjectSearch::FromOQL('SELECT CMDBChangeOpDelete WHERE objclass = :objclass AND objkey = :objkey', array('objclass' => $sRootClass, 'objkey' => $iKey));
+ $oSearch = DBObjectSearch::FromOQL('SELECT CMDBChangeOpDelete WHERE objclass = :objclass AND objkey = :objkey', ['objclass' => $sRootClass, 'objkey' => $iKey]);
$oSet = new DBObjectSet($oSearch);
$oRecord = $oSet->Fetch();
// An empty fname is obtained with iTop < 2.0
@@ -7071,10 +6444,8 @@ abstract class MetaModel
{
self::_check_subclass($sClass);
$oRet = new $sClass();
- if (is_array($aValues))
- {
- foreach($aValues as $sAttCode => $value)
- {
+ if (is_array($aValues)) {
+ foreach ($aValues as $sAttCode => $value) {
$oRet->Set($sAttCode, $value);
}
}
@@ -7124,7 +6495,7 @@ abstract class MetaModel
while ($bExecuteQuery) {
$oSet = new DBObjectSet($oFilter);
$oSet->SetLimit($iMaxChunkSize);
- $oSet->OptimizeColumnLoad(array($sTargetClass => array('finalclass')));
+ $oSet->OptimizeColumnLoad([$sTargetClass => ['finalclass']]);
$aIdToClass = $oSet->GetColumnAsArray('finalclass', true);
$aIds = array_keys($aIdToClass);
@@ -7168,11 +6539,9 @@ abstract class MetaModel
self::_check_subclass($sClass);
// 1-N links (referenced by my class), returns an array of sAttCode=>sClass
- $aResult = array();
- foreach(self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef)
- {
- if ($oAttDef->IsExternalKey())
- {
+ $aResult = [];
+ foreach (self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef) {
+ if ($oAttDef->IsExternalKey()) {
$aResult[$sAttCode] = $oAttDef->GetTargetClass();
}
}
@@ -7192,39 +6561,31 @@ abstract class MetaModel
{
self::_check_subclass($sClass);
- if ($bSkipLinkingClasses)
- {
+ if ($bSkipLinkingClasses) {
$aLinksClasses = array_keys(self::GetLinkClasses());
}
// 1-N links (referencing my class), array of sClass => array of sAttcode
- $aResult = array();
- foreach(self::$m_aAttribDefs as $sSomeClass => $aClassAttributes)
- {
- if ($bSkipLinkingClasses && in_array($sSomeClass, $aLinksClasses))
- {
+ $aResult = [];
+ foreach (self::$m_aAttribDefs as $sSomeClass => $aClassAttributes) {
+ if ($bSkipLinkingClasses && in_array($sSomeClass, $aLinksClasses)) {
continue;
}
- $aExtKeys = array();
- foreach($aClassAttributes as $sAttCode => $oAttDef)
- {
- if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass)
- {
+ $aExtKeys = [];
+ foreach ($aClassAttributes as $sAttCode => $oAttDef) {
+ if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) {
continue;
}
- if ($oAttDef->IsExternalKey() && (self::IsParentClass($oAttDef->GetTargetClass(), $sClass)))
- {
- if ($bInnerJoinsOnly && $oAttDef->IsNullAllowed())
- {
+ if ($oAttDef->IsExternalKey() && (self::IsParentClass($oAttDef->GetTargetClass(), $sClass))) {
+ if ($bInnerJoinsOnly && $oAttDef->IsNullAllowed()) {
continue;
}
// Ok, I want this one
$aExtKeys[$sAttCode] = $oAttDef;
}
}
- if (count($aExtKeys) != 0)
- {
+ if (count($aExtKeys) != 0) {
$aResult[$sSomeClass] = $aExtKeys;
}
}
@@ -7254,11 +6615,11 @@ abstract class MetaModel
*/
public static function GetLinkClasses(): array
{
- $aRet = array();
- foreach(self::GetClasses() as $sClass) {
+ $aRet = [];
+ foreach (self::GetClasses() as $sClass) {
if (self::IsLinkClass($sClass)) {
- $aExtKeys = array();
- foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) {
+ $aExtKeys = [];
+ foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) {
if ($oAttDef->IsExternalKey()) {
$aExtKeys[$sAttCode] = $oAttDef->GetTargetClass();
}
@@ -7309,8 +6670,8 @@ abstract class MetaModel
$aParams['APP_URL'] = utils::GetAbsoluteUrlAppRoot();
$aParams['MODULES_URL'] = utils::GetAbsoluteUrlModulesRoot();
- $aSearches = array();
- $aReplacements = array();
+ $aSearches = [];
+ $aReplacements = [];
foreach ($aParams as $sSearch => $replace) {
// Some environment parameters are objects, we just need scalars
if (is_object($replace)) {
@@ -7322,10 +6683,10 @@ abstract class MetaModel
// 1 - The delimiter
// 2 - The arrow
// 3 - The attribute code
- $aRegExps = array(
+ $aRegExps = [
'/(\\$)'.$sName.'-(>|>)([^\\$]+)\\$/', // Support both syntaxes: $this->xxx$ or $this->xxx$ for HTML compatibility
'/(%24)'.$sName.'-(>|>)([^%24]+)%24/', // Support for urlencoded in HTML attributes (%20this->xxx%20)
- );
+ ];
foreach ($aRegExps as $sRegExp) {
if (preg_match_all($sRegExp, $sInput, $aMatches)) {
foreach ($aMatches[3] as $idx => $sPlaceholderAttCode) {
@@ -7335,8 +6696,7 @@ abstract class MetaModel
$aReplacements[] = $sReplacement;
$aSearches[] = $aMatches[1][$idx].$sName.'-'.$aMatches[2][$idx].$sPlaceholderAttCode.$aMatches[1][$idx];
}
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$aContext = [
'placeholder' => $sPlaceholderAttCode,
'replace class' => get_class($replace),
@@ -7357,13 +6717,13 @@ abstract class MetaModel
continue; // Ignore this non-scalar value
}
} else {
- $aRegExps = array(
+ $aRegExps = [
'/(\$)'.$sSearch.'\$/', // Regular placeholders (eg. $APP_URL$) or placeholders with an arrow in plain text (eg. $foo->bar$)
'/(%24)'.$sSearch.'%24/', // Regular placeholders url-encoded in HTML attributes (eg. %24APP_URL%24)
'/(\$)'.utils::EscapeHtml($sSearch).'\$/', // Placeholders with an arrow in HTML (eg. $foo->bar$)
'/(%24)'.utils::EscapeHtml($sSearch).'%24/', // Placeholders with an arrow url-encoded in HTML attributes (eg. %24->bar%24)
- );
+ ];
foreach ($aRegExps as $sRegExp) {
if (preg_match_all($sRegExp, $sInput, $aMatches)) {
foreach ($aMatches[1] as $idx => $sDelimiter) {
@@ -7375,8 +6735,7 @@ abstract class MetaModel
// With an arrow in HTML
$aReplacements[] = (string) $replace;
$aSearches[] = $aMatches[1][$idx].utils::EscapeHtml($sSearch).$aMatches[1][$idx];
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
IssueLog::Debug(
'Invalid placeholder in notification, no replacement will occur !',
LogChannels::NOTIFICATIONS,
@@ -7430,21 +6789,17 @@ abstract class MetaModel
*/
public static function GetCacheEntries($sEnvironment = null)
{
- if (is_null($sEnvironment))
- {
+ if (is_null($sEnvironment)) {
$sEnvironment = MetaModel::GetEnvironmentId();
}
- $aEntries = array();
+ $aEntries = [];
$aCacheUserData = apc_cache_info_compat();
- if (is_array($aCacheUserData) && isset($aCacheUserData['cache_list']))
- {
+ if (is_array($aCacheUserData) && isset($aCacheUserData['cache_list'])) {
$sPrefix = 'itop-'.$sEnvironment.'-';
- foreach($aCacheUserData['cache_list'] as $i => $aEntry)
- {
+ foreach ($aCacheUserData['cache_list'] as $i => $aEntry) {
$sEntryKey = array_key_exists('info', $aEntry) ? $aEntry['info'] : $aEntry['key'];
- if (strpos($sEntryKey, $sPrefix) === 0)
- {
+ if (strpos($sEntryKey, $sPrefix) === 0) {
$sCleanKey = substr($sEntryKey, strlen($sPrefix));
$aEntries[$sCleanKey] = $aEntry;
$aEntries[$sCleanKey]['info'] = $sEntryKey;
@@ -7507,42 +6862,29 @@ abstract class MetaModel
{
$sRet = $sField;
- if ($sField == 'id')
- {
+ if ($sField == 'id') {
$sRet = 'id';
- }
- elseif ($sField == 'friendlyname')
- {
+ } elseif ($sField == 'friendlyname') {
$sFriendlyNameAttCode = static::GetFriendlyNameAttributeCode($sClass);
- if (!is_null($sFriendlyNameAttCode))
- {
+ if (!is_null($sFriendlyNameAttCode)) {
// The friendly name is made of a single attribute
$sRet = $sFriendlyNameAttCode;
}
- }
- else
- {
+ } else {
$oAttDef = static::GetAttributeDef($sClass, $sField);
- if ($oAttDef->IsExternalField())
- {
- if ($oAttDef->IsFriendlyName())
- {
+ if ($oAttDef->IsExternalField()) {
+ if ($oAttDef->IsFriendlyName()) {
$oKeyAttDef = MetaModel::GetAttributeDef($sClass, $oAttDef->GetKeyAttCode());
$sRemoteClass = $oKeyAttDef->GetTargetClass();
$sFriendlyNameAttCode = static::GetFriendlyNameAttributeCode($sRemoteClass);
- if (is_null($sFriendlyNameAttCode))
- {
+ if (is_null($sFriendlyNameAttCode)) {
// The friendly name is made of several attributes
$sRet = $oAttDef->GetKeyAttCode().'->friendlyname';
- }
- else
- {
+ } else {
// The friendly name is made of a single attribute
$sRet = $oAttDef->GetKeyAttCode().'->'.$sFriendlyNameAttCode;
}
- }
- else
- {
+ } else {
$sRet = $oAttDef->GetKeyAttCode().'->'.$oAttDef->GetExtAttCode();
}
}
@@ -7552,11 +6894,10 @@ abstract class MetaModel
private static function GetAdditionalRequestAfterAlter($sClass, $sTable, $sField)
{
- $aRequests = array();
+ $aRequests = [];
// Copy finalclass fields from root class to intermediate classes
- if ($sField == self::DBGetClassField($sClass))
- {
+ if ($sField == self::DBGetClassField($sClass)) {
$sRootClass = MetaModel::GetRootClass($sClass);
$sRootTable = self::DBGetTable($sRootClass);
$sKey = self::DBGetKey($sClass);
@@ -7670,7 +7011,7 @@ abstract class MetaModel
'ModuleHandlerApiInterface',
];
foreach ($aInterfaces as $sInterface) {
- self::$m_aExtensionClassNames[$sInterface] = array();
+ self::$m_aExtensionClassNames[$sInterface] = [];
}
foreach (get_declared_classes() as $sPHPClass) {
@@ -7685,15 +7026,14 @@ abstract class MetaModel
}
}
-
// Standard attribute lists
-MetaModel::RegisterZList("noneditable", array("description" => "non editable fields", "type" => "attributes"));
+MetaModel::RegisterZList("noneditable", ["description" => "non editable fields", "type" => "attributes"]);
-MetaModel::RegisterZList("details", array("description" => "All attributes to be displayed for the 'details' of an object", "type" => "attributes"));
-MetaModel::RegisterZList("summary", array("description" => "All attributes to be displayed for shorter 'details' of an object", "type" => "attributes"));
-MetaModel::RegisterZList("list", array("description" => "All attributes to be displayed for a list of objects", "type" => "attributes"));
-MetaModel::RegisterZList("preview", array("description" => "All attributes visible in preview mode", "type" => "attributes"));
+MetaModel::RegisterZList("details", ["description" => "All attributes to be displayed for the 'details' of an object", "type" => "attributes"]);
+MetaModel::RegisterZList("summary", ["description" => "All attributes to be displayed for shorter 'details' of an object", "type" => "attributes"]);
+MetaModel::RegisterZList("list", ["description" => "All attributes to be displayed for a list of objects", "type" => "attributes"]);
+MetaModel::RegisterZList("preview", ["description" => "All attributes visible in preview mode", "type" => "attributes"]);
-MetaModel::RegisterZList("standard_search", array("description" => "List of criteria for the standard search", "type" => "filters"));
-MetaModel::RegisterZList("advanced_search", array("description" => "List of criteria for the advanced search", "type" => "filters"));
-MetaModel::RegisterZList("default_search", array("description" => "List of criteria displayed by default during search", "type" => "filters"));
+MetaModel::RegisterZList("standard_search", ["description" => "List of criteria for the standard search", "type" => "filters"]);
+MetaModel::RegisterZList("advanced_search", ["description" => "List of criteria for the advanced search", "type" => "filters"]);
+MetaModel::RegisterZList("default_search", ["description" => "List of criteria displayed by default during search", "type" => "filters"]);
diff --git a/core/oqlactualclasstreeresolver.class.inc.php b/core/oqlactualclasstreeresolver.class.inc.php
index 59a9bb34e..46fdb0470 100644
--- a/core/oqlactualclasstreeresolver.class.inc.php
+++ b/core/oqlactualclasstreeresolver.class.inc.php
@@ -1,10 +1,10 @@
oOQLClassNode->GetNodeClass();
$sClassAlias = $this->oOQLClassNode->GetNodeClassAlias();
$aExpectedAttributes = $this->oBuild->m_oQBExpressions->GetUnresolvedFields($sClassAlias);
- if (!is_null($sIncomingKeyAttCode) && !isset($aExpectedAttributes[$sIncomingKeyAttCode]))
- {
+ if (!is_null($sIncomingKeyAttCode) && !isset($aExpectedAttributes[$sIncomingKeyAttCode])) {
// Add entry point as expected attribute
$aExpectedAttributes[$sIncomingKeyAttCode] = new FieldExpression($sIncomingKeyAttCode, $sClassAlias);
}
$aClasses = MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL, false);
/** @var OQLClassNode[] $aClassAndAncestorsNodes */
- $aClassAndAncestorsNodes = array();
- foreach ($aClasses as $sFamilyClass)
- {
+ $aClassAndAncestorsNodes = [];
+ foreach ($aClasses as $sFamilyClass) {
// Remove unnecessary classes
- if (MetaModel::HasTable($sFamilyClass))
- {
+ if (MetaModel::HasTable($sFamilyClass)) {
$aClassAndAncestorsNodes[$sFamilyClass] = null;
}
}
- if (empty($aClassAndAncestorsNodes))
- {
+ if (empty($aClassAndAncestorsNodes)) {
throw new CoreException("Impossible to query the class $sClass");
}
$oBaseNode = null;
- $aTranslateFields = array();
- foreach ($aExpectedAttributes as $sAttCode => $oExpression)
- {
+ $aTranslateFields = [];
+ foreach ($aExpectedAttributes as $sAttCode => $oExpression) {
// 'id' is managed later
- if ($sAttCode == 'id')
- {
+ if ($sAttCode == 'id') {
continue;
}
// Attributes can be stored in attributes list or for magic ones into filter codes list.
$sOriginClass = null;
if (MetaModel::IsValidAttCode($sClass, $sAttCode)) {
$sOriginClass = MetaModel::GetAttributeOrigin($sClass, $sAttCode);
- } else if ($sAttCode == 'id') {
+ } elseif ($sAttCode == 'id') {
$sOriginClass = $sClass;
} else {
continue;
}
- if (!isset($aClassAndAncestorsNodes[$sOriginClass]) || is_null($aClassAndAncestorsNodes[$sOriginClass]))
- {
- if ($sOriginClass == $sClass)
- {
+ if (!isset($aClassAndAncestorsNodes[$sOriginClass]) || is_null($aClassAndAncestorsNodes[$sOriginClass])) {
+ if ($sOriginClass == $sClass) {
$sOriginClassAlias = $sClassAlias;
- }
- else
- {
+ } else {
$sOriginClassAlias = $this->oBuild->GenerateTableAlias($sClassAlias.'_'.$sOriginClass, $sClass);
}
$oOriginClassNode = new OQLClassNode($this->oBuild, $sOriginClass, $sOriginClassAlias, $sClassAlias);
$aClassAndAncestorsNodes[$sOriginClass] = $oOriginClassNode;
- }
- else
- {
+ } else {
$oOriginClassNode = $aClassAndAncestorsNodes[$sOriginClass];
}
- if ($sOriginClass != $sClass)
- {
+ if ($sOriginClass != $sClass) {
// Alias changed, set a new translation
$sOriginClassAlias = $oOriginClassNode->GetNodeClassAlias();
$aTranslateFields[$sClassAlias][$sAttCode] = new FieldExpression($sAttCode, $sOriginClassAlias);
@@ -107,8 +94,7 @@ class OQLActualClassTreeResolver
// Add Joins corresponding to external keys
$this->ResolveJoins($sAttCode, $oOriginClassNode);
- if ($sAttCode === $sIncomingKeyAttCode)
- {
+ if ($sAttCode === $sIncomingKeyAttCode) {
// This is the entry point of the class
$oBaseNode = $oOriginClassNode;
}
@@ -117,47 +103,37 @@ class OQLActualClassTreeResolver
// Create joins for ancestor classes
/** @var \OQLClassNode $oBaseNode */
$sFirstValidAncestor = null;
- foreach ($aClassAndAncestorsNodes as $sOriginClass => $oOriginClassNode)
- {
- if (is_null($sFirstValidAncestor))
- {
+ foreach ($aClassAndAncestorsNodes as $sOriginClass => $oOriginClassNode) {
+ if (is_null($sFirstValidAncestor)) {
$sFirstValidAncestor = $sOriginClass;
}
- if (is_null($oOriginClassNode))
- {
+ if (is_null($oOriginClassNode)) {
continue;
}
- if (is_null($oBaseNode))
- {
+ if (is_null($oBaseNode)) {
$oBaseNode = $oOriginClassNode;
continue;
}
- if ($oBaseNode === $oOriginClassNode)
- {
+ if ($oBaseNode === $oOriginClassNode) {
// Don't link to itself
continue;
}
$oBaseNode->AddInnerJoin($oOriginClassNode, 'id', 'id');
}
- if (is_null($oBaseNode))
- {
+ if (is_null($oBaseNode)) {
// If no class was generated above, keep the first valid ancestor
- if (is_null($sFirstValidAncestor) || ($sFirstValidAncestor == $sClass))
- {
+ if (is_null($sFirstValidAncestor) || ($sFirstValidAncestor == $sClass)) {
// take current node
$oBaseNode = $this->oOQLClassNode->CloneNode();
- }
- else
- {
+ } else {
// Use the first valid class to build a default node
$sDefaultClassAlias = $this->oBuild->GenerateTableAlias($sClassAlias.'_'.$sFirstValidAncestor, $sClass);
$oBaseNode = new OQLClassNode($this->oBuild, $sFirstValidAncestor, $sDefaultClassAlias);
}
}
- if (isset($aExpectedAttributes['id']) && !isset($aClassAndAncestorsNodes[$sClass]))
- {
+ if (isset($aExpectedAttributes['id']) && !isset($aClassAndAncestorsNodes[$sClass])) {
$sFirstClassAlias = $oBaseNode->GetNodeClassAlias();
$aTranslateFields[$sClassAlias]['id'] = new FieldExpression('id', $sFirstClassAlias);
}
@@ -167,12 +143,11 @@ class OQLActualClassTreeResolver
$this->ResolveJoins('id', $oBaseNode);
// Add finalclass condition if not the requested class
- if ($oBaseNode->GetNodeClass() != $sClass)
- {
+ if ($oBaseNode->GetNodeClass() != $sClass) {
$sExpectedClasses = implode("', '", MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL));
$oInExpression = Expression::FromOQL("`".$oBaseNode->GetNodeClassAlias()."`.finalclass IN ('$sExpectedClasses')");
$oTrueExpression = new TrueExpression();
- $aCoalesceAttr = array($oInExpression, $oTrueExpression);
+ $aCoalesceAttr = [$oInExpression, $oTrueExpression];
$oFinalClassRestriction = new FunctionExpression("COALESCE", $aCoalesceAttr);
$this->oBuild->m_oQBExpressions->AddCondition($oFinalClassRestriction);
}
@@ -194,10 +169,8 @@ class OQLActualClassTreeResolver
// Joins on the selected class
$aJoins = $this->oOQLClassNode->GetJoins();
- if (isset($aJoins[$sAttCode]))
- {
- foreach ($aJoins[$sAttCode] as $oBaseOQLJoin)
- {
+ if (isset($aJoins[$sAttCode])) {
+ foreach ($aJoins[$sAttCode] as $oBaseOQLJoin) {
// transfer the join from OQL class tree to actual class tree
$oBaseJoinedClassNode = $oBaseOQLJoin->GetOOQLClassNode();
$oOQLActualClassTreeResolver = new OQLActualClassTreeResolver($oBaseJoinedClassNode, $this->oBuild);
diff --git a/core/ormdocument.class.inc.php b/core/ormdocument.class.inc.php
index 527465d4f..56618dcaf 100644
--- a/core/ormdocument.class.inc.php
+++ b/core/ormdocument.class.inc.php
@@ -407,16 +407,16 @@ class ormDocument
* @return ormDocument The resampled image
*
*/
- public function ResizeImageToFit(int $iMaxWidth, int $iMaxHeight, array|null &$aFinalDimensions = null) : static
+ public function ResizeImageToFit(int $iMaxWidth, int $iMaxHeight, array|null &$aFinalDimensions = null): static
{
$aFinalDimensions = null;
// If gd extension is not loaded, we put a warning in the log and return the image as is
if (extension_loaded('gd') === false) {
- IssueLog::Warning('Image could not be resized as the "gd" extension does not seem to be loaded. Its dimensions will remain the same instead of ' . $iMaxWidth . 'x' . $iMaxHeight);
+ IssueLog::Warning('Image could not be resized as the "gd" extension does not seem to be loaded. Its dimensions will remain the same instead of '.$iMaxWidth.'x'.$iMaxHeight);
return $this;
}
$oGdImage = false;
- switch($this->GetMimeType()) {
+ switch ($this->GetMimeType()) {
case 'image/gif':
case 'image/jpeg':
case 'image/png':
@@ -428,18 +428,18 @@ class ormDocument
}
if ($oGdImage === false) {
- IssueLog::Warning('Image could not be resized as . It will remain as imagecreatefromstring could not read its data.Its dimensions will remain the same instead of ' . $iMaxWidth . 'x' . $iMaxHeight);
+ IssueLog::Warning('Image could not be resized as . It will remain as imagecreatefromstring could not read its data.Its dimensions will remain the same instead of '.$iMaxWidth.'x'.$iMaxHeight);
return $this;
}
$iWidth = imagesx($oGdImage);
$iHeight = imagesy($oGdImage);
- if ( ($iMaxWidth === 0 || $iWidth <= $iMaxWidth) && ($iMaxHeight === 0 || $iHeight <= $iMaxHeight)) {
+ if (($iMaxWidth === 0 || $iWidth <= $iMaxWidth) && ($iMaxHeight === 0 || $iHeight <= $iMaxHeight)) {
// No need to resize
$aFinalDimensions = [
'width' => $iWidth,
- 'height' =>$iHeight
+ 'height' => $iHeight,
];
return $this;
}
@@ -456,14 +456,13 @@ class ormDocument
$oNewGdImage = imagecreatetruecolor($iNewWidth, $iNewHeight);
-
$aFinalDimensions = [
'width' => $iNewWidth,
- 'height' =>$iNewHeight
+ 'height' => $iNewHeight,
];
// Preserve transparency
- if($this->GetMimeType() == "image/gif" || $this->GetMimeType() == "image/png") {
+ if ($this->GetMimeType() == "image/gif" || $this->GetMimeType() == "image/png") {
imagecolortransparent($oNewGdImage, imagecolorallocatealpha($oNewGdImage, 0, 0, 0, 127));
imagealphablending($oNewGdImage, false);
imagesavealpha($oNewGdImage, true);
@@ -473,16 +472,16 @@ class ormDocument
ob_start();
switch ($this->GetMimeType()) {
case 'image/gif':
- imagegif($oNewGdImage); // send image to output buffer
- break;
+ imagegif($oNewGdImage); // send image to output buffer
+ break;
case 'image/jpeg':
- imagejpeg($oNewGdImage, null, 80); // null = send image to output buffer, 80 = good quality
- break;
+ imagejpeg($oNewGdImage, null, 80); // null = send image to output buffer, 80 = good quality
+ break;
case 'image/png':
- imagepng($oNewGdImage, null, 5); // null = send image to output buffer, 5 = medium compression
- break;
+ imagepng($oNewGdImage, null, 5); // null = send image to output buffer, 5 = medium compression
+ break;
}
$oResampledImage = new ormDocument(ob_get_contents(), $this->GetMimeType(), $this->GetFileName());
@ob_end_clean();
@@ -502,5 +501,4 @@ class ormDocument
return md5($this->GetData() ?? '');
}
-
}
diff --git a/core/ormlinkset.class.inc.php b/core/ormlinkset.class.inc.php
index 872b6e3bf..56573dc51 100644
--- a/core/ormlinkset.class.inc.php
+++ b/core/ormlinkset.class.inc.php
@@ -1,4 +1,5 @@
DBObject
*/
- protected $aPreserved = array();
+ protected $aPreserved = [];
/**
* @var DBObject[] New items
*/
- protected $aAdded = array();
+ protected $aAdded = [];
/**
* @var DBObject[] Modified items (could also be found in aPreserved)
*/
- protected $aModified = array();
+ protected $aModified = [];
/**
* @var int[] Removed items
*/
- protected $aRemoved = array();
+ protected $aRemoved = [];
/**
* @var int Position in the collection
@@ -100,13 +100,11 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
$this->oOriginalSet = $oOriginalSet ? clone $oOriginalSet : null;
$oAttDef = MetaModel::GetAttributeDef($sHostClass, $sAttCode);
- if (!$oAttDef instanceof AttributeLinkedSet)
- {
+ if (!$oAttDef instanceof AttributeLinkedSet) {
throw new Exception("ormLinkSet: $sAttCode is not a link set");
}
$this->sClass = $oAttDef->GetLinkedClass();
- if ($oOriginalSet && ($oOriginalSet->GetClass() != $this->sClass))
- {
+ if ($oOriginalSet && ($oOriginalSet->GetClass() != $this->sClass)) {
throw new Exception("ormLinkSet: wrong class for the original set, found {$oOriginalSet->GetClass()} while expecting {$oAttDef->GetLinkedClass()}");
}
}
@@ -140,7 +138,7 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
{
assert($oLink instanceof $this->sClass);
// No impact on the iteration algorithm
- $iObjectId = $oLink->GetKey();
+ $iObjectId = $oLink->GetKey();
$this->aAdded[$iObjectId] = $oLink;
$this->bHasDelta = true;
}
@@ -150,19 +148,15 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
*/
public function RemoveItem($iObjectId)
{
- if (array_key_exists($iObjectId, $this->aPreserved))
- {
+ if (array_key_exists($iObjectId, $this->aPreserved)) {
unset($this->aPreserved[$iObjectId]);
$this->aRemoved[$iObjectId] = $iObjectId;
$this->bHasDelta = true;
+ } else {
+ if (array_key_exists($iObjectId, $this->aAdded)) {
+ unset($this->aAdded[$iObjectId]);
+ }
}
- else
- {
- if (array_key_exists($iObjectId, $this->aAdded))
- {
- unset($this->aAdded[$iObjectId]);
- }
- }
}
/**
@@ -173,12 +167,11 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
assert($oLink instanceof $this->sClass);
$iObjectId = $oLink->GetKey();
- if (array_key_exists($iObjectId, $this->aPreserved))
- {
- unset($this->aPreserved[$iObjectId]);
- $this->aModified[$iObjectId] = $oLink;
- $this->bHasDelta = true;
- }
+ if (array_key_exists($iObjectId, $this->aPreserved)) {
+ unset($this->aPreserved[$iObjectId]);
+ $this->aModified[$iObjectId] = $oLink;
+ $this->bHasDelta = true;
+ }
}
/**
@@ -188,33 +181,25 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
*/
protected function LoadOriginalIds()
{
- if ($this->aOriginalObjects === null)
- {
- if ($this->oOriginalSet)
- {
+ if ($this->aOriginalObjects === null) {
+ if ($this->oOriginalSet) {
$this->aOriginalObjects = $this->GetArrayOfIndex();
$this->aPreserved = $this->aOriginalObjects; // Copy (not effective until aPreserved gets modified)
- foreach ($this->aRemoved as $iObjectId)
- {
- if (array_key_exists($iObjectId, $this->aPreserved))
- {
- unset($this->aPreserved[$iObjectId]);
- }
- }
- foreach ($this->aModified as $iObjectId => $oLink)
- {
- if (array_key_exists($iObjectId, $this->aPreserved))
- {
- unset($this->aPreserved[$iObjectId]);
- }
- }
- }
- else
- {
+ foreach ($this->aRemoved as $iObjectId) {
+ if (array_key_exists($iObjectId, $this->aPreserved)) {
+ unset($this->aPreserved[$iObjectId]);
+ }
+ }
+ foreach ($this->aModified as $iObjectId => $oLink) {
+ if (array_key_exists($iObjectId, $this->aPreserved)) {
+ unset($this->aPreserved[$iObjectId]);
+ }
+ }
+ } else {
// Nothing to load
- $this->aOriginalObjects = array();
- $this->aPreserved = array();
+ $this->aOriginalObjects = [];
+ $this->aPreserved = [];
}
}
}
@@ -230,39 +215,34 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
*/
protected function GetArrayOfIndex()
{
- $aRet = array();
+ $aRet = [];
$this->oOriginalSet->Rewind();
$iRow = 0;
- while ($oObject = $this->oOriginalSet->Fetch())
- {
+ while ($oObject = $this->oOriginalSet->Fetch()) {
$aRet[$oObject->GetKey()] = $iRow++;
}
return $aRet;
}
- /**
- * @param string $sAttCode
- * @param bool $bWithId
- * @return array
- */
- public function GetColumnAsArray($sAttCode, $bWithId = true)
- {
- $aRet = array();
- foreach($this as $oItem)
- {
- if ($bWithId)
- {
- $aRet[$oItem->GetKey()] = $oItem->Get($sAttCode);
- }
- else
- {
- $aRet[] = $oItem->Get($sAttCode);
- }
- }
- return $aRet;
- }
+ /**
+ * @param string $sAttCode
+ * @param bool $bWithId
+ * @return array
+ */
+ public function GetColumnAsArray($sAttCode, $bWithId = true)
+ {
+ $aRet = [];
+ foreach ($this as $oItem) {
+ if ($bWithId) {
+ $aRet[$oItem->GetKey()] = $oItem->Get($sAttCode);
+ } else {
+ $aRet[] = $oItem->Get($sAttCode);
+ }
+ }
+ return $aRet;
+ }
- /**
+ /**
* The class of the objects of the collection (at least a common ancestor)
*
* @return string
@@ -300,13 +280,11 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
$this->LoadOriginalIds();
$iCount = $this->Count();
- if ($iPosition >= $iCount)
- {
+ if ($iPosition >= $iCount) {
throw new Exception("Invalid position $iPosition: the link set is made of $iCount items.");
}
$this->rewind();
- for($iPos = 0 ; $iPos < $iPosition ; $iPos++)
- {
+ for ($iPos = 0 ; $iPos < $iPosition ; $iPos++) {
$this->next();
}
}
@@ -324,8 +302,7 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
$this->LoadOriginalIds();
$ret = $this->current();
- if ($ret === false)
- {
+ if ($ret === false) {
$ret = null;
}
$this->next();
@@ -350,22 +327,16 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
$this->LoadOriginalIds();
$iPreservedCount = count($this->aPreserved);
- if ($this->iCursor < $iPreservedCount)
- {
+ if ($this->iCursor < $iPreservedCount) {
$sId = key($this->aPreserved);
$oRet = MetaModel::GetObject($this->sClass, $sId);
- }
- else
- {
- $iModifiedCount = count($this->aModified);
- if($this->iCursor < $iPreservedCount + $iModifiedCount)
- {
- $oRet = current($this->aModified);
- }
- else
- {
- $oRet = current($this->aAdded);
- }
+ } else {
+ $iModifiedCount = count($this->aModified);
+ if ($this->iCursor < $iPreservedCount + $iModifiedCount) {
+ $oRet = current($this->aModified);
+ } else {
+ $oRet = current($this->aAdded);
+ }
}
return $oRet;
}
@@ -384,21 +355,15 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
$this->LoadOriginalIds();
$iPreservedCount = count($this->aPreserved);
- if ($this->iCursor < $iPreservedCount)
- {
+ if ($this->iCursor < $iPreservedCount) {
next($this->aPreserved);
- }
- else
- {
- $iModifiedCount = count($this->aModified);
- if($this->iCursor < $iPreservedCount + $iModifiedCount)
- {
- next($this->aModified);
- }
- else
- {
- next($this->aAdded);
- }
+ } else {
+ $iModifiedCount = count($this->aModified);
+ if ($this->iCursor < $iPreservedCount + $iModifiedCount) {
+ next($this->aModified);
+ } else {
+ next($this->aAdded);
+ }
}
// Increment AFTER moving the internal cursors because when starting aModified / aAdded, we must leave it intact
$this->iCursor++;
@@ -446,12 +411,12 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
*/
public function rewind(): void
{
- $this->LoadOriginalIds();
+ $this->LoadOriginalIds();
- $this->iCursor = 0;
+ $this->iCursor = 0;
reset($this->aPreserved);
- reset($this->aAdded);
- reset($this->aModified);
+ reset($this->aAdded);
+ reset($this->aModified);
}
/**
@@ -473,19 +438,14 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
public function Equals(ormLinkSet $oFellow)
{
$bRet = null;
- if ($this === $oFellow)
- {
+ if ($this === $oFellow) {
$bRet = true;
- }
- else
- {
- if ( ($this->oOriginalSet !== $oFellow->oOriginalSet)
- && ($this->oOriginalSet->GetFilter()->ToOQL() != $oFellow->oOriginalSet->GetFilter()->ToOQL()) )
- {
+ } else {
+ if (($this->oOriginalSet !== $oFellow->oOriginalSet)
+ && ($this->oOriginalSet->GetFilter()->ToOQL() != $oFellow->oOriginalSet->GetFilter()->ToOQL())) {
throw new Exception('ormLinkSet::Equals assumes that compared link sets have the same original scope');
}
- if ($this->HasDelta())
- {
+ if ($this->HasDelta()) {
throw new Exception('ormLinkSet::Equals assumes that left link set had no delta');
}
$bRet = !$oFellow->HasDelta();
@@ -501,16 +461,13 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
*/
public function UpdateFromCompleteList(iDBObjectSetIterator $oFellow)
{
- if ($oFellow === $this)
- {
+ if ($oFellow === $this) {
throw new Exception('ormLinkSet::UpdateFromCompleteList assumes that the passed link set is at least a clone of the current one');
}
$bUpdateFromDelta = false;
- if ($oFellow instanceof ormLinkSet)
- {
- if ( ($this->oOriginalSet === $oFellow->oOriginalSet)
- || ($this->oOriginalSet->GetFilter()->ToOQL() == $oFellow->oOriginalSet->GetFilter()->ToOQL()) )
- {
+ if ($oFellow instanceof ormLinkSet) {
+ if (($this->oOriginalSet === $oFellow->oOriginalSet)
+ || ($this->oOriginalSet->GetFilter()->ToOQL() == $oFellow->oOriginalSet->GetFilter()->ToOQL())) {
$bUpdateFromDelta = true;
}
} else {
@@ -526,8 +483,7 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
}
}
- if ($bUpdateFromDelta)
- {
+ if ($bUpdateFromDelta) {
// Same original set -> simply update the delta
$this->iCursor = 0;
$this->aAdded = $oFellow->aAdded;
@@ -535,42 +491,36 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
$this->aModified = $oFellow->aModified;
$this->aPreserved = $oFellow->aPreserved;
$this->bHasDelta = $oFellow->bHasDelta;
- }
- else
- {
+ } else {
// For backward compatibility reasons, let's rebuild a delta...
// Reset the delta
$this->iCursor = 0;
- $this->aAdded = array();
- $this->aRemoved = array();
- $this->aModified = array();
- $this->aPreserved = ($this->aOriginalObjects === null) ? array() : $this->aOriginalObjects;
+ $this->aAdded = [];
+ $this->aRemoved = [];
+ $this->aModified = [];
+ $this->aPreserved = ($this->aOriginalObjects === null) ? [] : $this->aOriginalObjects;
$this->bHasDelta = false;
/** @var \AttributeLinkedSet|\AttributeLinkedSetIndirect $oAttDef */
$oAttDef = MetaModel::GetAttributeDef($this->sHostClass, $this->sAttCode);
$sExtKeyToMe = $oAttDef->GetExtKeyToMe();
$sAdditionalKey = null;
- if ($oAttDef->IsIndirect() && !$oAttDef->DuplicatesAllowed())
- {
+ if ($oAttDef->IsIndirect() && !$oAttDef->DuplicatesAllowed()) {
$sAdditionalKey = $oAttDef->GetExtKeyToRemote();
}
// Compare both collections by iterating the whole sets, order them, a build a fingerprint based on meaningful data (what make the difference)
/** @var \DBObject $oLink */
- $oComparator = new DBObjectSetComparator($this, $oFellow, array($sExtKeyToMe), $sAdditionalKey);
+ $oComparator = new DBObjectSetComparator($this, $oFellow, [$sExtKeyToMe], $sAdditionalKey);
$aChanges = $oComparator->GetDifferences();
- foreach ($aChanges['added'] as $oLink)
- {
+ foreach ($aChanges['added'] as $oLink) {
$this->AddItem($oLink);
}
- foreach ($aChanges['modified'] as $oLink)
- {
+ foreach ($aChanges['modified'] as $oLink) {
$this->ModifyItem($oLink);
}
- foreach ($aChanges['removed'] as $oLink)
- {
+ foreach ($aChanges['removed'] as $oLink) {
$this->RemoveItem($oLink->GetKey());
}
}
@@ -586,9 +536,8 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
{
$aAdded = $this->aAdded;
$aModified = $this->aModified;
- $aRemoved = array();
- if (count($this->aRemoved) > 0)
- {
+ $aRemoved = [];
+ if (count($this->aRemoved) > 0) {
$oSearch = new DBObjectSearch($this->sClass);
$oSearch->AddCondition('id', $this->aRemoved, 'IN');
$oSet = new DBObjectSet($oSearch);
@@ -618,30 +567,23 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
$sExtKeyToMe = $oAttDef->GetExtKeyToMe();
$sExtKeyToRemote = $oAttDef->IsIndirect() ? $oAttDef->GetExtKeyToRemote() : 'n/a';
- $aCheckLinks = array();
- $aCheckRemote = array();
- foreach ($this->aAdded as $oLink)
- {
- if ($oLink->IsNew())
- {
- if ($oAttDef->IsIndirect() && !$oAttDef->DuplicatesAllowed())
- {
+ $aCheckLinks = [];
+ $aCheckRemote = [];
+ foreach ($this->aAdded as $oLink) {
+ if ($oLink->IsNew()) {
+ if ($oAttDef->IsIndirect() && !$oAttDef->DuplicatesAllowed()) {
//todo: faire un test qui passe dans cette branche !
$aCheckRemote[] = $oLink->Get($sExtKeyToRemote);
}
- }
- else
- {
+ } else {
//todo: faire un test qui passe dans cette branche !
$aCheckLinks[] = $oLink->GetKey();
}
}
- foreach ($this->aRemoved as $iLinkId)
- {
+ foreach ($this->aRemoved as $iLinkId) {
$aCheckLinks[] = $iLinkId;
}
- foreach ($this->aModified as $iLinkId => $oLink)
- {
+ foreach ($this->aModified as $iLinkId => $oLink) {
$aCheckLinks[] = $oLink->GetKey();
}
@@ -653,11 +595,10 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
// Check for the existing links
//
/** @var DBObject[] $aExistingLinks */
- $aExistingLinks = array();
+ $aExistingLinks = [];
/** @var Int[] $aExistingRemote */
- $aExistingRemote = array();
- if (count($aCheckLinks) > 0)
- {
+ $aExistingRemote = [];
+ if (count($aCheckLinks) > 0) {
$oSearch = new DBObjectSearch($this->sClass);
$oSearch->AddCondition('id', $aCheckLinks, 'IN');
$oSet = new DBObjectSet($oSearch);
@@ -666,8 +607,7 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
// Check for the existing remote objects
//
- if (count($aCheckRemote) > 0)
- {
+ if (count($aCheckRemote) > 0) {
$oSearch = new DBObjectSearch($this->sClass);
$oSearch->AddCondition($sExtKeyToMe, $oHostObject->GetKey(), '=');
$oSearch->AddCondition($sExtKeyToRemote, $aCheckRemote, 'IN');
@@ -677,33 +617,27 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
// Write the links according to the existing links
//
- foreach ($this->aAdded as $oLink)
- {
+ foreach ($this->aAdded as $oLink) {
// Make sure that the objects in the set point to "this"
$oLink->Set($sExtKeyToMe, $oHostObject->GetKey());
- if ($oLink->IsNew())
- {
- if (count($aCheckRemote) > 0)
- {
- $bIsDuplicate = false;
- foreach($aExistingRemote as $sLinkKey => $sExtKey)
- {
- if ($sExtKey == $oLink->Get($sExtKeyToRemote))
- {
- // Do not create a duplicate
- // + In the case of a remove action followed by an add action
- // of an existing link,
- // the final state to consider is add action,
- // so suppress the entry in the removed list.
- if (array_key_exists($sLinkKey, $this->aRemoved))
- {
- unset($this->aRemoved[$sLinkKey]);
- }
- $bIsDuplicate = true;
- break;
- }
- }
+ if ($oLink->IsNew()) {
+ if (count($aCheckRemote) > 0) {
+ $bIsDuplicate = false;
+ foreach ($aExistingRemote as $sLinkKey => $sExtKey) {
+ if ($sExtKey == $oLink->Get($sExtKeyToRemote)) {
+ // Do not create a duplicate
+ // + In the case of a remove action followed by an add action
+ // of an existing link,
+ // the final state to consider is add action,
+ // so suppress the entry in the removed list.
+ if (array_key_exists($sLinkKey, $this->aRemoved)) {
+ unset($this->aRemoved[$sLinkKey]);
+ }
+ $bIsDuplicate = true;
+ break;
+ }
+ }
if ($bIsDuplicate) {
continue;
}
@@ -781,8 +715,7 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
/** @var \AttributeLinkedSet|\AttributeLinkedSetIndirect $oAttDef */
$oAttDef = MetaModel::GetAttributeDef($this->sHostClass, $this->sAttCode);
$oLinkSearch = $this->GetFilter();
- if ($oAttDef->IsIndirect())
- {
+ if ($oAttDef->IsIndirect()) {
$oLinkSearch->RenameAlias($oLinkSearch->GetClassAlias(), self::LINK_ALIAS);
$sExtKeyToRemote = $oAttDef->GetExtKeyToRemote();
/** @var \AttributeExternalKey $oLinkingAttDef */
@@ -793,8 +726,7 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
$sTargetClass = $oLinkingAttDef->GetTargetClass();
$oRemoteClassSearch = new DBObjectSearch($sTargetClass, self::REMOTE_ALIAS);
- if (!$bShowObsolete && MetaModel::IsObsoletable($sTargetClass))
- {
+ if (!$bShowObsolete && MetaModel::IsObsoletable($sTargetClass)) {
$oNotObsolete = new BinaryExpression(
new FieldExpression('obsolescence_flag', self::REMOTE_ALIAS),
'=',
@@ -803,8 +735,7 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
$oRemoteClassSearch->AddConditionExpression($oNotObsolete);
}
- if (!utils::IsArchiveMode() && MetaModel::IsArchivable($sTargetClass))
- {
+ if (!utils::IsArchiveMode() && MetaModel::IsArchivable($sTargetClass)) {
$oNotArchived = new BinaryExpression(
new FieldExpression('archive_flag', self::REMOTE_ALIAS),
'=',
@@ -845,7 +776,7 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
*/
public function GetValues()
{
- $aValues = array();
+ $aValues = [];
foreach ($this->aPreserved as $sTagCode => $oTag) {
$aValues[] = $sTagCode;
}
diff --git a/core/ormstopwatch.class.inc.php b/core/ormstopwatch.class.inc.php
index 2f77667b3..0e4a673a3 100644
--- a/core/ormstopwatch.class.inc.php
+++ b/core/ormstopwatch.class.inc.php
@@ -1,9 +1,10 @@
iLastStart = $iLastStart;
$this->iStopped = $iStopped;
- $this->aThresholds = array();
+ $this->aThresholds = [];
}
/**
* Necessary for the triggers
- */
+ */
public function __toString()
{
return (string) $this->iTimeSpent;
@@ -64,12 +64,12 @@ class ormStopWatch
public function DefineThreshold($iPercent, $tDeadline = null, $bPassed = false, $bTriggered = false, $iOverrun = null, $aHighlightDef = null)
{
- $this->aThresholds[$iPercent] = array(
+ $this->aThresholds[$iPercent] = [
'deadline' => $tDeadline, // unix time (seconds)
'triggered' => $bTriggered,
'overrun' => $iOverrun,
'highlight' => $aHighlightDef, // array('code' => string, 'persistent' => boolean)
- );
+ ];
}
public function MarkThresholdAsTriggered($iPercent)
@@ -94,18 +94,14 @@ class ormStopWatch
*/
public function GetElapsedTime($oAttDef, $oObject)
{
- if (is_null($this->iLastStart))
- {
+ if (is_null($this->iLastStart)) {
return $this->GetTimeSpent();
- }
- else
- {
+ } else {
$iElapsed = $this->ComputeDuration($oObject, $oAttDef, $this->iLastStart, time());
return $this->iTimeSpent + $iElapsed;
}
}
-
public function GetStartDate()
{
return $this->iStarted;
@@ -123,39 +119,30 @@ class ormStopWatch
public function GetThresholdDate($iPercent)
{
- if (array_key_exists($iPercent, $this->aThresholds))
- {
+ if (array_key_exists($iPercent, $this->aThresholds)) {
return $this->aThresholds[$iPercent]['deadline'];
- }
- else
- {
+ } else {
return null;
}
}
public function GetOverrun($iPercent)
{
- if (array_key_exists($iPercent, $this->aThresholds))
- {
+ if (array_key_exists($iPercent, $this->aThresholds)) {
return $this->aThresholds[$iPercent]['overrun'];
- }
- else
- {
+ } else {
return null;
}
}
public function IsThresholdPassed($iPercent)
{
$bRet = false;
- if (array_key_exists($iPercent, $this->aThresholds))
- {
+ if (array_key_exists($iPercent, $this->aThresholds)) {
$aThresholdData = $this->aThresholds[$iPercent];
- if (!is_null($aThresholdData['deadline']) && ($aThresholdData['deadline'] <= time()))
- {
+ if (!is_null($aThresholdData['deadline']) && ($aThresholdData['deadline'] <= time())) {
$bRet = true;
}
- if (isset($aThresholdData['overrun']) && ($aThresholdData['overrun'] > 0))
- {
+ if (isset($aThresholdData['overrun']) && ($aThresholdData['overrun'] > 0)) {
$bRet = true;
}
}
@@ -163,34 +150,27 @@ class ormStopWatch
}
public function IsThresholdTriggered($iPercent)
{
- if (array_key_exists($iPercent, $this->aThresholds))
- {
+ if (array_key_exists($iPercent, $this->aThresholds)) {
return $this->aThresholds[$iPercent]['triggered'];
- }
- else
- {
+ } else {
return false;
}
}
-
+
public function GetHighlightCode()
{
$sCode = '';
// Process the thresholds in ascending order
- $aPercents = array();
- foreach($this->aThresholds as $iPercent => $aDefs)
- {
+ $aPercents = [];
+ foreach ($this->aThresholds as $iPercent => $aDefs) {
$aPercents[] = $iPercent;
}
sort($aPercents, SORT_NUMERIC);
- foreach($aPercents as $iPercent)
- {
+ foreach ($aPercents as $iPercent) {
$aDefs = $this->aThresholds[$iPercent];
- if (array_key_exists('highlight', $aDefs) && is_array($aDefs['highlight']) && $this->IsThresholdPassed($iPercent))
- {
+ if (array_key_exists('highlight', $aDefs) && is_array($aDefs['highlight']) && $this->IsThresholdPassed($iPercent)) {
// If persistant or SW running...
- if (($aDefs['highlight']['persistent'] == true) || (($aDefs['highlight']['persistent'] == false) && !is_null($this->iLastStart)))
- {
+ if (($aDefs['highlight']['persistent'] == true) || (($aDefs['highlight']['persistent'] == false) && !is_null($this->iLastStart))) {
$sCode = $aDefs['highlight']['code'];
}
}
@@ -200,47 +180,37 @@ class ormStopWatch
public function GetAsHTML($oAttDef, $oHostObject = null)
{
- $aProperties = array();
+ $aProperties = [];
$aProperties['States'] = implode(', ', $oAttDef->GetStates());
- if (is_null($this->iLastStart))
- {
- if (is_null($this->iStarted))
- {
+ if (is_null($this->iLastStart)) {
+ if (is_null($this->iStarted)) {
$aProperties['Elapsed'] = 'never started';
- }
- else
- {
+ } else {
$aProperties['Elapsed'] = $this->iTimeSpent.' s';
}
- }
- else
- {
- $aProperties['Elapsed'] = 'running ';
+ } else {
+ $aProperties['Elapsed'] = 'running ';
}
$aProperties['Started'] = $oAttDef->SecondsToDate($this->iStarted);
$aProperties['LastStart'] = $oAttDef->SecondsToDate($this->iLastStart);
$aProperties['Stopped'] = $oAttDef->SecondsToDate($this->iStopped);
- foreach ($this->aThresholds as $iPercent => $aThresholdData)
- {
+ foreach ($this->aThresholds as $iPercent => $aThresholdData) {
$sThresholdDesc = $oAttDef->SecondsToDate($aThresholdData['deadline']);
- if ($aThresholdData['triggered'])
- {
+ if ($aThresholdData['triggered']) {
$sThresholdDesc .= " TRIGGERED ";
}
- if ($aThresholdData['overrun'])
- {
+ if ($aThresholdData['overrun']) {
$sThresholdDesc .= " Overrun:".(int) $aThresholdData['overrun']." sec.";
}
$aProperties[$iPercent.'%'] = $sThresholdDesc;
}
$sRes = "";
$sRes .= "";
- foreach ($aProperties as $sProperty => $sValue)
- {
+ foreach ($aProperties as $sProperty => $sValue) {
$sRes .= "";
$sCell = str_replace("\n", " \n", $sValue ?? '');
$sRes .= "$sProperty $sCell ";
@@ -265,9 +235,8 @@ class ormStopWatch
/** @var \iMetricComputer $oComputer */
$oComputer = new $sMetricComputer();
- $aCallSpec = array($oComputer, 'ComputeMetric');
- if (!is_callable($aCallSpec))
- {
+ $aCallSpec = [$oComputer, 'ComputeMetric'];
+ if (!is_callable($aCallSpec)) {
throw new CoreException("Unknown class/verb '$sMetricComputer/ComputeMetric'");
}
@@ -287,14 +256,12 @@ class ormStopWatch
protected function ComputeDeadline($oObject, $oAttDef, $iPercent, $iStartTime, $iDurationSec)
{
$sWorkingTimeComputer = $oAttDef->Get('working_time_computing');
- if ($sWorkingTimeComputer == '')
- {
+ if ($sWorkingTimeComputer == '') {
$sWorkingTimeComputer = MetaModel::GetWorkingTime(get_class($oObject));
}
$oComputer = new $sWorkingTimeComputer();
- $aCallSpec = array($oComputer, 'GetDeadline');
- if (!is_callable($aCallSpec))
- {
+ $aCallSpec = [$oComputer, 'GetDeadline'];
+ if (!is_callable($aCallSpec)) {
throw new CoreException("Unknown class/verb '$sWorkingTimeComputer/GetDeadline'");
}
// GetDeadline($oObject, $iDuration, DateTime $oStartDate)
@@ -316,14 +283,12 @@ class ormStopWatch
protected function ComputeDuration($oObject, $oAttDef, $iStartTime, $iEndTime)
{
$sWorkingTimeComputer = $oAttDef->Get('working_time_computing');
- if ($sWorkingTimeComputer == '')
- {
+ if ($sWorkingTimeComputer == '') {
$sWorkingTimeComputer = MetaModel::GetWorkingTime(get_class($oObject));
}
$oComputer = new $sWorkingTimeComputer();
- $aCallSpec = array($oComputer, 'GetOpenDuration');
- if (!is_callable($aCallSpec))
- {
+ $aCallSpec = [$oComputer, 'GetOpenDuration'];
+ if (!is_callable($aCallSpec)) {
throw new CoreException("Unknown class/verb '$sWorkingTimeComputer/GetOpenDuration'");
}
// GetOpenDuration($oObject, DateTime $oStartDate, DateTime $oEndDate)
@@ -339,14 +304,12 @@ class ormStopWatch
$this->iStopped = null;
$this->iStarted = null;
- foreach ($this->aThresholds as $iPercent => &$aThresholdData)
- {
+ foreach ($this->aThresholds as $iPercent => &$aThresholdData) {
$aThresholdData['triggered'] = false;
$aThresholdData['overrun'] = null;
}
- if (!is_null($this->iLastStart))
- {
+ if (!is_null($this->iLastStart)) {
// Currently running... starting again from now!
$this->iStarted = time();
$this->iLastStart = time();
@@ -357,23 +320,20 @@ class ormStopWatch
/**
* Start or continue
* It is the responsibility of the caller to compute the deadlines
- * (to avoid computing twice for the same result)
- */
+ * (to avoid computing twice for the same result)
+ */
public function Start($oObject, $oAttDef, $iNow = null)
{
- if (!is_null($this->iLastStart))
- {
+ if (!is_null($this->iLastStart)) {
// Already started
return false;
}
- if (is_null($iNow))
- {
+ if (is_null($iNow)) {
$iNow = time();
}
- if (is_null($this->iStarted))
- {
+ if (is_null($this->iStarted)) {
$this->iStarted = $iNow;
}
$this->iLastStart = $iNow;
@@ -384,39 +344,31 @@ class ormStopWatch
/**
* Compute or recompute the goal and threshold deadlines
- */
+ */
public function ComputeDeadlines($oObject, $oAttDef)
{
- if (is_null($this->iLastStart))
- {
+ if (is_null($this->iLastStart)) {
// Currently stopped - do nothing
return false;
}
$iDurationGoal = $this->ComputeGoal($oObject, $oAttDef);
$iComputationRefTime = time();
- foreach ($this->aThresholds as $iPercent => &$aThresholdData)
- {
- if (is_null($iDurationGoal))
- {
+ foreach ($this->aThresholds as $iPercent => &$aThresholdData) {
+ if (is_null($iDurationGoal)) {
// No limit: leave null thresholds
$aThresholdData['deadline'] = null;
- }
- else
- {
+ } else {
$iThresholdDuration = round($iPercent * $iDurationGoal / 100);
- if (class_exists('WorkingTimeRecorder'))
- {
+ if (class_exists('WorkingTimeRecorder')) {
$sClass = get_class($oObject);
$sAttCode = $oAttDef->GetCode();
- WorkingTimeRecorder::Start($oObject, $iComputationRefTime, "ormStopWatch-Deadline-$iPercent-$sAttCode", 'Core:ExplainWTC:StopWatch-Deadline', array("Class:$sClass/Attribute:$sAttCode", $iPercent));
+ WorkingTimeRecorder::Start($oObject, $iComputationRefTime, "ormStopWatch-Deadline-$iPercent-$sAttCode", 'Core:ExplainWTC:StopWatch-Deadline', ["Class:$sClass/Attribute:$sAttCode", $iPercent]);
}
$iRemaining = $iThresholdDuration - $this->iTimeSpent;
- if ($iRemaining < 0)
- {
- if (class_exists('WorkingTimeRecorder'))
- {
+ if ($iRemaining < 0) {
+ if (class_exists('WorkingTimeRecorder')) {
$sClass = get_class($oObject);
$sKey = $oObject->GetKey();
$sAttCode = $oAttDef->GetCode();
@@ -428,13 +380,11 @@ class ormStopWatch
$aThresholdData['deadline'] = $this->ComputeDeadline($oObject, $oAttDef, $iPercent, $this->iLastStart, $iRemaining);
// OR $aThresholdData['deadline'] = $this->ComputeDeadline($oObject, $oAttDef, $iPercent, $this->iStarted, $iThresholdDuration);
- if (class_exists('WorkingTimeRecorder'))
- {
+ if (class_exists('WorkingTimeRecorder')) {
WorkingTimeRecorder::End();
}
}
- if (is_null($aThresholdData['deadline']) || ($aThresholdData['deadline'] > time()))
- {
+ if (is_null($aThresholdData['deadline']) || ($aThresholdData['deadline'] > time())) {
// The threshold is in the future, reset
$aThresholdData['triggered'] = false;
$aThresholdData['overrun'] = null;
@@ -452,51 +402,41 @@ class ormStopWatch
/**
* Stop counting if not already done
- */
+ */
public function Stop($oObject, $oAttDef, $iNow = null)
{
- if (is_null($this->iLastStart))
- {
+ if (is_null($this->iLastStart)) {
// Already stopped
return false;
}
- if (is_null($iNow))
- {
+ if (is_null($iNow)) {
$iNow = time();
}
- if (class_exists('WorkingTimeRecorder'))
- {
+ if (class_exists('WorkingTimeRecorder')) {
$sClass = get_class($oObject);
$sAttCode = $oAttDef->GetCode();
- WorkingTimeRecorder::Start($oObject, $iNow, "ormStopWatch-TimeSpent-$sAttCode", 'Core:ExplainWTC:StopWatch-TimeSpent', array("Class:$sClass/Attribute:$sAttCode"), true /*cumulative*/);
+ WorkingTimeRecorder::Start($oObject, $iNow, "ormStopWatch-TimeSpent-$sAttCode", 'Core:ExplainWTC:StopWatch-TimeSpent', ["Class:$sClass/Attribute:$sAttCode"], true /*cumulative*/);
}
$iElapsed = $this->ComputeDuration($oObject, $oAttDef, $this->iLastStart, $iNow);
$this->iTimeSpent = $this->iTimeSpent + $iElapsed;
- if (class_exists('WorkingTimeRecorder'))
- {
+ if (class_exists('WorkingTimeRecorder')) {
WorkingTimeRecorder::End();
}
- foreach ($this->aThresholds as $iPercent => &$aThresholdData)
- {
- if (!is_null($aThresholdData['deadline']) && ($iNow > $aThresholdData['deadline']))
- {
- if ($aThresholdData['overrun'] > 0)
- {
+ foreach ($this->aThresholds as $iPercent => &$aThresholdData) {
+ if (!is_null($aThresholdData['deadline']) && ($iNow > $aThresholdData['deadline'])) {
+ if ($aThresholdData['overrun'] > 0) {
// Accumulate from last start
$aThresholdData['overrun'] += $iElapsed;
- }
- else
- {
+ } else {
// First stop after the deadline has been passed
$iOverrun = $this->ComputeDuration($oObject, $oAttDef, $aThresholdData['deadline'], $iNow);
$aThresholdData['overrun'] = $iOverrun;
}
}
- if ($aThresholdData['overrun'] == 0)
- {
+ if ($aThresholdData['overrun'] == 0) {
$aThresholdData['deadline'] = null;
}
}
@@ -510,76 +450,65 @@ class ormStopWatch
/**
* CheckStopWatchThresholds
- * Implements the automatic actions
+ * Implements the automatic actions
*
* @package itopORM
*/
class CheckStopWatchThresholds implements iBackgroundProcess
{
public function GetPeriodicity()
- {
+ {
return 10; // seconds
}
public function Process($iTimeLimit)
{
- $aList = array();
- foreach (MetaModel::GetClasses() as $sClass)
- {
- foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
- {
- if ($oAttDef instanceof AttributeStopWatch)
- {
- foreach ($oAttDef->ListThresholds() as $iThreshold => $aThresholdData)
- {
+ $aList = [];
+ foreach (MetaModel::GetClasses() as $sClass) {
+ foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) {
+ if ($oAttDef instanceof AttributeStopWatch) {
+ foreach ($oAttDef->ListThresholds() as $iThreshold => $aThresholdData) {
$iPercent = $aThresholdData['percent']; // could be different than the index !
-
+
$sNow = date(AttributeDateTime::GetSQLFormat());
$sExpression = "SELECT $sClass WHERE {$sAttCode}_laststart AND {$sAttCode}_{$iThreshold}_triggered = 0 AND {$sAttCode}_{$iThreshold}_deadline < :now";
$oFilter = DBObjectSearch::FromOQL($sExpression);
- $oSet = new DBObjectSet($oFilter, array(), array('now' => $sNow));
- $oSet->OptimizeColumnLoad(array($sClass => array($sAttCode)));
- while ((time() < $iTimeLimit) && ($oObj = $oSet->Fetch()))
- {
+ $oSet = new DBObjectSet($oFilter, [], ['now' => $sNow]);
+ $oSet->OptimizeColumnLoad([$sClass => [$sAttCode]]);
+ while ((time() < $iTimeLimit) && ($oObj = $oSet->Fetch())) {
$sClass = get_class($oObj);
$aList[] = $sClass.'::'.$oObj->GetKey().' '.$sAttCode.' '.$iThreshold;
// Execute planned actions
//
- foreach ($aThresholdData['actions'] as $aActionData)
- {
+ foreach ($aThresholdData['actions'] as $aActionData) {
$sVerb = $aActionData['verb'];
$aParams = $aActionData['params'];
- $aValues = array();
- foreach($aParams as $def)
- {
- if (is_string($def))
- {
+ $aValues = [];
+ foreach ($aParams as $def) {
+ if (is_string($def)) {
// Old method (pre-2.1.0) non typed parameters
$aValues[] = $def;
- }
- else // if(is_array($def))
- {
+ } else { // if(is_array($def))
$sParamType = array_key_exists('type', $def) ? $def['type'] : 'string';
- switch($sParamType)
- {
+ switch ($sParamType) {
case 'int':
$value = (int)$def['value'];
break;
-
+
case 'float':
$value = (float)$def['value'];
break;
-
+
case 'bool':
$value = (bool)$def['value'];
break;
-
+
case 'reference':
$value = ${$def['value']};
break;
-
+
case 'string':
default:
$value = (string)$def['value'];
@@ -587,7 +516,7 @@ class CheckStopWatchThresholds implements iBackgroundProcess
$aValues[] = $value;
}
}
- $aCallSpec = array($oObj, $sVerb);
+ $aCallSpec = [$oObj, $sVerb];
call_user_func_array($aCallSpec, $aValues);
}
@@ -604,22 +533,18 @@ class CheckStopWatchThresholds implements iBackgroundProcess
}
// Activate any existing trigger
- //
+ //
$sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
$oTriggerSet = new DBObjectSet(
DBObjectSearch::FromOQL("SELECT TriggerOnThresholdReached AS t WHERE t.target_class IN ('$sClassList') AND stop_watch_code MATCHES :stop_watch_code AND threshold_index = :threshold_index"),
- array(), // order by
- array('stop_watch_code' => $sAttCode, 'threshold_index' => $iThreshold)
+ [], // order by
+ ['stop_watch_code' => $sAttCode, 'threshold_index' => $iThreshold]
);
- while ($oTrigger = $oTriggerSet->Fetch())
- {
- try
- {
+ while ($oTrigger = $oTriggerSet->Fetch()) {
+ try {
$oTrigger->DoActivate($oObj->ToArgs('this'));
- }
- catch(Exception $e)
- {
+ } catch (Exception $e) {
utils::EnrichRaisedException($oTrigger, $e);
}
}
diff --git a/core/restservices.class.inc.php b/core/restservices.class.inc.php
index 76661e3d9..02bf355f8 100644
--- a/core/restservices.class.inc.php
+++ b/core/restservices.class.inc.php
@@ -1,9 +1,10 @@
message = '';
$this->class = $sClass;
$this->key = $iId;
- $this->fields = array();
+ $this->fields = [];
}
/**
@@ -84,36 +85,32 @@ class ObjectResult
* @param boolean $bExtendedOutput Output all of the link set attributes ?
* @param integer $iCode An error code (RestResult::OK is no issue has been found)
* @param string $sMessage Description of the error if any, an empty string otherwise
- *
+ *
* @return ObjectResult
*/
- public static function FromDBObject(DBObject $oObj, ?array $aFieldSpec = null, $bExtendedOutput = false, $iCode = 0, $sMessage = '') : ObjectResult {
+ public static function FromDBObject(DBObject $oObj, ?array $aFieldSpec = null, $bExtendedOutput = false, $iCode = 0, $sMessage = ''): ObjectResult
+ {
$oObjRes = new ObjectResult($oObj::class, $oObj->GetKey());
$oObjRes->code = $iCode;
$oObjRes->message = $sMessage;
$aFields = null;
- if (!is_null($aFieldSpec))
- {
+ if (!is_null($aFieldSpec)) {
// Enum all classes in the hierarchy, starting with the current one
- foreach (MetaModel::EnumParentClasses($oObj::class, ENUM_PARENT_CLASSES_ALL, false) as $sRefClass)
- {
- if (array_key_exists($sRefClass, $aFieldSpec))
- {
+ foreach (MetaModel::EnumParentClasses($oObj::class, ENUM_PARENT_CLASSES_ALL, false) as $sRefClass) {
+ if (array_key_exists($sRefClass, $aFieldSpec)) {
$aFields = $aFieldSpec[$sRefClass];
break;
}
}
}
- if (is_null($aFields))
- {
+ if (is_null($aFields)) {
// No fieldspec given, or not found...
- $aFields = array('id', 'friendlyname');
+ $aFields = ['id', 'friendlyname'];
}
- foreach ($aFields as $sAttCode)
- {
+ foreach ($aFields as $sAttCode) {
$oObjRes->AddField($oObj, $sAttCode, $bExtendedOutput);
}
@@ -121,7 +118,6 @@ class ObjectResult
}
-
/**
* Helper to make an output value for a given attribute
*
@@ -138,48 +134,37 @@ class ObjectResult
*/
protected function MakeResultValue(DBObject $oObject, $sAttCode, $bExtendedOutput = false)
{
- if ($sAttCode == 'id')
- {
+ if ($sAttCode == 'id') {
$value = $oObject->GetKey();
- }
- else
- {
+ } else {
$sClass = get_class($oObject);
$oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
- if ($oAttDef instanceof AttributeLinkedSet)
- {
+ if ($oAttDef instanceof AttributeLinkedSet) {
// Iterate on the set and build an array of array of attcode=>value
$oSet = $oObject->Get($sAttCode);
- $value = array();
- while ($oLnk = $oSet->Fetch())
- {
+ $value = [];
+ while ($oLnk = $oSet->Fetch()) {
$sLnkRefClass = $bExtendedOutput ? get_class($oLnk) : $oAttDef->GetLinkedClass();
- $aLnkValues = array();
- foreach (MetaModel::ListAttributeDefs($sLnkRefClass) as $sLnkAttCode => $oLnkAttDef)
- {
+ $aLnkValues = [];
+ foreach (MetaModel::ListAttributeDefs($sLnkRefClass) as $sLnkAttCode => $oLnkAttDef) {
// Skip attributes pointing to the current object (redundant data)
- if ($sLnkAttCode == $oAttDef->GetExtKeyToMe())
- {
+ if ($sLnkAttCode == $oAttDef->GetExtKeyToMe()) {
continue;
}
// Skip any attribute of the link that points to the current object
$oLnkAttDef = MetaModel::GetAttributeDef($sLnkRefClass, $sLnkAttCode);
- if (method_exists($oLnkAttDef, 'GetKeyAttCode'))
- {
- if ($oLnkAttDef->GetKeyAttCode() == $oAttDef->GetExtKeyToMe())
- {
+ if (method_exists($oLnkAttDef, 'GetKeyAttCode')) {
+ if ($oLnkAttDef->GetKeyAttCode() == $oAttDef->GetExtKeyToMe()) {
continue;
}
}
-
+
$aLnkValues[$sLnkAttCode] = $this->MakeResultValue($oLnk, $sLnkAttCode, $bExtendedOutput);
}
$value[] = $aLnkValues;
}
- }
- else
- {
+ } else {
$value = $oAttDef->GetForJSON($oObject->Get($sAttCode));
}
}
@@ -207,19 +192,17 @@ class ObjectResult
public function SanitizeContent()
{
- foreach($this->fields as $sFieldAttCode => $fieldValue) {
- try {
- $oAttDef = MetaModel::GetAttributeDef($this->class, $sFieldAttCode);
- } catch (Exception $e) { // for special cases like ID
- continue;
- }
+ foreach ($this->fields as $sFieldAttCode => $fieldValue) {
+ try {
+ $oAttDef = MetaModel::GetAttributeDef($this->class, $sFieldAttCode);
+ } catch (Exception $e) { // for special cases like ID
+ continue;
+ }
$this->SanitizeFieldIfSensitive($this->fields, $sFieldAttCode, $fieldValue, $oAttDef);
}
}
}
-
-
/**
* REST response for services managing objects. Derive this structure to add information and/or constants
*
@@ -255,12 +238,11 @@ class RestResultWithObjects extends RestResult
$this->objects[$sObjKey] = $oObjRes;
}
-public function SanitizeContent()
+ public function SanitizeContent()
{
parent::SanitizeContent();
- foreach($this->objects as $sObjKey => $oObjRes)
- {
+ foreach ($this->objects as $sObjKey => $oObjRes) {
$oObjRes->SanitizeContent();
}
}
@@ -280,7 +262,7 @@ class RestResultWithRelations extends RestResultWithObjects
public function __construct()
{
parent::__construct();
- $this->relations = array();
+ $this->relations = [];
}
/**
@@ -292,11 +274,10 @@ class RestResultWithRelations extends RestResultWithObjects
*/
public function AddRelation($sSrcKey, $sDestKey)
{
- if (!array_key_exists($sSrcKey, $this->relations))
- {
- $this->relations[$sSrcKey] = array();
+ if (!array_key_exists($sSrcKey, $this->relations)) {
+ $this->relations[$sSrcKey] = [];
}
- $this->relations[$sSrcKey][] = array('key' => $sDestKey);
+ $this->relations[$sSrcKey][] = ['key' => $sDestKey];
}
}
@@ -305,7 +286,7 @@ class RestResultWithRelations extends RestResultWithObjects
*
* @package RESTAPI
* @api
- * @since 2.0.1
+ * @since 2.0.1
*/
class RestDelete
{
@@ -313,37 +294,37 @@ class RestDelete
* Result: Object deleted as per the initial request
* @api
*/
- const OK = 0;
+ public const OK = 0;
/**
* Result: general issue (user rights or ... ?)
* @api
*/
- const ISSUE = 1;
+ public const ISSUE = 1;
/**
* Result: Must be deleted to preserve database integrity
* @api
*/
- const AUTO_DELETE = 2;
+ public const AUTO_DELETE = 2;
/**
* Result: Must be deleted to preserve database integrity, but that is NOT possible
* @api
*/
- const AUTO_DELETE_ISSUE = 3;
+ public const AUTO_DELETE_ISSUE = 3;
/**
* Result: Must be deleted to preserve database integrity, but this must be requested explicitly
* @api
*/
- const REQUEST_EXPLICITELY = 4;
+ public const REQUEST_EXPLICITELY = 4;
/**
* Result: Must be updated to preserve database integrity
* @api
*/
- const AUTO_UPDATE = 5;
+ public const AUTO_UPDATE = 5;
/**
* Result: Must be updated to preserve database integrity, but that is NOT possible
* @api
*/
- const AUTO_UPDATE_ISSUE = 6;
+ public const AUTO_UPDATE_ISSUE = 6;
}
/**
@@ -353,10 +334,10 @@ class RestDelete
*/
class CoreServices implements iRestServiceProvider, iRestInputSanitizer
{
- use SanitizeTrait;
- /**
+ use SanitizeTrait;
+ /**
* Enumerate services delivered by this class
- *
+ *
* @param string $sVersion The version (e.g. 1.0) supported by the services
* @return array An array of hash 'verb' => verb, 'description' => description
*/
@@ -368,37 +349,36 @@ class CoreServices implements iRestServiceProvider, iRestInputSanitizer
// 1.1 - In the reply, objects have a 'key' entry so that it is no more necessary to split class::key programmaticaly
// 1.0 - Initial implementation in iTop 2.0.1
//
- $aOps = array();
- if (in_array($sVersion, array('1.0', '1.1', '1.2', '1.3', '1.4')))
- {
- $aOps[] = array(
+ $aOps = [];
+ if (in_array($sVersion, ['1.0', '1.1', '1.2', '1.3', '1.4'])) {
+ $aOps[] = [
'verb' => 'core/create',
- 'description' => 'Create an object'
- );
- $aOps[] = array(
+ 'description' => 'Create an object',
+ ];
+ $aOps[] = [
'verb' => 'core/update',
- 'description' => 'Update an object'
- );
- $aOps[] = array(
+ 'description' => 'Update an object',
+ ];
+ $aOps[] = [
'verb' => 'core/apply_stimulus',
- 'description' => 'Apply a stimulus to change the state of an object'
- );
- $aOps[] = array(
+ 'description' => 'Apply a stimulus to change the state of an object',
+ ];
+ $aOps[] = [
'verb' => 'core/get',
- 'description' => 'Search for objects'
- );
- $aOps[] = array(
+ 'description' => 'Search for objects',
+ ];
+ $aOps[] = [
'verb' => 'core/delete',
- 'description' => 'Delete objects'
- );
- $aOps[] = array(
+ 'description' => 'Delete objects',
+ ];
+ $aOps[] = [
'verb' => 'core/get_related',
- 'description' => 'Get related objects through the specified relation'
- );
- $aOps[] = array(
+ 'description' => 'Get related objects through the specified relation',
+ ];
+ $aOps[] = [
'verb' => 'core/check_credentials',
- 'description' => 'Check user credentials'
- );
+ 'description' => 'Check user credentials',
+ ];
}
return $aOps;
}
@@ -419,457 +399,355 @@ class CoreServices implements iRestServiceProvider, iRestInputSanitizer
public function ExecOperation($sVersion, $sVerb, $aParams)
{
$oResult = new RestResultWithObjects();
- switch ($sVerb)
- {
- case 'core/create':
- RestUtils::InitTrackingComment($aParams);
- $sClass = RestUtils::GetClass($aParams, 'class');
- $aFields = RestUtils::GetMandatoryParam($aParams, 'fields');
- $aShowFields = RestUtils::GetFieldList($sClass, $aParams, 'output_fields');
- $bExtendedOutput = (RestUtils::GetOptionalParam($aParams, 'output_fields', '*') == '*+');
+ switch ($sVerb) {
+ case 'core/create':
+ RestUtils::InitTrackingComment($aParams);
+ $sClass = RestUtils::GetClass($aParams, 'class');
+ $aFields = RestUtils::GetMandatoryParam($aParams, 'fields');
+ $aShowFields = RestUtils::GetFieldList($sClass, $aParams, 'output_fields');
+ $bExtendedOutput = (RestUtils::GetOptionalParam($aParams, 'output_fields', '*') == '*+');
- if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) != UR_ALLOWED_YES)
- {
- $oResult->code = RestResult::UNAUTHORIZED;
- $oResult->message = "The current user does not have enough permissions for creating data of class $sClass";
- }
- elseif (UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_MODIFY) != UR_ALLOWED_YES)
- {
- $oResult->code = RestResult::UNAUTHORIZED;
- $oResult->message = "The current user does not have enough permissions for massively creating data of class $sClass";
- }
- else
- {
- $oObject = RestUtils::MakeObjectFromFields($sClass, $aFields);
- $oObject->DBInsert();
- $oResult->AddObject(0, 'created', $oObject, $aShowFields, $bExtendedOutput);
- }
- break;
-
- case 'core/update':
- RestUtils::InitTrackingComment($aParams);
- $sClass = RestUtils::GetClass($aParams, 'class');
- $key = RestUtils::GetMandatoryParam($aParams, 'key');
- $aFields = RestUtils::GetMandatoryParam($aParams, 'fields');
- $aShowFields = RestUtils::GetFieldList($sClass, $aParams, 'output_fields');
- $bExtendedOutput = (RestUtils::GetOptionalParam($aParams, 'output_fields', '*') == '*+');
-
- // Note: the target class cannot be based on the result of FindObjectFromKey, because in case the user does not have read access, that function already fails with msg 'Nothing found'
- $sTargetClass = RestUtils::GetObjectSetFromKey($sClass, $key)->GetFilter()->GetClass();
- if (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_MODIFY) != UR_ALLOWED_YES)
- {
- $oResult->code = RestResult::UNAUTHORIZED;
- $oResult->message = "The current user does not have enough permissions for modifying data of class $sTargetClass";
- }
- elseif (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_MODIFY) != UR_ALLOWED_YES)
- {
- $oResult->code = RestResult::UNAUTHORIZED;
- $oResult->message = "The current user does not have enough permissions for massively modifying data of class $sTargetClass";
- }
- else
- {
- $oObject = RestUtils::FindObjectFromKey($sClass, $key);
- RestUtils::UpdateObjectFromFields($oObject, $aFields);
- $oObject->DBUpdate();
- $oResult->AddObject(0, 'updated', $oObject, $aShowFields, $bExtendedOutput);
- }
- break;
-
- case 'core/apply_stimulus':
- RestUtils::InitTrackingComment($aParams);
- $sClass = RestUtils::GetClass($aParams, 'class');
- $key = RestUtils::GetMandatoryParam($aParams, 'key');
- $aFields = RestUtils::GetMandatoryParam($aParams, 'fields');
- $aShowFields = RestUtils::GetFieldList($sClass, $aParams, 'output_fields');
- $bExtendedOutput = (RestUtils::GetOptionalParam($aParams, 'output_fields', '*') == '*+');
- $sStimulus = RestUtils::GetMandatoryParam($aParams, 'stimulus');
-
- // Note: the target class cannot be based on the result of FindObjectFromKey, because in case the user does not have read access, that function already fails with msg 'Nothing found'
- $sTargetClass = RestUtils::GetObjectSetFromKey($sClass, $key)->GetFilter()->GetClass();
- if (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_MODIFY) != UR_ALLOWED_YES)
- {
- $oResult->code = RestResult::UNAUTHORIZED;
- $oResult->message = "The current user does not have enough permissions for modifying data of class $sTargetClass";
- }
- elseif (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_BULK_MODIFY) != UR_ALLOWED_YES)
- {
- $oResult->code = RestResult::UNAUTHORIZED;
- $oResult->message = "The current user does not have enough permissions for massively modifying data of class $sTargetClass";
- }
- else
- {
- $oObject = RestUtils::FindObjectFromKey($sClass, $key);
- RestUtils::UpdateObjectFromFields($oObject, $aFields);
-
- $aTransitions = $oObject->EnumTransitions();
- $aStimuli = MetaModel::EnumStimuli(get_class($oObject));
- if (!isset($aTransitions[$sStimulus]))
- {
- // Invalid stimulus
- $oResult->code = RestResult::INTERNAL_ERROR;
- $oResult->message = "Invalid stimulus: '$sStimulus' on the object ".$oObject->GetName()." in state '".$oObject->GetState()."'";
+ if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) != UR_ALLOWED_YES) {
+ $oResult->code = RestResult::UNAUTHORIZED;
+ $oResult->message = "The current user does not have enough permissions for creating data of class $sClass";
+ } elseif (UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_MODIFY) != UR_ALLOWED_YES) {
+ $oResult->code = RestResult::UNAUTHORIZED;
+ $oResult->message = "The current user does not have enough permissions for massively creating data of class $sClass";
+ } else {
+ $oObject = RestUtils::MakeObjectFromFields($sClass, $aFields);
+ $oObject->DBInsert();
+ $oResult->AddObject(0, 'created', $oObject, $aShowFields, $bExtendedOutput);
}
- else
- {
- $aTransition = $aTransitions[$sStimulus];
- $sTargetState = $aTransition['target_state'];
- $aStates = MetaModel::EnumStates($sClass);
- $aTargetStateDef = $aStates[$sTargetState];
- $aExpectedAttributes = $aTargetStateDef['attribute_list'];
-
- $aMissingMandatory = array();
- foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
- {
- if ( ($iExpectCode & OPT_ATT_MANDATORY) && ($oObject->Get($sAttCode) == ''))
- {
- $aMissingMandatory[] = $sAttCode;
- }
- }
- if (count($aMissingMandatory) == 0)
- {
- // If all the mandatory fields are already present, just apply the transition silently...
- if ($oObject->ApplyStimulus($sStimulus))
- {
- $oObject->DBUpdate();
- $oResult->AddObject(0, 'updated', $oObject, $aShowFields, $bExtendedOutput);
- }
- }
- else
- {
- // Missing mandatory attributes for the transition
+ break;
+
+ case 'core/update':
+ RestUtils::InitTrackingComment($aParams);
+ $sClass = RestUtils::GetClass($aParams, 'class');
+ $key = RestUtils::GetMandatoryParam($aParams, 'key');
+ $aFields = RestUtils::GetMandatoryParam($aParams, 'fields');
+ $aShowFields = RestUtils::GetFieldList($sClass, $aParams, 'output_fields');
+ $bExtendedOutput = (RestUtils::GetOptionalParam($aParams, 'output_fields', '*') == '*+');
+
+ // Note: the target class cannot be based on the result of FindObjectFromKey, because in case the user does not have read access, that function already fails with msg 'Nothing found'
+ $sTargetClass = RestUtils::GetObjectSetFromKey($sClass, $key)->GetFilter()->GetClass();
+ if (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_MODIFY) != UR_ALLOWED_YES) {
+ $oResult->code = RestResult::UNAUTHORIZED;
+ $oResult->message = "The current user does not have enough permissions for modifying data of class $sTargetClass";
+ } elseif (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_MODIFY) != UR_ALLOWED_YES) {
+ $oResult->code = RestResult::UNAUTHORIZED;
+ $oResult->message = "The current user does not have enough permissions for massively modifying data of class $sTargetClass";
+ } else {
+ $oObject = RestUtils::FindObjectFromKey($sClass, $key);
+ RestUtils::UpdateObjectFromFields($oObject, $aFields);
+ $oObject->DBUpdate();
+ $oResult->AddObject(0, 'updated', $oObject, $aShowFields, $bExtendedOutput);
+ }
+ break;
+
+ case 'core/apply_stimulus':
+ RestUtils::InitTrackingComment($aParams);
+ $sClass = RestUtils::GetClass($aParams, 'class');
+ $key = RestUtils::GetMandatoryParam($aParams, 'key');
+ $aFields = RestUtils::GetMandatoryParam($aParams, 'fields');
+ $aShowFields = RestUtils::GetFieldList($sClass, $aParams, 'output_fields');
+ $bExtendedOutput = (RestUtils::GetOptionalParam($aParams, 'output_fields', '*') == '*+');
+ $sStimulus = RestUtils::GetMandatoryParam($aParams, 'stimulus');
+
+ // Note: the target class cannot be based on the result of FindObjectFromKey, because in case the user does not have read access, that function already fails with msg 'Nothing found'
+ $sTargetClass = RestUtils::GetObjectSetFromKey($sClass, $key)->GetFilter()->GetClass();
+ if (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_MODIFY) != UR_ALLOWED_YES) {
+ $oResult->code = RestResult::UNAUTHORIZED;
+ $oResult->message = "The current user does not have enough permissions for modifying data of class $sTargetClass";
+ } elseif (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_BULK_MODIFY) != UR_ALLOWED_YES) {
+ $oResult->code = RestResult::UNAUTHORIZED;
+ $oResult->message = "The current user does not have enough permissions for massively modifying data of class $sTargetClass";
+ } else {
+ $oObject = RestUtils::FindObjectFromKey($sClass, $key);
+ RestUtils::UpdateObjectFromFields($oObject, $aFields);
+
+ $aTransitions = $oObject->EnumTransitions();
+ $aStimuli = MetaModel::EnumStimuli(get_class($oObject));
+ if (!isset($aTransitions[$sStimulus])) {
+ // Invalid stimulus
$oResult->code = RestResult::INTERNAL_ERROR;
- $oResult->message = 'Missing mandatory attribute(s) for applying the stimulus: '.implode(', ', $aMissingMandatory).'.';
+ $oResult->message = "Invalid stimulus: '$sStimulus' on the object ".$oObject->GetName()." in state '".$oObject->GetState()."'";
+ } else {
+ $aTransition = $aTransitions[$sStimulus];
+ $sTargetState = $aTransition['target_state'];
+ $aStates = MetaModel::EnumStates($sClass);
+ $aTargetStateDef = $aStates[$sTargetState];
+ $aExpectedAttributes = $aTargetStateDef['attribute_list'];
+
+ $aMissingMandatory = [];
+ foreach ($aExpectedAttributes as $sAttCode => $iExpectCode) {
+ if (($iExpectCode & OPT_ATT_MANDATORY) && ($oObject->Get($sAttCode) == '')) {
+ $aMissingMandatory[] = $sAttCode;
+ }
+ }
+ if (count($aMissingMandatory) == 0) {
+ // If all the mandatory fields are already present, just apply the transition silently...
+ if ($oObject->ApplyStimulus($sStimulus)) {
+ $oObject->DBUpdate();
+ $oResult->AddObject(0, 'updated', $oObject, $aShowFields, $bExtendedOutput);
+ }
+ } else {
+ // Missing mandatory attributes for the transition
+ $oResult->code = RestResult::INTERNAL_ERROR;
+ $oResult->message = 'Missing mandatory attribute(s) for applying the stimulus: '.implode(', ', $aMissingMandatory).'.';
+ }
}
}
- }
- break;
-
- case 'core/get':
- $sClass = RestUtils::GetClass($aParams, 'class');
- $key = RestUtils::GetMandatoryParam($aParams, 'key');
- $aShowFields = RestUtils::GetFieldList($sClass, $aParams, 'output_fields');
- $bExtendedOutput = (RestUtils::GetOptionalParam($aParams, 'output_fields', '*') == '*+');
- $iLimit = (int)RestUtils::GetOptionalParam($aParams, 'limit', 0);
- $iPage = (int)RestUtils::GetOptionalParam($aParams, 'page', 1);
+ break;
- $oObjectSet = RestUtils::GetObjectSetFromKey($sClass, $key, $iLimit, self::getOffsetFromLimitAndPage($iLimit, $iPage));
- $sTargetClass = $oObjectSet->GetFilter()->GetClass();
-
- if (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_READ) != UR_ALLOWED_YES)
- {
- $oResult->code = RestResult::UNAUTHORIZED;
- $oResult->message = "The current user does not have enough permissions for reading data of class $sTargetClass";
- }
- elseif (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_BULK_READ) != UR_ALLOWED_YES)
- {
- $oResult->code = RestResult::UNAUTHORIZED;
- $oResult->message = "The current user does not have enough permissions for exporting data of class $sTargetClass";
- }
- elseif ($iPage < 1)
- {
- $oResult->code = RestResult::INVALID_PAGE;
- $oResult->message = "The request page number is not valid. It must be an integer greater than 0";
- }
- else
- {
- if (!$bExtendedOutput && RestUtils::GetOptionalParam($aParams, 'output_fields', '*') != '*')
- {
- $aFields = $aShowFields[$sClass];
- //Id is not a valid attribute to optimize
- if (in_array('id', $aFields))
- {
- unset($aFields[array_search('id', $aFields)]);
- }
- $aAttToLoad = array($oObjectSet->GetClassAlias() => $aFields);
- $oObjectSet->OptimizeColumnLoad($aAttToLoad);
- }
+ case 'core/get':
+ $sClass = RestUtils::GetClass($aParams, 'class');
+ $key = RestUtils::GetMandatoryParam($aParams, 'key');
+ $aShowFields = RestUtils::GetFieldList($sClass, $aParams, 'output_fields');
+ $bExtendedOutput = (RestUtils::GetOptionalParam($aParams, 'output_fields', '*') == '*+');
+ $iLimit = (int)RestUtils::GetOptionalParam($aParams, 'limit', 0);
+ $iPage = (int)RestUtils::GetOptionalParam($aParams, 'page', 1);
- while ($oObject = $oObjectSet->Fetch())
- {
- $oResult->AddObject(0, '', $oObject, $aShowFields, $bExtendedOutput);
+ $oObjectSet = RestUtils::GetObjectSetFromKey($sClass, $key, $iLimit, self::getOffsetFromLimitAndPage($iLimit, $iPage));
+ $sTargetClass = $oObjectSet->GetFilter()->GetClass();
+
+ if (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_READ) != UR_ALLOWED_YES) {
+ $oResult->code = RestResult::UNAUTHORIZED;
+ $oResult->message = "The current user does not have enough permissions for reading data of class $sTargetClass";
+ } elseif (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_BULK_READ) != UR_ALLOWED_YES) {
+ $oResult->code = RestResult::UNAUTHORIZED;
+ $oResult->message = "The current user does not have enough permissions for exporting data of class $sTargetClass";
+ } elseif ($iPage < 1) {
+ $oResult->code = RestResult::INVALID_PAGE;
+ $oResult->message = "The request page number is not valid. It must be an integer greater than 0";
+ } else {
+ if (!$bExtendedOutput && RestUtils::GetOptionalParam($aParams, 'output_fields', '*') != '*') {
+ $aFields = $aShowFields[$sClass];
+ //Id is not a valid attribute to optimize
+ if (in_array('id', $aFields)) {
+ unset($aFields[array_search('id', $aFields)]);
+ }
+ $aAttToLoad = [$oObjectSet->GetClassAlias() => $aFields];
+ $oObjectSet->OptimizeColumnLoad($aAttToLoad);
+ }
+
+ while ($oObject = $oObjectSet->Fetch()) {
+ $oResult->AddObject(0, '', $oObject, $aShowFields, $bExtendedOutput);
+ }
+ $oResult->message = "Found: ".$oObjectSet->Count();
}
- $oResult->message = "Found: ".$oObjectSet->Count();
- }
- break;
+ break;
- case 'core/delete':
- RestUtils::InitTrackingComment($aParams);
- $sClass = RestUtils::GetClass($aParams, 'class');
- $key = RestUtils::GetMandatoryParam($aParams, 'key');
- $bSimulate = RestUtils::GetOptionalParam($aParams, 'simulate', false);
-
- $oObjectSet = RestUtils::GetObjectSetFromKey($sClass, $key);
- $sTargetClass = $oObjectSet->GetFilter()->GetClass();
-
- if (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_DELETE) != UR_ALLOWED_YES)
- {
- $oResult->code = RestResult::UNAUTHORIZED;
- $oResult->message = "The current user does not have enough permissions for deleting data of class $sTargetClass";
- }
- elseif (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_DELETE) != UR_ALLOWED_YES)
- {
- $oResult->code = RestResult::UNAUTHORIZED;
- $oResult->message = "The current user does not have enough permissions for massively deleting data of class $sTargetClass";
- }
- else
- {
- $aObjects = $oObjectSet->ToArray();
- $this->DeleteObjects($oResult, $aObjects, $bSimulate);
- }
- break;
+ case 'core/delete':
+ RestUtils::InitTrackingComment($aParams);
+ $sClass = RestUtils::GetClass($aParams, 'class');
+ $key = RestUtils::GetMandatoryParam($aParams, 'key');
+ $bSimulate = RestUtils::GetOptionalParam($aParams, 'simulate', false);
- case 'core/get_related':
- $oResult = new RestResultWithRelations();
- $sClass = RestUtils::GetClass($aParams, 'class');
- $key = RestUtils::GetMandatoryParam($aParams, 'key');
- $sRelation = RestUtils::GetMandatoryParam($aParams, 'relation');
- $iMaxRecursionDepth = RestUtils::GetOptionalParam($aParams, 'depth', 20 /* = MAX_RECURSION_DEPTH */);
- $sDirection = RestUtils::GetOptionalParam($aParams, 'direction', null);
- $bEnableRedundancy = RestUtils::GetOptionalParam($aParams, 'redundancy', false);
- $bReverse = false;
+ $oObjectSet = RestUtils::GetObjectSetFromKey($sClass, $key);
+ $sTargetClass = $oObjectSet->GetFilter()->GetClass();
- if (is_null($sDirection) && ($sRelation == 'depends on'))
- {
- // Legacy behavior, consider "depends on" as a forward relation
- $sRelation = 'impacts';
- $sDirection = 'up';
- $bReverse = true; // emulate the legacy behavior by returning the edges
- }
- else if(is_null($sDirection))
- {
- $sDirection = 'down';
- }
-
- $oObjectSet = RestUtils::GetObjectSetFromKey($sClass, $key);
- if ($sDirection == 'down')
- {
- $oRelationGraph = $oObjectSet->GetRelatedObjectsDown($sRelation, $iMaxRecursionDepth, $bEnableRedundancy);
- }
- else if ($sDirection == 'up')
- {
- $oRelationGraph = $oObjectSet->GetRelatedObjectsUp($sRelation, $iMaxRecursionDepth, $bEnableRedundancy);
- }
- else
- {
- $oResult->code = RestResult::INTERNAL_ERROR;
- $oResult->message = "Invalid value: '$sDirection' for the parameter 'direction'. Valid values are 'up' and 'down'";
- return $oResult;
-
- }
-
- if ($bEnableRedundancy)
- {
- // Remove the redundancy nodes from the output
- $oIterator = new RelationTypeIterator($oRelationGraph, 'Node');
- foreach($oIterator as $oNode)
- {
- if ($oNode instanceof RelationRedundancyNode)
- {
- $oRelationGraph->FilterNode($oNode);
+ if (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_DELETE) != UR_ALLOWED_YES) {
+ $oResult->code = RestResult::UNAUTHORIZED;
+ $oResult->message = "The current user does not have enough permissions for deleting data of class $sTargetClass";
+ } elseif (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_DELETE) != UR_ALLOWED_YES) {
+ $oResult->code = RestResult::UNAUTHORIZED;
+ $oResult->message = "The current user does not have enough permissions for massively deleting data of class $sTargetClass";
+ } else {
+ $aObjects = $oObjectSet->ToArray();
+ $this->DeleteObjects($oResult, $aObjects, $bSimulate);
+ }
+ break;
+
+ case 'core/get_related':
+ $oResult = new RestResultWithRelations();
+ $sClass = RestUtils::GetClass($aParams, 'class');
+ $key = RestUtils::GetMandatoryParam($aParams, 'key');
+ $sRelation = RestUtils::GetMandatoryParam($aParams, 'relation');
+ $iMaxRecursionDepth = RestUtils::GetOptionalParam($aParams, 'depth', 20 /* = MAX_RECURSION_DEPTH */);
+ $sDirection = RestUtils::GetOptionalParam($aParams, 'direction', null);
+ $bEnableRedundancy = RestUtils::GetOptionalParam($aParams, 'redundancy', false);
+ $bReverse = false;
+
+ if (is_null($sDirection) && ($sRelation == 'depends on')) {
+ // Legacy behavior, consider "depends on" as a forward relation
+ $sRelation = 'impacts';
+ $sDirection = 'up';
+ $bReverse = true; // emulate the legacy behavior by returning the edges
+ } elseif (is_null($sDirection)) {
+ $sDirection = 'down';
+ }
+
+ $oObjectSet = RestUtils::GetObjectSetFromKey($sClass, $key);
+ if ($sDirection == 'down') {
+ $oRelationGraph = $oObjectSet->GetRelatedObjectsDown($sRelation, $iMaxRecursionDepth, $bEnableRedundancy);
+ } elseif ($sDirection == 'up') {
+ $oRelationGraph = $oObjectSet->GetRelatedObjectsUp($sRelation, $iMaxRecursionDepth, $bEnableRedundancy);
+ } else {
+ $oResult->code = RestResult::INTERNAL_ERROR;
+ $oResult->message = "Invalid value: '$sDirection' for the parameter 'direction'. Valid values are 'up' and 'down'";
+ return $oResult;
+
+ }
+
+ if ($bEnableRedundancy) {
+ // Remove the redundancy nodes from the output
+ $oIterator = new RelationTypeIterator($oRelationGraph, 'Node');
+ foreach ($oIterator as $oNode) {
+ if ($oNode instanceof RelationRedundancyNode) {
+ $oRelationGraph->FilterNode($oNode);
+ }
}
}
- }
-
- $aIndexByClass = array();
- $oIterator = new RelationTypeIterator($oRelationGraph);
- foreach($oIterator as $oElement)
- {
- if ($oElement instanceof RelationObjectNode)
- {
- $oObject = $oElement->GetProperty('object');
- if ($oObject)
- {
- if ($bEnableRedundancy && $sDirection == 'down')
- {
- // Add only the "reached" objects
- if ($oElement->GetProperty('is_reached'))
- {
+
+ $aIndexByClass = [];
+ $oIterator = new RelationTypeIterator($oRelationGraph);
+ foreach ($oIterator as $oElement) {
+ if ($oElement instanceof RelationObjectNode) {
+ $oObject = $oElement->GetProperty('object');
+ if ($oObject) {
+ if ($bEnableRedundancy && $sDirection == 'down') {
+ // Add only the "reached" objects
+ if ($oElement->GetProperty('is_reached')) {
+ $aIndexByClass[get_class($oObject)][$oObject->GetKey()] = null;
+ $oResult->AddObject(0, '', $oObject);
+ }
+ } else {
$aIndexByClass[get_class($oObject)][$oObject->GetKey()] = null;
$oResult->AddObject(0, '', $oObject);
}
}
- else
- {
- $aIndexByClass[get_class($oObject)][$oObject->GetKey()] = null;
- $oResult->AddObject(0, '', $oObject);
- }
- }
- }
- else if ($oElement instanceof RelationEdge)
- {
- $oSrcObj = $oElement->GetSourceNode()->GetProperty('object');
- $oDestObj = $oElement->GetSinkNode()->GetProperty('object');
- $sSrcKey = get_class($oSrcObj).'::'.$oSrcObj->GetKey();
- $sDestKey = get_class($oDestObj).'::'.$oDestObj->GetKey();
- if ($bEnableRedundancy)
- {
- // Add only the edges where both source and destination are "reached"
- if ($oElement->GetSourceNode()->GetProperty('is_reached') && $oElement->GetSinkNode()->GetProperty('is_reached'))
- {
- if ($bReverse)
- {
- $oResult->AddRelation($sDestKey, $sSrcKey);
+ } elseif ($oElement instanceof RelationEdge) {
+ $oSrcObj = $oElement->GetSourceNode()->GetProperty('object');
+ $oDestObj = $oElement->GetSinkNode()->GetProperty('object');
+ $sSrcKey = get_class($oSrcObj).'::'.$oSrcObj->GetKey();
+ $sDestKey = get_class($oDestObj).'::'.$oDestObj->GetKey();
+ if ($bEnableRedundancy) {
+ // Add only the edges where both source and destination are "reached"
+ if ($oElement->GetSourceNode()->GetProperty('is_reached') && $oElement->GetSinkNode()->GetProperty('is_reached')) {
+ if ($bReverse) {
+ $oResult->AddRelation($sDestKey, $sSrcKey);
+ } else {
+ $oResult->AddRelation($sSrcKey, $sDestKey);
+ }
}
- else
- {
+ } else {
+ if ($bReverse) {
+ $oResult->AddRelation($sDestKey, $sSrcKey);
+ } else {
$oResult->AddRelation($sSrcKey, $sDestKey);
}
}
}
- else
- {
- if ($bReverse)
- {
- $oResult->AddRelation($sDestKey, $sSrcKey);
- }
- else
- {
- $oResult->AddRelation($sSrcKey, $sDestKey);
- }
- }
}
- }
- if (count($aIndexByClass) > 0)
- {
- $aStats = array();
- $aUnauthorizedClasses = array();
- foreach ($aIndexByClass as $sClass => $aIds)
- {
- if (UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_READ) != UR_ALLOWED_YES)
- {
- $aUnauthorizedClasses[$sClass] = true;
+ if (count($aIndexByClass) > 0) {
+ $aStats = [];
+ $aUnauthorizedClasses = [];
+ foreach ($aIndexByClass as $sClass => $aIds) {
+ if (UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_READ) != UR_ALLOWED_YES) {
+ $aUnauthorizedClasses[$sClass] = true;
+ }
+ $aStats[] = $sClass.'= '.count($aIds);
}
- $aStats[] = $sClass.'= '.count($aIds);
+ if (count($aUnauthorizedClasses) > 0) {
+ $sClasses = implode(', ', array_keys($aUnauthorizedClasses));
+ $oResult = new RestResult();
+ $oResult->code = RestResult::UNAUTHORIZED;
+ $oResult->message = "The current user does not have enough permissions for exporting data of class(es): $sClasses";
+ } else {
+ $oResult->message = "Scope: ".$oObjectSet->Count()."; Related objects: ".implode(', ', $aStats);
+ }
+ } else {
+ $oResult->message = "Nothing found";
}
- if (count($aUnauthorizedClasses) > 0)
- {
- $sClasses = implode(', ', array_keys($aUnauthorizedClasses));
- $oResult = new RestResult();
- $oResult->code = RestResult::UNAUTHORIZED;
- $oResult->message = "The current user does not have enough permissions for exporting data of class(es): $sClasses";
- }
- else
- {
- $oResult->message = "Scope: ".$oObjectSet->Count()."; Related objects: ".implode(', ', $aStats);
- }
- }
- else
- {
- $oResult->message = "Nothing found";
- }
- break;
-
- case 'core/check_credentials':
- $oResult = new RestResult();
- $sUser = RestUtils::GetMandatoryParam($aParams, 'user');
- $sPassword = RestUtils::GetMandatoryParam($aParams, 'password');
+ break;
- if (UserRights::CheckCredentials($sUser, $sPassword) !== true)
- {
- $oResult->authorized = false;
- }
- else
- {
- $oResult->authorized = true;
- }
- break;
-
- default:
- // unknown operation: handled at a higher level
+ case 'core/check_credentials':
+ $oResult = new RestResult();
+ $sUser = RestUtils::GetMandatoryParam($aParams, 'user');
+ $sPassword = RestUtils::GetMandatoryParam($aParams, 'password');
+
+ if (UserRights::CheckCredentials($sUser, $sPassword) !== true) {
+ $oResult->authorized = false;
+ } else {
+ $oResult->authorized = true;
+ }
+ break;
+
+ default:
+ // unknown operation: handled at a higher level
}
return $oResult;
}
public function SanitizeJsonInput(string $sJsonInput): string
{
- $sSanitizedJsonInput = $sJsonInput;
- $aJsonData = json_decode($sSanitizedJsonInput, true);
- $sOperation = $aJsonData['operation'];
+ $sSanitizedJsonInput = $sJsonInput;
+ $aJsonData = json_decode($sSanitizedJsonInput, true);
+ $sOperation = $aJsonData['operation'];
- switch ($sOperation) {
- case 'core/check_credentials':
- if (isset($aJsonData['password'])) {
- $aJsonData['password'] = '*****';
- }
- break;
- case 'core/update':
- case 'core/create':
- default :
- $sClass = $aJsonData['class'];
- if (isset($aJsonData['fields'])) {
- foreach ($aJsonData['fields'] as $sFieldAttCode => $fieldValue) {
- $oAttDef = MetaModel::GetAttributeDef($sClass, $sFieldAttCode);
- $this->SanitizeFieldIfSensitive($aJsonData['fields'], $sFieldAttCode, $fieldValue, $oAttDef);
- }
- }
- break;
- }
+ switch ($sOperation) {
+ case 'core/check_credentials':
+ if (isset($aJsonData['password'])) {
+ $aJsonData['password'] = '*****';
+ }
+ break;
+ case 'core/update':
+ case 'core/create':
+ default:
+ $sClass = $aJsonData['class'];
+ if (isset($aJsonData['fields'])) {
+ foreach ($aJsonData['fields'] as $sFieldAttCode => $fieldValue) {
+ $oAttDef = MetaModel::GetAttributeDef($sClass, $sFieldAttCode);
+ $this->SanitizeFieldIfSensitive($aJsonData['fields'], $sFieldAttCode, $fieldValue, $oAttDef);
+ }
+ }
+ break;
+ }
return json_encode($aJsonData, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
}
/**
- * Helper for object deletion
+ * Helper for object deletion
*/
public function DeleteObjects($oResult, $aObjects, $bSimulate)
{
$oDeletionPlan = new DeletionPlan();
- foreach($aObjects as $oObj)
- {
- if ($bSimulate)
- {
+ foreach ($aObjects as $oObj) {
+ if ($bSimulate) {
$oObj->CheckToDelete($oDeletionPlan);
- }
- else
- {
+ } else {
$oObj->DBDelete($oDeletionPlan);
}
}
- foreach ($oDeletionPlan->ListDeletes() as $sTargetClass => $aDeletes)
- {
- foreach ($aDeletes as $iId => $aData)
- {
+ foreach ($oDeletionPlan->ListDeletes() as $sTargetClass => $aDeletes) {
+ foreach ($aDeletes as $iId => $aData) {
$oToDelete = $aData['to_delete'];
$bAutoDel = (($aData['mode'] == DEL_SILENT) || ($aData['mode'] == DEL_AUTO));
- if (array_key_exists('issue', $aData))
- {
- if ($bAutoDel)
- {
- if (isset($aData['requested_explicitely'])) // i.e. in the initial list of objects to delete
- {
+ if (array_key_exists('issue', $aData)) {
+ if ($bAutoDel) {
+ if (isset($aData['requested_explicitely'])) { // i.e. in the initial list of objects to delete
$iCode = RestDelete::ISSUE;
$sPlanned = 'Cannot be deleted: '.$aData['issue'];
- }
- else
- {
+ } else {
$iCode = RestDelete::AUTO_DELETE_ISSUE;
$sPlanned = 'Should be deleted automatically... but: '.$aData['issue'];
}
- }
- else
- {
+ } else {
$iCode = RestDelete::REQUEST_EXPLICITELY;
$sPlanned = 'Must be deleted explicitely... but: '.$aData['issue'];
}
- }
- else
- {
- if ($bAutoDel)
- {
- if (isset($aData['requested_explicitely']))
- {
+ } else {
+ if ($bAutoDel) {
+ if (isset($aData['requested_explicitely'])) {
$iCode = RestDelete::OK;
- $sPlanned = '';
- }
- else
- {
+ $sPlanned = '';
+ } else {
$iCode = RestDelete::AUTO_DELETE;
$sPlanned = 'Deleted automatically';
}
- }
- else
- {
+ } else {
$iCode = RestDelete::REQUEST_EXPLICITELY;
$sPlanned = 'Must be deleted explicitely';
}
@@ -877,60 +755,43 @@ class CoreServices implements iRestServiceProvider, iRestInputSanitizer
$oResult->AddObject($iCode, $sPlanned, $oToDelete);
}
}
- foreach ($oDeletionPlan->ListUpdates() as $sRemoteClass => $aToUpdate)
- {
- foreach ($aToUpdate as $iId => $aData)
- {
+ foreach ($oDeletionPlan->ListUpdates() as $sRemoteClass => $aToUpdate) {
+ foreach ($aToUpdate as $iId => $aData) {
$oToUpdate = $aData['to_reset'];
- if (array_key_exists('issue', $aData))
- {
+ if (array_key_exists('issue', $aData)) {
$iCode = RestDelete::AUTO_UPDATE_ISSUE;
$sPlanned = 'Should be updated automatically... but: '.$aData['issue'];
- }
- else
- {
+ } else {
$iCode = RestDelete::AUTO_UPDATE;
$sPlanned = 'Reset external keys: '.$aData['attributes_list'];
}
$oResult->AddObject($iCode, $sPlanned, $oToUpdate);
}
}
-
- if ($oDeletionPlan->FoundStopper())
- {
- if ($oDeletionPlan->FoundSecurityIssue())
- {
+
+ if ($oDeletionPlan->FoundStopper()) {
+ if ($oDeletionPlan->FoundSecurityIssue()) {
$iRes = RestResult::UNAUTHORIZED;
$sRes = 'Deletion not allowed on some objects';
- }
- elseif ($oDeletionPlan->FoundManualOperation())
- {
- $iRes = RestResult::UNSAFE;
+ } elseif ($oDeletionPlan->FoundManualOperation()) {
+ $iRes = RestResult::UNSAFE;
$sRes = 'The deletion requires that other objects be deleted/updated, and those operations must be requested explicitely';
- }
- else
- {
- $iRes = RestResult::INTERNAL_ERROR;
+ } else {
+ $iRes = RestResult::INTERNAL_ERROR;
$sRes = 'Some issues have been encountered. See the list of planned changes for more information about the issue(s).';
- }
- }
- else
- {
- $iRes = RestResult::OK;
+ }
+ } else {
+ $iRes = RestResult::OK;
$sRes = 'Deleted: '.count($aObjects);
$iIndirect = $oDeletionPlan->GetTargetCount() - count($aObjects);
- if ($iIndirect > 0)
- {
+ if ($iIndirect > 0) {
$sRes .= ' plus (for DB integrity) '.$iIndirect;
}
}
$oResult->code = $iRes;
- if ($bSimulate)
- {
+ if ($bSimulate) {
$oResult->message = 'SIMULATING: '.$sRes;
- }
- else
- {
+ } else {
$oResult->message = $sRes;
}
}
@@ -953,46 +814,45 @@ class CoreServices implements iRestServiceProvider, iRestInputSanitizer
*/
trait SanitizeTrait
{
- /**
- * Sanitize a field if it is sensitive.
- *
- * @param array $fields The fields array
- * @param string $sFieldAttCode The attribute code
- * @param mixed $oAttDef The attribute definition
- * @throws Exception
- */
- private function SanitizeFieldIfSensitive(array &$fields, string $sFieldAttCode, $fieldValue, $oAttDef): void
- {
- // for simple attribute
- if ($oAttDef instanceof iAttributeNoGroupBy) { // iAttributeNoGroupBy is equivalent to sensitive attribute
- $fields[$sFieldAttCode] = '*****';
- return;
- }
- // for 1-n / n-n relation
- if ($oAttDef instanceof AttributeLinkedSet) {
- foreach ($fieldValue as $i => $aLnkValues) {
- foreach ($aLnkValues as $sLnkAttCode => $sLnkValue) {
- $oLnkAttDef = MetaModel::GetAttributeDef($oAttDef->GetLinkedClass(), $sLnkAttCode);
- if ($oLnkAttDef instanceof iAttributeNoGroupBy) { // 1-n relation
- $fields[$sFieldAttCode][$i][$sLnkAttCode] = '*****';
- }
- elseif ($oAttDef instanceof AttributeLinkedSetIndirect && $oLnkAttDef instanceof AttributeExternalField) { // for n-n relation
- $oExtKeyAttDef = MetaModel::GetAttributeDef($oLnkAttDef->GetTargetClass(), $oLnkAttDef->GetExtAttCode());
- if ($oExtKeyAttDef instanceof iAttributeNoGroupBy) {
- $fields[$sFieldAttCode][$i][$sLnkAttCode] = '*****';
- }
- }
- }
- }
- return;
- }
+ /**
+ * Sanitize a field if it is sensitive.
+ *
+ * @param array $fields The fields array
+ * @param string $sFieldAttCode The attribute code
+ * @param mixed $oAttDef The attribute definition
+ * @throws Exception
+ */
+ private function SanitizeFieldIfSensitive(array &$fields, string $sFieldAttCode, $fieldValue, $oAttDef): void
+ {
+ // for simple attribute
+ if ($oAttDef instanceof iAttributeNoGroupBy) { // iAttributeNoGroupBy is equivalent to sensitive attribute
+ $fields[$sFieldAttCode] = '*****';
+ return;
+ }
+ // for 1-n / n-n relation
+ if ($oAttDef instanceof AttributeLinkedSet) {
+ foreach ($fieldValue as $i => $aLnkValues) {
+ foreach ($aLnkValues as $sLnkAttCode => $sLnkValue) {
+ $oLnkAttDef = MetaModel::GetAttributeDef($oAttDef->GetLinkedClass(), $sLnkAttCode);
+ if ($oLnkAttDef instanceof iAttributeNoGroupBy) { // 1-n relation
+ $fields[$sFieldAttCode][$i][$sLnkAttCode] = '*****';
+ } elseif ($oAttDef instanceof AttributeLinkedSetIndirect && $oLnkAttDef instanceof AttributeExternalField) { // for n-n relation
+ $oExtKeyAttDef = MetaModel::GetAttributeDef($oLnkAttDef->GetTargetClass(), $oLnkAttDef->GetExtAttCode());
+ if ($oExtKeyAttDef instanceof iAttributeNoGroupBy) {
+ $fields[$sFieldAttCode][$i][$sLnkAttCode] = '*****';
+ }
+ }
+ }
+ }
+ return;
+ }
- // for external attribute
- if ($oAttDef instanceof AttributeExternalField) {
- $oExtKeyAttDef = MetaModel::GetAttributeDef($oAttDef->GetTargetClass(), $oAttDef->GetExtAttCode());
- if ($oExtKeyAttDef instanceof iAttributeNoGroupBy) {
- $fields[$sFieldAttCode] = '*****';
- }
- }
- }
-}
\ No newline at end of file
+ // for external attribute
+ if ($oAttDef instanceof AttributeExternalField) {
+ $oExtKeyAttDef = MetaModel::GetAttributeDef($oAttDef->GetTargetClass(), $oAttDef->GetExtAttCode());
+ if ($oExtKeyAttDef instanceof iAttributeNoGroupBy) {
+ $fields[$sFieldAttCode] = '*****';
+ }
+ }
+ }
+}
diff --git a/core/simplecrypt.class.inc.php b/core/simplecrypt.class.inc.php
index e9c304f3d..ea6885d07 100644
--- a/core/simplecrypt.class.inc.php
+++ b/core/simplecrypt.class.inc.php
@@ -412,4 +412,4 @@ class SimpleCryptOpenSSLMcryptCompatibilityEngine implements CryptEngine
return trim($plaintext);
}
-}
\ No newline at end of file
+}
diff --git a/core/simplegraph.class.inc.php b/core/simplegraph.class.inc.php
index 614ab031e..43084ba7f 100644
--- a/core/simplegraph.class.inc.php
+++ b/core/simplegraph.class.inc.php
@@ -1,4 +1,5 @@
sId = $sId;
- $this->aProperties = array();
+ $this->aProperties = [];
}
-
+
/**
* Get the identifier of the object in the graph
* @return string
@@ -51,7 +51,7 @@ class GraphElement
{
return $this->sId;
}
-
+
/**
* Get the value of the given named property for the object
* @param string $sPropName The name of the property to get
@@ -73,7 +73,7 @@ class GraphElement
{
$this->aProperties[$sPropName] = $value;
}
-
+
/**
* Get all the known properties of the object
* @return Ambigous
@@ -91,7 +91,7 @@ class GraphNode extends GraphElement
{
protected $aIncomingEdges;
protected $aOutgoingEdges;
-
+
/**
* Create a new node inside a graph
* @param SimpleGraph $oGraph
@@ -100,16 +100,15 @@ class GraphNode extends GraphElement
public function __construct(SimpleGraph $oGraph, $sId)
{
parent::__construct($sId);
- $this->aIncomingEdges = array();
- $this->aOutgoingEdges = array();
+ $this->aIncomingEdges = [];
+ $this->aOutgoingEdges = [];
$oGraph->_AddNode($this);
}
-
+
public function GetDotAttributes($bNoLabel = false)
{
$sDot = '';
- if (!$bNoLabel)
- {
+ if (!$bNoLabel) {
$sLabel = addslashes($this->GetProperty('label', $this->GetId()));
$sDot = 'label="'.$sLabel.'"';
}
@@ -133,7 +132,7 @@ class GraphNode extends GraphElement
{
$this->aOutgoingEdges[$oEdge->GetId()] = $oEdge;
}
-
+
/**
* INTERNAL USE ONLY
* @param GraphEdge $oEdge
@@ -151,7 +150,7 @@ class GraphNode extends GraphElement
{
unset($this->aOutgoingEdges[$oEdge->GetId()]);
}
-
+
/**
* Get the list of all incoming edges on the current node
* @return Ambigous
@@ -160,7 +159,7 @@ class GraphNode extends GraphElement
{
return $this->aIncomingEdges;
}
-
+
/**
* Get the list of all outgoing edges from the current node
* @return Ambigous
@@ -169,7 +168,7 @@ class GraphNode extends GraphElement
{
return $this->aOutgoingEdges;
}
-
+
/**
* Flood fill the chart with the given value for the specified property
* @param string $sPropName The name of the property to set
@@ -179,29 +178,24 @@ class GraphNode extends GraphElement
*/
public function FloodProperty($sPropName, $value, $bFloodDown, $bFloodUp)
{
- if ($this->GetProperty($sPropName, null) == null)
- {
+ if ($this->GetProperty($sPropName, null) == null) {
// Property not already set, let's do it
$this->SetProperty($sPropName, $value);
- if ($bFloodDown)
- {
- foreach($this->GetOutgoingEdges() as $oEdge)
- {
+ if ($bFloodDown) {
+ foreach ($this->GetOutgoingEdges() as $oEdge) {
$oEdge->SetProperty($sPropName, $value);
$oEdge->GetSinkNode()->FloodProperty($sPropName, $value, $bFloodDown, $bFloodUp);
}
}
- if ($bFloodUp)
- {
- foreach($this->GetIncomingEdges() as $oEdge)
- {
+ if ($bFloodUp) {
+ foreach ($this->GetIncomingEdges() as $oEdge) {
$oEdge->SetProperty($sPropName, $value);
$oEdge->GetSourceNode()->FloodProperty($sPropName, $value, $bFloodDown, $bFloodUp);
}
}
}
}
-
+
}
/**
@@ -237,7 +231,7 @@ class GraphEdge extends GraphElement
{
return $this->oSourceNode;
}
-
+
/**
* Get the "sink" node for this edge
* @return GraphNode
@@ -250,8 +244,7 @@ class GraphEdge extends GraphElement
public function GetDotAttributes($bNoLabel = false)
{
$sDot = '';
- if (!$bNoLabel)
- {
+ if (!$bNoLabel) {
$sLabel = addslashes($this->GetProperty('label', ''));
$sDot = 'label="'.$sLabel.'"';
}
@@ -266,16 +259,16 @@ class SimpleGraph
{
protected $aNodes;
protected $aEdges;
-
+
/**
* Creates a new empty graph
*/
public function __construct()
{
- $this->aNodes = array();
- $this->aEdges = array();
+ $this->aNodes = [];
+ $this->aEdges = [];
}
-
+
/**
* INTERNAL USE ONLY
* @return Ambigous
@@ -284,7 +277,7 @@ class SimpleGraph
{
return $this->aNodes;
}
-
+
/**
* INTERNAL USE ONLY
* @return Ambigous
@@ -293,32 +286,34 @@ class SimpleGraph
{
return $this->aEdges;
}
-
+
/**
* INTERNAL USE ONLY
* @return Ambigous
*/
public function _AddNode(GraphNode $oNode)
{
- if (array_key_exists($oNode->GetId(), $this->aNodes)) throw new SimpleGraphException('Cannot add node (id='.$oNode->GetId().') to the graph. A node with the same id already exists in the graph.');
-
+ if (array_key_exists($oNode->GetId(), $this->aNodes)) {
+ throw new SimpleGraphException('Cannot add node (id='.$oNode->GetId().') to the graph. A node with the same id already exists in the graph.');
+ }
+
$this->aNodes[$oNode->GetId()] = $oNode;
}
-
+
/**
* INTERNAL USE ONLY
* @return Ambigous
*/
public function _RemoveNode(GraphNode $oNode)
{
- if (!array_key_exists($oNode->GetId(), $this->aNodes)) throw new SimpleGraphException('Cannot remove the node (id='.$oNode->GetId().') from the graph. The node was not found in the graph.');
-
- foreach($oNode->GetOutgoingEdges() as $oEdge)
- {
+ if (!array_key_exists($oNode->GetId(), $this->aNodes)) {
+ throw new SimpleGraphException('Cannot remove the node (id='.$oNode->GetId().') from the graph. The node was not found in the graph.');
+ }
+
+ foreach ($oNode->GetOutgoingEdges() as $oEdge) {
$this->_RemoveEdge($oEdge);
}
- foreach($oNode->GetIncomingEdges() as $oEdge)
- {
+ foreach ($oNode->GetIncomingEdges() as $oEdge) {
$this->_RemoveEdge($oEdge);
}
unset($this->aNodes[$oNode->GetId()]);
@@ -333,42 +328,37 @@ class SimpleGraph
*/
public function FilterNode(GraphNode $oNode, $bAllowLoopingEdge = false)
{
- if (!array_key_exists($oNode->GetId(), $this->aNodes)) throw new SimpleGraphException('Cannot filter the node (id='.$oNode->GetId().') from the graph. The node was not found in the graph.');
-
- $aSourceNodes = array();
- $aSinkNodes = array();
- foreach($oNode->GetOutgoingEdges() as $oEdge)
- {
+ if (!array_key_exists($oNode->GetId(), $this->aNodes)) {
+ throw new SimpleGraphException('Cannot filter the node (id='.$oNode->GetId().') from the graph. The node was not found in the graph.');
+ }
+
+ $aSourceNodes = [];
+ $aSinkNodes = [];
+ foreach ($oNode->GetOutgoingEdges() as $oEdge) {
$sSinkId = $oEdge->GetSinkNode()->GetId();
- if ($sSinkId != $oNode->GetId())
- {
+ if ($sSinkId != $oNode->GetId()) {
$aSinkNodes[$sSinkId] = $oEdge->GetSinkNode();
}
$this->_RemoveEdge($oEdge);
}
- foreach($oNode->GetIncomingEdges() as $oEdge)
- {
+ foreach ($oNode->GetIncomingEdges() as $oEdge) {
$sSourceId = $oEdge->GetSourceNode()->GetId();
- if ($sSourceId != $oNode->GetId())
- {
+ if ($sSourceId != $oNode->GetId()) {
$aSourceNodes[$sSourceId] = $oEdge->GetSourceNode();
}
$this->_RemoveEdge($oEdge);
}
unset($this->aNodes[$oNode->GetId()]);
- foreach($aSourceNodes as $sSourceId => $oSourceNode)
- {
- foreach($aSinkNodes as $sSinkId => $oSinkNode)
- {
- if ($bAllowLoopingEdge || ($oSourceNode->GetId() != $oSinkNode->GetId()))
- {
+ foreach ($aSourceNodes as $sSourceId => $oSourceNode) {
+ foreach ($aSinkNodes as $sSinkId => $oSinkNode) {
+ if ($bAllowLoopingEdge || ($oSourceNode->GetId() != $oSinkNode->GetId())) {
$oEdge = new RelationEdge($this, $oSourceNode, $oSinkNode);
}
}
}
}
-
+
/**
* Get the node identified by $sId or null if not found
* @param string $sId
@@ -376,7 +366,7 @@ class SimpleGraph
*/
public function GetNode($sId)
{
- return array_key_exists($sId, $this->aNodes) ? $this->aNodes[$sId] : null;
+ return array_key_exists($sId, $this->aNodes) ? $this->aNodes[$sId] : null;
}
/**
@@ -386,7 +376,7 @@ class SimpleGraph
*/
public function HasNode($sId)
{
- return array_key_exists($sId, $this->aNodes);
+ return array_key_exists($sId, $this->aNodes);
}
/**
@@ -397,23 +387,19 @@ class SimpleGraph
*/
public function _AddEdge(GraphEdge $oEdge, $bMustBeUnique = false)
{
- if (array_key_exists($oEdge->GetId(), $this->aEdges))
- {
- if ($bMustBeUnique)
- {
- throw new SimpleGraphException('Cannot add edge (id=' . $oEdge->GetId() . ') to the graph. An edge with the same id already exists in the graph.');
- }
- else
- {
+ if (array_key_exists($oEdge->GetId(), $this->aEdges)) {
+ if ($bMustBeUnique) {
+ throw new SimpleGraphException('Cannot add edge (id='.$oEdge->GetId().') to the graph. An edge with the same id already exists in the graph.');
+ } else {
return;
}
}
-
+
$this->aEdges[$oEdge->GetId()] = $oEdge;
$oEdge->GetSourceNode()->_AddOutgoingEdge($oEdge);
$oEdge->GetSinkNode()->_AddIncomingEdge($oEdge);
}
-
+
/**
* INTERNAL USE ONLY
* @param GraphEdge $oEdge
@@ -421,14 +407,16 @@ class SimpleGraph
*/
public function _RemoveEdge(GraphEdge $oEdge)
{
- if (!array_key_exists($oEdge->GetId(), $this->aEdges)) throw new SimpleGraphException('Cannot remove edge (id='.$oEdge->GetId().') from the graph. The edge was not found.');
-
+ if (!array_key_exists($oEdge->GetId(), $this->aEdges)) {
+ throw new SimpleGraphException('Cannot remove edge (id='.$oEdge->GetId().') from the graph. The edge was not found.');
+ }
+
$oEdge->GetSourceNode()->_RemoveOutgoingEdge($oEdge);
$oEdge->GetSinkNode()->_RemoveIncomingEdge($oEdge);
-
+
unset($this->aEdges[$oEdge->GetId()]);
}
-
+
/**
* Get the edge indentified by $sId or null if not found
* @param string $sId
@@ -438,7 +426,7 @@ class SimpleGraph
{
return array_key_exists($sId, $this->aEdges) ? $this->aEdges[$sId] : null;
}
-
+
/**
* Determine if the id already exists in amongst the existing edges
* @param string $sId
@@ -446,7 +434,7 @@ class SimpleGraph
*/
public function HasEdge($sId)
{
- return array_key_exists($sId, $this->aEdges);
+ return array_key_exists($sId, $this->aEdges);
}
/**
@@ -470,23 +458,20 @@ EOF
;
$oIterator = new RelationTypeIterator($this, 'Node');
-
- foreach($oIterator as $key => $oNode)
- {
+
+ foreach ($oIterator as $key => $oNode) {
$sDot .= "\t\"".$oNode->GetId()."\" [ ".$oNode->GetDotAttributes($bNoLabel)." ];\n";
- if (count($oNode->GetOutgoingEdges()) > 0)
- {
- foreach($oNode->GetOutgoingEdges() as $oEdge)
- {
+ if (count($oNode->GetOutgoingEdges()) > 0) {
+ foreach ($oNode->GetOutgoingEdges() as $oEdge) {
$sDot .= "\t\"".$oNode->GetId()."\" -> \"".$oEdge->GetSinkNode()->GetId()."\" [ ".$oEdge->GetDotAttributes($bNoLabel)." ];\n";
}
}
}
-
+
$sDot .= "}\n";
- return $sDot;
+ return $sDot;
}
-
+
/**
* Get the description of the graph as an embedded PNG image (using a data: url) as
* generated by graphviz (requires graphviz to be installed on the machine and the path to
@@ -497,51 +482,43 @@ EOF
public function DumpAsHtmlImage()
{
$sDotExecutable = MetaModel::GetConfig()->Get('graphviz_path');
- if (file_exists($sDotExecutable))
- {
+ if (file_exists($sDotExecutable)) {
// create the file with Graphviz
- if (!is_dir(utils::GetDataPath()))
- {
+ if (!is_dir(utils::GetDataPath())) {
@mkdir(utils::GetDataPath());
}
- if (!is_dir(utils::GetDataPath()."tmp"))
- {
+ if (!is_dir(utils::GetDataPath()."tmp")) {
@mkdir(utils::GetDataPath()."tmp");
}
$sImageFilePath = tempnam(utils::GetDataPath()."tmp", 'png-');
$sDotDescription = $this->GetDotDescription();
$sDotFilePath = tempnam(utils::GetDataPath()."tmp", 'dot-');
-
+
$rFile = @fopen($sDotFilePath, "w");
@fwrite($rFile, $sDotDescription);
@fclose($rFile);
- $aOutput = array();
+ $aOutput = [];
$CommandLine = "\"$sDotExecutable\" -v -Tpng < \"$sDotFilePath\" -o\"$sImageFilePath\" 2>&1";
-
+
exec($CommandLine, $aOutput, $iRetCode);
- if ($iRetCode != 0)
- {
+ if ($iRetCode != 0) {
$sHtml = '';
$sHtml .= "Error:
";
$sHtml .= "The command:
$CommandLine returned $iRetCode";
$sHtml .= "The output of the command is:
\n".implode("\n", $aOutput)." ";
$sHtml .= " ";
$sHtml .= "Content of the '".basename($sDotFilePath)."' file:
\n$sDotDescription ";
- }
- else
- {
+ } else {
$sHtml = ' ';
@unlink($sImageFilePath);
}
@unlink($sDotFilePath);
- }
- else
- {
- throw new Exception('graphviz not found');
+ } else {
+ throw new Exception('graphviz not found');
}
return $sHtml;
}
-
+
/**
* Get the description of the graph as text string in the XDot format
* including the positions of the nodes and egdes (requires graphviz
@@ -553,51 +530,42 @@ EOF
public function DumpAsXDot()
{
$sDotExecutable = MetaModel::GetConfig()->Get('graphviz_path');
- if (file_exists($sDotExecutable))
- {
+ if (file_exists($sDotExecutable)) {
// create the file with Graphviz
- if (!is_dir(utils::GetDataPath()))
- {
+ if (!is_dir(utils::GetDataPath())) {
@mkdir(utils::GetDataPath());
}
- if (!is_dir(utils::GetDataPath()."tmp"))
- {
+ if (!is_dir(utils::GetDataPath()."tmp")) {
@mkdir(utils::GetDataPath()."tmp");
}
$sXdotFilePath = tempnam(utils::GetDataPath()."tmp", 'xdot-');
$sDotDescription = $this->GetDotDescription(true); // true => don't put (localized) labels in the file, since it makes it harder to parse
$sDotFilePath = tempnam(utils::GetDataPath()."tmp", 'dot-');
-
+
$rFile = @fopen($sDotFilePath, "w");
@fwrite($rFile, $sDotDescription);
@fclose($rFile);
- $aOutput = array();
+ $aOutput = [];
$CommandLine = "\"$sDotExecutable\" -v -Tdot < \"$sDotFilePath\" -o\"$sXdotFilePath\" 2>&1";
-
+
exec($CommandLine, $aOutput, $iRetCode);
- if ($iRetCode != 0)
- {
+ if ($iRetCode != 0) {
$sHtml = '';
$sHtml .= "Error:
";
$sHtml .= "The command:
$CommandLine returned $iRetCode";
$sHtml .= "The output of the command is:
\n".implode("\n", $aOutput)." ";
IssueLog::Error($sHtml);
- }
- else
- {
+ } else {
$sHtml = ''.file_get_contents($sXdotFilePath).' ';
@unlink($sXdotFilePath);
}
@unlink($sDotFilePath);
- }
- else
- {
- throw new Exception('graphviz not found');
+ } else {
+ throw new Exception('graphviz not found');
}
return $sHtml;
}
-
-
+
/**
* Get the description of the graph as some HTML text
* @return string
@@ -606,42 +574,36 @@ EOF
{
$sHtml = '';
$oIterator = new RelationTypeIterator($this);
-
- foreach($oIterator as $key => $oElement)
- {
+
+ foreach ($oIterator as $key => $oElement) {
$sHtml .= "$key: ".get_class($oElement)."::".$oElement->GetId()."
";
-
- switch(get_class($oElement))
- {
+
+ switch (get_class($oElement)) {
case 'GraphNode':
- if (count($oElement->GetIncomingEdges()) > 0)
- {
+ if (count($oElement->GetIncomingEdges()) > 0) {
$sHtml .= "Incoming edges:\n";
- foreach($oElement->GetIncomingEdges() as $oEdge)
- {
+ foreach ($oElement->GetIncomingEdges() as $oEdge) {
$sHtml .= "From: ".$oEdge->GetSourceNode()->GetId()." \n";
}
$sHtml .= " \n";
}
- if (count($oElement->GetOutgoingEdges()) > 0)
- {
+ if (count($oElement->GetOutgoingEdges()) > 0) {
$sHtml .= "Outgoing edges:\n";
- foreach($oElement->GetOutgoingEdges() as $oEdge)
- {
+ foreach ($oElement->GetOutgoingEdges() as $oEdge) {
$sHtml .= "To: ".$oEdge->GetSinkNode()->GetId()." \n";
}
$sHtml .= " \n";
}
break;
-
+
case 'GraphEdge':
$sHtml .= "From: ".$oElement->GetSourceNode()->GetId().", to:".$oElement->GetSinkNode()->GetId()."
\n";
break;
}
}
- return $sHtml;
+ return $sHtml;
}
-
+
/**
* Split the graph in a array of non connected subgraphs
* @return multitype:SimpleGraph unknown
@@ -649,48 +611,40 @@ EOF
public function GetSubgraphs()
{
$iNbColors = 0;
- $aResult = array();
+ $aResult = [];
$oIterator = new RelationTypeIterator($this, 'Node');
- foreach($oIterator as $oNode)
- {
+ foreach ($oIterator as $oNode) {
$iPrevColor = $oNode->GetProperty('color', null);
-
- if ($iPrevColor == null)
- {
+
+ if ($iPrevColor == null) {
$iNbColors++; // Start a new color
$oNode->FloodProperty('color', $iNbColors, true, true);
}
}
- if ($iNbColors == 1)
- {
+ if ($iNbColors == 1) {
// Everything is connected together, only one subgraph
$aResult[] = $this;
- }
- else
- {
+ } else {
// Let's reconstruct each separate graph
$sClass = get_class($this);
- for($i = 1; $i <= $iNbColors; $i++)
- {
+ for ($i = 1; $i <= $iNbColors; $i++) {
$aResult[$i] = new $sClass();
}
-
- foreach($oIterator as $oNode)
- {
+
+ foreach ($oIterator as $oNode) {
$iNodeColor = $oNode->GetProperty('color');
$aResult[$iNodeColor]->_AddNode($oNode);
}
-
+
$oIter2 = new RelationTypeIterator($this, 'Edge');
- foreach($oIter2 as $oEdge)
- {
+ foreach ($oIter2 as $oEdge) {
$iEdgeColor = $oEdge->GetProperty('color');
$aResult[$iEdgeColor]->_AddEdge($oEdge);
}
}
- return $aResult;
+ return $aResult;
}
-
+
/**
* Merge back two subgraphs into one
* @param SimpleGraph $oGraph
@@ -698,13 +652,11 @@ EOF
public function Merge(SimpleGraph $oGraph)
{
$oIter1 = new RelationTypeIterator($oGraph, 'Node');
- foreach($oIter1 as $oNode)
- {
+ foreach ($oIter1 as $oNode) {
$this->_AddNode($oNode);
}
$oIter2 = new RelationTypeIterator($oGraph, 'Edge');
- foreach($oIter2 as $oEdge)
- {
+ foreach ($oIter2 as $oEdge) {
$this->_AddEdge($oEdge);
}
}
@@ -718,7 +670,7 @@ class RelationTypeIterator implements Iterator
{
protected $iCurrentIdx;
protected $aList;
-
+
/**
* Constructor
* @param SimpleGraph $oGraph The graph to browse
@@ -727,46 +679,53 @@ class RelationTypeIterator implements Iterator
public function __construct(SimpleGraph $oGraph, $sType = null)
{
$this->iCurrentIdx = -1;
- $this->aList = array();
-
- switch($sType)
- {
+ $this->aList = [];
+
+ switch ($sType) {
case 'Node':
- foreach($oGraph->_GetNodes() as $oNode) $this->aList[] = $oNode;
- break;
-
+ foreach ($oGraph->_GetNodes() as $oNode) {
+ $this->aList[] = $oNode;
+ }
+ break;
+
case 'Edge':
- foreach($oGraph->_GetEdges() as $oEdge) $this->aList[] = $oEdge;
- break;
-
+ foreach ($oGraph->_GetEdges() as $oEdge) {
+ $this->aList[] = $oEdge;
+ }
+ break;
+
default:
- foreach($oGraph->_GetNodes() as $oNode) $this->aList[] = $oNode;
- foreach($oGraph->_GetEdges() as $oEdge) $this->aList[] = $oEdge;
+ foreach ($oGraph->_GetNodes() as $oNode) {
+ $this->aList[] = $oNode;
+ }
+ foreach ($oGraph->_GetEdges() as $oEdge) {
+ $this->aList[] = $oEdge;
+ }
}
}
-
+
public function rewind(): void
{
$this->iCurrentIdx = 0;
}
-
+
public function valid(): bool
{
return array_key_exists($this->iCurrentIdx, $this->aList);
}
-
+
public function next(): void
{
$this->iCurrentIdx++;
}
-
+
// Return type mixed is not supported by PHP 7.4, we can remove the following PHP attribute and add the return type once iTop min PHP version is PHP 8.0+
#[\ReturnTypeWillChange]
public function current()
{
return $this->aList[$this->iCurrentIdx];
}
-
+
// Return type mixed is not supported by PHP 7.4, we can remove the following PHP attribute and add the return type once iTop min PHP version is PHP 8.0+
#[\ReturnTypeWillChange]
public function key()
diff --git a/core/trigger.class.inc.php b/core/trigger.class.inc.php
index cd6c56d01..fdd816e37 100644
--- a/core/trigger.class.inc.php
+++ b/core/trigger.class.inc.php
@@ -1,4 +1,5 @@
"grant_by_profile,core/cmdb",
"key_type" => "autoincrement",
"name_attcode" => "description",
@@ -45,21 +46,23 @@ abstract class Trigger extends cmdbAbstractObject
"db_key_field" => "id",
"db_finalclass_field" => "realclass",
'style' => new ormStyle(null, null, null, null, null, '../images/icons/icons8-conflict.svg'),
- );
+ ];
MetaModel::Init_Params($aParams);
//MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeString("description", array("allowed_values" => null, "sql" => "description", "default_value" => null, "is_null_allowed" => false, "depends_on" => array())));
- MetaModel::Init_AddAttribute(new AttributeLinkedSetIndirect("action_list",
- array("linked_class" => "lnkTriggerAction", "ext_key_to_me" => "trigger_id", "ext_key_to_remote" => "action_id", "allowed_values" => null, "count_min" => 1, "count_max" => 0, "depends_on" => array())));
+ MetaModel::Init_AddAttribute(new AttributeString("description", ["allowed_values" => null, "sql" => "description", "default_value" => null, "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeLinkedSetIndirect(
+ "action_list",
+ ["linked_class" => "lnkTriggerAction", "ext_key_to_me" => "trigger_id", "ext_key_to_remote" => "action_id", "allowed_values" => null, "count_min" => 1, "count_max" => 0, "depends_on" => []]
+ ));
$aTags = ContextTag::GetTags();
- MetaModel::Init_AddAttribute(new AttributeEnumSet("context", array("allowed_values" => null, "possible_values" => new ValueSetEnumPadded($aTags, true), "sql" => "context", "depends_on" => array(), "is_null_allowed" => true, "max_items" => 12)));
+ MetaModel::Init_AddAttribute(new AttributeEnumSet("context", ["allowed_values" => null, "possible_values" => new ValueSetEnumPadded($aTags, true), "sql" => "context", "depends_on" => [], "is_null_allowed" => true, "max_items" => 12]));
// "complement" is a computed field, fed by Trigger sub-classes, in general in ComputeValues method, for eg. the TriggerOnObject fed it with target_class info
- MetaModel::Init_AddAttribute(new AttributeString("complement", array("allowed_values" => null, "sql" => "complement", "default_value" => null, "is_null_allowed" => true, "depends_on" => array())));
- MetaModel::Init_AddAttribute(new AttributeEnum("subscription_policy", array("allowed_values" => new ValueSetEnum(Combodo\iTop\Core\Trigger\Enum\SubscriptionPolicy::cases()), "sql" => "subscription_policy", "default_value" => \Combodo\iTop\Core\Trigger\Enum\SubscriptionPolicy::AllowNoChannel->value, "is_null_allowed" => false, "depends_on" => array())));
+ MetaModel::Init_AddAttribute(new AttributeString("complement", ["allowed_values" => null, "sql" => "complement", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeEnum("subscription_policy", ["allowed_values" => new ValueSetEnum(Combodo\iTop\Core\Trigger\Enum\SubscriptionPolicy::cases()), "sql" => "subscription_policy", "default_value" => \Combodo\iTop\Core\Trigger\Enum\SubscriptionPolicy::AllowNoChannel->value, "is_null_allowed" => false, "depends_on" => []]));
// Display lists
- MetaModel::Init_SetZListItems('details', array('finalclass', 'description', 'context', 'subscription_policy', 'action_list', 'complement')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('finalclass', 'complement')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['finalclass', 'description', 'context', 'subscription_policy', 'action_list', 'complement']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['finalclass', 'complement']); // Attributes to be displayed for a list
// Search criteria
// MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
// MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
@@ -78,17 +81,14 @@ abstract class Trigger extends cmdbAbstractObject
$oContext = $this->Get('context');
$bChecked = false;
$bValid = false;
- foreach ($oContext->GetValues() as $sValue)
- {
+ foreach ($oContext->GetValues() as $sValue) {
$bChecked = true;
- if (ContextTag::Check($sValue))
- {
+ if (ContextTag::Check($sValue)) {
$bValid = true;
break;
}
}
- if ($bChecked && !$bValid)
- {
+ if ($bChecked && !$bValid) {
// Trigger does not match the current context
return false;
}
@@ -105,8 +105,7 @@ abstract class Trigger extends cmdbAbstractObject
public function DoActivate($aContextArgs)
{
// Check the context
- if (!$this->IsContextValid())
- {
+ if (!$this->IsContextValid()) {
// Trigger does not match the current context
$sClass = get_class($this);
$sName = $this->Get('friendlyname');
@@ -128,7 +127,7 @@ abstract class Trigger extends cmdbAbstractObject
// Execute actions
foreach ($aActionListOrdered as $aActionSubList) {
- foreach ($aActionSubList as $oLink) /** @var \DBObject $oLink */ {
+ foreach ($aActionSubList as $oLink) { /** @var \DBObject $oLink */
/** @var \DBObject $oLink */
$iActionId = $oLink->Get('action_id');
/** @var \Action $oAction */
@@ -170,8 +169,8 @@ abstract class TriggerOnObject extends Trigger
*/
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "grant_by_profile,core/cmdb",
"key_type" => "autoincrement",
"name_attcode" => "description",
@@ -181,18 +180,20 @@ abstract class TriggerOnObject extends Trigger
"db_table" => "priv_trigger_onobject",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeClass("target_class",
- array("class_category" => "bizmodel", "more_values" => "User,UserExternal,UserInternal,UserLDAP,UserLocal", "sql" => "target_class", "default_value" => null, "is_null_allowed" => false, "depends_on" => array(), "class_exclusion_list" => "Attachment")));
- MetaModel::Init_AddAttribute(new AttributeOQL("filter", array("allowed_values" => null, "sql" => "filter", "default_value" => null, "is_null_allowed" => true, "depends_on" => array())));
+ MetaModel::Init_AddAttribute(new AttributeClass(
+ "target_class",
+ ["class_category" => "bizmodel", "more_values" => "User,UserExternal,UserInternal,UserLDAP,UserLocal", "sql" => "target_class", "default_value" => null, "is_null_allowed" => false, "depends_on" => [], "class_exclusion_list" => "Attachment"]
+ ));
+ MetaModel::Init_AddAttribute(new AttributeOQL("filter", ["allowed_values" => null, "sql" => "filter", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
// Display lists
- MetaModel::Init_SetZListItems('details', array('description', 'context', 'target_class', 'filter', 'subscription_policy', 'action_list')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('finalclass', 'target_class', 'description')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['description', 'context', 'target_class', 'filter', 'subscription_policy', 'action_list']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['finalclass', 'target_class', 'description']); // Attributes to be displayed for a list
// Search criteria
- MetaModel::Init_SetZListItems('default_search', array('description', 'target_class')); // Default criteria of the search banner
+ MetaModel::Init_SetZListItems('default_search', ['description', 'target_class']); // Default criteria of the search banner
// MetaModel::Init_SetZListItems('standard_search', array('name', 'target_class', 'description')); // Criteria of the search form
}
@@ -204,18 +205,14 @@ abstract class TriggerOnObject extends Trigger
parent::DoCheckToWrite();
$sFilter = trim($this->Get('filter') ?? '');
- if (strlen($sFilter) > 0)
- {
- try
- {
+ if (strlen($sFilter) > 0) {
+ try {
$oSearch = DBObjectSearch::FromOQL($sFilter);
- if (!MetaModel::IsParentClass($this->Get('target_class'), $oSearch->GetClass()))
- {
+ if (!MetaModel::IsParentClass($this->Get('target_class'), $oSearch->GetClass())) {
$this->m_aCheckIssues[] = Dict::Format('TriggerOnObject:WrongFilterClass', $this->Get('target_class'));
}
- } catch (OqlException $e)
- {
+ } catch (OqlException $e) {
$this->m_aCheckIssues[] = Dict::Format('TriggerOnObject:WrongFilterQuery', $e->getMessage());
}
}
@@ -235,7 +232,6 @@ abstract class TriggerOnObject extends Trigger
$this->Set('complement', 'class restriction: '.$this->Get('target_class'));
}
-
/**
* Check whether the given object is in the scope of this trigger
* and can potentially be the subject of notifications
@@ -261,47 +257,44 @@ abstract class TriggerOnObject extends Trigger
public function DoActivate($aContextArgs)
{
$bGo = true;
- if (isset($aContextArgs['this->object()']))
- {
+ if (isset($aContextArgs['this->object()'])) {
/** @var \DBObject $oObject */
$oObject = $aContextArgs['this->object()'];
$bGo = $this->IsTargetObject($oObject->GetKey(), $oObject->ListPreviousValuesForUpdatedAttributes());
}
- if ($bGo)
- {
+ if ($bGo) {
parent::DoActivate($aContextArgs);
}
}
- /**
- * if the target class is Attachment, then the trigger is read-only
- * @param $sAttCode
- * @param $aReasons
- * @param $sTargetState
- * @return int
- * @throws ArchivedObjectException
- * @throws CoreException
- */
- public function GetAttributeFlags($sAttCode, &$aReasons = array(), $sTargetState='')
+ /**
+ * if the target class is Attachment, then the trigger is read-only
+ * @param $sAttCode
+ * @param $aReasons
+ * @param $sTargetState
+ * @return int
+ * @throws ArchivedObjectException
+ * @throws CoreException
+ */
+ public function GetAttributeFlags($sAttCode, &$aReasons = [], $sTargetState = '')
{
- // Force the computed field to be read-only, preventing it to be written
- if ($this->Get('target_class') == 'Attachment' ) {
- return OPT_ATT_READONLY;
- }
- return parent::GetAttributeFlags($sAttCode, $aReasons, $sTargetState);
+ // Force the computed field to be read-only, preventing it to be written
+ if ($this->Get('target_class') == 'Attachment') {
+ return OPT_ATT_READONLY;
+ }
+ return parent::GetAttributeFlags($sAttCode, $aReasons, $sTargetState);
}
+ public function DisplayBareHeader(WebPage $oPage, $bEditMode = false)
+ {
+ $aHeaderBlocks = parent::DisplayBareHeader($oPage, $bEditMode);
+ if ($this->Get('target_class') == 'Attachment') {
+ $oPage->AddUiBlock(AlertUIBlockFactory::MakeForWarning('', Dict::S('Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage')));
+ $oPage->add_ready_script("$('#UIMenuModify').hide();");
+ }
- public function DisplayBareHeader(WebPage $oPage, $bEditMode = false)
- {
- $aHeaderBlocks = parent::DisplayBareHeader($oPage, $bEditMode);
- if ($this->Get('target_class') == 'Attachment' ) {
- $oPage->AddUiBlock(AlertUIBlockFactory::MakeForWarning('', Dict::S('Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage')));
- $oPage->add_ready_script("$('#UIMenuModify').hide();");
- }
-
- return $aHeaderBlocks;
- }
+ return $aHeaderBlocks;
+ }
/**
* Activate trigger based on attribute list given instead of changed attributes
@@ -319,8 +312,7 @@ abstract class TriggerOnObject extends Trigger
*/
public function DoActivateForSpecificAttributes(array $aContextArgs, ?array $aAttributes)
{
- if (isset($aContextArgs['this->object()']))
- {
+ if (isset($aContextArgs['this->object()'])) {
/** @var \DBObject $oObject */
$oObject = $aContextArgs['this->object()'];
if (is_null($aAttributes)) {
@@ -347,7 +339,7 @@ abstract class TriggerOnObject extends Trigger
* @throws \MySQLHasGoneAwayException
* @throws \OQLException
*/
- public function IsTargetObject($iObjectId, $aChanges = array())
+ public function IsTargetObject($iObjectId, $aChanges = [])
{
$sFilter = trim($this->Get('filter') ?? '');
if (strlen($sFilter) > 0) {
@@ -404,8 +396,8 @@ class TriggerOnPortalUpdate extends TriggerOnObject
*/
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "grant_by_profile,core/cmdb,application",
"key_type" => "autoincrement",
"name_attcode" => "description",
@@ -415,13 +407,13 @@ class TriggerOnPortalUpdate extends TriggerOnObject
"db_table" => "priv_trigger_onportalupdate",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
// Display lists
- MetaModel::Init_SetZListItems('details', array('description', 'context', 'target_class', 'filter', 'subscription_policy', 'action_list')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('finalclass', 'target_class', 'description')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['description', 'context', 'target_class', 'filter', 'subscription_policy', 'action_list']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['finalclass', 'target_class', 'description']); // Attributes to be displayed for a list
// Search criteria
}
}
@@ -437,8 +429,8 @@ abstract class TriggerOnStateChange extends TriggerOnObject
*/
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "grant_by_profile,core/cmdb",
"key_type" => "autoincrement",
"name_attcode" => "description",
@@ -448,16 +440,16 @@ abstract class TriggerOnStateChange extends TriggerOnObject
"db_table" => "priv_trigger_onstatechange",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeClassState("state", array("class_field" => 'target_class', "allowed_values" => null, "sql" => "state", "default_value" => null, "is_null_allowed" => false, "depends_on" => array('target_class'))));
+ MetaModel::Init_AddAttribute(new AttributeClassState("state", ["class_field" => 'target_class', "allowed_values" => null, "sql" => "state", "default_value" => null, "is_null_allowed" => false, "depends_on" => ['target_class']]));
// Display lists
- MetaModel::Init_SetZListItems('details', array('description', 'context', 'target_class', 'filter', 'state', 'subscription_policy', 'action_list')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('finalclass', 'target_class', 'state')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['description', 'context', 'target_class', 'filter', 'state', 'subscription_policy', 'action_list']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['finalclass', 'target_class', 'state']); // Attributes to be displayed for a list
// Search criteria
- MetaModel::Init_SetZListItems('standard_search', array('description', 'target_class', 'state')); // Criteria of the std search form
+ MetaModel::Init_SetZListItems('standard_search', ['description', 'target_class', 'state']); // Criteria of the std search form
// MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
}
}
@@ -472,8 +464,8 @@ class TriggerOnStateEnter extends TriggerOnStateChange
*/
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "grant_by_profile,core/cmdb,application",
"key_type" => "autoincrement",
"name_attcode" => "description",
@@ -483,15 +475,15 @@ class TriggerOnStateEnter extends TriggerOnStateChange
"db_table" => "priv_trigger_onstateenter",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
// Display lists
- MetaModel::Init_SetZListItems('details', array('description', 'context', 'target_class', 'filter', 'state', 'subscription_policy', 'action_list')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('target_class', 'state')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['description', 'context', 'target_class', 'filter', 'state', 'subscription_policy', 'action_list']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['target_class', 'state']); // Attributes to be displayed for a list
// Search criteria
- MetaModel::Init_SetZListItems('standard_search', array('description', 'target_class', 'state')); // Criteria of the std search form
+ MetaModel::Init_SetZListItems('standard_search', ['description', 'target_class', 'state']); // Criteria of the std search form
// MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
}
}
@@ -506,8 +498,8 @@ class TriggerOnStateLeave extends TriggerOnStateChange
*/
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "grant_by_profile,core/cmdb,application",
"key_type" => "autoincrement",
"name_attcode" => "description",
@@ -517,15 +509,15 @@ class TriggerOnStateLeave extends TriggerOnStateChange
"db_table" => "priv_trigger_onstateleave",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
// Display lists
- MetaModel::Init_SetZListItems('details', array('description', 'context', 'target_class', 'filter', 'state', 'subscription_policy', 'action_list')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('target_class', 'state')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['description', 'context', 'target_class', 'filter', 'state', 'subscription_policy', 'action_list']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['target_class', 'state']); // Attributes to be displayed for a list
// Search criteria
- MetaModel::Init_SetZListItems('standard_search', array('description', 'target_class', 'state')); // Criteria of the std search form
+ MetaModel::Init_SetZListItems('standard_search', ['description', 'target_class', 'state']); // Criteria of the std search form
// MetaModel::Init_SetZListItems('advanced_search', array('')); // Criteria of the advanced search form
}
}
@@ -540,8 +532,8 @@ class TriggerOnObjectCreate extends TriggerOnObject
*/
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "grant_by_profile,core/cmdb,application",
"key_type" => "autoincrement",
"name_attcode" => "description",
@@ -551,15 +543,15 @@ class TriggerOnObjectCreate extends TriggerOnObject
"db_table" => "priv_trigger_onobjcreate",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
// Display lists
- MetaModel::Init_SetZListItems('details', array('description', 'context', 'target_class', 'filter', 'subscription_policy', 'action_list')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('finalclass', 'target_class')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['description', 'context', 'target_class', 'filter', 'subscription_policy', 'action_list']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['finalclass', 'target_class']); // Attributes to be displayed for a list
// Search criteria
- MetaModel::Init_SetZListItems('standard_search', array('description', 'target_class')); // Criteria of the std search form
+ MetaModel::Init_SetZListItems('standard_search', ['description', 'target_class']); // Criteria of the std search form
// MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
}
@@ -575,8 +567,8 @@ class TriggerOnObjectDelete extends TriggerOnObject
*/
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "grant_by_profile,core/cmdb,application",
"key_type" => "autoincrement",
"name_attcode" => "description",
@@ -586,15 +578,15 @@ class TriggerOnObjectDelete extends TriggerOnObject
"db_table" => "priv_trigger_onobjdelete",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
// Display lists
- MetaModel::Init_SetZListItems('details', array('description', 'context', 'target_class', 'filter', 'subscription_policy', 'action_list')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('finalclass', 'target_class')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['description', 'context', 'target_class', 'filter', 'subscription_policy', 'action_list']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['finalclass', 'target_class']); // Attributes to be displayed for a list
// Search criteria
- MetaModel::Init_SetZListItems('standard_search', array('description', 'target_class')); // Criteria of the std search form
+ MetaModel::Init_SetZListItems('standard_search', ['description', 'target_class']); // Criteria of the std search form
// MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
}
}
@@ -610,8 +602,8 @@ class TriggerOnObjectUpdate extends TriggerOnObject
*/
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "grant_by_profile,core/cmdb,application",
"key_type" => "autoincrement",
"name_attcode" => "description",
@@ -621,37 +613,33 @@ class TriggerOnObjectUpdate extends TriggerOnObject
"db_table" => "priv_trigger_onobjupdate",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeClassAttCodeSet('target_attcodes', array("allowed_values" => null, "class_field" => "target_class", "sql" => "target_attcodes", "default_value" => null, "is_null_allowed" => true, "max_items" => 20, "min_items" => 0, "attribute_definition_exclusion_list" => "AttributeDashboard,AttributeExternalField,AttributeFinalClass,AttributeFriendlyName,AttributeObsolescenceDate,AttributeObsolescenceFlag,AttributeSubItem", "attribute_definition_list" => null, "depends_on" => array('target_class'))));
+ MetaModel::Init_AddAttribute(new AttributeClassAttCodeSet('target_attcodes', ["allowed_values" => null, "class_field" => "target_class", "sql" => "target_attcodes", "default_value" => null, "is_null_allowed" => true, "max_items" => 20, "min_items" => 0, "attribute_definition_exclusion_list" => "AttributeDashboard,AttributeExternalField,AttributeFinalClass,AttributeFriendlyName,AttributeObsolescenceDate,AttributeObsolescenceFlag,AttributeSubItem", "attribute_definition_list" => null, "depends_on" => ['target_class']]));
// Display lists
- MetaModel::Init_SetZListItems('details', array('description', 'context', 'target_class', 'filter', 'target_attcodes', 'subscription_policy', 'action_list')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('finalclass', 'target_class')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['description', 'context', 'target_class', 'filter', 'target_attcodes', 'subscription_policy', 'action_list']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['finalclass', 'target_class']); // Attributes to be displayed for a list
// Search criteria
- MetaModel::Init_SetZListItems('standard_search', array('description', 'target_class')); // Criteria of the std search form
+ MetaModel::Init_SetZListItems('standard_search', ['description', 'target_class']); // Criteria of the std search form
}
- public function IsTargetObject($iObjectId, $aChanges = array())
+ public function IsTargetObject($iObjectId, $aChanges = [])
{
- if (!parent::IsTargetObject($iObjectId, $aChanges))
- {
+ if (!parent::IsTargetObject($iObjectId, $aChanges)) {
return false;
}
// Check the attribute
$oAttCodeSet = $this->Get('target_attcodes');
$aAttCodes = $oAttCodeSet->GetValues();
- if (empty($aAttCodes))
- {
+ if (empty($aAttCodes)) {
return true;
}
- foreach($aAttCodes as $sAttCode)
- {
- if (array_key_exists($sAttCode, $aChanges))
- {
+ foreach ($aAttCodes as $sAttCode) {
+ if (array_key_exists($sAttCode, $aChanges)) {
return true;
}
}
@@ -664,26 +652,22 @@ class TriggerOnObjectUpdate extends TriggerOnObject
// Remove unwanted attribute codes
$aChanges = $this->ListChanges();
- if (isset($aChanges['target_attcodes']))
- {
+ if (isset($aChanges['target_attcodes'])) {
$oAttDef = MetaModel::GetAttributeDef(get_class($this), 'target_attcodes');
- $aArgs = array('this' => $this);
+ $aArgs = ['this' => $this];
$aAllowedValues = $oAttDef->GetAllowedValues($aArgs);
/** @var \ormSet $oValue */
$oValue = $this->Get('target_attcodes');
$aValues = $oValue->GetValues();
$bChanged = false;
- foreach($aValues as $key => $sValue)
- {
- if (!isset($aAllowedValues[$sValue]))
- {
+ foreach ($aValues as $key => $sValue) {
+ if (!isset($aAllowedValues[$sValue])) {
unset($aValues[$key]);
$bChanged = true;
}
}
- if ($bChanged)
- {
+ if ($bChanged) {
$oValue->SetValues($aValues);
$this->Set('target_attcodes', $oValue);
}
@@ -706,8 +690,8 @@ class TriggerOnObjectMention extends TriggerOnObject
*/
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "grant_by_profile,core/cmdb,application",
"key_type" => "autoincrement",
"name_attcode" => "description",
@@ -718,16 +702,16 @@ class TriggerOnObjectMention extends TriggerOnObject
"db_key_field" => "id",
"db_finalclass_field" => "",
"display_template" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeOQL("mentioned_filter", array("allowed_values" => null, "sql" => "mentioned_filter", "default_value" => null, "is_null_allowed" => true, "depends_on" => array())));
+ MetaModel::Init_AddAttribute(new AttributeOQL("mentioned_filter", ["allowed_values" => null, "sql" => "mentioned_filter", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
// Display lists
- MetaModel::Init_SetZListItems('details', array('description', 'context', 'target_class', 'filter', 'mentioned_filter', 'subscription_policy', 'action_list')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('finalclass', 'target_class')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['description', 'context', 'target_class', 'filter', 'mentioned_filter', 'subscription_policy', 'action_list']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['finalclass', 'target_class']); // Attributes to be displayed for a list
// Search criteria
- MetaModel::Init_SetZListItems('standard_search', array('description', 'target_class')); // Criteria of the std search form
+ MetaModel::Init_SetZListItems('standard_search', ['description', 'target_class']); // Criteria of the std search form
}
/**
@@ -745,8 +729,7 @@ class TriggerOnObjectMention extends TriggerOnObject
public function IsMentionedObjectInScope(DBObject $oObject)
{
$sFilter = trim($this->Get('mentioned_filter'));
- if (strlen($sFilter) > 0)
- {
+ if (strlen($sFilter) > 0) {
$oSearch = DBObjectSearch::FromOQL($sFilter);
$sSearchClass = $oSearch->GetClass();
@@ -763,9 +746,7 @@ class TriggerOnObjectMention extends TriggerOnObject
$aParams = $oObject->ToArgs('this');
$oSet = new DBObjectSet($oSearch, [], $aParams);
$bRet = $oSet->CountExceeds(0);
- }
- else
- {
+ } else {
$bRet = true;
}
@@ -787,8 +768,8 @@ class TriggerOnAttributeBlobDownload extends TriggerOnObject
*/
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "grant_by_profile,core/cmdb,application",
"key_type" => "autoincrement",
"name_attcode" => "description",
@@ -799,7 +780,7 @@ class TriggerOnAttributeBlobDownload extends TriggerOnObject
"db_key_field" => "id",
"db_finalclass_field" => "",
"display_template" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
}
@@ -816,42 +797,42 @@ class lnkTriggerAction extends cmdbAbstractObject
*/
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "grant_by_profile,core/cmdb,application",
"key_type" => "autoincrement",
"name_attcode" => "",
"state_attcode" => "",
- "reconc_keys" => array('action_id', 'trigger_id'),
+ "reconc_keys" => ['action_id', 'trigger_id'],
"db_table" => "priv_link_action_trigger",
"db_key_field" => "link_id",
"db_finalclass_field" => "",
"is_link" => true,
- 'uniqueness_rules' => array(
- 'no_duplicate' => array(
- 'attributes' => array(
+ 'uniqueness_rules' => [
+ 'no_duplicate' => [
+ 'attributes' => [
0 => 'action_id',
1 => 'trigger_id',
- ),
+ ],
'filter' => '',
'disabled' => false,
'is_blocking' => true,
- ),
- ),
- );
+ ],
+ ],
+ ];
MetaModel::Init_Params($aParams);
- MetaModel::Init_AddAttribute(new AttributeExternalKey("action_id", array("targetclass" => "Action", "jointype" => '', "allowed_values" => null, "sql" => "action_id", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => array())));
- MetaModel::Init_AddAttribute(new AttributeExternalField("action_name", array("allowed_values" => null, "extkey_attcode" => 'action_id', "target_attcode" => "name")));
- MetaModel::Init_AddAttribute(new AttributeExternalKey("trigger_id", array("targetclass" => "Trigger", "jointype" => '', "allowed_values" => null, "sql" => "trigger_id", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => array())));
- MetaModel::Init_AddAttribute(new AttributeExternalField("trigger_name", array("allowed_values" => null, "extkey_attcode" => 'trigger_id', "target_attcode" => "description")));
- MetaModel::Init_AddAttribute(new AttributeInteger("order", array("allowed_values" => null, "sql" => "order", "default_value" => 0, "is_null_allowed" => true, "depends_on" => array())));
+ MetaModel::Init_AddAttribute(new AttributeExternalKey("action_id", ["targetclass" => "Action", "jointype" => '', "allowed_values" => null, "sql" => "action_id", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeExternalField("action_name", ["allowed_values" => null, "extkey_attcode" => 'action_id', "target_attcode" => "name"]));
+ MetaModel::Init_AddAttribute(new AttributeExternalKey("trigger_id", ["targetclass" => "Trigger", "jointype" => '', "allowed_values" => null, "sql" => "trigger_id", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeExternalField("trigger_name", ["allowed_values" => null, "extkey_attcode" => 'trigger_id', "target_attcode" => "description"]));
+ MetaModel::Init_AddAttribute(new AttributeInteger("order", ["allowed_values" => null, "sql" => "order", "default_value" => 0, "is_null_allowed" => true, "depends_on" => []]));
// Display lists
- MetaModel::Init_SetZListItems('details', array('action_id', 'trigger_id', 'order')); // Attributes to be displayed for a list
- MetaModel::Init_SetZListItems('list', array('action_id', 'trigger_id', 'order')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['action_id', 'trigger_id', 'order']); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('list', ['action_id', 'trigger_id', 'order']); // Attributes to be displayed for a list
// Search criteria
- MetaModel::Init_SetZListItems('standard_search', array('action_id', 'trigger_id', 'order')); // Criteria of the std search form
- MetaModel::Init_SetZListItems('advanced_search', array('action_id', 'trigger_id', 'order')); // Criteria of the advanced search form
+ MetaModel::Init_SetZListItems('standard_search', ['action_id', 'trigger_id', 'order']); // Criteria of the std search form
+ MetaModel::Init_SetZListItems('advanced_search', ['action_id', 'trigger_id', 'order']); // Criteria of the advanced search form
}
}
@@ -866,8 +847,8 @@ class TriggerOnThresholdReached extends TriggerOnObject
*/
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "grant_by_profile,core/cmdb,application",
"key_type" => "autoincrement",
"name_attcode" => "description",
@@ -877,18 +858,18 @@ class TriggerOnThresholdReached extends TriggerOnObject
"db_table" => "priv_trigger_threshold",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeClassAttCodeSet('stop_watch_code', array("allowed_values" => null, "class_field" => "target_class", "sql" => "stop_watch_code", "default_value" => null, "is_null_allowed" => false, "max_items" => 1, "min_items" => 1, "attribute_definition_exclusion_list" => null, "attribute_definition_list" => "AttributeStopWatch", "include_child_classes_attributes" => true, "depends_on" => array('target_class'))));
- MetaModel::Init_AddAttribute(new AttributeString("threshold_index", array("allowed_values" => null, "sql" => "threshold_index", "default_value" => null, "is_null_allowed" => false, "depends_on" => array())));
+ MetaModel::Init_AddAttribute(new AttributeClassAttCodeSet('stop_watch_code', ["allowed_values" => null, "class_field" => "target_class", "sql" => "stop_watch_code", "default_value" => null, "is_null_allowed" => false, "max_items" => 1, "min_items" => 1, "attribute_definition_exclusion_list" => null, "attribute_definition_list" => "AttributeStopWatch", "include_child_classes_attributes" => true, "depends_on" => ['target_class']]));
+ MetaModel::Init_AddAttribute(new AttributeString("threshold_index", ["allowed_values" => null, "sql" => "threshold_index", "default_value" => null, "is_null_allowed" => false, "depends_on" => []]));
// Display lists
- MetaModel::Init_SetZListItems('details', array('description', 'context', 'target_class', 'stop_watch_code', 'threshold_index', 'filter', 'subscription_policy', 'action_list')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('target_class', 'threshold_index', 'threshold_index')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['description', 'context', 'target_class', 'stop_watch_code', 'threshold_index', 'filter', 'subscription_policy', 'action_list']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['target_class', 'threshold_index', 'threshold_index']); // Attributes to be displayed for a list
// Search criteria
- MetaModel::Init_SetZListItems('standard_search', array('description', 'target_class')); // Criteria of the std search form
+ MetaModel::Init_SetZListItems('standard_search', ['description', 'target_class']); // Criteria of the std search form
// MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
}
}
diff --git a/core/valuesetdef.class.inc.php b/core/valuesetdef.class.inc.php
index 5fed013b0..8a9c91494 100644
--- a/core/valuesetdef.class.inc.php
+++ b/core/valuesetdef.class.inc.php
@@ -1,4 +1,5 @@
-
/**
* Value set definitions (from a fixed list or from a query, etc.)
*
@@ -37,16 +37,14 @@ require_once('MyHelpers.class.inc.php');
abstract class ValueSetDefinition
{
protected $m_bIsLoaded = false;
- protected $m_aValues = array();
-
+ protected $m_aValues = [];
// Displayable description that could be computed out of the std usage context
public function GetValuesDescription()
{
- $aValues = $this->GetValues(array(), '');
- $aDisplayedValues = array();
- foreach($aValues as $key => $value)
- {
+ $aValues = $this->GetValues([], '');
+ $aDisplayedValues = [];
+ foreach ($aValues as $key => $value) {
$aDisplayedValues[] = "$key => $value";
}
$sAllowedValues = implode(', ', $aDisplayedValues);
@@ -62,24 +60,18 @@ abstract class ValueSetDefinition
*/
public function GetValues($aArgs, $sContains = '', $sOperation = 'contains')
{
- if (!$this->m_bIsLoaded)
- {
+ if (!$this->m_bIsLoaded) {
$this->LoadValues($aArgs);
$this->m_bIsLoaded = true;
}
- if (strlen($sContains) == 0)
- {
+ if (strlen($sContains) == 0) {
// No filtering
$aRet = $this->m_aValues;
- }
- else
- {
+ } else {
// Filter on results containing the needle
- $aRet = array();
- foreach ($this->m_aValues as $sKey=>$sValue)
- {
- if (stripos($sValue, $sContains) !== false)
- {
+ $aRet = [];
+ foreach ($this->m_aValues as $sKey => $sValue) {
+ if (stripos($sValue, $sContains) !== false) {
$aRet[$sKey] = $sValue;
}
}
@@ -103,7 +95,6 @@ abstract class ValueSetDefinition
abstract protected function LoadValues($aArgs);
}
-
/**
* Set of existing values for an attribute, given a search filter
*
@@ -122,11 +113,10 @@ class ValueSetObjects extends ValueSetDefinition
private $m_bSort;
private $m_iLimit;
-
/**
* @param hash $aOrderBy Array of '[.]attcode' => bAscending
*/
- public function __construct($sFilterExp, $sValueAttCode = '', $aOrderBy = array(), $bAllowAllData = false, $aModifierProperties = array())
+ public function __construct($sFilterExp, $sValueAttCode = '', $aOrderBy = [], $bAllowAllData = false, $aModifierProperties = [])
{
$this->m_sContains = '';
$this->m_sOperation = '';
@@ -155,54 +145,48 @@ class ValueSetObjects extends ValueSetDefinition
{
$this->m_aOrderBy = $aOrderBy;
}
- public function ToObjectSet($aArgs = array(), $sContains = '', $iAdditionalValue = null)
+ public function ToObjectSet($aArgs = [], $sContains = '', $iAdditionalValue = null)
{
- if ($this->m_bAllowAllData)
- {
+ if ($this->m_bAllowAllData) {
$oFilter = DBObjectSearch::FromOQL_AllData($this->m_sFilterExpr);
- }
- else
- {
+ } else {
$oFilter = DBObjectSearch::FromOQL($this->m_sFilterExpr);
}
- if (!is_null($this->m_oExtraCondition))
- {
+ if (!is_null($this->m_oExtraCondition)) {
$oFilter = $oFilter->Intersect($this->m_oExtraCondition);
}
- foreach($this->m_aModifierProperties as $sPluginClass => $aProperties)
- {
- foreach ($aProperties as $sProperty => $value)
- {
+ foreach ($this->m_aModifierProperties as $sPluginClass => $aProperties) {
+ foreach ($aProperties as $sProperty => $value) {
$oFilter->SetModifierProperty($sPluginClass, $sProperty, $value);
}
}
- if ($iAdditionalValue > 0)
- {
+ if ($iAdditionalValue > 0) {
$oSearchAdditionalValue = new DBObjectSearch($oFilter->GetClass());
- $oSearchAdditionalValue->AddConditionExpression( new BinaryExpression(
- new FieldExpression('id', $oSearchAdditionalValue->GetClassAlias()),
- '=',
- new VariableExpression('current_extkey_id'))
- );
+ $oSearchAdditionalValue->AddConditionExpression(
+ new BinaryExpression(
+ new FieldExpression('id', $oSearchAdditionalValue->GetClassAlias()),
+ '=',
+ new VariableExpression('current_extkey_id')
+ )
+ );
$oSearchAdditionalValue->AllowAllData();
$oSearchAdditionalValue->SetArchiveMode(true);
- $oSearchAdditionalValue->SetInternalParams( array('current_extkey_id' => $iAdditionalValue) );
+ $oSearchAdditionalValue->SetInternalParams(['current_extkey_id' => $iAdditionalValue]);
- $oFilter = new DBUnionSearch(array($oFilter, $oSearchAdditionalValue));
+ $oFilter = new DBUnionSearch([$oFilter, $oSearchAdditionalValue]);
}
return new DBObjectSet($oFilter, $this->m_aOrderBy, $aArgs);
}
- /**
- * @inheritDoc
- * @throws CoreException
- * @throws OQLException
- */
- public function GetValues($aArgs, $sContains = '', $sOperation = 'contains')
+ /**
+ * @inheritDoc
+ * @throws CoreException
+ * @throws OQLException
+ */
+ public function GetValues($aArgs, $sContains = '', $sOperation = 'contains')
{
- if (!$this->m_bIsLoaded || ($sContains != $this->m_sContains) || ($sOperation != $this->m_sOperation))
- {
+ if (!$this->m_bIsLoaded || ($sContains != $this->m_sContains) || ($sOperation != $this->m_sOperation)) {
$this->LoadValues($aArgs, $sContains, $sOperation);
$this->m_bIsLoaded = true;
}
@@ -225,15 +209,15 @@ class ValueSetObjects extends ValueSetDefinition
$this->m_sContains = $sContains;
$this->m_sOperation = $sOperation;
- $this->m_aValues = array();
+ $this->m_aValues = [];
$oFilter = $this->GetFilter($sOperation, $sContains);
$oObjects = new DBObjectSet($oFilter, $this->m_aOrderBy, $aArgs, null, $this->m_iLimit, 0, $this->m_bSort);
if (empty($this->m_sValueAttCode)) {
- $aAttToLoad = array($oFilter->GetClassAlias() => array('friendlyname'));
+ $aAttToLoad = [$oFilter->GetClassAlias() => ['friendlyname']];
} else {
- $aAttToLoad = array($oFilter->GetClassAlias() => array($this->m_sValueAttCode));
+ $aAttToLoad = [$oFilter->GetClassAlias() => [$this->m_sValueAttCode]];
}
$oObjects->OptimizeColumnLoad($aAttToLoad);
while ($oObject = $oObjects->Fetch()) {
@@ -247,7 +231,6 @@ class ValueSetObjects extends ValueSetDefinition
return true;
}
-
/**
* Get filter for functions LoadValues and LoadValuesForAutocomplete
*
@@ -297,7 +280,7 @@ class ValueSetObjects extends ValueSetDefinition
$aAttributes = MetaModel::GetFriendlyNameAttributeCodeList($sClass);
if (count($aAttributes) > 0) {
$sClassAlias = $oFilter->GetClassAlias();
- $aFilters = array();
+ $aFilters = [];
$oValueExpr = new ScalarExpression($this->m_sContains);
foreach ($aAttributes as $sAttribute) {
$oNewFilter = $oFilter->DeepClone();
@@ -355,8 +338,7 @@ class ValueSetObjects extends ValueSetDefinition
public function GetValuesForAutocomplete($aArgs, $sContains = '', $sOperation = 'contains')
{
- if (!$this->m_bIsLoaded || ($sContains != $this->m_sContains) || ($sOperation != $this->m_sOperation))
- {
+ if (!$this->m_bIsLoaded || ($sContains != $this->m_sContains) || ($sOperation != $this->m_sOperation)) {
$this->LoadValuesForAutocomplete($aArgs, $sContains, $sOperation);
$this->m_bIsLoaded = true;
}
@@ -376,7 +358,7 @@ class ValueSetObjects extends ValueSetDefinition
*/
protected function LoadValuesForAutocomplete($aArgs, $sContains = '', $sOperation = 'contains')
{
- $this->m_aValues = array();
+ $this->m_aValues = [];
$oFilter = $this->GetFilter($sOperation, $sContains);
$sClass = $oFilter->GetClass();
@@ -444,7 +426,6 @@ class ValueSetObjects extends ValueSetDefinition
}
}
-
/**
* Fixed set values (could be hardcoded in the business model)
*
@@ -514,8 +495,7 @@ class ValueSetEnum extends ValueSetDefinition
protected function LoadValues($aArgs)
{
$aValues = [];
- if (is_array($this->m_values))
- {
+ if (is_array($this->m_values)) {
foreach ($this->m_values as $key => $value) {
// Handle backed-enum case
if (is_object($value) && enum_exists(get_class($value))) {
@@ -525,18 +505,13 @@ class ValueSetEnum extends ValueSetDefinition
$aValues[$key] = $value;
}
- }
- elseif (is_string($this->m_values) && strlen($this->m_values) > 0)
- {
- foreach (explode(",", $this->m_values) as $sVal)
- {
+ } elseif (is_string($this->m_values) && strlen($this->m_values) > 0) {
+ foreach (explode(",", $this->m_values) as $sVal) {
$sVal = trim($sVal);
$sKey = $sVal;
$aValues[$sKey] = $sVal;
}
- }
- else
- {
+ } else {
$aValues = [];
}
$this->m_aValues = $aValues;
@@ -553,17 +528,13 @@ class ValueSetEnumPadded extends ValueSetEnum
public function __construct($Values, bool $bSortByValues = false)
{
parent::__construct($Values, $bSortByValues);
- if (is_string($Values))
- {
+ if (is_string($Values)) {
$this->LoadValues(null);
- }
- else
- {
+ } else {
$this->m_aValues = $Values;
}
- $aPaddedValues = array();
- foreach ($this->m_aValues as $sKey => $sVal)
- {
+ $aPaddedValues = [];
+ foreach ($this->m_aValues as $sKey => $sVal) {
// Pad keys to the min. length required by the \AttributeSet
$sKey = str_pad($sKey, 3, '_', STR_PAD_LEFT);
$aPaddedValues[$sKey] = $sVal;
@@ -592,15 +563,13 @@ class ValueSetRange extends ValueSetDefinition
protected function LoadValues($aArgs)
{
$iValue = $this->m_iStart;
- for($iValue = $this->m_iStart; $iValue <= $this->m_iEnd; $iValue += $this->m_iStep)
- {
+ for ($iValue = $this->m_iStart; $iValue <= $this->m_iEnd; $iValue += $this->m_iStep) {
$this->m_aValues[$iValue] = $iValue;
}
return true;
}
}
-
/**
* Data model classes
*
@@ -622,27 +591,19 @@ class ValueSetEnumClasses extends ValueSetEnum
parent::LoadValues($aArgs);
// Translate the labels of the additional values
- foreach($this->m_aValues as $sClass => $void)
- {
- if (MetaModel::IsValidClass($sClass))
- {
+ foreach ($this->m_aValues as $sClass => $void) {
+ if (MetaModel::IsValidClass($sClass)) {
$this->m_aValues[$sClass] = MetaModel::GetName($sClass);
- }
- else
- {
+ } else {
unset($this->m_aValues[$sClass]);
}
}
// Then, add the classes from the category definition
- foreach (MetaModel::GetClasses($this->m_sCategories) as $sClass)
- {
- if (MetaModel::IsValidClass($sClass))
- {
+ foreach (MetaModel::GetClasses($this->m_sCategories) as $sClass) {
+ if (MetaModel::IsValidClass($sClass)) {
$this->m_aValues[$sClass] = MetaModel::GetName($sClass);
- }
- else
- {
+ } else {
unset($this->m_aValues[$sClass]);
}
}
diff --git a/datamodels/2.x/authent-cas/module.authent-cas.php b/datamodels/2.x/authent-cas/module.authent-cas.php
index 7f67bf3d1..bce236835 100644
--- a/datamodels/2.x/authent-cas/module.authent-cas.php
+++ b/datamodels/2.x/authent-cas/module.authent-cas.php
@@ -1,4 +1,5 @@
'CAS SSO',
@@ -14,36 +15,36 @@ SetupWebPage::AddModule(
// Setup
//
- 'dependencies' => array(
-
- ),
+ 'dependencies' => [
+
+ ],
'mandatory' => true,
'visible' => true,
// Components
//
- 'datamodel' => array(
+ 'datamodel' => [
'vendor/autoload.php',
'src/CASLoginExtension.php',
- ),
- 'webservice' => array(
-
- ),
- 'data.struct' => array(
+ ],
+ 'webservice' => [
+
+ ],
+ 'data.struct' => [
// add your 'structure' definition XML files here,
- ),
- 'data.sample' => array(
+ ],
+ 'data.sample' => [
// add your sample data XML files here,
- ),
-
+ ],
+
// Documentation
//
'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any
- 'doc.more_information' => '', // hyperlink to more information, if any
+ 'doc.more_information' => '', // hyperlink to more information, if any
// Default settings
//
- 'settings' => array(
+ 'settings' => [
// Authentication
'cas_debug' => false,
'cas_host' => '',
@@ -51,6 +52,6 @@ SetupWebPage::AddModule(
'cas_context' => '',
'cas_version' => '',
'service_base_url' => '',
- ),
- )
+ ],
+ ]
);
diff --git a/datamodels/2.x/authent-external/module.authent-external.php b/datamodels/2.x/authent-external/module.authent-external.php
index cd74ddbb2..d8046f28e 100755
--- a/datamodels/2.x/authent-external/module.authent-external.php
+++ b/datamodels/2.x/authent-external/module.authent-external.php
@@ -1,9 +1,10 @@
-
/**
* Authent External
* Module definition file for the "External Authentication" module
@@ -28,7 +28,7 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'authent-external/3.3.0',
- array(
+ [
// Identification
//
'label' => 'External user authentication',
@@ -36,23 +36,23 @@ SetupWebPage::AddModule(
// Setup
//
- 'dependencies' => array(
- ),
+ 'dependencies' => [
+ ],
'mandatory' => false,
'visible' => true,
// Components
//
- 'datamodel' => array(
+ 'datamodel' => [
'model.authent-external.php',
- ),
- 'data.struct' => array(
+ ],
+ 'data.struct' => [
//'data.struct.authent-ldap.xml',
- ),
- 'data.sample' => array(
+ ],
+ 'data.sample' => [
//'data.sample.authent-ldap.xml',
- ),
-
+ ],
+
// Documentation
//
'doc.manual_setup' => '',
@@ -60,6 +60,6 @@ SetupWebPage::AddModule(
// Default settings
//
- 'settings' => array(),
- )
+ 'settings' => [],
+ ]
);
diff --git a/datamodels/2.x/authent-ldap/module.authent-ldap.php b/datamodels/2.x/authent-ldap/module.authent-ldap.php
index d1f7cf715..7e66a72b7 100755
--- a/datamodels/2.x/authent-ldap/module.authent-ldap.php
+++ b/datamodels/2.x/authent-ldap/module.authent-ldap.php
@@ -1,100 +1,98 @@
'User authentication based on LDAP',
- 'category' => 'authentication',
+ SetupWebPage::AddModule(
+ __FILE__, // Path to the current file, all other file names are relative to the directory containing this file
+ 'authent-ldap/3.3.0',
+ [
+ // Identification
+ //
+ 'label' => 'User authentication based on LDAP',
+ 'category' => 'authentication',
- // Setup
- //
- 'dependencies' => array(
- ),
- 'mandatory' => false,
- 'visible' => true,
- 'installer' => 'AuthentLDAPInstaller',
+ // Setup
+ //
+ 'dependencies' => [
+ ],
+ 'mandatory' => false,
+ 'visible' => true,
+ 'installer' => 'AuthentLDAPInstaller',
- // Components
- //
- 'datamodel' => array(
- ),
- 'data.struct' => array(
- //'data.struct.authent-ldap.xml',
- ),
- 'data.sample' => array(
- //'data.sample.authent-ldap.xml',
- ),
-
- // Documentation
- //
- 'doc.manual_setup' => '',
- 'doc.more_information' => '',
+ // Components
+ //
+ 'datamodel' => [
+ ],
+ 'data.struct' => [
+ //'data.struct.authent-ldap.xml',
+ ],
+ 'data.sample' => [
+ //'data.sample.authent-ldap.xml',
+ ],
- // Default settings
- //
- 'settings' => array(
- 'uri' => 'ldap://localhost', // URI with host or IP address of your LDAP server
- 'default_user' => '', // User and password used for initial "Anonymous" bind to LDAP
- 'default_pwd' => '', // Leave both blank, if anonymous (read-only) bind is allowed
- 'base_dn' => 'dc=yourcompany,dc=com', // Base DN for User queries, adjust it to your LDAP schema
- 'user_query' => '(&(uid=%1$s)(inetuserstatus=ACTIVE))', // Query used to retrieve each user %1$s => iTop login
- // For Windows AD use (samaccountname=%1$s) or (userprincipalname=%1$s)
-
- // Some extra LDAP options, refer to: http://www.php.net/manual/en/function.ldap-set-option.php for more info
- 'options' => array(
- LDAP_OPT_PROTOCOL_VERSION => 3,
- LDAP_OPT_REFERRALS => 0,
- ),
- 'start_tls' => false,
- 'debug' => false,
- 'servers' => array(),
- ),
- )
-);
+ // Documentation
+ //
+ 'doc.manual_setup' => '',
+ 'doc.more_information' => '',
-// Module installation handler
-//
-class AuthentLDAPInstaller extends ModuleInstallerAPI
-{
- public static function AfterDataLoad(Config $oConfiguration, $sPreviousVersion, $sCurrentVersion)
+ // Default settings
+ //
+ 'settings' => [
+ 'uri' => 'ldap://localhost', // URI with host or IP address of your LDAP server
+ 'default_user' => '', // User and password used for initial "Anonymous" bind to LDAP
+ 'default_pwd' => '', // Leave both blank, if anonymous (read-only) bind is allowed
+ 'base_dn' => 'dc=yourcompany,dc=com', // Base DN for User queries, adjust it to your LDAP schema
+ 'user_query' => '(&(uid=%1$s)(inetuserstatus=ACTIVE))', // Query used to retrieve each user %1$s => iTop login
+ // For Windows AD use (samaccountname=%1$s) or (userprincipalname=%1$s)
+
+ // Some extra LDAP options, refer to: http://www.php.net/manual/en/function.ldap-set-option.php for more info
+ 'options' => [
+ LDAP_OPT_PROTOCOL_VERSION => 3,
+ LDAP_OPT_REFERRALS => 0,
+ ],
+ 'start_tls' => false,
+ 'debug' => false,
+ 'servers' => [],
+ ],
+ ]
+ );
+
+ // Module installation handler
+ //
+ class AuthentLDAPInstaller extends ModuleInstallerAPI
{
- // Create missing table entries
- $sUserLDAPTable = MetaModel::DBGetTable('UserLDAP');
- $sUserTable = MetaModel::DBGetTable('User');
- $sSQL = "insert into $sUserLDAPTable (id) select U.id from $sUserTable as U left join $sUserLDAPTable as L on U.id = L.id where U.finalclass='UserLDAP' and isnull(L.id);";
- CMDBSource::Query($sSQL);
- }
-
- public static function BeforeWritingConfig(Config $oConfiguration)
- {
- $sURI = $oConfiguration->GetModuleSetting('authent-ldap', 'uri');
- if (empty($sURI)) {
- $sLDAPHost = MetaModel::GetModuleSetting('authent-ldap', 'host', 'localhost');
- $iLDAPPort = MetaModel::GetModuleSetting('authent-ldap', 'port', 389);
- $sURI = preg_match('#^ldaps?://#i', $sLDAPHost) ? $sLDAPHost : 'ldap://'.$sLDAPHost.':'.$iLDAPPort;
- $oConfiguration->SetModuleSetting('authent-ldap', 'uri', $sURI);
+ public static function AfterDataLoad(Config $oConfiguration, $sPreviousVersion, $sCurrentVersion)
+ {
+ // Create missing table entries
+ $sUserLDAPTable = MetaModel::DBGetTable('UserLDAP');
+ $sUserTable = MetaModel::DBGetTable('User');
+ $sSQL = "insert into $sUserLDAPTable (id) select U.id from $sUserTable as U left join $sUserLDAPTable as L on U.id = L.id where U.finalclass='UserLDAP' and isnull(L.id);";
+ CMDBSource::Query($sSQL);
}
- $aServers = $oConfiguration->GetModuleSetting('authent-ldap', 'servers', []);
- foreach ($aServers as &$aServer) {
- if (!array_key_exists($aServer, 'uri')) {
- $sLDAPHost = $aServerParams['host'] ?? 'localhost';
- $iLDAPPort = $aServerParams['port'] ?? 389;
- $aServer['uri'] = preg_match('#^ldaps?://#i', $sLDAPHost) ? $sLDAPHost : 'ldap://'.$sLDAPHost.':'.$iLDAPPort;
+ public static function BeforeWritingConfig(Config $oConfiguration)
+ {
+ $sURI = $oConfiguration->GetModuleSetting('authent-ldap', 'uri');
+ if (empty($sURI)) {
+ $sLDAPHost = MetaModel::GetModuleSetting('authent-ldap', 'host', 'localhost');
+ $iLDAPPort = MetaModel::GetModuleSetting('authent-ldap', 'port', 389);
+ $sURI = preg_match('#^ldaps?://#i', $sLDAPHost) ? $sLDAPHost : 'ldap://'.$sLDAPHost.':'.$iLDAPPort;
+ $oConfiguration->SetModuleSetting('authent-ldap', 'uri', $sURI);
}
+
+ $aServers = $oConfiguration->GetModuleSetting('authent-ldap', 'servers', []);
+ foreach ($aServers as &$aServer) {
+ if (!array_key_exists($aServer, 'uri')) {
+ $sLDAPHost = $aServerParams['host'] ?? 'localhost';
+ $iLDAPPort = $aServerParams['port'] ?? 389;
+ $aServer['uri'] = preg_match('#^ldaps?://#i', $sLDAPHost) ? $sLDAPHost : 'ldap://'.$sLDAPHost.':'.$iLDAPPort;
+ }
+ }
+ $oConfiguration->SetModuleSetting('authent-ldap', 'servers', $aServers);
}
- $oConfiguration->SetModuleSetting('authent-ldap', 'servers', $aServers);
}
-}
} // if (function_exists('ldap_connect'))
diff --git a/datamodels/2.x/authent-local/module.authent-local.php b/datamodels/2.x/authent-local/module.authent-local.php
index c1f008f39..19eb5e854 100755
--- a/datamodels/2.x/authent-local/module.authent-local.php
+++ b/datamodels/2.x/authent-local/module.authent-local.php
@@ -1,10 +1,9 @@
'User authentication based on the local DB',
@@ -12,23 +11,23 @@ SetupWebPage::AddModule(
// Setup
//
- 'dependencies' => array(
- ),
+ 'dependencies' => [
+ ],
'mandatory' => true,
'visible' => true,
// Components
//
- 'datamodel' => array(
+ 'datamodel' => [
'model.authent-local.php',
- ),
- 'data.struct' => array(
+ ],
+ 'data.struct' => [
//'data.struct.authent-local.xml',
- ),
- 'data.sample' => array(
+ ],
+ 'data.sample' => [
//'data.sample.authent-local.xml',
- ),
-
+ ],
+
// Documentation
//
'doc.manual_setup' => '',
@@ -37,8 +36,8 @@ SetupWebPage::AddModule(
// Default settings
//
- 'settings' => array(
+ 'settings' => [
// see the './datamodel.authent-local.xml' for the default settings!
- ),
- )
+ ],
+ ]
);
diff --git a/datamodels/2.x/combodo-backoffice-darkmoon-theme/module.combodo-backoffice-darkmoon-theme.php b/datamodels/2.x/combodo-backoffice-darkmoon-theme/module.combodo-backoffice-darkmoon-theme.php
index abda98f5e..9175680f0 100644
--- a/datamodels/2.x/combodo-backoffice-darkmoon-theme/module.combodo-backoffice-darkmoon-theme.php
+++ b/datamodels/2.x/combodo-backoffice-darkmoon-theme/module.combodo-backoffice-darkmoon-theme.php
@@ -1,4 +1,5 @@
'Backoffice: Darkmoon theme',
@@ -14,38 +15,35 @@ SetupWebPage::AddModule(
// Setup
//
- 'dependencies' => array(
-
- ),
+ 'dependencies' => [
+
+ ],
'mandatory' => true,
'visible' => false,
// Components
//
- 'datamodel' => array(
- ),
- 'webservice' => array(
-
- ),
- 'data.struct' => array(
+ 'datamodel' => [
+ ],
+ 'webservice' => [
+
+ ],
+ 'data.struct' => [
// add your 'structure' definition XML files here,
- ),
- 'data.sample' => array(
+ ],
+ 'data.sample' => [
// add your sample data XML files here,
- ),
-
+ ],
+
// Documentation
//
'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any
- 'doc.more_information' => '', // hyperlink to more information, if any
+ 'doc.more_information' => '', // hyperlink to more information, if any
// Default settings
//
- 'settings' => array(
+ 'settings' => [
// Module specific settings go here, if any
- ),
- )
+ ],
+ ]
);
-
-
-?>
diff --git a/datamodels/2.x/combodo-backoffice-fullmoon-high-contrast-theme/module.combodo-backoffice-fullmoon-high-contrast-theme.php b/datamodels/2.x/combodo-backoffice-fullmoon-high-contrast-theme/module.combodo-backoffice-fullmoon-high-contrast-theme.php
index d9567881f..87d38fa5a 100644
--- a/datamodels/2.x/combodo-backoffice-fullmoon-high-contrast-theme/module.combodo-backoffice-fullmoon-high-contrast-theme.php
+++ b/datamodels/2.x/combodo-backoffice-fullmoon-high-contrast-theme/module.combodo-backoffice-fullmoon-high-contrast-theme.php
@@ -1,4 +1,5 @@
'Backoffice: Fullmoon with high contrast accessibility theme',
@@ -14,38 +15,35 @@ SetupWebPage::AddModule(
// Setup
//
- 'dependencies' => array(
-
- ),
+ 'dependencies' => [
+
+ ],
'mandatory' => true,
'visible' => false,
// Components
//
- 'datamodel' => array(
- ),
- 'webservice' => array(
-
- ),
- 'data.struct' => array(
+ 'datamodel' => [
+ ],
+ 'webservice' => [
+
+ ],
+ 'data.struct' => [
// add your 'structure' definition XML files here,
- ),
- 'data.sample' => array(
+ ],
+ 'data.sample' => [
// add your sample data XML files here,
- ),
-
+ ],
+
// Documentation
//
'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any
- 'doc.more_information' => '', // hyperlink to more information, if any
+ 'doc.more_information' => '', // hyperlink to more information, if any
// Default settings
//
- 'settings' => array(
+ 'settings' => [
// Module specific settings go here, if any
- ),
- )
+ ],
+ ]
);
-
-
-?>
diff --git a/datamodels/2.x/combodo-backoffice-fullmoon-protanopia-deuteranopia-theme/module.combodo-backoffice-fullmoon-protanopia-deuteranopia-theme.php b/datamodels/2.x/combodo-backoffice-fullmoon-protanopia-deuteranopia-theme/module.combodo-backoffice-fullmoon-protanopia-deuteranopia-theme.php
index a058c5690..1f4fd1016 100644
--- a/datamodels/2.x/combodo-backoffice-fullmoon-protanopia-deuteranopia-theme/module.combodo-backoffice-fullmoon-protanopia-deuteranopia-theme.php
+++ b/datamodels/2.x/combodo-backoffice-fullmoon-protanopia-deuteranopia-theme/module.combodo-backoffice-fullmoon-protanopia-deuteranopia-theme.php
@@ -1,4 +1,5 @@
'Backoffice: Fullmoon with protonopia & deuteranopia accessibility theme',
@@ -14,38 +15,35 @@ SetupWebPage::AddModule(
// Setup
//
- 'dependencies' => array(
-
- ),
+ 'dependencies' => [
+
+ ],
'mandatory' => true,
'visible' => false,
// Components
//
- 'datamodel' => array(
- ),
- 'webservice' => array(
-
- ),
- 'data.struct' => array(
+ 'datamodel' => [
+ ],
+ 'webservice' => [
+
+ ],
+ 'data.struct' => [
// add your 'structure' definition XML files here,
- ),
- 'data.sample' => array(
+ ],
+ 'data.sample' => [
// add your sample data XML files here,
- ),
-
+ ],
+
// Documentation
//
'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any
- 'doc.more_information' => '', // hyperlink to more information, if any
+ 'doc.more_information' => '', // hyperlink to more information, if any
// Default settings
//
- 'settings' => array(
+ 'settings' => [
// Module specific settings go here, if any
- ),
- )
+ ],
+ ]
);
-
-
-?>
diff --git a/datamodels/2.x/combodo-backoffice-fullmoon-tritanopia-theme/module.combodo-backoffice-fullmoon-tritanopia-theme.php b/datamodels/2.x/combodo-backoffice-fullmoon-tritanopia-theme/module.combodo-backoffice-fullmoon-tritanopia-theme.php
index ed02d278a..d4d818f38 100644
--- a/datamodels/2.x/combodo-backoffice-fullmoon-tritanopia-theme/module.combodo-backoffice-fullmoon-tritanopia-theme.php
+++ b/datamodels/2.x/combodo-backoffice-fullmoon-tritanopia-theme/module.combodo-backoffice-fullmoon-tritanopia-theme.php
@@ -1,4 +1,5 @@
'Backoffice: Fullmoon with tritanopia accessibility theme',
@@ -14,38 +15,35 @@ SetupWebPage::AddModule(
// Setup
//
- 'dependencies' => array(
-
- ),
+ 'dependencies' => [
+
+ ],
'mandatory' => true,
'visible' => false,
// Components
//
- 'datamodel' => array(
- ),
- 'webservice' => array(
-
- ),
- 'data.struct' => array(
+ 'datamodel' => [
+ ],
+ 'webservice' => [
+
+ ],
+ 'data.struct' => [
// add your 'structure' definition XML files here,
- ),
- 'data.sample' => array(
+ ],
+ 'data.sample' => [
// add your sample data XML files here,
- ),
-
+ ],
+
// Documentation
//
'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any
- 'doc.more_information' => '', // hyperlink to more information, if any
+ 'doc.more_information' => '', // hyperlink to more information, if any
// Default settings
//
- 'settings' => array(
+ 'settings' => [
// Module specific settings go here, if any
- ),
- )
+ ],
+ ]
);
-
-
-?>
diff --git a/datamodels/2.x/combodo-db-tools/module.combodo-db-tools.php b/datamodels/2.x/combodo-db-tools/module.combodo-db-tools.php
index 5c48fe12b..a2a33fd89 100644
--- a/datamodels/2.x/combodo-db-tools/module.combodo-db-tools.php
+++ b/datamodels/2.x/combodo-db-tools/module.combodo-db-tools.php
@@ -1,4 +1,5 @@
'Database maintenance tools',
@@ -33,21 +34,21 @@ SetupWebPage::AddModule(
// Setup
//
- 'dependencies' => array(
+ 'dependencies' => [
'itop-structure/3.0.0',
- ),
+ ],
'mandatory' => false,
'visible' => true,
// Components
//
- 'datamodel' => array(
+ 'datamodel' => [
'src/Service/DBToolsUtils.php',
- 'src/Service/DBAnalyzerUtils.php',
- ),
- 'webservice' => array(),
- 'data.struct' => array(),
- 'data.sample' => array(),
+ 'src/Service/DBAnalyzerUtils.php',
+ ],
+ 'webservice' => [],
+ 'data.struct' => [],
+ 'data.sample' => [],
// Documentation
//
@@ -56,6 +57,6 @@ SetupWebPage::AddModule(
// Default settings
//
- 'settings' => array(),
- )
+ 'settings' => [],
+ ]
);
diff --git a/datamodels/2.x/itop-attachments/dictionaries/cs.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/cs.dict.itop-attachments.php
index 7d72ab48b..bf417ccc8 100644
--- a/datamodels/2.x/itop-attachments/dictionaries/cs.dict.itop-attachments.php
+++ b/datamodels/2.x/itop-attachments/dictionaries/cs.dict.itop-attachments.php
@@ -1,17 +1,18 @@
* @author Daniel Rokos
*
*/
-Dict::Add('CS CZ', 'Czech', 'Čeština', array(
+Dict::Add('CS CZ', 'Czech', 'Čeština', [
'Attachments:TabTitle_Count' => 'Přílohy (%1$d)',
'Attachments:EmptyTabTitle' => 'Přílohy',
'Attachments:FieldsetTitle' => 'Přílohy',
@@ -32,13 +33,13 @@ nebe se zeptejte'.ITOP_APPLICATION_SHORT.' správce '.ITOP_APPLICATION_SHORT.' z
'Attachments:Render:Icons' => 'Zobrazit jako ikony',
'Attachments:Render:Table' => 'Zobrazit jako seznam',
'UI:Attachments:DropYourFileHint' => 'Drop files anywhere in this area~~',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('CS CZ', 'Czech', 'Čeština', array(
+Dict::Add('CS CZ', 'Czech', 'Čeština', [
'Class:Attachment' => 'Příloha',
'Class:Attachment+' => '~~',
'Class:Attachment/Attribute:expire' => 'Exspirace',
@@ -53,10 +54,9 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array(
'Class:Attachment/Attribute:item_org_id+' => '~~',
'Class:Attachment/Attribute:contents' => 'Obsah',
'Class:Attachment/Attribute:contents+' => '~~',
-));
+]);
-
-Dict::Add('CS CZ', 'Czech', 'Čeština', array(
+Dict::Add('CS CZ', 'Czech', 'Čeština', [
'Attachments:File:Thumbnail' => 'Ikona',
'Attachments:File:Name' => 'Jméno souboru',
'Attachments:File:Date' => 'Datum nahrání',
@@ -64,25 +64,25 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array(
'Attachments:File:Size' => 'Velikost',
'Attachments:File:MimeType' => 'Typ',
'Attachments:File:DownloadsCount' => 'Staženo',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('CS CZ', 'Czech', 'Čeština', array(
+Dict::Add('CS CZ', 'Czech', 'Čeština', [
'Class:Attachment/Attribute:creation_date' => 'Datum vytvoření',
'Class:Attachment/Attribute:creation_date+' => '~~',
'Class:Attachment/Attribute:user_id' => 'Jméno uživatele',
'Class:Attachment/Attribute:user_id+' => '~~',
'Class:Attachment/Attribute:contact_id' => 'Kontakt',
'Class:Attachment/Attribute:contact_id+' => '~~',
-));
+]);
//
// Class: TriggerOnAttachmentDownload
//
-Dict::Add('CS CZ', 'Czech', 'Čeština', array(
+Dict::Add('CS CZ', 'Czech', 'Čeština', [
'Class:TriggerOnAttachmentDownload' => 'Trigger (on object\'s attachment download)~~',
'Class:TriggerOnAttachmentDownload+' => 'Trigger on object\'s attachment download of [a child class of] the given class~~',
'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~',
@@ -91,5 +91,5 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array(
'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~',
'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~',
'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~',
- 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
-));
+ 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
+]);
diff --git a/datamodels/2.x/itop-attachments/dictionaries/da.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/da.dict.itop-attachments.php
index c570511bf..6fbbe5f2a 100644
--- a/datamodels/2.x/itop-attachments/dictionaries/da.dict.itop-attachments.php
+++ b/datamodels/2.x/itop-attachments/dictionaries/da.dict.itop-attachments.php
@@ -1,16 +1,17 @@
*
*/
-Dict::Add('DA DA', 'Danish', 'Dansk', array(
+Dict::Add('DA DA', 'Danish', 'Dansk', [
'Attachments:TabTitle_Count' => 'Vedhæftninger (%1$d)',
'Attachments:EmptyTabTitle' => 'Vedhæftninger',
'Attachments:FieldsetTitle' => 'Vedhæftninger',
@@ -31,13 +32,13 @@ or ask your '.ITOP_APPLICATION_SHORT.' administrator if the '.ITOP_APPLICATION_S
'Attachments:Render:Icons' => 'Display as icons~~',
'Attachments:Render:Table' => 'Display as list~~',
'UI:Attachments:DropYourFileHint' => 'Drop files anywhere in this area~~',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('DA DA', 'Danish', 'Dansk', array(
+Dict::Add('DA DA', 'Danish', 'Dansk', [
'Class:Attachment' => 'Attachment~~',
'Class:Attachment+' => '~~',
'Class:Attachment/Attribute:expire' => 'Expire~~',
@@ -52,10 +53,9 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array(
'Class:Attachment/Attribute:item_org_id+' => '~~',
'Class:Attachment/Attribute:contents' => 'Contents~~',
'Class:Attachment/Attribute:contents+' => '~~',
-));
+]);
-
-Dict::Add('DA DA', 'Danish', 'Dansk', array(
+Dict::Add('DA DA', 'Danish', 'Dansk', [
'Attachments:File:Thumbnail' => 'Icon~~',
'Attachments:File:Name' => 'File name~~',
'Attachments:File:Date' => 'Upload date~~',
@@ -63,25 +63,25 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array(
'Attachments:File:Size' => 'Size~~',
'Attachments:File:MimeType' => 'Type~~',
'Attachments:File:DownloadsCount' => 'Downloads~~',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('DA DA', 'Danish', 'Dansk', array(
+Dict::Add('DA DA', 'Danish', 'Dansk', [
'Class:Attachment/Attribute:creation_date' => 'Creation date~~',
'Class:Attachment/Attribute:creation_date+' => '~~',
'Class:Attachment/Attribute:user_id' => 'User id~~',
'Class:Attachment/Attribute:user_id+' => '~~',
'Class:Attachment/Attribute:contact_id' => 'Contact id~~',
'Class:Attachment/Attribute:contact_id+' => '~~',
-));
+]);
//
// Class: TriggerOnAttachmentDownload
//
-Dict::Add('DA DA', 'Danish', 'Dansk', array(
+Dict::Add('DA DA', 'Danish', 'Dansk', [
'Class:TriggerOnAttachmentDownload' => 'Trigger (on object\'s attachment download)~~',
'Class:TriggerOnAttachmentDownload+' => 'Trigger on object\'s attachment download of [a child class of] the given class~~',
'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~',
@@ -90,5 +90,5 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array(
'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~',
'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~',
'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~',
- 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
-));
+ 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
+]);
diff --git a/datamodels/2.x/itop-attachments/dictionaries/de.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/de.dict.itop-attachments.php
index 40d74d363..5749f92b9 100644
--- a/datamodels/2.x/itop-attachments/dictionaries/de.dict.itop-attachments.php
+++ b/datamodels/2.x/itop-attachments/dictionaries/de.dict.itop-attachments.php
@@ -1,16 +1,17 @@
*
*/
-Dict::Add('DE DE', 'German', 'Deutsch', array(
+Dict::Add('DE DE', 'German', 'Deutsch', [
'Attachments:TabTitle_Count' => 'Attachments (%1$d)',
'Attachments:EmptyTabTitle' => 'Attachments',
'Attachments:FieldsetTitle' => 'Attachments',
@@ -31,13 +32,13 @@ oder melden Sie dem '.ITOP_APPLICATION_SHORT.' Administrator diesen Fehler, weil
'Attachments:Render:Icons' => 'Als Icons anzeigen',
'Attachments:Render:Table' => 'Als Liste anzeigen',
'UI:Attachments:DropYourFileHint' => 'Dateien in diesem Bereich ablegen...',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('DE DE', 'German', 'Deutsch', array(
+Dict::Add('DE DE', 'German', 'Deutsch', [
'Class:Attachment' => 'Attachment',
'Class:Attachment+' => '',
'Class:Attachment/Attribute:expire' => 'Läuft ab',
@@ -52,10 +53,9 @@ Dict::Add('DE DE', 'German', 'Deutsch', array(
'Class:Attachment/Attribute:item_org_id+' => '',
'Class:Attachment/Attribute:contents' => 'Inhalt',
'Class:Attachment/Attribute:contents+' => '',
-));
+]);
-
-Dict::Add('DE DE', 'German', 'Deutsch', array(
+Dict::Add('DE DE', 'German', 'Deutsch', [
'Attachments:File:Thumbnail' => 'Icon',
'Attachments:File:Name' => 'Dateiname',
'Attachments:File:Date' => 'Upload-Datum',
@@ -63,25 +63,25 @@ Dict::Add('DE DE', 'German', 'Deutsch', array(
'Attachments:File:Size' => 'Größe',
'Attachments:File:MimeType' => 'Typ',
'Attachments:File:DownloadsCount' => 'Downloads',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('DE DE', 'German', 'Deutsch', array(
+Dict::Add('DE DE', 'German', 'Deutsch', [
'Class:Attachment/Attribute:creation_date' => 'Erstellungsdatum',
'Class:Attachment/Attribute:creation_date+' => '',
'Class:Attachment/Attribute:user_id' => 'Benutzer ID',
'Class:Attachment/Attribute:user_id+' => '',
'Class:Attachment/Attribute:contact_id' => 'Kontakt ID',
'Class:Attachment/Attribute:contact_id+' => '',
-));
+]);
//
// Class: TriggerOnAttachmentDownload
//
-Dict::Add('DE DE', 'German', 'Deutsch', array(
+Dict::Add('DE DE', 'German', 'Deutsch', [
'Class:TriggerOnAttachmentDownload' => 'Trigger (beim Herunterladen eines Attachment eines Objekts)',
'Class:TriggerOnAttachmentDownload+' => 'Trigger für das Herunterladen des Attachments der angegebenen Klasse oder einer Unterklasse',
'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~',
@@ -90,5 +90,5 @@ Dict::Add('DE DE', 'German', 'Deutsch', array(
'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~',
'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~',
'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~',
- 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
-));
+ 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
+]);
diff --git a/datamodels/2.x/itop-attachments/dictionaries/en.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/en.dict.itop-attachments.php
index f334994eb..3263ab53c 100644
--- a/datamodels/2.x/itop-attachments/dictionaries/en.dict.itop-attachments.php
+++ b/datamodels/2.x/itop-attachments/dictionaries/en.dict.itop-attachments.php
@@ -1,4 +1,5 @@
'Attachments (%1$d)',
'Attachments:EmptyTabTitle' => 'Attachments',
'Attachments:FieldsetTitle' => 'Attachments',
@@ -38,13 +39,13 @@ or ask your '.ITOP_APPLICATION_SHORT.' administrator if the '.ITOP_APPLICATION_S
'Attachments:Render:Icons' => 'Display as icons',
'Attachments:Render:Table' => 'Display as list',
'UI:Attachments:DropYourFileHint' => 'Drop files anywhere in this area',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('EN US', 'English', 'English', array(
+Dict::Add('EN US', 'English', 'English', [
'Class:Attachment' => 'Attachment',
'Class:Attachment+' => '',
'Class:Attachment/Attribute:expire' => 'Expire',
@@ -59,10 +60,9 @@ Dict::Add('EN US', 'English', 'English', array(
'Class:Attachment/Attribute:item_org_id+' => '',
'Class:Attachment/Attribute:contents' => 'Contents',
'Class:Attachment/Attribute:contents+' => '',
-));
+]);
-
-Dict::Add('EN US', 'English', 'English', array(
+Dict::Add('EN US', 'English', 'English', [
'Attachments:File:Thumbnail' => 'Icon',
'Attachments:File:Name' => 'File name',
'Attachments:File:Date' => 'Upload date',
@@ -70,25 +70,25 @@ Dict::Add('EN US', 'English', 'English', array(
'Attachments:File:Size' => 'Size',
'Attachments:File:MimeType' => 'Type',
'Attachments:File:DownloadsCount' => 'Downloads',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('EN US', 'English', 'English', array(
+Dict::Add('EN US', 'English', 'English', [
'Class:Attachment/Attribute:creation_date' => 'Creation date',
'Class:Attachment/Attribute:creation_date+' => '',
'Class:Attachment/Attribute:user_id' => 'User id',
'Class:Attachment/Attribute:user_id+' => '',
'Class:Attachment/Attribute:contact_id' => 'Contact id',
'Class:Attachment/Attribute:contact_id+' => '',
-));
+]);
//
// Class: TriggerOnAttachmentDownload
//
-Dict::Add('EN US', 'English', 'English', array(
+Dict::Add('EN US', 'English', 'English', [
'Class:TriggerOnAttachmentDownload' => 'Trigger (on object\'s attachment download)',
'Class:TriggerOnAttachmentDownload+' => 'Trigger on object\'s attachment download of [a child class of] the given class',
'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)',
@@ -97,5 +97,5 @@ Dict::Add('EN US', 'English', 'English', array(
'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete',
'Class:TriggerOnAttachmentCreate/Attribute:file_in_email' => 'Add file in email',
'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered',
- 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger',
-));
+ 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger',
+]);
diff --git a/datamodels/2.x/itop-attachments/dictionaries/es_cr.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/es_cr.dict.itop-attachments.php
index 3f0e7d721..522fec5b2 100644
--- a/datamodels/2.x/itop-attachments/dictionaries/es_cr.dict.itop-attachments.php
+++ b/datamodels/2.x/itop-attachments/dictionaries/es_cr.dict.itop-attachments.php
@@ -1,13 +1,14 @@
- * @notas Utilizar codificación UTF-8 para mostrar acentos y otros caracteres especiales
+ * @notas Utilizar codificación UTF-8 para mostrar acentos y otros caracteres especiales
*/
-Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array(
+Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [
'Attachments:TabTitle_Count' => 'Anexos (%1$d)',
'Attachments:EmptyTabTitle' => 'Anexos',
'Attachments:FieldsetTitle' => 'Anexos',
@@ -28,13 +29,13 @@ o pregunte al administador de iTop si el servidor que ha quedado sin espacio en
'Attachments:Render:Icons' => 'Desplegar como icono',
'Attachments:Render:Table' => 'Desplegar como lista',
'UI:Attachments:DropYourFileHint' => 'Arrastre los archivos en cualquier lugar de esta área',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array(
+Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [
'Class:Attachment' => 'Anexo',
'Class:Attachment+' => 'Anexo',
'Class:Attachment/Attribute:expire' => 'Expira',
@@ -49,10 +50,9 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array(
'Class:Attachment/Attribute:item_org_id+' => '',
'Class:Attachment/Attribute:contents' => 'Contenido',
'Class:Attachment/Attribute:contents+' => '',
-));
+]);
-
-Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array(
+Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [
'Attachments:File:Thumbnail' => 'Ícono',
'Attachments:File:Name' => 'Nombre de Archivo',
'Attachments:File:Date' => 'Fecha de Carga',
@@ -60,25 +60,25 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array(
'Attachments:File:Size' => 'Tamaño',
'Attachments:File:MimeType' => 'Tipo',
'Attachments:File:DownloadsCount' => 'Descargas',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array(
+Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [
'Class:Attachment/Attribute:creation_date' => 'Fecha de Creación',
'Class:Attachment/Attribute:creation_date+' => '',
'Class:Attachment/Attribute:user_id' => 'Id del Usuario',
'Class:Attachment/Attribute:user_id+' => '',
'Class:Attachment/Attribute:contact_id' => 'Id del Contacto',
'Class:Attachment/Attribute:contact_id+' => '',
-));
+]);
//
// Class: TriggerOnAttachmentDownload
//
-Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array(
+Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [
'Class:TriggerOnAttachmentDownload' => 'Disparador (al descargar el archivo adjunto del objeto)',
'Class:TriggerOnAttachmentDownload+' => 'Disparador al descargar el archivo adjunto del objeto de [una clase secundaria de] la clase dada',
'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~',
@@ -87,5 +87,5 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array(
'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~',
'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~',
'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~',
- 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
-));
+ 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
+]);
diff --git a/datamodels/2.x/itop-attachments/dictionaries/fr.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/fr.dict.itop-attachments.php
index cc3c012dc..016362763 100644
--- a/datamodels/2.x/itop-attachments/dictionaries/fr.dict.itop-attachments.php
+++ b/datamodels/2.x/itop-attachments/dictionaries/fr.dict.itop-attachments.php
@@ -1,15 +1,16 @@
'Pièces jointes (%1$d)',
'Attachments:EmptyTabTitle' => 'Pièces jointes',
'Attachments:FieldsetTitle' => 'Pièces jointes',
@@ -30,13 +31,13 @@ Soit demandez à votre administrateur système s\'il reste de la place disque di
'Attachments:Render:Icons' => 'Affichage en icônes',
'Attachments:Render:Table' => 'Affichage en liste',
'UI:Attachments:DropYourFileHint' => 'Déposez vos fichiers dans cet espace',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('FR FR', 'French', 'Français', array(
+Dict::Add('FR FR', 'French', 'Français', [
'Class:Attachment' => 'Attachement',
'Class:Attachment+' => '',
'Class:Attachment/Attribute:expire' => 'Expire',
@@ -51,10 +52,9 @@ Dict::Add('FR FR', 'French', 'Français', array(
'Class:Attachment/Attribute:item_org_id+' => '',
'Class:Attachment/Attribute:contents' => 'Contenu',
'Class:Attachment/Attribute:contents+' => '',
-));
+]);
-
-Dict::Add('FR FR', 'French', 'Français', array(
+Dict::Add('FR FR', 'French', 'Français', [
'Attachments:File:Thumbnail' => 'Icône',
'Attachments:File:Name' => 'Nom du fichier',
'Attachments:File:Date' => 'Date de chargement',
@@ -62,25 +62,25 @@ Dict::Add('FR FR', 'French', 'Français', array(
'Attachments:File:Size' => 'Taille',
'Attachments:File:MimeType' => 'Type',
'Attachments:File:DownloadsCount' => 'Téléchargements',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('FR FR', 'French', 'Français', array(
+Dict::Add('FR FR', 'French', 'Français', [
'Class:Attachment/Attribute:creation_date' => 'Date de création',
'Class:Attachment/Attribute:creation_date+' => '',
'Class:Attachment/Attribute:user_id' => 'Utilisateur',
'Class:Attachment/Attribute:user_id+' => '',
'Class:Attachment/Attribute:contact_id' => 'Contact',
'Class:Attachment/Attribute:contact_id+' => '',
-));
+]);
//
// Class: TriggerOnAttachmentDownload
//
-Dict::Add('FR FR', 'French', 'Français', array(
+Dict::Add('FR FR', 'French', 'Français', [
'Class:TriggerOnAttachmentDownload' => 'Déclencheur sur le téléchargement d\'une pièce jointe d\'un objet',
'Class:TriggerOnAttachmentDownload+' => '',
'Class:TriggerOnAttachmentCreate' => 'Déclencheur sur la création d\'une pièce jointe',
@@ -89,5 +89,5 @@ Dict::Add('FR FR', 'French', 'Français', array(
'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'Si coché, le fichier sera automatiquement attaché à l\'email quand l\'action email est lancée',
'Class:TriggerOnAttachmentDelete' => 'Déclencheur sur la suppression d\'une pièce jointe',
'Class:TriggerOnAttachmentDelete+' => '',
- 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Les Triggers sur les objets ne sont pas autorisés sur la classe Attachement. Veuillez utiliser les triggers spécifiques pour cette classe',
-));
+ 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Les Triggers sur les objets ne sont pas autorisés sur la classe Attachement. Veuillez utiliser les triggers spécifiques pour cette classe',
+]);
diff --git a/datamodels/2.x/itop-attachments/dictionaries/hu.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/hu.dict.itop-attachments.php
index d3db4276b..14f6ba869 100644
--- a/datamodels/2.x/itop-attachments/dictionaries/hu.dict.itop-attachments.php
+++ b/datamodels/2.x/itop-attachments/dictionaries/hu.dict.itop-attachments.php
@@ -1,15 +1,16 @@
'Mellékletek (%1$d)',
'Attachments:EmptyTabTitle' => 'Mellékletek',
'Attachments:FieldsetTitle' => 'Mellékletek',
@@ -28,13 +29,13 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array(
'Attachments:Render:Icons' => 'Mutassa ikonként',
'Attachments:Render:Table' => 'Mutassa listaként',
'UI:Attachments:DropYourFileHint' => 'Húzza a fájlokat erre a területre',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('HU HU', 'Hungarian', 'Magyar', array(
+Dict::Add('HU HU', 'Hungarian', 'Magyar', [
'Class:Attachment' => 'Mellékletek',
'Class:Attachment+' => '~~',
'Class:Attachment/Attribute:expire' => 'Lejárat',
@@ -49,10 +50,9 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array(
'Class:Attachment/Attribute:item_org_id+' => '~~',
'Class:Attachment/Attribute:contents' => 'Tartalom',
'Class:Attachment/Attribute:contents+' => '~~',
-));
+]);
-
-Dict::Add('HU HU', 'Hungarian', 'Magyar', array(
+Dict::Add('HU HU', 'Hungarian', 'Magyar', [
'Attachments:File:Thumbnail' => 'Ikon',
'Attachments:File:Name' => 'Fájlnév',
'Attachments:File:Date' => 'Feltöltés dátuma',
@@ -60,25 +60,25 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array(
'Attachments:File:Size' => 'Méret',
'Attachments:File:MimeType' => 'Típus',
'Attachments:File:DownloadsCount' => 'Downloads~~',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('HU HU', 'Hungarian', 'Magyar', array(
+Dict::Add('HU HU', 'Hungarian', 'Magyar', [
'Class:Attachment/Attribute:creation_date' => 'Létrehozás dátuma',
'Class:Attachment/Attribute:creation_date+' => '~~',
'Class:Attachment/Attribute:user_id' => 'Felhasználó',
'Class:Attachment/Attribute:user_id+' => '~~',
'Class:Attachment/Attribute:contact_id' => 'Kapcsolattartó',
'Class:Attachment/Attribute:contact_id+' => '~~',
-));
+]);
//
// Class: TriggerOnAttachmentDownload
//
-Dict::Add('HU HU', 'Hungarian', 'Magyar', array(
+Dict::Add('HU HU', 'Hungarian', 'Magyar', [
'Class:TriggerOnAttachmentDownload' => 'Trigger (on object\'s attachment download)~~',
'Class:TriggerOnAttachmentDownload+' => 'Trigger on object\'s attachment download of [a child class of] the given class~~',
'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~',
@@ -87,5 +87,5 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array(
'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~',
'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~',
'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~',
- 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
-));
+ 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
+]);
diff --git a/datamodels/2.x/itop-attachments/dictionaries/it.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/it.dict.itop-attachments.php
index bba364b74..d766a1864 100644
--- a/datamodels/2.x/itop-attachments/dictionaries/it.dict.itop-attachments.php
+++ b/datamodels/2.x/itop-attachments/dictionaries/it.dict.itop-attachments.php
@@ -1,15 +1,16 @@
'Allegati (%1$d)',
'Attachments:EmptyTabTitle' => 'Allegati',
'Attachments:FieldsetTitle' => 'Allegati',
@@ -30,13 +31,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Attachments:Render:Icons' => 'Visualizza come icone',
'Attachments:Render:Table' => 'Visualizza come lista',
'UI:Attachments:DropYourFileHint' => 'Rilascia i file ovunque in quest\'area',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:Attachment' => 'Allegato',
'Class:Attachment+' => '~~',
'Class:Attachment/Attribute:expire' => 'Scadenza',
@@ -51,10 +52,9 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:Attachment/Attribute:item_org_id+' => '~~',
'Class:Attachment/Attribute:contents' => 'Contenuti',
'Class:Attachment/Attribute:contents+' => '~~',
-));
+]);
-
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Attachments:File:Thumbnail' => 'Icona',
'Attachments:File:Name' => 'Nome del file',
'Attachments:File:Date' => 'Data di caricamento',
@@ -62,32 +62,32 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Attachments:File:Size' => 'Dimensione',
'Attachments:File:MimeType' => 'Tipo',
'Attachments:File:DownloadsCount' => 'Download',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:Attachment/Attribute:creation_date' => 'Data di creazione',
'Class:Attachment/Attribute:creation_date+' => '~~',
'Class:Attachment/Attribute:user_id' => 'ID utente',
'Class:Attachment/Attribute:user_id+' => '~~',
'Class:Attachment/Attribute:contact_id' => 'ID contatto',
'Class:Attachment/Attribute:contact_id+' => '~~',
-));
+]);
//
// Class: TriggerOnAttachmentDownload
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:TriggerOnAttachmentDownload' => 'Trigger (al download di un allegato dell\'oggetto)',
'Class:TriggerOnAttachmentDownload+' => 'Trigger al download di un allegato di un oggetto di [una sottoclasse di] la classe data',
- 'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~',
- 'Class:TriggerOnAttachmentCreate+' => 'Trigger on object\'s attachment create~~',
+ 'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~',
+ 'Class:TriggerOnAttachmentCreate+' => 'Trigger on object\'s attachment create~~',
'Class:TriggerOnAttachmentCreate/Attribute:file_in_email' => 'Add file in email~~',
'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~',
'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~',
'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~',
- 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
-));
+ 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
+]);
diff --git a/datamodels/2.x/itop-attachments/dictionaries/ja.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/ja.dict.itop-attachments.php
index fb5d450d2..45f88c3d2 100644
--- a/datamodels/2.x/itop-attachments/dictionaries/ja.dict.itop-attachments.php
+++ b/datamodels/2.x/itop-attachments/dictionaries/ja.dict.itop-attachments.php
@@ -1,15 +1,16 @@
'添付 (%1$d)',
'Attachments:EmptyTabTitle' => '添付',
'Attachments:FieldsetTitle' => '添付',
@@ -30,13 +31,13 @@ or ask your '.ITOP_APPLICATION_SHORT.' administrator if the '.ITOP_APPLICATION_S
'Attachments:Render:Icons' => 'Display as icons~~',
'Attachments:Render:Table' => 'Display as list~~',
'UI:Attachments:DropYourFileHint' => 'Drop files anywhere in this area~~',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('JA JP', 'Japanese', '日本語', array(
+Dict::Add('JA JP', 'Japanese', '日本語', [
'Class:Attachment' => 'Attachment~~',
'Class:Attachment+' => '~~',
'Class:Attachment/Attribute:expire' => 'Expire~~',
@@ -51,10 +52,9 @@ Dict::Add('JA JP', 'Japanese', '日本語', array(
'Class:Attachment/Attribute:item_org_id+' => '~~',
'Class:Attachment/Attribute:contents' => 'Contents~~',
'Class:Attachment/Attribute:contents+' => '~~',
-));
+]);
-
-Dict::Add('JA JP', 'Japanese', '日本語', array(
+Dict::Add('JA JP', 'Japanese', '日本語', [
'Attachments:File:Thumbnail' => 'Icon~~',
'Attachments:File:Name' => 'File name~~',
'Attachments:File:Date' => 'Upload date~~',
@@ -62,25 +62,25 @@ Dict::Add('JA JP', 'Japanese', '日本語', array(
'Attachments:File:Size' => 'Size~~',
'Attachments:File:MimeType' => 'Type~~',
'Attachments:File:DownloadsCount' => 'Downloads~~',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('JA JP', 'Japanese', '日本語', array(
+Dict::Add('JA JP', 'Japanese', '日本語', [
'Class:Attachment/Attribute:creation_date' => 'Creation date~~',
'Class:Attachment/Attribute:creation_date+' => '~~',
'Class:Attachment/Attribute:user_id' => 'User id~~',
'Class:Attachment/Attribute:user_id+' => '~~',
'Class:Attachment/Attribute:contact_id' => 'Contact id~~',
'Class:Attachment/Attribute:contact_id+' => '~~',
-));
+]);
//
// Class: TriggerOnAttachmentDownload
//
-Dict::Add('JA JP', 'Japanese', '日本語', array(
+Dict::Add('JA JP', 'Japanese', '日本語', [
'Class:TriggerOnAttachmentDownload' => 'Trigger (on object\'s attachment download)~~',
'Class:TriggerOnAttachmentDownload+' => 'Trigger on object\'s attachment download of [a child class of] the given class~~',
'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~',
@@ -89,5 +89,5 @@ Dict::Add('JA JP', 'Japanese', '日本語', array(
'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~',
'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~',
'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~',
- 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
-));
+ 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
+]);
diff --git a/datamodels/2.x/itop-attachments/dictionaries/nl.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/nl.dict.itop-attachments.php
index 682be462b..0d00101d3 100644
--- a/datamodels/2.x/itop-attachments/dictionaries/nl.dict.itop-attachments.php
+++ b/datamodels/2.x/itop-attachments/dictionaries/nl.dict.itop-attachments.php
@@ -1,17 +1,18 @@
* @author Jeffrey Bostoen (2018 - 2022)
* @author Thomas Casteleyn
*/
-Dict::Add('NL NL', 'Dutch', 'Nederlands', array(
+Dict::Add('NL NL', 'Dutch', 'Nederlands', [
'Attachments:TabTitle_Count' => 'Bijlagen (%1$d)',
'Attachments:EmptyTabTitle' => 'Bijlagen',
'Attachments:FieldsetTitle' => 'Bijlagen',
@@ -32,13 +33,13 @@ of vraag de iTop administrator om de opslagruimte van de iTop-server na te kijke
'Attachments:Render:Icons' => 'Toon als pictogram',
'Attachments:Render:Table' => 'Toon als lijst',
'UI:Attachments:DropYourFileHint' => 'Sleep bestanden in dit gebied',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('NL NL', 'Dutch', 'Nederlands', array(
+Dict::Add('NL NL', 'Dutch', 'Nederlands', [
'Class:Attachment' => 'Bijlage',
'Class:Attachment+' => '',
'Class:Attachment/Attribute:expire' => 'Vervalt',
@@ -53,10 +54,9 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array(
'Class:Attachment/Attribute:item_org_id+' => '',
'Class:Attachment/Attribute:contents' => 'Inhoud',
'Class:Attachment/Attribute:contents+' => '',
-));
+]);
-
-Dict::Add('NL NL', 'Dutch', 'Nederlands', array(
+Dict::Add('NL NL', 'Dutch', 'Nederlands', [
'Attachments:File:Thumbnail' => 'Pictogram',
'Attachments:File:Name' => 'Bestandsnaam',
'Attachments:File:Date' => 'Geüpload op',
@@ -64,32 +64,32 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array(
'Attachments:File:Size' => 'Grootte',
'Attachments:File:MimeType' => 'Type',
'Attachments:File:DownloadsCount' => 'Downloads',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('NL NL', 'Dutch', 'Nederlands', array(
+Dict::Add('NL NL', 'Dutch', 'Nederlands', [
'Class:Attachment/Attribute:creation_date' => 'Datum creatie',
'Class:Attachment/Attribute:creation_date+' => '',
'Class:Attachment/Attribute:user_id' => 'ID Gebruiker',
'Class:Attachment/Attribute:user_id+' => '',
'Class:Attachment/Attribute:contact_id' => 'ID Contact',
'Class:Attachment/Attribute:contact_id+' => '',
-));
+]);
//
// Class: TriggerOnAttachmentDownload
//
-Dict::Add('NL NL', 'Dutch', 'Nederlands', array(
+Dict::Add('NL NL', 'Dutch', 'Nederlands', [
'Class:TriggerOnAttachmentDownload' => 'Trigger (Bij het downloaden van een bijlage)',
'Class:TriggerOnAttachmentDownload+' => 'Trigger bij het downloaden van een bijlage van een object van de opgegeven klasse (of subklasse ervan)',
- 'Class:TriggerOnAttachmentCreate' => 'Trigger (Bij het toevoegen van een bijlage)',
- 'Class:TriggerOnAttachmentCreate+' => 'Trigger bij het toevoegen van een bijlage aan een object van de opgegeven klasse (of subklasse ervan)',
+ 'Class:TriggerOnAttachmentCreate' => 'Trigger (Bij het toevoegen van een bijlage)',
+ 'Class:TriggerOnAttachmentCreate+' => 'Trigger bij het toevoegen van een bijlage aan een object van de opgegeven klasse (of subklasse ervan)',
'Class:TriggerOnAttachmentCreate/Attribute:file_in_email' => 'Bestand toevoegen in e-mail',
- 'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+'=> 'If checked, the file will be automatically attached to the email when an email action is triggered~~',
+ 'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~',
'Class:TriggerOnAttachmentDelete' => 'Trigger (Bij het verwijderen van een bijlage)',
'Class:TriggerOnAttachmentDelete+' => 'Trigger bij het verwijderen van een bijlage van een object van de opgegeven klasse (of subklasse ervan)',
- 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
-));
+ 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
+]);
diff --git a/datamodels/2.x/itop-attachments/dictionaries/pl.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/pl.dict.itop-attachments.php
index abba580e0..67a1dc9f8 100644
--- a/datamodels/2.x/itop-attachments/dictionaries/pl.dict.itop-attachments.php
+++ b/datamodels/2.x/itop-attachments/dictionaries/pl.dict.itop-attachments.php
@@ -1,15 +1,16 @@
'Załączniki (%1$d)',
'Attachments:EmptyTabTitle' => 'Załączniki',
'Attachments:FieldsetTitle' => 'Załączniki',
@@ -30,13 +31,13 @@ lub zapytaj administratora '.ITOP_APPLICATION_SHORT.', czy dysk serwera '.ITOP_A
'Attachments:Render:Icons' => 'Wyświetlaj jako ikony',
'Attachments:Render:Table' => 'Wyświetl jako listę',
'UI:Attachments:DropYourFileHint' => 'Upuść pliki w dowolnym miejscu w tym obszarze',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('PL PL', 'Polish', 'Polski', array(
+Dict::Add('PL PL', 'Polish', 'Polski', [
'Class:Attachment' => 'Załącznik',
'Class:Attachment+' => '',
'Class:Attachment/Attribute:expire' => 'Wygasa',
@@ -51,10 +52,9 @@ Dict::Add('PL PL', 'Polish', 'Polski', array(
'Class:Attachment/Attribute:item_org_id+' => '',
'Class:Attachment/Attribute:contents' => 'Zawartość',
'Class:Attachment/Attribute:contents+' => '',
-));
+]);
-
-Dict::Add('PL PL', 'Polish', 'Polski', array(
+Dict::Add('PL PL', 'Polish', 'Polski', [
'Attachments:File:Thumbnail' => 'Ikona',
'Attachments:File:Name' => 'Nazwa pliku',
'Attachments:File:Date' => 'Data przesłania',
@@ -62,32 +62,32 @@ Dict::Add('PL PL', 'Polish', 'Polski', array(
'Attachments:File:Size' => 'Rozmiar',
'Attachments:File:MimeType' => 'Typ',
'Attachments:File:DownloadsCount' => 'Pobrano',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('PL PL', 'Polish', 'Polski', array(
+Dict::Add('PL PL', 'Polish', 'Polski', [
'Class:Attachment/Attribute:creation_date' => 'Data utworzenia',
'Class:Attachment/Attribute:creation_date+' => '',
'Class:Attachment/Attribute:user_id' => 'Id użytkownika',
'Class:Attachment/Attribute:user_id+' => '',
'Class:Attachment/Attribute:contact_id' => 'Id kontaktu',
'Class:Attachment/Attribute:contact_id+' => '',
-));
+]);
//
// Class: TriggerOnAttachmentDownload
//
-Dict::Add('PL PL', 'Polish', 'Polski', array(
+Dict::Add('PL PL', 'Polish', 'Polski', [
'Class:TriggerOnAttachmentDownload' => 'Wyzwalacz (po pobraniu załącznika obiektu)',
'Class:TriggerOnAttachmentDownload+' => 'Wyzwalacz po pobraniu załącznika obiektu [klasy podrzędnej] danej klasy',
- 'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~',
- 'Class:TriggerOnAttachmentCreate+' => 'Trigger on object\'s attachment create~~',
+ 'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~',
+ 'Class:TriggerOnAttachmentCreate+' => 'Trigger on object\'s attachment create~~',
'Class:TriggerOnAttachmentCreate/Attribute:file_in_email' => 'Add file in email~~',
'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~',
'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~',
'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~',
- 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
-));
+ 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
+]);
diff --git a/datamodels/2.x/itop-attachments/dictionaries/pt_br.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/pt_br.dict.itop-attachments.php
index 744e159f2..5afa8f22d 100644
--- a/datamodels/2.x/itop-attachments/dictionaries/pt_br.dict.itop-attachments.php
+++ b/datamodels/2.x/itop-attachments/dictionaries/pt_br.dict.itop-attachments.php
@@ -1,15 +1,16 @@
'Anexos (%1$d)',
'Attachments:EmptyTabTitle' => 'Anexos',
'Attachments:FieldsetTitle' => 'Anexos',
@@ -30,13 +31,13 @@ ou entre em contato com o seu administrador do '.ITOP_APPLICATION_SHORT.' pois o
'Attachments:Render:Icons' => 'Exibir como ícones',
'Attachments:Render:Table' => 'Exibir como lista',
'UI:Attachments:DropYourFileHint' => 'Solte arquivos em qualquer lugar nesta área',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:Attachment' => 'Anexo',
'Class:Attachment+' => '',
'Class:Attachment/Attribute:expire' => 'Expira',
@@ -51,10 +52,9 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:Attachment/Attribute:item_org_id+' => '',
'Class:Attachment/Attribute:contents' => 'Conteúdo',
'Class:Attachment/Attribute:contents+' => '',
-));
+]);
-
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Attachments:File:Thumbnail' => 'Ícone',
'Attachments:File:Name' => 'Nome do arquivo',
'Attachments:File:Date' => 'Data de envio',
@@ -62,25 +62,25 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Attachments:File:Size' => 'Tamanho',
'Attachments:File:MimeType' => 'Tipo',
'Attachments:File:DownloadsCount' => 'Downloads~~',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:Attachment/Attribute:creation_date' => 'Data de criação',
'Class:Attachment/Attribute:creation_date+' => '',
'Class:Attachment/Attribute:user_id' => 'Identificador do usuário',
'Class:Attachment/Attribute:user_id+' => '',
'Class:Attachment/Attribute:contact_id' => 'Identificador do contato',
'Class:Attachment/Attribute:contact_id+' => '',
-));
+]);
//
// Class: TriggerOnAttachmentDownload
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:TriggerOnAttachmentDownload' => 'Trigger (on object\'s attachment download)~~',
'Class:TriggerOnAttachmentDownload+' => 'Trigger on object\'s attachment download of [a child class of] the given class~~',
'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~',
@@ -89,5 +89,5 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~',
'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~',
'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~',
- 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
-));
+ 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
+]);
diff --git a/datamodels/2.x/itop-attachments/dictionaries/ru.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/ru.dict.itop-attachments.php
index 9e314c412..666492848 100644
--- a/datamodels/2.x/itop-attachments/dictionaries/ru.dict.itop-attachments.php
+++ b/datamodels/2.x/itop-attachments/dictionaries/ru.dict.itop-attachments.php
@@ -1,16 +1,17 @@
*
*/
-Dict::Add('RU RU', 'Russian', 'Русский', array(
+Dict::Add('RU RU', 'Russian', 'Русский', [
'Attachments:TabTitle_Count' => 'Вложения (%1$d)',
'Attachments:EmptyTabTitle' => 'Вложения',
'Attachments:FieldsetTitle' => 'Вложения',
@@ -31,13 +32,13 @@ or ask your '.ITOP_APPLICATION_SHORT.' administrator if the '.ITOP_APPLICATION_S
'Attachments:Render:Icons' => 'Display as icons~~',
'Attachments:Render:Table' => 'Display as list~~',
'UI:Attachments:DropYourFileHint' => 'Drop files anywhere in this area~~',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('RU RU', 'Russian', 'Русский', array(
+Dict::Add('RU RU', 'Russian', 'Русский', [
'Class:Attachment' => 'Вложение',
'Class:Attachment+' => '',
'Class:Attachment/Attribute:expire' => 'Истекает',
@@ -52,10 +53,9 @@ Dict::Add('RU RU', 'Russian', 'Русский', array(
'Class:Attachment/Attribute:item_org_id+' => '',
'Class:Attachment/Attribute:contents' => 'Содержимое',
'Class:Attachment/Attribute:contents+' => '',
-));
+]);
-
-Dict::Add('RU RU', 'Russian', 'Русский', array(
+Dict::Add('RU RU', 'Russian', 'Русский', [
'Attachments:File:Thumbnail' => 'Предпросмотр',
'Attachments:File:Name' => 'Имя файла',
'Attachments:File:Date' => 'Дата',
@@ -63,25 +63,25 @@ Dict::Add('RU RU', 'Russian', 'Русский', array(
'Attachments:File:Size' => 'Размер',
'Attachments:File:MimeType' => 'Тип',
'Attachments:File:DownloadsCount' => 'Downloads~~',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('RU RU', 'Russian', 'Русский', array(
+Dict::Add('RU RU', 'Russian', 'Русский', [
'Class:Attachment/Attribute:creation_date' => 'Дата создания',
'Class:Attachment/Attribute:creation_date+' => '',
'Class:Attachment/Attribute:user_id' => 'Пользователь',
'Class:Attachment/Attribute:user_id+' => '',
'Class:Attachment/Attribute:contact_id' => 'Контакт',
'Class:Attachment/Attribute:contact_id+' => '',
-));
+]);
//
// Class: TriggerOnAttachmentDownload
//
-Dict::Add('RU RU', 'Russian', 'Русский', array(
+Dict::Add('RU RU', 'Russian', 'Русский', [
'Class:TriggerOnAttachmentDownload' => 'Trigger (on object\'s attachment download)~~',
'Class:TriggerOnAttachmentDownload+' => 'Trigger on object\'s attachment download of [a child class of] the given class~~',
'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~',
@@ -90,5 +90,5 @@ Dict::Add('RU RU', 'Russian', 'Русский', array(
'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~',
'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~',
'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~',
- 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
-));
+ 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
+]);
diff --git a/datamodels/2.x/itop-attachments/dictionaries/sk.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/sk.dict.itop-attachments.php
index d27b9ec93..fafea2013 100644
--- a/datamodels/2.x/itop-attachments/dictionaries/sk.dict.itop-attachments.php
+++ b/datamodels/2.x/itop-attachments/dictionaries/sk.dict.itop-attachments.php
@@ -1,15 +1,16 @@
'Prílohy (%1$d)',
'Attachments:EmptyTabTitle' => 'Prílohy',
'Attachments:FieldsetTitle' => 'Prílohy',
@@ -30,13 +31,13 @@ or ask your '.ITOP_APPLICATION_SHORT.' administrator if the '.ITOP_APPLICATION_S
'Attachments:Render:Icons' => 'Display as icons~~',
'Attachments:Render:Table' => 'Display as list~~',
'UI:Attachments:DropYourFileHint' => 'Drop files anywhere in this area~~',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('SK SK', 'Slovak', 'Slovenčina', array(
+Dict::Add('SK SK', 'Slovak', 'Slovenčina', [
'Class:Attachment' => 'Attachment~~',
'Class:Attachment+' => '~~',
'Class:Attachment/Attribute:expire' => 'Expire~~',
@@ -51,10 +52,9 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array(
'Class:Attachment/Attribute:item_org_id+' => '~~',
'Class:Attachment/Attribute:contents' => 'Contents~~',
'Class:Attachment/Attribute:contents+' => '~~',
-));
+]);
-
-Dict::Add('SK SK', 'Slovak', 'Slovenčina', array(
+Dict::Add('SK SK', 'Slovak', 'Slovenčina', [
'Attachments:File:Thumbnail' => 'Icon~~',
'Attachments:File:Name' => 'File name~~',
'Attachments:File:Date' => 'Upload date~~',
@@ -62,25 +62,25 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array(
'Attachments:File:Size' => 'Size~~',
'Attachments:File:MimeType' => 'Type~~',
'Attachments:File:DownloadsCount' => 'Downloads~~',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('SK SK', 'Slovak', 'Slovenčina', array(
+Dict::Add('SK SK', 'Slovak', 'Slovenčina', [
'Class:Attachment/Attribute:creation_date' => 'Creation date~~',
'Class:Attachment/Attribute:creation_date+' => '~~',
'Class:Attachment/Attribute:user_id' => 'User id~~',
'Class:Attachment/Attribute:user_id+' => '~~',
'Class:Attachment/Attribute:contact_id' => 'Contact id~~',
'Class:Attachment/Attribute:contact_id+' => '~~',
-));
+]);
//
// Class: TriggerOnAttachmentDownload
//
-Dict::Add('SK SK', 'Slovak', 'Slovenčina', array(
+Dict::Add('SK SK', 'Slovak', 'Slovenčina', [
'Class:TriggerOnAttachmentDownload' => 'Trigger (on object\'s attachment download)~~',
'Class:TriggerOnAttachmentDownload+' => 'Trigger on object\'s attachment download of [a child class of] the given class~~',
'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~',
@@ -89,5 +89,5 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array(
'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~',
'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~',
'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~',
- 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
-));
+ 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
+]);
diff --git a/datamodels/2.x/itop-attachments/dictionaries/tr.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/tr.dict.itop-attachments.php
index 67e311d0e..9c361fe06 100644
--- a/datamodels/2.x/itop-attachments/dictionaries/tr.dict.itop-attachments.php
+++ b/datamodels/2.x/itop-attachments/dictionaries/tr.dict.itop-attachments.php
@@ -1,15 +1,16 @@
'Attachments (%1$d)~~',
'Attachments:EmptyTabTitle' => 'Attachments~~',
'Attachments:FieldsetTitle' => 'Attachments~~',
@@ -30,13 +31,13 @@ or ask your '.ITOP_APPLICATION_SHORT.' administrator if the '.ITOP_APPLICATION_S
'Attachments:Render:Icons' => 'Display as icons~~',
'Attachments:Render:Table' => 'Display as list~~',
'UI:Attachments:DropYourFileHint' => 'Drop files anywhere in this area~~',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('TR TR', 'Turkish', 'Türkçe', array(
+Dict::Add('TR TR', 'Turkish', 'Türkçe', [
'Class:Attachment' => 'Attachment~~',
'Class:Attachment+' => '~~',
'Class:Attachment/Attribute:expire' => 'Expire~~',
@@ -51,10 +52,9 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array(
'Class:Attachment/Attribute:item_org_id+' => '~~',
'Class:Attachment/Attribute:contents' => 'Contents~~',
'Class:Attachment/Attribute:contents+' => '~~',
-));
+]);
-
-Dict::Add('TR TR', 'Turkish', 'Türkçe', array(
+Dict::Add('TR TR', 'Turkish', 'Türkçe', [
'Attachments:File:Thumbnail' => 'Icon~~',
'Attachments:File:Name' => 'File name~~',
'Attachments:File:Date' => 'Upload date~~',
@@ -62,25 +62,25 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array(
'Attachments:File:Size' => 'Size~~',
'Attachments:File:MimeType' => 'Type~~',
'Attachments:File:DownloadsCount' => 'Downloads~~',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('TR TR', 'Turkish', 'Türkçe', array(
+Dict::Add('TR TR', 'Turkish', 'Türkçe', [
'Class:Attachment/Attribute:creation_date' => 'Creation date~~',
'Class:Attachment/Attribute:creation_date+' => '~~',
'Class:Attachment/Attribute:user_id' => 'User id~~',
'Class:Attachment/Attribute:user_id+' => '~~',
'Class:Attachment/Attribute:contact_id' => 'Contact id~~',
'Class:Attachment/Attribute:contact_id+' => '~~',
-));
+]);
//
// Class: TriggerOnAttachmentDownload
//
-Dict::Add('TR TR', 'Turkish', 'Türkçe', array(
+Dict::Add('TR TR', 'Turkish', 'Türkçe', [
'Class:TriggerOnAttachmentDownload' => 'Trigger (on object\'s attachment download)~~',
'Class:TriggerOnAttachmentDownload+' => 'Trigger on object\'s attachment download of [a child class of] the given class~~',
'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~',
@@ -89,5 +89,5 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array(
'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~',
'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~',
'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~',
- 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
-));
+ 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
+]);
diff --git a/datamodels/2.x/itop-attachments/dictionaries/zh_cn.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/zh_cn.dict.itop-attachments.php
index 2756f8190..ebf9b4a82 100644
--- a/datamodels/2.x/itop-attachments/dictionaries/zh_cn.dict.itop-attachments.php
+++ b/datamodels/2.x/itop-attachments/dictionaries/zh_cn.dict.itop-attachments.php
@@ -1,4 +1,5 @@
'附件 (%1$d)',
'Attachments:EmptyTabTitle' => '附件',
'Attachments:FieldsetTitle' => '附件',
@@ -30,13 +31,13 @@ Dict::Add('ZH CN', 'Chinese', '简体中文', array(
'Attachments:Render:Icons' => '显示为图标',
'Attachments:Render:Table' => '显示为列表',
'UI:Attachments:DropYourFileHint' => '将文件拖放到此区域的任意位置',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('ZH CN', 'Chinese', '简体中文', array(
+Dict::Add('ZH CN', 'Chinese', '简体中文', [
'Class:Attachment' => '附件',
'Class:Attachment+' => '',
'Class:Attachment/Attribute:expire' => '过期',
@@ -51,10 +52,9 @@ Dict::Add('ZH CN', 'Chinese', '简体中文', array(
'Class:Attachment/Attribute:item_org_id+' => '',
'Class:Attachment/Attribute:contents' => '内容',
'Class:Attachment/Attribute:contents+' => '',
-));
+]);
-
-Dict::Add('ZH CN', 'Chinese', '简体中文', array(
+Dict::Add('ZH CN', 'Chinese', '简体中文', [
'Attachments:File:Thumbnail' => '图标',
'Attachments:File:Name' => '文件名',
'Attachments:File:Date' => '上传日期',
@@ -62,32 +62,32 @@ Dict::Add('ZH CN', 'Chinese', '简体中文', array(
'Attachments:File:Size' => '大小',
'Attachments:File:MimeType' => '类型',
'Attachments:File:DownloadsCount' => '下载',
-));
+]);
//
// Class: Attachment
//
-Dict::Add('ZH CN', 'Chinese', '简体中文', array(
+Dict::Add('ZH CN', 'Chinese', '简体中文', [
'Class:Attachment/Attribute:creation_date' => '创建日期',
'Class:Attachment/Attribute:creation_date+' => '~~',
'Class:Attachment/Attribute:user_id' => '用户编号',
'Class:Attachment/Attribute:user_id+' => '~~',
'Class:Attachment/Attribute:contact_id' => '联系人编号',
'Class:Attachment/Attribute:contact_id+' => '~~',
-));
+]);
//
// Class: TriggerOnAttachmentDownload
//
-Dict::Add('ZH CN', 'Chinese', '简体中文', array(
+Dict::Add('ZH CN', 'Chinese', '简体中文', [
'Class:TriggerOnAttachmentDownload' => '触发器 (于对象附件下载时)',
'Class:TriggerOnAttachmentDownload+' => '触发器于指定类型 [子类型] 对象附件下载时',
'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~',
- 'Class:TriggerOnAttachmentCreate+' => 'Trigger on object\'s attachment create~~',
+ 'Class:TriggerOnAttachmentCreate+' => 'Trigger on object\'s attachment create~~',
'Class:TriggerOnAttachmentCreate/Attribute:file_in_email' => 'Add file in email~~',
'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~',
'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~',
'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~',
- 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
-));
+ 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~',
+]);
diff --git a/datamodels/2.x/itop-attachments/main.itop-attachments.php b/datamodels/2.x/itop-attachments/main.itop-attachments.php
index d7ee5d17d..e2025e731 100644
--- a/datamodels/2.x/itop-attachments/main.itop-attachments.php
+++ b/datamodels/2.x/itop-attachments/main.itop-attachments.php
@@ -1,4 +1,5 @@
GetAttachmentsPosition() == 'properties')
- {
+ if ($this->GetAttachmentsPosition() == 'properties') {
$this->DisplayAttachments($oObject, $oPage, $bEditMode);
}
}
public function OnDisplayRelations($oObject, WebPage $oPage, $bEditMode = false)
{
- if ($this->GetAttachmentsPosition() == 'relations')
- {
+ if ($this->GetAttachmentsPosition() == 'relations') {
$this->DisplayAttachments($oObject, $oPage, $bEditMode);
}
}
public function OnFormSubmit($oObject, $sFormPrefix = '')
{
- if ($this->IsTargetObject($oObject))
- {
+ if ($this->IsTargetObject($oObject)) {
// For new objects attachments are processed in OnDBInsert
- if (!$oObject->IsNew())
- {
+ if (!$oObject->IsNew()) {
self::UpdateAttachments($oObject);
}
}
@@ -53,12 +50,9 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup
public static function GetMaxUploadSize()
{
$sMaxUpload = ini_get('upload_max_filesize');
- if (!$sMaxUpload)
- {
+ if (!$sMaxUpload) {
$result = false;
- }
- else
- {
+ } else {
$result = utils::ConvertToBytes($sMaxUpload);
}
@@ -71,13 +65,11 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup
* @return bool
* @since 3.2.1 N°7534
*/
- public static function IsAttachmentAllowedForObject(cmdbAbstractObject $oObject) : bool
+ public static function IsAttachmentAllowedForObject(cmdbAbstractObject $oObject): bool
{
- $aAllowedClasses = MetaModel::GetModuleSetting('itop-attachments', 'allowed_classes', array('Ticket'));
- foreach ($aAllowedClasses as $sAllowedClass)
- {
- if ($oObject instanceof $sAllowedClass)
- {
+ $aAllowedClasses = MetaModel::GetModuleSetting('itop-attachments', 'allowed_classes', ['Ticket']);
+ foreach ($aAllowedClasses as $sAllowedClass) {
+ if ($oObject instanceof $sAllowedClass) {
return true;
}
}
@@ -92,24 +84,15 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup
public static function GetMaxUpload()
{
$iMaxUpload = static::GetMaxUploadSize();
- if (!$iMaxUpload)
- {
+ if (!$iMaxUpload) {
$sRet = Dict::S('Attachments:UploadNotAllowedOnThisSystem');
- }
- else
- {
- if ($iMaxUpload > 1024 * 1024 * 1024)
- {
+ } else {
+ if ($iMaxUpload > 1024 * 1024 * 1024) {
$sRet = Dict::Format('Attachment:Max_Go', sprintf('%0.2f', $iMaxUpload / (1024 * 1024 * 1024)));
- }
- else
- {
- if ($iMaxUpload > 1024 * 1024)
- {
+ } else {
+ if ($iMaxUpload > 1024 * 1024) {
$sRet = Dict::Format('Attachment:Max_Mo', sprintf('%0.2f', $iMaxUpload / (1024 * 1024)));
- }
- else
- {
+ } else {
$sRet = Dict::Format('Attachment:Max_Ko', sprintf('%0.2f', $iMaxUpload / (1024)));
}
}
@@ -128,9 +111,8 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup
// Delete all "pending" attachments for this form
$sOQL = 'SELECT Attachment WHERE temp_id = :temp_id';
$oSearch = DBObjectSearch::FromOQL($sOQL);
- $oSet = new DBObjectSet($oSearch, array(), array('temp_id' => $sTempId));
- while ($oAttachment = $oSet->Fetch())
- {
+ $oSet = new DBObjectSet($oSearch, [], ['temp_id' => $sTempId]);
+ while ($oAttachment = $oSet->Fetch()) {
$oAttachment->DBDelete();
// Pending attachment, don't mention it in the history
}
@@ -138,7 +120,7 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup
public function EnumUsedAttributes($oObject)
{
- return array();
+ return [];
}
public function GetIcon($oObject)
@@ -149,17 +131,17 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup
public function GetHilightClass($oObject)
{
// Possible return values are:
- // HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
+ // HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
return HILIGHT_CLASS_NONE;
}
public function EnumAllowedActions(DBObjectSet $oSet)
{
// No action
- return array();
+ return [];
}
- public function RegisterEventsAndListeners() : void
+ public function RegisterEventsAndListeners(): void
{
EventService::RegisterListener(EVENT_DB_AFTER_WRITE, [$this, 'OnDBAfterWrite']);
EventService::RegisterListener(EVENT_DB_AFTER_DELETE, [$this, 'OnDBAfterDelete']);
@@ -171,17 +153,14 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup
$oCMDBChange = $oEventData->Get('cmdb_change');
$bIsNew = $oEventData->Get('is_new');
- if ($this->IsTargetObject($oObject))
- {
- if($bIsNew){
+ if ($this->IsTargetObject($oObject)) {
+ if ($bIsNew) {
self::UpdateAttachments($oObject, $oCMDBChange);
- }
- else{
+ } else {
// Get all current attachments
$oSearch = DBObjectSearch::FromOQL("SELECT Attachment WHERE item_class = :class AND item_id = :item_id");
- $oSet = new DBObjectSet($oSearch, array(), array('class' => get_class($oObject), 'item_id' => $oObject->GetKey()));
- while ($oAttachment = $oSet->Fetch())
- {
+ $oSet = new DBObjectSet($oSearch, [], ['class' => get_class($oObject), 'item_id' => $oObject->GetKey()]);
+ while ($oAttachment = $oSet->Fetch()) {
$oAttachment->SetItem($oObject, true /*updateonchange*/);
}
}
@@ -192,12 +171,10 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup
{
$oObject = $oEventData->Get('object');
- if ($this->IsTargetObject($oObject))
- {
+ if ($this->IsTargetObject($oObject)) {
$oSearch = DBObjectSearch::FromOQL("SELECT Attachment WHERE item_class = :class AND item_id = :item_id");
- $oSet = new DBObjectSet($oSearch, array(), array('class' => get_class($oObject), 'item_id' => $oObject->GetKey()));
- while ($oAttachment = $oSet->Fetch())
- {
+ $oSet = new DBObjectSet($oSearch, [], ['class' => get_class($oObject), 'item_id' => $oObject->GetKey()]);
+ while ($oAttachment = $oSet->Fetch()) {
$oAttachment->DBDelete();
}
}
@@ -211,11 +188,9 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup
protected function IsTargetObject($oObject)
{
- $aAllowedClasses = MetaModel::GetModuleSetting('itop-attachments', 'allowed_classes', array('Ticket'));
- foreach ($aAllowedClasses as $sAllowedClass)
- {
- if ($oObject instanceof $sAllowedClass)
- {
+ $aAllowedClasses = MetaModel::GetModuleSetting('itop-attachments', 'allowed_classes', ['Ticket']);
+ foreach ($aAllowedClasses as $sAllowedClass) {
+ if ($oObject instanceof $sAllowedClass) {
return true;
}
}
@@ -228,7 +203,7 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup
return MetaModel::GetModuleSetting('itop-attachments', 'position', 'relations');
}
- var $m_bDeleteEnabled = true;
+ public $m_bDeleteEnabled = true;
public function EnableDelete($bEnabled)
{
@@ -249,34 +224,28 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup
public function DisplayAttachments(DBObject $oObject, WebPage $oPage, $bEditMode = false)
{
// Exit here if the class is not allowed
- if (!$this->IsTargetObject($oObject))
- {
+ if (!$this->IsTargetObject($oObject)) {
return;
}
$sObjClass = get_class($oObject);
$iObjKey = $oObject->GetKey();
$sTransactionId = $oPage->GetTransactionId();
- if ($bEditMode && empty($sTransactionId))
- {
+ if ($bEditMode && empty($sTransactionId)) {
throw new InvalidParameterException('Attachments renderer : invalid transaction id');
}
$oAttachmentsRenderer = AttachmentsRendererFactory::GetInstance($oPage, $sObjClass, $iObjKey, $sTransactionId);
- if ($this->GetAttachmentsPosition() === 'relations')
- {
+ if ($this->GetAttachmentsPosition() === 'relations') {
$iCount = $oAttachmentsRenderer->GetAttachmentsSet()->Count() + $oAttachmentsRenderer->GetTempAttachmentsSet()->Count();
$sTitle = ($iCount > 0) ? Dict::Format('Attachments:TabTitle_Count', $iCount) : Dict::S('Attachments:EmptyTabTitle');
$oPage->SetCurrentTab('Attachments:Tab', $sTitle);
}
-
+
$bIsReadOnlyState = self::IsReadonlyState($oObject, $oObject->GetState(), AttachmentPlugIn::ENUM_GUI_BACKOFFICE);
- if ($bEditMode && !$bIsReadOnlyState)
- {
+ if ($bEditMode && !$bIsReadOnlyState) {
$oAttachmentsRenderer->RenderEditAttachmentsList();
- }
- else
- {
+ } else {
$oAttachmentsRenderer->RenderViewAttachmentsList();
}
}
@@ -300,27 +269,23 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup
*/
protected static function UpdateAttachments($oObject, $oCMDBChange = null)
{
- if (utils::ReadParam('attachment_plugin', 'not-in-form') == 'not-in-form')
- {
+ if (utils::ReadParam('attachment_plugin', 'not-in-form') == 'not-in-form') {
// Workaround to an issue in iTop < 2.0
// Leave silently if there is no trace of the attachment form
return;
}
$sTransactionId = utils::ReadParam('transaction_id', null, false, 'transaction_id');
- if (!is_null($sTransactionId))
- {
- $aActions = array();
- $aRemovedAttachmentIds = utils::ReadParam('removed_attachments', array());
+ if (!is_null($sTransactionId)) {
+ $aActions = [];
+ $aRemovedAttachmentIds = utils::ReadParam('removed_attachments', []);
// Get all current attachments
$oSearch = DBObjectSearch::FromOQL("SELECT Attachment WHERE item_class = :class AND item_id = :item_id");
$oSearch->AllowAllData();
- $oSet = new DBObjectSet($oSearch, array(), array('class' => get_class($oObject), 'item_id' => $oObject->GetKey()));
- while ($oAttachment = $oSet->Fetch())
- {
+ $oSet = new DBObjectSet($oSearch, [], ['class' => get_class($oObject), 'item_id' => $oObject->GetKey()]);
+ while ($oAttachment = $oSet->Fetch()) {
// Remove attachments that are no longer attached to the current object
- if (in_array($oAttachment->GetKey(), $aRemovedAttachmentIds))
- {
+ if (in_array($oAttachment->GetKey(), $aRemovedAttachmentIds)) {
$aData = ['attachment' => $oAttachment];
$oObject->FireEvent(EVENT_REMOVE_ATTACHMENT_FROM_OBJECT, $aData);
$oAttachment->DBDelete();
@@ -335,11 +300,9 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup
$sOQL = 'SELECT Attachment WHERE temp_id = :temp_id';
$oSearch = DBObjectSearch::FromOQL($sOQL);
$oSearch->AllowAllData();
- $oSet = new DBObjectSet($oSearch, array(), array('temp_id' => $sTempId));
- while ($oAttachment = $oSet->Fetch())
- {
- if (in_array($oAttachment->GetKey(), $aRemovedAttachmentIds))
- {
+ $oSet = new DBObjectSet($oSearch, [], ['temp_id' => $sTempId]);
+ while ($oAttachment = $oSet->Fetch()) {
+ if (in_array($oAttachment->GetKey(), $aRemovedAttachmentIds)) {
$oAttachment->DBDelete();
// temporary attachment removed, don't even mention it in the history
} else {
@@ -352,10 +315,8 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup
$oObject->FireEvent(EVENT_ADD_ATTACHMENT_TO_OBJECT, $aData);
}
}
- if (count($aActions) > 0)
- {
- foreach ($aActions as $oChangeOp)
- {
+ if (count($aActions) > 0) {
+ foreach ($aActions as $oChangeOp) {
self::RecordHistory($oCMDBChange, $oObject, $oChangeOp);
}
@@ -367,11 +328,10 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup
public static function CopyAttachments($oObject, $sTransactionId)
{
$oSearch = DBObjectSearch::FromOQL("SELECT Attachment WHERE item_class = :class AND item_id = :item_id");
- $oSet = new DBObjectSet($oSearch, array(), array('class' => get_class($oObject), 'item_id' => $oObject->GetKey()));
+ $oSet = new DBObjectSet($oSearch, [], ['class' => get_class($oObject), 'item_id' => $oObject->GetKey()]);
// Attach new (temporary) attachments
$sTempId = utils::GetUploadTempId($sTransactionId);
- while ($oAttachment = $oSet->Fetch())
- {
+ while ($oAttachment = $oSet->Fetch()) {
$oTempAttachment = clone $oAttachment;
$oTempAttachment->Set('expire', time() + utils::GetConfig()->Get('draft_attachments_lifetime'));
$oTempAttachment->Set('item_id', null);
@@ -384,15 +344,11 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup
public static function GetFileIcon($sFileName)
{
$aPathParts = pathinfo($sFileName);
- if (!array_key_exists('extension', $aPathParts))
- {
+ if (!array_key_exists('extension', $aPathParts)) {
// No extension: use the default icon
$sIcon = 'icons8-file.svg';
- }
- else
- {
- switch (strtolower($aPathParts['extension']))
- {
+ } else {
+ switch (strtolower($aPathParts['extension'])) {
case 'doc':
case 'docx':
$sIcon = 'icons8-word.svg';
@@ -425,7 +381,7 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup
case 'vb':
$sIcon = 'icons8-code-file.svg';
break;
-
+
case 'pdf':
$sIcon = 'icons8-pdf.svg';
break;
@@ -478,7 +434,7 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup
case 'ai':
$sIcon = 'icons8-image-file.svg';
break;
-
+
case 'zip':
case 'gz':
case 'tgz':
@@ -512,34 +468,34 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup
case 'wma':
$sIcon = 'icons8-audio-file.svg';
break;
-
+
case 'csv':
$sIcon = 'icons8-csv.svg';
break;
-
+
case 'log':
$sIcon = 'icons8-event-log.svg';
break;
-
+
case 'sql':
$sIcon = 'icons8-sql.svg';
break;
-
+
case 'xml':
$sIcon = 'icons8-xml-file.svg';
- break;
-
+ break;
+
case 'email':
case 'eml':
case 'emlx':
case 'msg':
$sIcon = 'icons8-mail.svg';
break;
-
+
case 'patch':
$sIcon = 'icons8-bandage.svg';
break;
-
+
default:
$sIcon = 'icons8-file.svg';
break;
@@ -552,8 +508,7 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup
/////////////////////////////////////////////////////////////////////////
private static function RecordHistory($oCMDBChange, $oTargetObject, $oMyChangeOp)
{
- if (!is_null($oCMDBChange))
- {
+ if (!is_null($oCMDBChange)) {
$oMyChangeOp->Set("change", $oCMDBChange->GetKey());
}
$oMyChangeOp->Set("objclass", get_class($oTargetObject));
@@ -566,14 +521,11 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup
{
$oBlob = $oAttachment->Get('contents');
$sFileName = $oBlob->GetFileName();
- if ($bCreate)
- {
+ if ($bCreate) {
$oChangeOp = new CMDBChangeOpAttachmentAdded();
$oChangeOp->Set('attachment_id', $oAttachment->GetKey());
$oChangeOp->Set('filename', $sFileName);
- }
- else
- {
+ } else {
$oChangeOp = new CMDBChangeOpAttachmentRemoved();
$oChangeOp->Set('filename', $sFileName);
}
@@ -595,44 +547,36 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup
*/
public static function IsReadonlyState(DBObject $oObject, $sState, $sGUI = self::ENUM_GUI_ALL)
{
- $aParamDefaultValue = array(
- static::ENUM_GUI_ALL => array(
- 'Ticket' => array('closed'),
- ),
- );
+ $aParamDefaultValue = [
+ static::ENUM_GUI_ALL => [
+ 'Ticket' => ['closed'],
+ ],
+ ];
$bReadonly = false;
$sClass = get_class($oObject);
$aReadonlyStatus = MetaModel::GetModuleSetting('itop-attachments', 'readonly_states', $aParamDefaultValue);
- if (!empty($aReadonlyStatus))
- {
+ if (!empty($aReadonlyStatus)) {
// Merging GUIs entries
- $aEntries = array();
+ $aEntries = [];
// - All
- if (array_key_exists(static::ENUM_GUI_ALL, $aReadonlyStatus))
- {
+ if (array_key_exists(static::ENUM_GUI_ALL, $aReadonlyStatus)) {
$aEntries = array_merge_recursive($aEntries, $aReadonlyStatus[static::ENUM_GUI_ALL]);
}
// - Backoffice & Portals
- foreach (array(static::ENUM_GUI_BACKOFFICE, static::ENUM_GUI_PORTALS) as $sEnumGUI)
- {
- if (in_array($sGUI, array(static::ENUM_GUI_ALL, $sEnumGUI)))
- {
- if (array_key_exists($sEnumGUI, $aReadonlyStatus))
- {
+ foreach ([static::ENUM_GUI_BACKOFFICE, static::ENUM_GUI_PORTALS] as $sEnumGUI) {
+ if (in_array($sGUI, [static::ENUM_GUI_ALL, $sEnumGUI])) {
+ if (array_key_exists($sEnumGUI, $aReadonlyStatus)) {
$aEntries = array_merge_recursive($aEntries, $aReadonlyStatus[$sEnumGUI]);
}
}
}
$aParentClasses = array_reverse(MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
- foreach ($aParentClasses as $sParentClass)
- {
- if (array_key_exists($sParentClass, $aEntries))
- {
+ foreach ($aParentClasses as $sParentClass) {
+ if (array_key_exists($sParentClass, $aEntries)) {
// If we found an ancestor of the object's class, we stop looking event if the current state is not specified
- if (in_array($oObject->GetState(), $aEntries[$sParentClass]))
- {
+ if (in_array($oObject->GetState(), $aEntries[$sParentClass])) {
$bReadonly = true;
}
break;
@@ -643,7 +587,6 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup
return $bReadonly;
}
-
}
/**
@@ -658,38 +601,38 @@ class CMDBChangeOpAttachmentAdded extends CMDBChangeOp
{
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "core/cmdb, grant_by_profile",
"key_type" => "",
"name_attcode" => "change",
"state_attcode" => "",
- "reconc_keys" => array(),
+ "reconc_keys" => [],
"db_table" => "priv_changeop_attachment_added",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeExternalKey("attachment_id", array(
+ MetaModel::Init_AddAttribute(new AttributeExternalKey("attachment_id", [
"targetclass" => "Attachment",
"allowed_values" => null,
"sql" => "attachment_id",
"is_null_allowed" => true,
"on_target_delete" => DEL_SILENT,
- "depends_on" => array(),
- )));
- MetaModel::Init_AddAttribute(new AttributeString("filename", array(
+ "depends_on" => [],
+ ]));
+ MetaModel::Init_AddAttribute(new AttributeString("filename", [
"allowed_values" => null,
"sql" => "filename",
"default_value" => "",
"is_null_allowed" => false,
- "depends_on" => array(),
- )));
+ "depends_on" => [],
+ ]));
// Display lists
- MetaModel::Init_SetZListItems('details', array('attachment_id')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('attachment_id')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['attachment_id']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['attachment_id']); // Attributes to be displayed for a list
}
/**
@@ -709,12 +652,15 @@ class CMDBChangeOpAttachmentAdded extends CMDBChangeOp
$oAttachment = $oMonoObjectSet->Fetch();
$oDoc = $oAttachment->Get('contents');
$sPreview = $oDoc->IsPreviewAvailable() ? 'data-preview="true"' : '';
- $sResult = Dict::Format('Attachments:History_File_Added',
- ''.$sFilename.' ');
- }
- else
- {
+ $sResult = Dict::Format(
+ 'Attachments:History_File_Added',
+ ''.$sFilename.' '
+ );
+ } else {
$sResult = Dict::Format('Attachments:History_File_Added', ''.$sFilename.' ');
}
@@ -726,30 +672,30 @@ class CMDBChangeOpAttachmentRemoved extends CMDBChangeOp
{
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "core/cmdb, grant_by_profile",
"key_type" => "",
"name_attcode" => "change",
"state_attcode" => "",
- "reconc_keys" => array(),
+ "reconc_keys" => [],
"db_table" => "priv_changeop_attachment_removed",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeString("filename", array(
+ MetaModel::Init_AddAttribute(new AttributeString("filename", [
"allowed_values" => null,
"sql" => "filename",
"default_value" => "",
"is_null_allowed" => false,
- "depends_on" => array(),
- )));
+ "depends_on" => [],
+ ]));
// Display lists
- MetaModel::Init_SetZListItems('details', array('filename')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('filename')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['filename']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['filename']); // Attributes to be displayed for a list
}
/**
@@ -758,8 +704,10 @@ class CMDBChangeOpAttachmentRemoved extends CMDBChangeOp
public function GetDescription()
{
// Temporary, until we change the options of GetDescription() -needs a more global revision
- $sResult = Dict::Format('Attachments:History_File_Removed',
- ''.utils::EscapeHtml($this->Get('filename')).' ');
+ $sResult = Dict::Format(
+ 'Attachments:History_File_Removed',
+ ''.utils::EscapeHtml($this->Get('filename')).' '
+ );
return $sResult;
}
@@ -776,29 +724,22 @@ class AttachmentsHelper
public static function GetAttachmentsDateAddedFromDb($sObjClass, $iObjKey)
{
$sQuery = "SELECT CMDBChangeOpAttachmentAdded WHERE objclass='$sObjClass' AND objkey=$iObjKey";
- try
- {
+ try {
$oSearch = DBObjectSearch::FromOQL($sQuery);
- }
- catch (OQLException $e)
- {
- return array();
+ } catch (OQLException $e) {
+ return [];
}
$oSet = new DBObjectSet($oSearch);
- try
- {
- $aAttachmentDates = array();
- while ($oChangeOpAttAdded = $oSet->Fetch())
- {
+ try {
+ $aAttachmentDates = [];
+ while ($oChangeOpAttAdded = $oSet->Fetch()) {
$iAttachmentId = $oChangeOpAttAdded->Get('attachment_id');
$sAttachmentDate = $oChangeOpAttAdded->Get('date');
$aAttachmentDates[$iAttachmentId] = $sAttachmentDate;
}
- }
- catch (Exception $e)
- {
- return array();
+ } catch (Exception $e) {
+ return [];
}
return $aAttachmentDates;
diff --git a/datamodels/2.x/itop-attachments/module.itop-attachments.php b/datamodels/2.x/itop-attachments/module.itop-attachments.php
index b383836b4..cf2291758 100644
--- a/datamodels/2.x/itop-attachments/module.itop-attachments.php
+++ b/datamodels/2.x/itop-attachments/module.itop-attachments.php
@@ -1,9 +1,10 @@
-
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-attachments/3.3.0',
- array(
+ [
// Identification
//
'label' => 'Tickets Attachments',
@@ -28,52 +28,51 @@ SetupWebPage::AddModule(
// Setup
//
- 'dependencies' => array(),
+ 'dependencies' => [],
'mandatory' => false,
'visible' => true,
'installer' => 'AttachmentInstaller',
// Components
//
- 'datamodel' => array(
+ 'datamodel' => [
'vendor/autoload.php',
'main.itop-attachments.php',
'src/Trigger/TriggerOnAttachmentCreate.php',
'src/Trigger/TriggerOnAttachmentDelete.php',
'src/Trigger/TriggerOnAttachmentDownload.php',
'renderers.itop-attachments.php',
- ),
- 'webservice' => array(
-
- ),
- 'dictionary' => array(
+ ],
+ 'webservice' => [
- ),
- 'data.struct' => array(
+ ],
+ 'dictionary' => [
+
+ ],
+ 'data.struct' => [
// add your 'structure' definition XML files here,
- ),
- 'data.sample' => array(
+ ],
+ 'data.sample' => [
// add your sample data XML files here,
- ),
-
+ ],
+
// Documentation
//
'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any
- 'doc.more_information' => '', // hyperlink to more information, if any
+ 'doc.more_information' => '', // hyperlink to more information, if any
// Default settings
//
- 'settings' => array(
- 'allowed_classes' => array('Ticket'), // List of classes for which to manage "Attachments"
+ 'settings' => [
+ 'allowed_classes' => ['Ticket'], // List of classes for which to manage "Attachments"
'position' => 'relations', // Where to display the attachments: relations | properties
'preview_max_width' => 290,
'icon_preview_max_size' => 500000, // Maximum size for attachment preview to be displayed as an icon. In bits
- ),
- )
+ ],
+ ]
);
-if (!class_exists('AttachmentInstaller'))
-{
+if (!class_exists('AttachmentInstaller')) {
// Module installation handler
//
class AttachmentInstaller extends ModuleInstallerAPI
@@ -94,7 +93,8 @@ if (!class_exists('AttachmentInstaller'))
* @throws \MySQLException
* @throws \MySQLHasGoneAwayException
*/
- public static function GetOrphanAttachmentIds($sTableName, $iBulkSize){
+ public static function GetOrphanAttachmentIds($sTableName, $iBulkSize)
+ {
$sSqlQuery = <<fetch_array()){
+ while ($aRow = $oQueryResult->fetch_array()) {
$aIds[] = $aRow['attachment_id'];
}
@@ -117,15 +117,13 @@ SQL;
*/
public static function BeforeDatabaseCreation(Config $oConfiguration, $sPreviousVersion, $sCurrentVersion)
{
- if ($sPreviousVersion != '')
- {
+ if ($sPreviousVersion != '') {
// Migrating from a previous version
// Check for records where item_id = '', since they are not attached to any object and cannot be migrated to the objkey schema
$sTableName = MetaModel::DBGetTable('Attachment');
$sCountQuery = "SELECT COUNT(*) FROM `$sTableName` WHERE (`item_id`='' OR `item_id` IS NULL)";
$iCount = CMDBSource::QueryToScalar($sCountQuery);
- if ($iCount > 0)
- {
+ if ($iCount > 0) {
SetupLog::Info("Cleanup of orphan attachments that cannot be migrated to the new ObjKey model: $iCount record(s) must be deleted.");
$iBulkSize = 100;
@@ -141,7 +139,7 @@ SQL;
$iDeletedCount += count($aIds);
$fElapsed = microtime(true) - $fStartTime;
- if ($fElapsed > $iMaxDuration){
+ if ($fElapsed > $iMaxDuration) {
SetupLog::Info(sprintf("Cleanup of orphan attachments interrupted after %.3f s. $iDeletedCount records were deleted among $iCount.", $fElapsed));
break;
}
@@ -149,12 +147,10 @@ SQL;
$aIds = self::GetOrphanAttachmentIds($sTableName, $iBulkSize);
}
- if (count($aIds) === 0){
+ if (count($aIds) === 0) {
SetupLog::Info("Cleanup of orphan attachments successfully completed.");
}
- }
- else
- {
+ } else {
SetupLog::Info("No orphan attachment found.");
}
}
@@ -169,7 +165,7 @@ SQL;
public static function AfterDatabaseCreation(Config $oConfiguration, $sPreviousVersion, $sCurrentVersion)
{
// For each record having item_org_id unset,
- // get the org_id from the container object
+ // get the org_id from the container object
//
// Prerequisite: change null into 0 (workaround to the fact that we cannot use IS NULL in OQL)
SetupLog::Info("Initializing attachment/item_org_id - null to zero");
@@ -185,11 +181,10 @@ SQL;
'Attachment' => [
'item_class',
'item_id',
- ]
+ ],
]);
$iUpdated = 0;
- while ($oAttachment = $oSet->Fetch())
- {
+ while ($oAttachment = $oSet->Fetch()) {
if (empty($oAttachment->Get('item_class'))) {
//do not treat orphan attachment
continue;
diff --git a/datamodels/2.x/itop-attachments/src/Hook/EventListener.php b/datamodels/2.x/itop-attachments/src/Hook/EventListener.php
index eb23cd5f6..47723b063 100644
--- a/datamodels/2.x/itop-attachments/src/Hook/EventListener.php
+++ b/datamodels/2.x/itop-attachments/src/Hook/EventListener.php
@@ -40,14 +40,14 @@ class EventListener implements iEventServiceSetup
[$this, 'OnAttachmentDownloadActivateTriggers'],
'Attachment'
);
- EventService::RegisterListener(
- \EVENT_ADD_ATTACHMENT_TO_OBJECT,
- [$this, 'OnAttachmentAddedActivateTriggers']
- );
- EventService::RegisterListener(
- \EVENT_REMOVE_ATTACHMENT_FROM_OBJECT,
- [$this, 'OnAttachmentRemovedActivateTriggers']
- );
+ EventService::RegisterListener(
+ \EVENT_ADD_ATTACHMENT_TO_OBJECT,
+ [$this, 'OnAttachmentAddedActivateTriggers']
+ );
+ EventService::RegisterListener(
+ \EVENT_REMOVE_ATTACHMENT_FROM_OBJECT,
+ [$this, 'OnAttachmentRemovedActivateTriggers']
+ );
}
/**
@@ -70,77 +70,77 @@ class EventListener implements iEventServiceSetup
/** @var \ormDocument $oDocument */
$oDocument = $oEventData->Get('document');
- $this->OnAttachmentActivateTriggers(
- $oHostObj,
- $oAttachment,
- $oDocument,
- TriggerOnAttachmentDownload::class
- );
- }
+ $this->OnAttachmentActivateTriggers(
+ $oHostObj,
+ $oAttachment,
+ $oDocument,
+ TriggerOnAttachmentDownload::class
+ );
+ }
- /**
- * Callback when an Attachment is added: Activate corresponding triggers
- *
- * @param \Combodo\iTop\Service\Events\EventData $oEventData
- *
- * @return void
- * @throws \CoreException
- */
- public function OnAttachmentAddedActivateTriggers(EventData $oEventData): void
- {
- /** @var DBObject $oAttachment */
- $oAttachment = $oEventData->Get('attachment');
- /** @var DBObject $oHostObj */
- $oHostObj = $oEventData->Get('object');
- /** @var ormDocument $oDocument */
- $oDocument = $oAttachment->Get('contents');
+ /**
+ * Callback when an Attachment is added: Activate corresponding triggers
+ *
+ * @param \Combodo\iTop\Service\Events\EventData $oEventData
+ *
+ * @return void
+ * @throws \CoreException
+ */
+ public function OnAttachmentAddedActivateTriggers(EventData $oEventData): void
+ {
+ /** @var DBObject $oAttachment */
+ $oAttachment = $oEventData->Get('attachment');
+ /** @var DBObject $oHostObj */
+ $oHostObj = $oEventData->Get('object');
+ /** @var ormDocument $oDocument */
+ $oDocument = $oAttachment->Get('contents');
- $this->OnAttachmentActivateTriggers(
- $oHostObj,
- $oAttachment,
- $oDocument,
- \TriggerOnAttachmentCreate::class
- );
- }
+ $this->OnAttachmentActivateTriggers(
+ $oHostObj,
+ $oAttachment,
+ $oDocument,
+ \TriggerOnAttachmentCreate::class
+ );
+ }
- /**
- * Callback when an Attachment is removed: Activate corresponding triggers
- *
- * @param \Combodo\iTop\Service\Events\EventData $oEventData
- *
- * @return void
- * @throws \CoreException
- */
- public function OnAttachmentRemovedActivateTriggers(EventData $oEventData): void
- {
- /** @var DBObject $oAttachment */
- $oAttachment = $oEventData->Get('attachment');
- /** @var DBObject $oHostObj */
- $oHostObj = $oEventData->Get('object');
- /** @var ormDocument $oDocument */
- $oDocument = $oAttachment->Get('contents');
+ /**
+ * Callback when an Attachment is removed: Activate corresponding triggers
+ *
+ * @param \Combodo\iTop\Service\Events\EventData $oEventData
+ *
+ * @return void
+ * @throws \CoreException
+ */
+ public function OnAttachmentRemovedActivateTriggers(EventData $oEventData): void
+ {
+ /** @var DBObject $oAttachment */
+ $oAttachment = $oEventData->Get('attachment');
+ /** @var DBObject $oHostObj */
+ $oHostObj = $oEventData->Get('object');
+ /** @var ormDocument $oDocument */
+ $oDocument = $oAttachment->Get('contents');
- $this->OnAttachmentActivateTriggers(
- $oHostObj,
- $oAttachment,
- $oDocument,
- \TriggerOnAttachmentDelete::class
- );
- }
+ $this->OnAttachmentActivateTriggers(
+ $oHostObj,
+ $oAttachment,
+ $oDocument,
+ \TriggerOnAttachmentDelete::class
+ );
+ }
- /**
- * Callback when an Attachment downloaded, added or removed: Activate corresponding triggers
- *
- * @param DBObject $oHostObj
- * @param DBObject $oAttachment
- * @param ormDocument $oDocument
- * @param string $sTriggerClass
- *
- * @return void
- * @throws \CoreException
- */
- protected function OnAttachmentActivateTriggers(DBObject $oHostObj, DBObject $oAttachment, ormDocument $oDocument, string $sTriggerClass): void
- {
+ /**
+ * Callback when an Attachment downloaded, added or removed: Activate corresponding triggers
+ *
+ * @param DBObject $oHostObj
+ * @param DBObject $oAttachment
+ * @param ormDocument $oDocument
+ * @param string $sTriggerClass
+ *
+ * @return void
+ * @throws \CoreException
+ */
+ protected function OnAttachmentActivateTriggers(DBObject $oHostObj, DBObject $oAttachment, ormDocument $oDocument, string $sTriggerClass): void
+ {
$aTriggerContextArgs = [
'this->object()' => $oHostObj,
'attachment->object()' => $oAttachment,
diff --git a/datamodels/2.x/itop-attachments/src/Trigger/TriggerOnAttachmentCreate.php b/datamodels/2.x/itop-attachments/src/Trigger/TriggerOnAttachmentCreate.php
index 8e755598e..2931de448 100644
--- a/datamodels/2.x/itop-attachments/src/Trigger/TriggerOnAttachmentCreate.php
+++ b/datamodels/2.x/itop-attachments/src/Trigger/TriggerOnAttachmentCreate.php
@@ -5,7 +5,6 @@
* @license http://opensource.org/licenses/AGPL-3.0
*/
-
/**
* Class TriggerOnAttachmentCreate
*
@@ -20,29 +19,28 @@ class TriggerOnAttachmentCreate extends TriggerOnObject
*/
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "grant_by_profile,core/cmdb,application",
"key_type" => "autoincrement",
"name_attcode" => "description",
- "complementary_name_attcode" => ['finalclass', 'complement'],
+ "complementary_name_attcode" => ['finalclass', 'complement'],
"state_attcode" => "",
"reconc_keys" => ['description'],
"db_table" => "priv_trigger_onattcreate",
"db_key_field" => "id",
"db_finalclass_field" => "",
"display_template" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeBoolean("file_in_email", array("sql"=>'file_in_email', "is_null_allowed"=>false, "default_value"=>'true', "allowed_values"=>null, "depends_on"=>array(), "always_load_in_tables"=>false)));
-
+ MetaModel::Init_AddAttribute(new AttributeBoolean("file_in_email", ["sql" => 'file_in_email', "is_null_allowed" => false, "default_value" => 'true', "allowed_values" => null, "depends_on" => [], "always_load_in_tables" => false]));
// Display lists
- MetaModel::Init_SetZListItems('details', array('description', 'context', 'filter', 'action_list', 'target_class', 'file_in_email')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('finalclass', 'target_class')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['description', 'context', 'filter', 'action_list', 'target_class', 'file_in_email']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['finalclass', 'target_class']); // Attributes to be displayed for a list
// Search criteria
- MetaModel::Init_SetZListItems('standard_search', array('description', 'target_class')); // Criteria of the std search form
+ MetaModel::Init_SetZListItems('standard_search', ['description', 'target_class']); // Criteria of the std search form
}
-}
\ No newline at end of file
+}
diff --git a/datamodels/2.x/itop-attachments/src/Trigger/TriggerOnAttachmentDelete.php b/datamodels/2.x/itop-attachments/src/Trigger/TriggerOnAttachmentDelete.php
index 8e7798a7c..a9c8ac7c6 100644
--- a/datamodels/2.x/itop-attachments/src/Trigger/TriggerOnAttachmentDelete.php
+++ b/datamodels/2.x/itop-attachments/src/Trigger/TriggerOnAttachmentDelete.php
@@ -5,7 +5,6 @@
* @license http://opensource.org/licenses/AGPL-3.0
*/
-
/**
* Class TriggerOnAttachmentCreate
*
@@ -20,28 +19,28 @@ class TriggerOnAttachmentDelete extends TriggerOnObject
*/
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "grant_by_profile,core/cmdb,application",
"key_type" => "autoincrement",
"name_attcode" => "description",
- "complementary_name_attcode" => ['finalclass', 'complement'],
+ "complementary_name_attcode" => ['finalclass', 'complement'],
"state_attcode" => "",
"reconc_keys" => ['description'],
"db_table" => "priv_trigger_onattdelete",
"db_key_field" => "id",
"db_finalclass_field" => "",
"display_template" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
// Display lists
- MetaModel::Init_SetZListItems('details', array('description', 'context', 'filter', 'action_list', 'target_class')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('finalclass', 'target_class')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['description', 'context', 'filter', 'action_list', 'target_class']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['finalclass', 'target_class']); // Attributes to be displayed for a list
// Search criteria
- MetaModel::Init_SetZListItems('standard_search', array('description', 'target_class')); // Criteria of the std search form
+ MetaModel::Init_SetZListItems('standard_search', ['description', 'target_class']); // Criteria of the std search form
}
-}
\ No newline at end of file
+}
diff --git a/datamodels/2.x/itop-attachments/src/Trigger/TriggerOnAttachmentDownload.php b/datamodels/2.x/itop-attachments/src/Trigger/TriggerOnAttachmentDownload.php
index 51088d72c..ceb9d3988 100644
--- a/datamodels/2.x/itop-attachments/src/Trigger/TriggerOnAttachmentDownload.php
+++ b/datamodels/2.x/itop-attachments/src/Trigger/TriggerOnAttachmentDownload.php
@@ -7,27 +7,27 @@
*/
class TriggerOnAttachmentDownload extends TriggerOnAttributeBlobDownload
{
- /**
- * @inheritDoc
- * @throws \CoreException
- * @throws \Exception
- */
- public static function Init()
- {
- $aParams = array
- (
- "category" => "grant_by_profile,core/cmdb,application",
- "key_type" => "autoincrement",
- "name_attcode" => "description",
- "complementary_name_attcode" => ['finalclass', 'complement'],
- "state_attcode" => "",
- "reconc_keys" => ['description'],
- "db_table" => "priv_trigger_onattdownload",
- "db_key_field" => "id",
- "db_finalclass_field" => "",
- "display_template" => "",
- );
- MetaModel::Init_Params($aParams);
- MetaModel::Init_InheritAttributes();
- }
-}
\ No newline at end of file
+ /**
+ * @inheritDoc
+ * @throws \CoreException
+ * @throws \Exception
+ */
+ public static function Init()
+ {
+ $aParams =
+ [
+ "category" => "grant_by_profile,core/cmdb,application",
+ "key_type" => "autoincrement",
+ "name_attcode" => "description",
+ "complementary_name_attcode" => ['finalclass', 'complement'],
+ "state_attcode" => "",
+ "reconc_keys" => ['description'],
+ "db_table" => "priv_trigger_onattdownload",
+ "db_key_field" => "id",
+ "db_finalclass_field" => "",
+ "display_template" => "",
+ ];
+ MetaModel::Init_Params($aParams);
+ MetaModel::Init_InheritAttributes();
+ }
+}
diff --git a/datamodels/2.x/itop-backup/dbrestore.class.inc.php b/datamodels/2.x/itop-backup/dbrestore.class.inc.php
index 8a0ccc014..5873145a9 100644
--- a/datamodels/2.x/itop-backup/dbrestore.class.inc.php
+++ b/datamodels/2.x/itop-backup/dbrestore.class.inc.php
@@ -1,4 +1,5 @@
-
class DBRestore extends DBBackup
{
/** @var string */
@@ -54,12 +54,9 @@ class DBRestore extends DBBackup
$sPwd = self::EscapeShellArg($this->sDBPwd);
$sDBName = self::EscapeShellArg($this->sDBName);
$sMySQLExe = DBBackup::MakeSafeMySQLCommand($this->sMySQLBinDir, 'mysql');
- if (is_null($this->iDBPort))
- {
+ if (is_null($this->iDBPort)) {
$sPortOption = '';
- }
- else
- {
+ } else {
$sPortOption = '--port='.$this->iDBPort.' ';
}
$sTlsOptions = self::GetMysqlCliTlsOptions($this->oConfig);
@@ -70,26 +67,20 @@ class DBRestore extends DBBackup
// Now run the command for real
$this->LogInfo("Executing command: $sCommandDisplay");
- $aOutput = array();
+ $aOutput = [];
$iRetCode = 0;
exec($sCommand, $aOutput, $iRetCode);
- foreach($aOutput as $sLine)
- {
+ foreach ($aOutput as $sLine) {
$this->LogInfo("mysql said: $sLine");
}
- if ($iRetCode != 0)
- {
+ if ($iRetCode != 0) {
$this->LogError("Failed to execute: $sCommandDisplay. The command returned:$iRetCode");
- foreach($aOutput as $sLine)
- {
+ foreach ($aOutput as $sLine) {
$this->LogError("mysql said: $sLine");
}
- if (count($aOutput) == 1)
- {
+ if (count($aOutput) == 1) {
$sMoreInfo = trim($aOutput[0]);
- }
- else
- {
+ } else {
$sMoreInfo = "Check the log file '".realpath(APPROOT.'/log/error.log')."' for more information.";
}
throw new BackupException("Failed to execute mysql: ".$sMoreInfo);
@@ -120,7 +111,6 @@ class DBRestore extends DBBackup
//safe zone for db backup => cron is stopped/ itop in readonly
$this->LogInfo("Starting restore of ".basename($sFile));
-
$sNormalizedFile = strtolower(basename($sFile));
if (substr($sNormalizedFile, -4) == '.zip') {
$this->LogInfo('zip file detected');
@@ -170,7 +160,7 @@ class DBRestore extends DBBackup
@chmod($sConfigFile, 0440); // Read-only
$aExtraFiles = $this->ListExtraFiles($sDataDir);
- foreach($aExtraFiles as $sSourceFilePath => $sDestinationFilePath) {
+ foreach ($aExtraFiles as $sSourceFilePath => $sDestinationFilePath) {
SetupUtils::builddir(dirname($sDestinationFilePath));
rename($sSourceFilePath, $sDestinationFilePath);
}
@@ -191,9 +181,7 @@ class DBRestore extends DBBackup
$this->LogInfo("Keep maintenance mode after restore");
}
}
- }
- finally
- {
+ } finally {
IssueLog::Info('Backup Restore - LOCK released.');
$oRestoreMutex->Unlock();
}
@@ -209,10 +197,9 @@ class DBRestore extends DBBackup
{
$aExtraFiles = [];
$aStandardFiles = ['config-itop.php', 'itop-dump.sql', 'production-modules', 'delta.xml'];
- $oDirectoryIterator = new RecursiveDirectoryIterator($sDataDir, FilesystemIterator::CURRENT_AS_FILEINFO|FilesystemIterator::SKIP_DOTS);
+ $oDirectoryIterator = new RecursiveDirectoryIterator($sDataDir, FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS);
$oIterator = new RecursiveIteratorIterator($oDirectoryIterator);
- foreach ($oIterator as $oFileInfo)
- {
+ foreach ($oIterator as $oFileInfo) {
if (in_array($oFileInfo->getFilename(), $aStandardFiles)) {
continue;
}
diff --git a/datamodels/2.x/itop-backup/main.itop-backup.php b/datamodels/2.x/itop-backup/main.itop-backup.php
index 9f7d326e7..9481e29ec 100644
--- a/datamodels/2.x/itop-backup/main.itop-backup.php
+++ b/datamodels/2.x/itop-backup/main.itop-backup.php
@@ -1,4 +1,5 @@
IsLocked())
- {
+ if ($oRestoreMutex->IsLocked()) {
IssueLog::Info(__class__.'::'.__function__.' A user is trying to use iTop while a restore is running. The requested page is in read-only mode.');
MetaModel::GetConfig()->Set('access_mode', ACCESS_READONLY, 'itop-backup');
MetaModel::GetConfig()->Set('access_message', ' - '.dict::S('bkp-restore-running'), 'itop-backup');
}
- }
- catch(Exception $e)
- {
+ } catch (Exception $e) {
IssueLog::Error(__class__.'::'.__function__.' Failed to check if a backup/restore is running: '.$e->getMessage());
}
}
@@ -65,22 +60,20 @@ class DBBackupScheduled extends DBBackup
*/
public function ListFiles($sBackupDir)
{
- $aFiles = array();
- $aTimes = array();
+ $aFiles = [];
+ $aTimes = [];
// Legacy format -limited to 4 Gb
- foreach(glob($sBackupDir.'*.zip') as $sFilePath)
- {
+ foreach (glob($sBackupDir.'*.zip') as $sFilePath) {
$aFiles[] = $sFilePath;
$aTimes[] = filemtime($sFilePath); // unix time
}
// Modern format
- foreach(glob($sBackupDir.'*.tar.gz') as $sFilePath)
- {
+ foreach (glob($sBackupDir.'*.tar.gz') as $sFilePath) {
$aFiles[] = $sFilePath;
$aTimes[] = filemtime($sFilePath); // unix time
}
array_multisort($aTimes, $aFiles);
-
+
return $aFiles;
}
}
@@ -107,20 +100,14 @@ class BackupExec extends AbstractWeeklyScheduledProcess
*/
public function __construct($sBackupDir = null, $iRetentionCount = null)
{
- if (is_null($sBackupDir))
- {
+ if (is_null($sBackupDir)) {
$this->sBackupDir = utils::GetDataPath().'backups/auto/';
- }
- else
- {
+ } else {
$this->sBackupDir = $sBackupDir;
}
- if (is_null($iRetentionCount))
- {
+ if (is_null($iRetentionCount)) {
$this->iRetentionCount = MetaModel::GetConfig()->GetModuleSetting($this->GetModuleName(), 'retention_count', 5);
- }
- else
- {
+ } else {
$this->iRetentionCount = $iRetentionCount;
}
}
@@ -135,53 +122,43 @@ class BackupExec extends AbstractWeeklyScheduledProcess
$oMutex = new iTopMutex('backup.'.utils::GetCurrentEnvironment());
$oMutex->Lock();
- try
- {
+ try {
// Make sure the target directory exists
SetupUtils::builddir($this->sBackupDir);
-
+
$oBackup = new DBBackupScheduled();
// Eliminate files exceeding the retention setting
//
- if ($this->iRetentionCount > 0)
- {
+ if ($this->iRetentionCount > 0) {
$aFiles = $oBackup->ListFiles($this->sBackupDir);
- while (count($aFiles) >= $this->iRetentionCount)
- {
+ while (count($aFiles) >= $this->iRetentionCount) {
$sFileToDelete = array_shift($aFiles);
unlink($sFileToDelete);
- if (file_exists($sFileToDelete))
- {
+ if (file_exists($sFileToDelete)) {
// Ok, do not loop indefinitely on this
break;
}
}
}
-
+
// Do execute the backup
//
$oBackup->SetMySQLBinDir(MetaModel::GetConfig()->GetModuleSetting($this->GetModuleName(), 'mysql_bindir', ''));
$sBackupFileFormat = MetaModel::GetConfig()->GetModuleSetting($this->GetModuleName(), 'file_name_format', '__DB__-%Y-%m-%d_%H_%M');
$sName = $oBackup->MakeName($sBackupFileFormat);
- if ($sName == '')
- {
+ if ($sName == '') {
$sName = $oBackup->MakeName(BACKUP_DEFAULT_FORMAT);
}
$sBackupFile = $this->sBackupDir.$sName;
$sSourceConfigFile = APPCONF.utils::GetCurrentEnvironment().'/'.ITOP_CONFIG_FILE;
- try
- {
+ try {
$oBackup->CreateCompressedBackup($sBackupFile, $sSourceConfigFile);
- }
- catch (BackupException $e)
- {
+ } catch (BackupException $e) {
throw new ProcessFatalException($e->getMessage());
}
- }
- catch (Exception $e)
- {
+ } catch (Exception $e) {
$oMutex->Unlock();
throw $e;
}
diff --git a/datamodels/2.x/itop-backup/module.itop-backup.php b/datamodels/2.x/itop-backup/module.itop-backup.php
index 7cc0972da..35fd85f0b 100644
--- a/datamodels/2.x/itop-backup/module.itop-backup.php
+++ b/datamodels/2.x/itop-backup/module.itop-backup.php
@@ -1,10 +1,9 @@
'Backup utilities',
@@ -12,31 +11,31 @@ SetupWebPage::AddModule(
// Setup
//
- 'dependencies' => array(
- ),
+ 'dependencies' => [
+ ],
'mandatory' => true,
'visible' => false,
// Components
//
- 'datamodel' => array(
+ 'datamodel' => [
'main.itop-backup.php',
- ),
- 'webservice' => array(
+ ],
+ 'webservice' => [
//'webservices.itop-backup.php',
- ),
- 'dictionary' => array(
+ ],
+ 'dictionary' => [
'en.dict.itop-backup.php',
'fr.dict.itop-backup.php',
//'de.dict.itop-backup.php',
- ),
- 'data.struct' => array(
+ ],
+ 'data.struct' => [
//'data.struct.itop-backup.xml',
- ),
- 'data.sample' => array(
+ ],
+ 'data.sample' => [
//'data.sample.itop-backup.xml',
- ),
-
+ ],
+
// Documentation
//
'doc.manual_setup' => '',
@@ -44,14 +43,14 @@ SetupWebPage::AddModule(
// Default settings
//
- 'settings' => array(
+ 'settings' => [
'mysql_bindir' => '',
'week_days' => 'monday, tuesday, wednesday, thursday, friday',
'time' => '23:30',
//'file_name_format' => '__DB__-%Y-%m-%d_%H_%M',
- 'retention_count' => 5,
+ 'retention_count' => 5,
'enabled' => true,
'itop_backup_incident' => '',
- ),
- )
+ ],
+ ]
);
diff --git a/datamodels/2.x/itop-bridge-cmdb-services/module.itop-bridge-cmdb-services.php b/datamodels/2.x/itop-bridge-cmdb-services/module.itop-bridge-cmdb-services.php
index 1e1a35161..57c31ad22 100644
--- a/datamodels/2.x/itop-bridge-cmdb-services/module.itop-bridge-cmdb-services.php
+++ b/datamodels/2.x/itop-bridge-cmdb-services/module.itop-bridge-cmdb-services.php
@@ -1,4 +1,5 @@
'Bridge for CMDB and Services',
@@ -14,40 +15,37 @@ SetupWebPage::AddModule(
// Setup
//
- 'dependencies' => array(
+ 'dependencies' => [
'itop-config-mgmt/2.7.1',
'itop-service-mgmt/2.7.1 || itop-service-mgmt-provider/2.7.1',
- ),
+ ],
'mandatory' => false,
'visible' => false,
'auto_select' => 'SetupInfo::ModuleIsSelected("itop-config-mgmt") && (SetupInfo::ModuleIsSelected("itop-service-mgmt") || SetupInfo::ModuleIsSelected("itop-service-mgmt-provider")) ',
// Components
//
- 'datamodel' => array(
- ),
- 'webservice' => array(
-
- ),
- 'data.struct' => array(
+ 'datamodel' => [
+ ],
+ 'webservice' => [
+
+ ],
+ 'data.struct' => [
// add your 'structure' definition XML files here,
- ),
- 'data.sample' => array(
+ ],
+ 'data.sample' => [
// add your sample data XML files here,
- ),
-
+ ],
+
// Documentation
//
'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any
- 'doc.more_information' => '', // hyperlink to more information, if any
+ 'doc.more_information' => '', // hyperlink to more information, if any
// Default settings
//
- 'settings' => array(
+ 'settings' => [
// Module specific settings go here, if any
- ),
- )
+ ],
+ ]
);
-
-
-?>
diff --git a/datamodels/2.x/itop-bridge-cmdb-ticket/dictionaries/pt_br.dict.itop-bridge-cmdb-ticket.php b/datamodels/2.x/itop-bridge-cmdb-ticket/dictionaries/pt_br.dict.itop-bridge-cmdb-ticket.php
index bd78f198d..1ee91b821 100644
--- a/datamodels/2.x/itop-bridge-cmdb-ticket/dictionaries/pt_br.dict.itop-bridge-cmdb-ticket.php
+++ b/datamodels/2.x/itop-bridge-cmdb-ticket/dictionaries/pt_br.dict.itop-bridge-cmdb-ticket.php
@@ -1,16 +1,17 @@
*
*/
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:lnkFunctionalCIToTicket' => 'Relação entre IC / Solicitação',
'Class:lnkFunctionalCIToTicket+' => '',
'Class:lnkFunctionalCIToTicket/Name' => '%1$s / %2$s~~',
@@ -30,12 +31,12 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:lnkFunctionalCIToTicket/Attribute:impact_code/Value:manual' => 'Adicionado manualmente',
'Class:lnkFunctionalCIToTicket/Attribute:impact_code/Value:computed' => 'Computado',
'Class:lnkFunctionalCIToTicket/Attribute:impact_code/Value:not_impacted' => 'Não impactado',
-));
+]);
//
// Class: FunctionalCI
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:FunctionalCI/Attribute:tickets_list' => 'Solicitações',
'Class:FunctionalCI/Attribute:tickets_list+' => 'Todas as Solicitações associadas à este Item de Configuração (IC)',
-));
+]);
diff --git a/datamodels/2.x/itop-bridge-cmdb-ticket/module.itop-bridge-cmdb-ticket.php b/datamodels/2.x/itop-bridge-cmdb-ticket/module.itop-bridge-cmdb-ticket.php
index 53ec4ed5c..399d46632 100644
--- a/datamodels/2.x/itop-bridge-cmdb-ticket/module.itop-bridge-cmdb-ticket.php
+++ b/datamodels/2.x/itop-bridge-cmdb-ticket/module.itop-bridge-cmdb-ticket.php
@@ -1,4 +1,5 @@
'Bridge for CMDB and Ticket',
@@ -14,40 +15,37 @@ SetupWebPage::AddModule(
// Setup
//
- 'dependencies' => array(
+ 'dependencies' => [
'itop-config-mgmt/2.7.1',
'itop-tickets/2.7.0',
- ),
+ ],
'mandatory' => false,
'visible' => false,
'auto_select' => 'SetupInfo::ModuleIsSelected("itop-config-mgmt") && SetupInfo::ModuleIsSelected("itop-tickets") ',
// Components
//
- 'datamodel' => array(
- ),
- 'webservice' => array(
-
- ),
- 'data.struct' => array(
+ 'datamodel' => [
+ ],
+ 'webservice' => [
+
+ ],
+ 'data.struct' => [
// add your 'structure' definition XML files here,
- ),
- 'data.sample' => array(
+ ],
+ 'data.sample' => [
// add your sample data XML files here,
- ),
-
+ ],
+
// Documentation
//
'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any
- 'doc.more_information' => '', // hyperlink to more information, if any
+ 'doc.more_information' => '', // hyperlink to more information, if any
// Default settings
//
- 'settings' => array(
+ 'settings' => [
// Module specific settings go here, if any
- ),
- )
+ ],
+ ]
);
-
-
-?>
diff --git a/datamodels/2.x/itop-bridge-datacenter-mgmt-services/module.itop-bridge-datacenter-mgmt-services.php b/datamodels/2.x/itop-bridge-datacenter-mgmt-services/module.itop-bridge-datacenter-mgmt-services.php
index 0666211da..84f239890 100644
--- a/datamodels/2.x/itop-bridge-datacenter-mgmt-services/module.itop-bridge-datacenter-mgmt-services.php
+++ b/datamodels/2.x/itop-bridge-datacenter-mgmt-services/module.itop-bridge-datacenter-mgmt-services.php
@@ -1,4 +1,5 @@
'Bridge for CMDB Virtualization objects and Services',
@@ -14,28 +15,28 @@ SetupWebPage::AddModule(
// Setup
//
- 'dependencies' => array(
+ 'dependencies' => [
'itop-config-mgmt/2.7.1',
'itop-service-mgmt/2.7.1 || itop-service-mgmt-provider/2.7.1',
'itop-datacenter-mgmt/3.1.0',
- ),
+ ],
'mandatory' => false,
'visible' => false,
'auto_select' => 'SetupInfo::ModuleIsSelected("itop-datacenter-mgmt") && (SetupInfo::ModuleIsSelected("itop-service-mgmt") || SetupInfo::ModuleIsSelected("itop-service-mgmt-provider")) ',
// Components
//
- 'datamodel' => array(
- ),
- 'webservice' => array(
+ 'datamodel' => [
+ ],
+ 'webservice' => [
- ),
- 'data.struct' => array(
+ ],
+ 'data.struct' => [
// add your 'structure' definition XML files here,
- ),
- 'data.sample' => array(
+ ],
+ 'data.sample' => [
// add your sample data XML files here,
- ),
+ ],
// Documentation
//
@@ -44,11 +45,8 @@ SetupWebPage::AddModule(
// Default settings
//
- 'settings' => array(
+ 'settings' => [
// Module specific settings go here, if any
- ),
- )
+ ],
+ ]
);
-
-
-?>
diff --git a/datamodels/2.x/itop-bridge-endusers-devices-services/module.itop-bridge-endusers-devices-services.php b/datamodels/2.x/itop-bridge-endusers-devices-services/module.itop-bridge-endusers-devices-services.php
index 81fecaaec..f02e4e978 100644
--- a/datamodels/2.x/itop-bridge-endusers-devices-services/module.itop-bridge-endusers-devices-services.php
+++ b/datamodels/2.x/itop-bridge-endusers-devices-services/module.itop-bridge-endusers-devices-services.php
@@ -1,4 +1,5 @@
'Bridge for CMDB endusers objects and Services',
@@ -14,29 +15,29 @@ SetupWebPage::AddModule(
// Setup
//
- 'dependencies' => array(
+ 'dependencies' => [
'itop-config-mgmt/2.7.1',
'itop-service-mgmt/2.7.1 || itop-service-mgmt-provider/2.7.1',
'itop-endusers-devices/3.1.0',
- ),
+ ],
'mandatory' => false,
'visible' => false,
'auto_select' => 'SetupInfo::ModuleIsSelected("itop-endusers-devices") && (SetupInfo::ModuleIsSelected("itop-service-mgmt") || SetupInfo::ModuleIsSelected("itop-service-mgmt-provider")) ',
// Components
//
- 'datamodel' => array(
- ),
- 'webservice' => array(
+ 'datamodel' => [
+ ],
+ 'webservice' => [
- ),
- 'data.struct' => array(
+ ],
+ 'data.struct' => [
// add your 'structure' definition XML files here,
- ),
- 'data.sample' => array(
+ ],
+ 'data.sample' => [
// add your sample data XML files here,
- ),
+ ],
// Documentation
//
@@ -45,11 +46,8 @@ SetupWebPage::AddModule(
// Default settings
//
- 'settings' => array(
+ 'settings' => [
// Module specific settings go here, if any
- ),
- )
+ ],
+ ]
);
-
-
-?>
diff --git a/datamodels/2.x/itop-bridge-storage-mgmt-services/module.itop-bridge-storage-mgmt-services.php b/datamodels/2.x/itop-bridge-storage-mgmt-services/module.itop-bridge-storage-mgmt-services.php
index 6fec063d1..5d0f1b1f9 100644
--- a/datamodels/2.x/itop-bridge-storage-mgmt-services/module.itop-bridge-storage-mgmt-services.php
+++ b/datamodels/2.x/itop-bridge-storage-mgmt-services/module.itop-bridge-storage-mgmt-services.php
@@ -1,4 +1,5 @@
'Bridge for CMDB Virtualization objects and Services',
@@ -14,28 +15,28 @@ SetupWebPage::AddModule(
// Setup
//
- 'dependencies' => array(
+ 'dependencies' => [
'itop-config-mgmt/2.7.1',
'itop-service-mgmt/2.7.1 || itop-service-mgmt-provider/2.7.1',
'itop-storage-mgmt/3.1.0',
- ),
+ ],
'mandatory' => false,
'visible' => false,
'auto_select' => 'SetupInfo::ModuleIsSelected("itop-storage-mgmt") && (SetupInfo::ModuleIsSelected("itop-service-mgmt") || SetupInfo::ModuleIsSelected("itop-service-mgmt-provider")) ',
// Components
//
- 'datamodel' => array(
- ),
- 'webservice' => array(
+ 'datamodel' => [
+ ],
+ 'webservice' => [
- ),
- 'data.struct' => array(
+ ],
+ 'data.struct' => [
// add your 'structure' definition XML files here,
- ),
- 'data.sample' => array(
+ ],
+ 'data.sample' => [
// add your sample data XML files here,
- ),
+ ],
// Documentation
//
@@ -44,11 +45,8 @@ SetupWebPage::AddModule(
// Default settings
//
- 'settings' => array(
+ 'settings' => [
// Module specific settings go here, if any
- ),
- )
+ ],
+ ]
);
-
-
-?>
diff --git a/datamodels/2.x/itop-bridge-virtualization-mgmt-services/module.itop-bridge-virtualization-mgmt-services.php b/datamodels/2.x/itop-bridge-virtualization-mgmt-services/module.itop-bridge-virtualization-mgmt-services.php
index cfe7a4f96..f1e92326f 100644
--- a/datamodels/2.x/itop-bridge-virtualization-mgmt-services/module.itop-bridge-virtualization-mgmt-services.php
+++ b/datamodels/2.x/itop-bridge-virtualization-mgmt-services/module.itop-bridge-virtualization-mgmt-services.php
@@ -1,4 +1,5 @@
'Bridge for CMDB Virtualization objects and Services',
@@ -14,28 +15,28 @@ SetupWebPage::AddModule(
// Setup
//
- 'dependencies' => array(
+ 'dependencies' => [
'itop-config-mgmt/2.7.1',
'itop-service-mgmt/2.7.1 || itop-service-mgmt-provider/2.7.1',
'itop-virtualization-mgmt/3.1.0',
- ),
+ ],
'mandatory' => false,
'visible' => false,
'auto_select' => 'SetupInfo::ModuleIsSelected("itop-virtualization-mgmt") && (SetupInfo::ModuleIsSelected("itop-service-mgmt") || SetupInfo::ModuleIsSelected("itop-service-mgmt-provider")) ',
// Components
//
- 'datamodel' => array(
- ),
- 'webservice' => array(
+ 'datamodel' => [
+ ],
+ 'webservice' => [
- ),
- 'data.struct' => array(
+ ],
+ 'data.struct' => [
// add your 'structure' definition XML files here,
- ),
- 'data.sample' => array(
+ ],
+ 'data.sample' => [
// add your sample data XML files here,
- ),
+ ],
// Documentation
//
@@ -44,11 +45,8 @@ SetupWebPage::AddModule(
// Default settings
//
- 'settings' => array(
+ 'settings' => [
// Module specific settings go here, if any
- ),
- )
+ ],
+ ]
);
-
-
-?>
diff --git a/datamodels/2.x/itop-bridge-virtualization-storage/module.itop-bridge-virtualization-storage.php b/datamodels/2.x/itop-bridge-virtualization-storage/module.itop-bridge-virtualization-storage.php
index 90dbd55a2..6fcb67b75 100644
--- a/datamodels/2.x/itop-bridge-virtualization-storage/module.itop-bridge-virtualization-storage.php
+++ b/datamodels/2.x/itop-bridge-virtualization-storage/module.itop-bridge-virtualization-storage.php
@@ -1,10 +1,9 @@
'Links between virtualization and storage',
@@ -12,25 +11,25 @@ SetupWebPage::AddModule(
// Setup
//
- 'dependencies' => array(
+ 'dependencies' => [
'itop-storage-mgmt/2.2.0',
'itop-virtualization-mgmt/2.2.0',
- ),
+ ],
'mandatory' => false,
'visible' => false,
'auto_select' => 'SetupInfo::ModuleIsSelected("itop-storage-mgmt") && SetupInfo::ModuleIsSelected("itop-virtualization-mgmt")',
// Components
//
- 'datamodel' => array(
- ),
- 'data.struct' => array(
+ 'datamodel' => [
+ ],
+ 'data.struct' => [
//'data.struct.itop-change-mgmt.xml',
- ),
- 'data.sample' => array(
+ ],
+ 'data.sample' => [
//'data.sample.itop-change-mgmt.xml',
- ),
-
+ ],
+
// Documentation
//
'doc.manual_setup' => '',
@@ -38,7 +37,7 @@ SetupWebPage::AddModule(
// Default settings
//
- 'settings' => array(
- ),
- )
+ 'settings' => [
+ ],
+ ]
);
diff --git a/datamodels/2.x/itop-change-mgmt-itil/module.itop-change-mgmt-itil.php b/datamodels/2.x/itop-change-mgmt-itil/module.itop-change-mgmt-itil.php
index ae5e63e41..5158d5294 100755
--- a/datamodels/2.x/itop-change-mgmt-itil/module.itop-change-mgmt-itil.php
+++ b/datamodels/2.x/itop-change-mgmt-itil/module.itop-change-mgmt-itil.php
@@ -1,10 +1,9 @@
'Change Management ITIL',
@@ -12,24 +11,24 @@ SetupWebPage::AddModule(
// Setup
//
- 'dependencies' => array(
+ 'dependencies' => [
'itop-config-mgmt/2.2.0',
'itop-tickets/2.0.0',
- ),
+ ],
'mandatory' => false,
'visible' => true,
// Components
//
- 'datamodel' => array(
- ),
- 'data.struct' => array(
+ 'datamodel' => [
+ ],
+ 'data.struct' => [
//'data.struct.itop-change-mgmt.xml',
- ),
- 'data.sample' => array(
+ ],
+ 'data.sample' => [
//'data.sample.itop-change-mgmt.xml',
- ),
-
+ ],
+
// Documentation
//
'doc.manual_setup' => '',
@@ -37,7 +36,7 @@ SetupWebPage::AddModule(
// Default settings
//
- 'settings' => array(
- ),
- )
+ 'settings' => [
+ ],
+ ]
);
diff --git a/datamodels/2.x/itop-change-mgmt/module.itop-change-mgmt.php b/datamodels/2.x/itop-change-mgmt/module.itop-change-mgmt.php
index 5790d730d..7489e2ed6 100755
--- a/datamodels/2.x/itop-change-mgmt/module.itop-change-mgmt.php
+++ b/datamodels/2.x/itop-change-mgmt/module.itop-change-mgmt.php
@@ -1,10 +1,9 @@
'Change Management',
@@ -12,25 +11,25 @@ SetupWebPage::AddModule(
// Setup
//
- 'dependencies' => array(
+ 'dependencies' => [
'itop-config-mgmt/2.2.0',
'itop-tickets/2.0.0',
- ),
+ ],
'mandatory' => false,
'visible' => true,
'installer' => 'ChangeManagementInstaller',
// Components
//
- 'datamodel' => array(
- ),
- 'data.struct' => array(
+ 'datamodel' => [
+ ],
+ 'data.struct' => [
//'data.struct.itop-change-mgmt.xml',
- ),
- 'data.sample' => array(
+ ],
+ 'data.sample' => [
//'data.sample.itop-change-mgmt.xml',
- ),
-
+ ],
+
// Documentation
//
'doc.manual_setup' => '',
@@ -38,9 +37,9 @@ SetupWebPage::AddModule(
// Default settings
//
- 'settings' => array(
- ),
- )
+ 'settings' => [
+ ],
+ ]
);
// Module installation handler
@@ -63,7 +62,7 @@ class ChangeManagementInstaller extends ModuleInstallerAPI
{
// If you want to migrate data from one format to another, do it here
}
-
+
/**
* Handler called after the creation/update of the database schema
* @param $oConfiguration Config The new configuration of the application
@@ -82,8 +81,7 @@ class ChangeManagementInstaller extends ModuleInstallerAPI
$sField = 'start_date';
- if (CMDBSource::IsField($sSourceTable, $sField) && CMDBSource::IsField($sTargetTable, $sField) && CMDBSource::IsField($sSourceTable, $sSourceKeyField) && CMDBSource::IsField($sTargetTable, $sTargetKeyField))
- {
+ if (CMDBSource::IsField($sSourceTable, $sField) && CMDBSource::IsField($sTargetTable, $sField) && CMDBSource::IsField($sSourceTable, $sSourceKeyField) && CMDBSource::IsField($sTargetTable, $sTargetKeyField)) {
SetupLog::Info("Issue #464 - Copying change/start_date into ticket/start_date");
$sRepair = "UPDATE `$sTargetTable`, `$sSourceTable` SET `$sTargetTable`.`$sField` = `$sSourceTable`.`$sField` WHERE `$sTargetTable`.`$sField` IS NULL AND`$sTargetTable`.`$sTargetKeyField` = `$sSourceTable`.`$sSourceKeyField`";
CMDBSource::Query($sRepair);
diff --git a/datamodels/2.x/itop-config-mgmt/dictionaries/it.dict.itop-config-mgmt.php b/datamodels/2.x/itop-config-mgmt/dictionaries/it.dict.itop-config-mgmt.php
index 02eaa125d..b691acb80 100644
--- a/datamodels/2.x/itop-config-mgmt/dictionaries/it.dict.itop-config-mgmt.php
+++ b/datamodels/2.x/itop-config-mgmt/dictionaries/it.dict.itop-config-mgmt.php
@@ -1,15 +1,16 @@
'Elementi impattati da...',
'Relation:impacts/DownStream' => 'Impatto...',
'Relation:impacts/DownStream+' => 'Elementi impattati da...',
@@ -21,8 +22,7 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Relation:impacts/LoadData' => 'Carica dati',
'Relation:impacts/NoFilteredData' => 'seleziona oggetti e carica dati',
'Relation:impacts/FilteredData' => 'Dati filtrati',
-));
-
+]);
// Dictionnay conventions
// Class:
@@ -65,7 +65,7 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
// Class: lnkContactToFunctionalCI
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:lnkContactToFunctionalCI' => 'Link Contact / FunctionalCI',
'Class:lnkContactToFunctionalCI+' => '~~',
'Class:lnkContactToFunctionalCI/Name' => '%1$s / %2$s',
@@ -77,13 +77,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:lnkContactToFunctionalCI/Attribute:contact_id+' => '~~',
'Class:lnkContactToFunctionalCI/Attribute:contact_name' => 'Nome Contatto',
'Class:lnkContactToFunctionalCI/Attribute:contact_name+' => '~~',
-));
+]);
//
// Class: FunctionalCI
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:FunctionalCI' => 'CI Funzionale',
'Class:FunctionalCI+' => '',
'Class:FunctionalCI/Attribute:name' => 'Nome',
@@ -116,13 +116,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:FunctionalCI/Attribute:finalclass+' => '',
'Class:FunctionalCI/Tab:OpenedTickets' => 'Ticket attivi',
'Class:FunctionalCI/Tab:OpenedTickets+' => 'Ticket attivi che stanno influenzando questa CI funzionale',
-));
+]);
//
// Class: PhysicalDevice
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:PhysicalDevice' => 'Dispositivo Fisico',
'Class:PhysicalDevice+' => '~~',
'Class:PhysicalDevice/ComplementaryName' => '%1$s - %2$s',
@@ -156,13 +156,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:PhysicalDevice/Attribute:purchase_date+' => '~~',
'Class:PhysicalDevice/Attribute:end_of_warranty' => 'Scadenza garanzia',
'Class:PhysicalDevice/Attribute:end_of_warranty+' => '~~',
-));
+]);
//
// Class: Rack
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:Rack' => 'Rack',
'Class:Rack+' => '~~',
'Class:Rack/ComplementaryName' => '%1$s - %2$s',
@@ -172,64 +172,64 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:Rack/Attribute:device_list+' => 'Tutti i dispositivi fisici installati in questo rack',
'Class:Rack/Attribute:enclosure_list' => 'Contenitori',
'Class:Rack/Attribute:enclosure_list+' => 'Tutti i contenitori in questo rack',
-));
+]);
//
// Class: TelephonyCI
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:TelephonyCI' => 'CI Telefoni',
'Class:TelephonyCI+' => '~~',
'Class:TelephonyCI/Attribute:phonenumber' => 'Numero di telefono',
'Class:TelephonyCI/Attribute:phonenumber+' => '~~',
-));
+]);
//
// Class: Phone
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:Phone' => 'Telefono fisso',
'Class:Phone+' => '~~',
-));
+]);
//
// Class: MobilePhone
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:MobilePhone' => 'Cellulari',
'Class:MobilePhone+' => '',
'Class:MobilePhone/Attribute:imei' => 'IMEI',
'Class:MobilePhone/Attribute:imei+' => '',
'Class:MobilePhone/Attribute:hw_pin' => 'Hardware PIN',
'Class:MobilePhone/Attribute:hw_pin+' => '',
-));
+]);
//
// Class: IPPhone
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:IPPhone' => 'Telefoni IP / VoIP',
'Class:IPPhone+' => '~~',
-));
+]);
//
// Class: Tablet
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:Tablet' => 'Tablet',
'Class:Tablet+' => '~~',
-));
+]);
//
// Class: ConnectableCI
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:ConnectableCI' => 'CI collegabile',
'Class:ConnectableCI+' => 'CI fisico',
'Class:ConnectableCI/ComplementaryName' => '%1$s - %2$s',
@@ -237,13 +237,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:ConnectableCI/Attribute:networkdevice_list+' => 'Tutti i dispositivi di rete collegati a questo dispositivo',
'Class:ConnectableCI/Attribute:physicalinterface_list' => 'Interfacce di rete',
'Class:ConnectableCI/Attribute:physicalinterface_list+' => 'Tutte le interfacce di rete fisiche',
-));
+]);
//
// Class: DatacenterDevice
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:DatacenterDevice' => 'Datacenter Device',
'Class:DatacenterDevice+' => '~~',
'Class:DatacenterDevice/ComplementaryName' => '%1$s - %2$s',
@@ -275,13 +275,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:DatacenterDevice/Attribute:redundancy/count' => 'Il dispositivo è operativo se almeno una connessione elettrica (A o B) è attiva',
'Class:DatacenterDevice/Attribute:redundancy/disabled' => 'Il dispositivo è operativo se tutte le sue connessioni elettriche sono attive',
'Class:DatacenterDevice/Attribute:redundancy/percent' => 'Il dispositivo è operativo se almeno il %1$s %% delle sue connessioni elettriche sono attive',
-));
+]);
//
// Class: NetworkDevice
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:NetworkDevice' => 'Dispositivi di rete',
'Class:NetworkDevice+' => '',
'Class:NetworkDevice/ComplementaryName' => '%1$s - %2$s',
@@ -297,13 +297,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:NetworkDevice/Attribute:iosversion_name+' => '~~',
'Class:NetworkDevice/Attribute:ram' => 'RAM',
'Class:NetworkDevice/Attribute:ram+' => '',
-));
+]);
//
// Class: Server
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:Server' => 'Server',
'Class:Server+' => '',
'Class:Server/ComplementaryName' => '%1$s - %2$s',
@@ -325,61 +325,61 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:Server/Attribute:ram+' => '',
'Class:Server/Attribute:logicalvolumes_list' => 'Volumi Logici',
'Class:Server/Attribute:logicalvolumes_list+' => 'Tutti i volumi logici collegati a questo server',
-));
+]);
//
// Class: StorageSystem
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:StorageSystem' => 'Sistema di Archiviazione',
'Class:StorageSystem+' => '~~',
'Class:StorageSystem/ComplementaryName' => '%1$s - %2$s',
'Class:StorageSystem/Attribute:logicalvolume_list' => 'Volumi Logici',
'Class:StorageSystem/Attribute:logicalvolume_list+' => 'Tutti i volumi logici in questo sistema di archiviazione',
-));
+]);
//
// Class: SANSwitch
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:SANSwitch' => 'SAN Switch',
'Class:SANSwitch+' => '~~',
'Class:SANSwitch/ComplementaryName' => '%1$s - %2$s',
'Class:SANSwitch/Attribute:datacenterdevice_list' => 'Dispositivi',
'Class:SANSwitch/Attribute:datacenterdevice_list+' => 'Tutti i dispositivi collegati a questo switch SAN',
-));
+]);
//
// Class: TapeLibrary
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:TapeLibrary' => 'Libreria di nastri',
'Class:TapeLibrary+' => '~~',
'Class:TapeLibrary/ComplementaryName' => '%1$s - %2$s',
'Class:TapeLibrary/Attribute:tapes_list' => 'Nastri',
'Class:TapeLibrary/Attribute:tapes_list+' => 'Tutti i nastri nella libreria di nastri',
-));
+]);
//
// Class: NAS
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:NAS' => 'NAS',
'Class:NAS+' => '~~',
'Class:NAS/ComplementaryName' => '%1$s - %2$s',
'Class:NAS/Attribute:nasfilesystem_list' => 'File system',
'Class:NAS/Attribute:nasfilesystem_list+' => 'Tutti i file system in questo NAS',
-));
+]);
//
// Class: PC
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:PC' => 'PC',
'Class:PC+' => '',
'Class:PC/ComplementaryName' => '%1$s - %2$s',
@@ -401,45 +401,45 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:PC/Attribute:type/Value:desktop+' => 'desktop~~',
'Class:PC/Attribute:type/Value:laptop' => 'laptop~~',
'Class:PC/Attribute:type/Value:laptop+' => 'laptop~~',
-));
+]);
//
// Class: Printer
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:Printer' => 'Stampante',
'Class:Printer+' => '',
'Class:Printer/ComplementaryName' => '%1$s - %2$s',
-));
+]);
//
// Class: PowerConnection
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:PowerConnection' => 'Connessione di Alimentazione',
'Class:PowerConnection+' => '~~',
'Class:PowerConnection/ComplementaryName' => '%1$s - %2$s',
-));
+]);
//
// Class: PowerSource
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:PowerSource' => 'Sorgente di Alimentazione',
'Class:PowerSource+' => '~~',
'Class:PowerSource/ComplementaryName' => '%1$s - %2$s',
'Class:PowerSource/Attribute:pdus_list' => 'PDU',
'Class:PowerSource/Attribute:pdus_list+' => 'Tutte le PDU che utilizzano questa sorgente di alimentazione',
-));
+]);
//
// Class: PDU
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:PDU' => 'PDU',
'Class:PDU+' => '~~',
'Class:PDU/ComplementaryName' => '%1$s - %2$s - %3$s - %4$s',
@@ -451,23 +451,23 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:PDU/Attribute:powerstart_id+' => '~~',
'Class:PDU/Attribute:powerstart_name' => 'Nome Avvio Alimentazione',
'Class:PDU/Attribute:powerstart_name+' => '~~',
-));
+]);
//
// Class: Peripheral
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:Peripheral' => 'Periferica',
'Class:Peripheral+' => '~~',
'Class:Peripheral/ComplementaryName' => '%1$s - %2$s',
-));
+]);
//
// Class: Enclosure
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:Enclosure' => 'Contenitore',
'Class:Enclosure+' => '~~',
'Class:Enclosure/ComplementaryName' => '%1$s - %2$s - %3$s',
@@ -479,13 +479,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:Enclosure/Attribute:nb_u+' => '~~',
'Class:Enclosure/Attribute:device_list' => 'Dispositivi',
'Class:Enclosure/Attribute:device_list+' => 'Tutti i dispositivi in questo contenitore',
-));
+]);
//
// Class: ApplicationSolution
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:ApplicationSolution' => 'Soluzione Applicativa',
'Class:ApplicationSolution+' => '',
'Class:ApplicationSolution/Attribute:functionalcis_list' => 'CIs',
@@ -502,13 +502,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:ApplicationSolution/Attribute:redundancy/disabled' => 'La soluzione è attiva se tutti gli elementi di configurazione sono attivi',
'Class:ApplicationSolution/Attribute:redundancy/count' => 'La soluzione è attiva se almeno %1$s elemento(i) di configurazione sono attivi',
'Class:ApplicationSolution/Attribute:redundancy/percent' => 'La soluzione è attiva se almeno il %1$s %% degli elementi di configurazione sono attivi',
-));
+]);
//
// Class: BusinessProcess
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:BusinessProcess' => 'Processi aziendali',
'Class:BusinessProcess+' => '',
'Class:BusinessProcess/Attribute:applicationsolutions_list' => 'Soluzioni applicative',
@@ -519,13 +519,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:BusinessProcess/Attribute:status/Value:active+' => 'attivo',
'Class:BusinessProcess/Attribute:status/Value:inactive' => 'inattivo',
'Class:BusinessProcess/Attribute:status/Value:inactive+' => 'inattivo',
-));
+]);
//
// Class: SoftwareInstance
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:SoftwareInstance' => 'Istanza Software',
'Class:SoftwareInstance+' => '',
'Class:SoftwareInstance/Attribute:system_id' => 'Sistema',
@@ -548,64 +548,64 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:SoftwareInstance/Attribute:status/Value:active+' => 'attivo',
'Class:SoftwareInstance/Attribute:status/Value:inactive' => 'inattivo',
'Class:SoftwareInstance/Attribute:status/Value:inactive+' => 'inattivo',
-));
+]);
//
// Class: Middleware
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:Middleware' => 'Middleware',
'Class:Middleware+' => '~~',
'Class:Middleware/Attribute:middlewareinstance_list' => 'Istanze Middleware',
'Class:Middleware/Attribute:middlewareinstance_list+' => 'Tutte le istanze del middleware fornite da questo middleware',
-));
+]);
//
// Class: DBServer
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:DBServer' => 'Database',
'Class:DBServer+' => 'Database server SW',
'Class:DBServer/Attribute:dbschema_list' => 'Schema Database',
'Class:DBServer/Attribute:dbschema_list+' => 'Tutti gli schemi del database per questo server di database',
-));
+]);
//
// Class: WebServer
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:WebServer' => 'Web server',
'Class:WebServer+' => '~~',
'Class:WebServer/Attribute:webapp_list' => 'Applicazioni web',
'Class:WebServer/Attribute:webapp_list+' => 'Tutte le applicazioni web disponibili su questo server web',
-));
+]);
//
// Class: PCSoftware
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:PCSoftware' => 'Software PC',
'Class:PCSoftware+' => '~~',
-));
+]);
//
// Class: OtherSoftware
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:OtherSoftware' => 'Altro Software',
'Class:OtherSoftware+' => '~~',
-));
+]);
//
// Class: MiddlewareInstance
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:MiddlewareInstance' => 'Istanza Middleware',
'Class:MiddlewareInstance+' => '~~',
'Class:MiddlewareInstance/ComplementaryName' => '%1$s - %2$s',
@@ -613,13 +613,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:MiddlewareInstance/Attribute:middleware_id+' => '~~',
'Class:MiddlewareInstance/Attribute:middleware_name' => 'Nome Middleware',
'Class:MiddlewareInstance/Attribute:middleware_name+' => '~~',
-));
+]);
//
// Class: DatabaseSchema
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:DatabaseSchema' => 'Schema del Database',
'Class:DatabaseSchema+' => '~~',
'Class:DatabaseSchema/ComplementaryName' => '%1$s - %2$s',
@@ -627,13 +627,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:DatabaseSchema/Attribute:dbserver_id+' => '~~',
'Class:DatabaseSchema/Attribute:dbserver_name' => 'Nome Server del Database',
'Class:DatabaseSchema/Attribute:dbserver_name+' => '~~',
-));
+]);
//
// Class: WebApplication
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:WebApplication' => 'Web Application',
'Class:WebApplication+' => '~~',
'Class:WebApplication/ComplementaryName' => '%1$s - %2$s',
@@ -643,14 +643,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:WebApplication/Attribute:webserver_name+' => '~~',
'Class:WebApplication/Attribute:url' => 'URL',
'Class:WebApplication/Attribute:url+' => '~~',
-));
-
+]);
//
// Class: VirtualDevice
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:VirtualDevice' => 'Dispositivo virtuale',
'Class:VirtualDevice+' => '~~',
'Class:VirtualDevice/Attribute:status' => 'Stato',
@@ -665,24 +664,24 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:VirtualDevice/Attribute:status/Value:stock+' => 'In Stock',
'Class:VirtualDevice/Attribute:logicalvolumes_list' => 'Volumi Logici',
'Class:VirtualDevice/Attribute:logicalvolumes_list+' => 'Tutti i volumi logici utilizzati da questo dispositivo',
-));
+]);
//
// Class: VirtualHost
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:VirtualHost' => 'Host Virtuale',
'Class:VirtualHost+' => '~~',
'Class:VirtualHost/Attribute:virtualmachine_list' => 'Macchine virtuali',
'Class:VirtualHost/Attribute:virtualmachine_list+' => 'Tutte le macchine virtuali ospitate da questo host',
-));
+]);
//
// Class: Hypervisor
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:Hypervisor' => 'Hypervisor',
'Class:Hypervisor+' => '~~',
'Class:Hypervisor/Attribute:farm_id' => 'Farm',
@@ -693,13 +692,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:Hypervisor/Attribute:server_id+' => '~~',
'Class:Hypervisor/Attribute:server_name' => 'Nome Server',
'Class:Hypervisor/Attribute:server_name+' => '~~',
-));
+]);
//
// Class: Farm
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:Farm' => 'Farm',
'Class:Farm+' => '~~',
'Class:Farm/Attribute:hypervisor_list' => 'Hypervisor',
@@ -708,13 +707,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:Farm/Attribute:redundancy/disabled' => 'La farm è attiva se tutti gli hypervisor sono attivi',
'Class:Farm/Attribute:redundancy/count' => 'La farm è attiva se almeno %1$s hypervisor è(sono) attivo(i)',
'Class:Farm/Attribute:redundancy/percent' => 'La farm è attiva se almeno %1$s %% degli hypervisor è attivo',
-));
+]);
//
// Class: VirtualMachine
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:VirtualMachine' => 'Macchina virtuale',
'Class:VirtualMachine+' => '~~',
'Class:VirtualMachine/ComplementaryName' => '%1$s - %2$s',
@@ -742,13 +741,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:VirtualMachine/Attribute:managementip+' => '~~',
'Class:VirtualMachine/Attribute:logicalinterface_list' => 'Interfacce di rete logiche',
'Class:VirtualMachine/Attribute:logicalinterface_list+' => 'Tutte le interfacce di rete logiche',
-));
+]);
//
// Class: LogicalVolume
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:LogicalVolume' => 'Volume Logico',
'Class:LogicalVolume+' => '~~',
'Class:LogicalVolume/Attribute:name' => 'Nome',
@@ -769,13 +768,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:LogicalVolume/Attribute:servers_list+' => 'Tutti i server che utilizzano questo volume',
'Class:LogicalVolume/Attribute:virtualdevices_list' => 'Dispositivi Virtuali',
'Class:LogicalVolume/Attribute:virtualdevices_list+' => 'Tutti i dispositivi virtuali che utilizzano questo volume',
-));
+]);
//
// Class: lnkServerToVolume
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:lnkServerToVolume' => 'Collegamento Server / Volume',
'Class:lnkServerToVolume+' => '~~',
'Class:lnkServerToVolume/Name' => '%1$s / %2$s',
@@ -789,13 +788,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:lnkServerToVolume/Attribute:server_name+' => '~~',
'Class:lnkServerToVolume/Attribute:size_used' => 'Dimensione utilizzata',
'Class:lnkServerToVolume/Attribute:size_used+' => '~~',
-));
+]);
//
// Class: lnkVirtualDeviceToVolume
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:lnkVirtualDeviceToVolume' => 'Collegamento dispositivo virtuale / volume',
'Class:lnkVirtualDeviceToVolume+' => '~~',
'Class:lnkVirtualDeviceToVolume/Name' => '%1$s / %2$s',
@@ -809,13 +808,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:lnkVirtualDeviceToVolume/Attribute:virtualdevice_name+' => '~~',
'Class:lnkVirtualDeviceToVolume/Attribute:size_used' => 'Dimensione utilizzata',
'Class:lnkVirtualDeviceToVolume/Attribute:size_used+' => '~~',
-));
+]);
//
// Class: lnkSanToDatacenterDevice
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:lnkSanToDatacenterDevice' => 'Collegamento SAN / Dispositivo Datacenter',
'Class:lnkSanToDatacenterDevice+' => '~~',
'Class:lnkSanToDatacenterDevice/Name' => '%1$s / %2$s',
@@ -831,13 +830,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:lnkSanToDatacenterDevice/Attribute:san_port+' => '~~',
'Class:lnkSanToDatacenterDevice/Attribute:datacenterdevice_port' => 'Porta dispositivo FC',
'Class:lnkSanToDatacenterDevice/Attribute:datacenterdevice_port+' => '~~',
-));
+]);
//
// Class: Tape
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:Tape' => 'Nastro',
'Class:Tape+' => '~~',
'Class:Tape/Attribute:name' => 'Nome',
@@ -850,13 +849,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:Tape/Attribute:tapelibrary_id+' => '~~',
'Class:Tape/Attribute:tapelibrary_name' => 'Nome della libreria di nastri',
'Class:Tape/Attribute:tapelibrary_name+' => '~~',
-));
+]);
//
// Class: NASFileSystem
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:NASFileSystem' => 'File System NAS',
'Class:NASFileSystem+' => '~~',
'Class:NASFileSystem/Attribute:name' => 'Nome',
@@ -871,13 +870,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:NASFileSystem/Attribute:nas_id+' => '~~',
'Class:NASFileSystem/Attribute:nas_name' => 'Nome del NAS',
'Class:NASFileSystem/Attribute:nas_name+' => '~~',
-));
+]);
//
// Class: Software
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:Software' => 'Software',
'Class:Software+' => '',
'Class:Software/ComplementaryName' => '%1$s - %2$s',
@@ -907,13 +906,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:Software/Attribute:softwarepatch_list+' => 'Tutte le patch per questo software',
'Class:Software/Attribute:softwarelicence_list' => 'Licenze Software',
'Class:Software/Attribute:softwarelicence_list+' => 'Tutte le licenze per questo software',
-));
+]);
//
// Class: Patch
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:Patch' => 'Patch',
'Class:Patch+' => '',
'Class:Patch/Attribute:name' => 'Nome',
@@ -924,13 +923,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:Patch/Attribute:description+' => '',
'Class:Patch/Attribute:finalclass' => 'Tipo',
'Class:Patch/Attribute:finalclass+' => 'Nome della classe finale',
-));
+]);
//
// Class: OSPatch
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:OSPatch' => 'Patch del Sistema Operativo',
'Class:OSPatch+' => '~~',
'Class:OSPatch/Attribute:functionalcis_list' => 'Dispositivi',
@@ -939,13 +938,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:OSPatch/Attribute:osversion_id+' => '~~',
'Class:OSPatch/Attribute:osversion_name' => 'Nome della Versione del Sistema Operativo',
'Class:OSPatch/Attribute:osversion_name+' => '~~',
-));
+]);
//
// Class: SoftwarePatch
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:SoftwarePatch' => 'Patch del Software',
'Class:SoftwarePatch+' => '~~',
'Class:SoftwarePatch/Attribute:software_id' => 'Software',
@@ -954,13 +953,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:SoftwarePatch/Attribute:software_name+' => '~~',
'Class:SoftwarePatch/Attribute:softwareinstances_list' => 'Istanze del Software',
'Class:SoftwarePatch/Attribute:softwareinstances_list+' => 'Tutti i sistemi in cui questa patch del software è installata',
-));
+]);
//
// Class: Licence
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:Licence' => 'Licenza',
'Class:Licence+' => '',
'Class:Licence/Attribute:name' => 'Nome',
@@ -989,13 +988,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:Licence/Attribute:perpetual/Value:yes+' => 'sì',
'Class:Licence/Attribute:finalclass' => 'Tipo',
'Class:Licence/Attribute:finalclass+' => 'Nome della classe finale',
-));
+]);
//
// Class: OSLicence
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:OSLicence' => 'Licenza OS',
'Class:OSLicence+' => '~~',
'Class:OSLicence/ComplementaryName' => '%1$s - %2$s',
@@ -1007,13 +1006,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:OSLicence/Attribute:virtualmachines_list+' => 'Tutte le macchine virtuali in cui questa licenza è utilizzata',
'Class:OSLicence/Attribute:servers_list' => 'Server',
'Class:OSLicence/Attribute:servers_list+' => 'Tutti i server in cui questa licenza è utilizzata',
-));
+]);
//
// Class: SoftwareLicence
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:SoftwareLicence' => 'Licenza software',
'Class:SoftwareLicence+' => '~~',
'Class:SoftwareLicence/ComplementaryName' => '%1$s - %2$s',
@@ -1023,13 +1022,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:SoftwareLicence/Attribute:software_name+' => '~~',
'Class:SoftwareLicence/Attribute:softwareinstance_list' => 'Istanze software',
'Class:SoftwareLicence/Attribute:softwareinstance_list+' => 'Tutti i sistemi in cui questa licenza è utilizzata',
-));
+]);
//
// Class: lnkDocumentToLicence
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:lnkDocumentToLicence' => 'Link Documento/Licenza',
'Class:lnkDocumentToLicence+' => '~~',
'Class:lnkDocumentToLicence/Name' => '%1$s / %2$s',
@@ -1041,48 +1040,48 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:lnkDocumentToLicence/Attribute:document_id+' => '~~',
'Class:lnkDocumentToLicence/Attribute:document_name' => 'Nome documento',
'Class:lnkDocumentToLicence/Attribute:document_name+' => '~~',
-));
+]);
//
// Class: OSVersion
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:OSVersion' => 'Versione del Sistema Operativo',
'Class:OSVersion+' => '~~',
'Class:OSVersion/Attribute:osfamily_id' => 'Famiglia del Sistema Operativo',
'Class:OSVersion/Attribute:osfamily_id+' => '~~',
'Class:OSVersion/Attribute:osfamily_name' => 'Nome della Famiglia del Sistema Operativo',
'Class:OSVersion/Attribute:osfamily_name+' => '~~',
-));
+]);
//
// Class: OSFamily
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:OSFamily' => 'Famiglia del Sistema Operativo',
'Class:OSFamily+' => '~~',
-));
+]);
//
// Class: Brand
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:Brand' => 'Marca',
'Class:Brand+' => '~~',
'Class:Brand/Attribute:physicaldevices_list' => 'Dispositivi fisici',
'Class:Brand/Attribute:physicaldevices_list+' => 'Tutti i dispositivi fisici corrispondenti a questa marca',
'Class:Brand/UniquenessRule:name+' => 'Il nome deve essere univoco',
'Class:Brand/UniquenessRule:name' => 'Questa marca esiste già',
-));
+]);
//
// Class: Model
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:Model' => 'Modello',
'Class:Model+' => '~~',
'Class:Model/Attribute/type/Value:NAS+' => 'NAS',
@@ -1157,37 +1156,37 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:Model/Attribute:physicaldevices_list+' => 'Tutti i dispositivi fisici corrispondenti a questo modello',
'Class:Model/UniquenessRule:name_brand+' => 'Il nome deve essere univoco nella marca',
'Class:Model/UniquenessRule:name_brand' => 'Questo modello esiste già per questa marca',
-));
+]);
//
// Class: NetworkDeviceType
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:NetworkDeviceType' => 'Tipo di Dispositivo di Rete',
'Class:NetworkDeviceType+' => '~~',
'Class:NetworkDeviceType/Attribute:networkdevicesdevices_list' => 'Dispositivi di Rete',
'Class:NetworkDeviceType/Attribute:networkdevicesdevices_list+' => 'Tutti i dispositivi di rete corrispondenti a questo tipo',
-));
+]);
//
// Class: IOSVersion
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:IOSVersion' => 'Versione IOS',
'Class:IOSVersion+' => '~~',
'Class:IOSVersion/Attribute:brand_id' => 'Marca',
'Class:IOSVersion/Attribute:brand_id+' => '~~',
'Class:IOSVersion/Attribute:brand_name' => 'Nome della marca',
'Class:IOSVersion/Attribute:brand_name+' => '~~',
-));
+]);
//
// Class: lnkDocumentToPatch
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:lnkDocumentToPatch' => 'Collegamento documento / patch',
'Class:lnkDocumentToPatch+' => '~~',
'Class:lnkDocumentToPatch/Name' => '%1$s / %2$s',
@@ -1199,13 +1198,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:lnkDocumentToPatch/Attribute:document_id+' => '~~',
'Class:lnkDocumentToPatch/Attribute:document_name' => 'Nome del documento',
'Class:lnkDocumentToPatch/Attribute:document_name+' => '~~',
-));
+]);
//
// Class: lnkSoftwareInstanceToSoftwarePatch
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:lnkSoftwareInstanceToSoftwarePatch' => 'Collegamento istanza software / patch software',
'Class:lnkSoftwareInstanceToSoftwarePatch+' => '~~',
'Class:lnkSoftwareInstanceToSoftwarePatch/Name' => '%1$s / %2$s',
@@ -1217,13 +1216,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:lnkSoftwareInstanceToSoftwarePatch/Attribute:softwareinstance_id+' => '~~',
'Class:lnkSoftwareInstanceToSoftwarePatch/Attribute:softwareinstance_name' => 'Nome dell\'istanza software',
'Class:lnkSoftwareInstanceToSoftwarePatch/Attribute:softwareinstance_name+' => '~~',
-));
+]);
//
// Class: lnkFunctionalCIToOSPatch
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:lnkFunctionalCIToOSPatch' => 'Collegamento CI funzionale / patch OS',
'Class:lnkFunctionalCIToOSPatch+' => '~~',
'Class:lnkFunctionalCIToOSPatch/Name' => '%1$s / %2$s',
@@ -1235,13 +1234,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:lnkFunctionalCIToOSPatch/Attribute:functionalci_id+' => '~~',
'Class:lnkFunctionalCIToOSPatch/Attribute:functionalci_name' => 'Nome del CI funzionale',
'Class:lnkFunctionalCIToOSPatch/Attribute:functionalci_name+' => '~~',
-));
+]);
//
// Class: lnkDocumentToSoftware
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:lnkDocumentToSoftware' => 'Collegamento documento / software',
'Class:lnkDocumentToSoftware+' => '~~',
'Class:lnkDocumentToSoftware/Name' => '%1$s / %2$s',
@@ -1253,13 +1252,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:lnkDocumentToSoftware/Attribute:document_id+' => '~~',
'Class:lnkDocumentToSoftware/Attribute:document_name' => 'Nome del documento',
'Class:lnkDocumentToSoftware/Attribute:document_name+' => '~~',
-));
+]);
//
// Class: Subnet
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:Subnet' => 'Subnet',
'Class:Subnet+' => '',
'Class:Subnet/Name' => '%1$s/%2$s',
@@ -1278,13 +1277,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:Subnet/Attribute:ip_mask+' => '',
'Class:Subnet/Attribute:vlans_list' => 'VLANs',
'Class:Subnet/Attribute:vlans_list+' => '~~',
-));
+]);
//
// Class: VLAN
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:VLAN' => 'VLAN',
'Class:VLAN+' => '~~',
'Class:VLAN/Attribute:vlan_tag' => 'VLAN Tag',
@@ -1299,13 +1298,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:VLAN/Attribute:subnets_list+' => '~~',
'Class:VLAN/Attribute:physicalinterfaces_list' => 'Interfacce di rete fisiche',
'Class:VLAN/Attribute:physicalinterfaces_list+' => '~~',
-));
+]);
//
// Class: lnkSubnetToVLAN
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:lnkSubnetToVLAN' => 'Link Subnet / VLAN',
'Class:lnkSubnetToVLAN+' => '~~',
'Class:lnkSubnetToVLAN/Name' => '%1$s / %2$s',
@@ -1319,26 +1318,26 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:lnkSubnetToVLAN/Attribute:vlan_id+' => '~~',
'Class:lnkSubnetToVLAN/Attribute:vlan_tag' => 'VLAN tag',
'Class:lnkSubnetToVLAN/Attribute:vlan_tag+' => '~~',
-));
+]);
//
// Class: NetworkInterface
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:NetworkInterface' => 'Interfaccia di Rete',
'Class:NetworkInterface+' => '',
'Class:NetworkInterface/Attribute:name' => 'Nome',
'Class:NetworkInterface/Attribute:name+' => '~~',
'Class:NetworkInterface/Attribute:finalclass' => 'Tipo',
'Class:NetworkInterface/Attribute:finalclass+' => 'Nome della classe finale',
-));
+]);
//
// Class: IPInterface
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:IPInterface' => 'Interfaccia IP',
'Class:IPInterface+' => '~~',
'Class:IPInterface/Attribute:ipaddress' => 'Indirizzo IP',
@@ -1353,13 +1352,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:IPInterface/Attribute:ipmask+' => '~~',
'Class:IPInterface/Attribute:speed' => 'Velocità',
'Class:IPInterface/Attribute:speed+' => '~~',
-));
+]);
//
// Class: PhysicalInterface
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:PhysicalInterface' => 'Interfaccia fisica',
'Class:PhysicalInterface+' => '~~',
'Class:PhysicalInterface/Name' => '%2$s %1$s',
@@ -1369,13 +1368,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:PhysicalInterface/Attribute:connectableci_name+' => '~~',
'Class:PhysicalInterface/Attribute:vlans_list' => 'VLAN',
'Class:PhysicalInterface/Attribute:vlans_list+' => '~~',
-));
+]);
//
// Class: lnkPhysicalInterfaceToVLAN
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:lnkPhysicalInterfaceToVLAN' => 'Collegamento interfaccia fisica / VLAN',
'Class:lnkPhysicalInterfaceToVLAN+' => '~~',
'Class:lnkPhysicalInterfaceToVLAN/Name' => '%1$s %2$s / %3$s',
@@ -1391,27 +1390,26 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:lnkPhysicalInterfaceToVLAN/Attribute:vlan_id+' => '~~',
'Class:lnkPhysicalInterfaceToVLAN/Attribute:vlan_tag' => 'Tag VLAN',
'Class:lnkPhysicalInterfaceToVLAN/Attribute:vlan_tag+' => '~~',
-));
-
+]);
//
// Class: LogicalInterface
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:LogicalInterface' => 'Interfaccia logica',
'Class:LogicalInterface+' => '~~',
'Class:LogicalInterface/Attribute:virtualmachine_id' => 'Macchina Virtuale',
'Class:LogicalInterface/Attribute:virtualmachine_id+' => '~~',
'Class:LogicalInterface/Attribute:virtualmachine_name' => 'Nome Macchina Virtuale',
'Class:LogicalInterface/Attribute:virtualmachine_name+' => '~~',
-));
+]);
//
// Class: FiberChannelInterface
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:FiberChannelInterface' => 'Interfaccia Fibre Channel',
'Class:FiberChannelInterface+' => '~~',
'Class:FiberChannelInterface/Attribute:speed' => 'Velocità',
@@ -1424,13 +1422,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:FiberChannelInterface/Attribute:datacenterdevice_id+' => '~~',
'Class:FiberChannelInterface/Attribute:datacenterdevice_name' => 'Nome Dispositivo',
'Class:FiberChannelInterface/Attribute:datacenterdevice_name+' => '~~',
-));
+]);
//
// Class: lnkConnectableCIToNetworkDevice
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:lnkConnectableCIToNetworkDevice' => 'Collega CI collegabile / Dispositivo di rete',
'Class:lnkConnectableCIToNetworkDevice+' => '~~',
'Class:lnkConnectableCIToNetworkDevice/Name' => '%1$s / %2$s',
@@ -1452,13 +1450,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:lnkConnectableCIToNetworkDevice/Attribute:connection_type/Value:downlink+' => 'Collegamento verso il basso',
'Class:lnkConnectableCIToNetworkDevice/Attribute:connection_type/Value:uplink' => 'Collegamento verso l\'alto',
'Class:lnkConnectableCIToNetworkDevice/Attribute:connection_type/Value:uplink+' => 'Collegamento verso l\'alto',
-));
+]);
//
// Class: lnkApplicationSolutionToFunctionalCI
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:lnkApplicationSolutionToFunctionalCI' => 'Collega soluzione applicativa / CI funzionale',
'Class:lnkApplicationSolutionToFunctionalCI+' => '~~',
'Class:lnkApplicationSolutionToFunctionalCI/Name' => '%1$s / %2$s',
@@ -1470,13 +1468,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:lnkApplicationSolutionToFunctionalCI/Attribute:functionalci_id+' => '~~',
'Class:lnkApplicationSolutionToFunctionalCI/Attribute:functionalci_name' => 'Nome CI funzionale',
'Class:lnkApplicationSolutionToFunctionalCI/Attribute:functionalci_name+' => '~~',
-));
+]);
//
// Class: lnkApplicationSolutionToBusinessProcess
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:lnkApplicationSolutionToBusinessProcess' => 'Collega Soluzione Applicativa / Processo Aziendale',
'Class:lnkApplicationSolutionToBusinessProcess+' => '~~',
'Class:lnkApplicationSolutionToBusinessProcess/Name' => '%1$s / %2$s',
@@ -1488,13 +1486,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:lnkApplicationSolutionToBusinessProcess/Attribute:applicationsolution_id+' => '~~',
'Class:lnkApplicationSolutionToBusinessProcess/Attribute:applicationsolution_name' => 'Nome Soluzione Applicativa',
'Class:lnkApplicationSolutionToBusinessProcess/Attribute:applicationsolution_name+' => '~~',
-));
+]);
//
// Class: Group
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:Group' => 'Gruppo',
'Class:Group+' => '',
'Class:Group/ComplementaryName' => '%1$s - %2$s',
@@ -1524,13 +1522,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:Group/Attribute:ci_list+' => 'Tutti gli elementi di configurazione collegati a questo gruppo',
'Class:Group/Attribute:parent_id_friendlyname' => 'Nome del gruppo padre',
'Class:Group/Attribute:parent_id_friendlyname+' => '~~',
-));
+]);
//
// Class: lnkGroupToCI
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:lnkGroupToCI' => 'Gruppo / CI',
'Class:lnkGroupToCI+' => '',
'Class:lnkGroupToCI/Name' => '%1$s / %2$s',
@@ -1544,11 +1542,11 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:lnkGroupToCI/Attribute:ci_name+' => '',
'Class:lnkGroupToCI/Attribute:reason' => 'Motivo',
'Class:lnkGroupToCI/Attribute:reason+' => '',
-));
+]);
// Add translation for Fieldsets
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Server:baseinfo' => 'Informazioni generali',
'Server:Date' => 'Date',
'Server:moreinfo' => 'Ulteriori informazioni',
@@ -1561,14 +1559,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:Subnet/Tab:FreeIPs-count' => 'IP liberi: %1$s',
'Class:Subnet/Tab:FreeIPs-explain' => 'Ecco un estratto di 10 indirizzi IP liberi',
'Class:Document:PreviewTab' => 'Anteprima',
-));
-
+]);
//
// Class: lnkDocumentToFunctionalCI
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Class:lnkDocumentToFunctionalCI' => 'Collegamento Documento / FunctionalCI',
'Class:lnkDocumentToFunctionalCI+' => '~~',
'Class:lnkDocumentToFunctionalCI/Name' => '%1$s / %2$s',
@@ -1580,13 +1577,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Class:lnkDocumentToFunctionalCI/Attribute:document_id+' => '~~',
'Class:lnkDocumentToFunctionalCI/Attribute:document_name' => 'Nome documento',
'Class:lnkDocumentToFunctionalCI/Attribute:document_name+' => '~~',
-));
+]);
//
// Application Menu
//
-Dict::Add('IT IT', 'Italian', 'Italiano', array(
+Dict::Add('IT IT', 'Italian', 'Italiano', [
'Menu:Application' => 'Applicazioni',
'Menu:Application+' => 'Tutte le applicazioni',
'Menu:DBServer' => 'Server di Database',
@@ -1631,5 +1628,4 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'Menu:OSVersion+' => '~~',
'Menu:Software' => 'Catalogo software',
'Menu:Software+' => 'Catalogo software',
-));
-
+]);
diff --git a/datamodels/2.x/itop-config-mgmt/dictionaries/pt_br.dict.itop-config-mgmt.php b/datamodels/2.x/itop-config-mgmt/dictionaries/pt_br.dict.itop-config-mgmt.php
index 4bd11a1c3..cbb232a58 100644
--- a/datamodels/2.x/itop-config-mgmt/dictionaries/pt_br.dict.itop-config-mgmt.php
+++ b/datamodels/2.x/itop-config-mgmt/dictionaries/pt_br.dict.itop-config-mgmt.php
@@ -1,15 +1,16 @@
'Elementos impactados por',
'Relation:impacts/DownStream' => 'Impacto...',
'Relation:impacts/DownStream+' => 'Elementos impactados por',
@@ -21,8 +22,7 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Relation:impacts/LoadData' => 'Carregando dados',
'Relation:impacts/NoFilteredData' => 'Por favor, selecione os objetos na tag de visualização Gráfica',
'Relation:impacts/FilteredData' => 'Filtered data~~',
-));
-
+]);
// Dictionnay conventions
// Class:
@@ -65,7 +65,7 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
// Class: lnkContactToFunctionalCI
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:lnkContactToFunctionalCI' => 'Relação entre Contato / IC',
'Class:lnkContactToFunctionalCI+' => '',
'Class:lnkContactToFunctionalCI/Name' => '%1$s / %2$s~~',
@@ -77,13 +77,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:lnkContactToFunctionalCI/Attribute:contact_id+' => '',
'Class:lnkContactToFunctionalCI/Attribute:contact_name' => 'Nome do contato',
'Class:lnkContactToFunctionalCI/Attribute:contact_name+' => '',
-));
+]);
//
// Class: FunctionalCI
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:FunctionalCI' => 'Item de Configuração',
'Class:FunctionalCI+' => '',
'Class:FunctionalCI/Attribute:name' => 'Nome',
@@ -116,13 +116,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:FunctionalCI/Attribute:finalclass+' => '',
'Class:FunctionalCI/Tab:OpenedTickets' => 'Solicitações ativas',
'Class:FunctionalCI/Tab:OpenedTickets+' => 'Active Tickets which are impacting this functional CI~~',
-));
+]);
//
// Class: PhysicalDevice
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:PhysicalDevice' => 'Dispositivo físico',
'Class:PhysicalDevice+' => 'Lista de Dispositivos Físicos',
'Class:PhysicalDevice/ComplementaryName' => '%1$s - %2$s~~',
@@ -156,13 +156,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:PhysicalDevice/Attribute:purchase_date+' => '',
'Class:PhysicalDevice/Attribute:end_of_warranty' => 'Fim da garantia',
'Class:PhysicalDevice/Attribute:end_of_warranty+' => '',
-));
+]);
//
// Class: Rack
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:Rack' => 'Rack',
'Class:Rack+' => '',
'Class:Rack/ComplementaryName' => '%1$s - %2$s~~',
@@ -172,64 +172,64 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:Rack/Attribute:device_list+' => 'Todos os Dispositivos físicos empilhados neste Rack',
'Class:Rack/Attribute:enclosure_list' => 'Gavetas',
'Class:Rack/Attribute:enclosure_list+' => 'Todas as Gavetas neste Rack',
-));
+]);
//
// Class: TelephonyCI
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:TelephonyCI' => 'Telefonia',
'Class:TelephonyCI+' => '',
'Class:TelephonyCI/Attribute:phonenumber' => 'Número de telefone',
'Class:TelephonyCI/Attribute:phonenumber+' => '',
-));
+]);
//
// Class: Phone
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:Phone' => 'Telefone',
'Class:Phone+' => '',
-));
+]);
//
// Class: MobilePhone
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:MobilePhone' => 'Telefone Celular',
'Class:MobilePhone+' => '',
'Class:MobilePhone/Attribute:imei' => 'IMEI',
'Class:MobilePhone/Attribute:imei+' => '',
'Class:MobilePhone/Attribute:hw_pin' => 'Hardware PIN',
'Class:MobilePhone/Attribute:hw_pin+' => '',
-));
+]);
//
// Class: IPPhone
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:IPPhone' => 'Telefone IP',
'Class:IPPhone+' => '',
-));
+]);
//
// Class: Tablet
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:Tablet' => 'Tablet',
'Class:Tablet+' => '',
-));
+]);
//
// Class: ConnectableCI
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:ConnectableCI' => 'Conectividade',
'Class:ConnectableCI+' => 'Físico',
'Class:ConnectableCI/ComplementaryName' => '%1$s - %2$s~~',
@@ -237,13 +237,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:ConnectableCI/Attribute:networkdevice_list+' => 'Todos os Dispositivos de rede conectados neste dispositivo',
'Class:ConnectableCI/Attribute:physicalinterface_list' => 'Interface de rede',
'Class:ConnectableCI/Attribute:physicalinterface_list+' => 'Todas as Interfaces de rede presentes neste dispositivo',
-));
+]);
//
// Class: DatacenterDevice
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:DatacenterDevice' => 'Dispositivo de Datacenter',
'Class:DatacenterDevice+' => '',
'Class:DatacenterDevice/ComplementaryName' => '%1$s - %2$s~~',
@@ -275,13 +275,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:DatacenterDevice/Attribute:redundancy/count' => 'O dispositivo está ativo se pelo menos uma conexão de energia (A ou B) estiver ativa',
'Class:DatacenterDevice/Attribute:redundancy/disabled' => 'O dispositivo está ativo se todas as conexões de energia estiverem ativadas',
'Class:DatacenterDevice/Attribute:redundancy/percent' => 'O dispositivo está ativo se pelo menos %1$s %% de suas conexões de energia estiverem funcionando',
-));
+]);
//
// Class: NetworkDevice
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:NetworkDevice' => 'Dispositivo de Rede',
'Class:NetworkDevice+' => '',
'Class:NetworkDevice/ComplementaryName' => '%1$s - %2$s~~',
@@ -297,13 +297,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:NetworkDevice/Attribute:iosversion_name+' => '',
'Class:NetworkDevice/Attribute:ram' => 'RAM',
'Class:NetworkDevice/Attribute:ram+' => '',
-));
+]);
//
// Class: Server
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:Server' => 'Servidor',
'Class:Server+' => '',
'Class:Server/ComplementaryName' => '%1$s - %2$s~~',
@@ -325,61 +325,61 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:Server/Attribute:ram+' => '',
'Class:Server/Attribute:logicalvolumes_list' => 'Volumes lógicos',
'Class:Server/Attribute:logicalvolumes_list+' => 'Todos os Volumes lógicos associados à este Servidor',
-));
+]);
//
// Class: StorageSystem
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:StorageSystem' => 'Sistema de Storage',
'Class:StorageSystem+' => '',
'Class:StorageSystem/ComplementaryName' => '%1$s - %2$s~~',
'Class:StorageSystem/Attribute:logicalvolume_list' => 'Volumes lógicos',
'Class:StorageSystem/Attribute:logicalvolume_list+' => 'Todos os Volumes lógicos neste Sistema de storage',
-));
+]);
//
// Class: SANSwitch
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:SANSwitch' => 'Switch SAN',
'Class:SANSwitch+' => '',
'Class:SANSwitch/ComplementaryName' => '%1$s - %2$s~~',
'Class:SANSwitch/Attribute:datacenterdevice_list' => 'Dispositivos',
'Class:SANSwitch/Attribute:datacenterdevice_list+' => 'Todos os Dispositivos associados à este Switch SAN',
-));
+]);
//
// Class: TapeLibrary
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:TapeLibrary' => 'Biblioteca de Fitas',
'Class:TapeLibrary+' => '',
'Class:TapeLibrary/ComplementaryName' => '%1$s - %2$s~~',
'Class:TapeLibrary/Attribute:tapes_list' => 'Fitas',
'Class:TapeLibrary/Attribute:tapes_list+' => 'Todas as Fitas associadas à esta Biblioteca de fitas',
-));
+]);
//
// Class: NAS
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:NAS' => 'NAS',
'Class:NAS+' => '',
'Class:NAS/ComplementaryName' => '%1$s - %2$s~~',
'Class:NAS/Attribute:nasfilesystem_list' => 'Sistemas de arquivos',
'Class:NAS/Attribute:nasfilesystem_list+' => 'Todos os Sistemas de arquivos para este NAS',
-));
+]);
//
// Class: PC
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:PC' => 'PC',
'Class:PC+' => '',
'Class:PC/ComplementaryName' => '%1$s - %2$s~~',
@@ -401,45 +401,45 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:PC/Attribute:type/Value:desktop+' => '',
'Class:PC/Attribute:type/Value:laptop' => 'Laptop',
'Class:PC/Attribute:type/Value:laptop+' => '',
-));
+]);
//
// Class: Printer
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:Printer' => 'Impressora',
'Class:Printer+' => '',
'Class:Printer/ComplementaryName' => '%1$s - %2$s~~',
-));
+]);
//
// Class: PowerConnection
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:PowerConnection' => 'Conexão de Energia',
'Class:PowerConnection+' => '',
'Class:PowerConnection/ComplementaryName' => '%1$s - %2$s~~',
-));
+]);
//
// Class: PowerSource
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:PowerSource' => 'Fonte de Energia',
'Class:PowerSource+' => '',
'Class:PowerSource/ComplementaryName' => '%1$s - %2$s~~',
'Class:PowerSource/Attribute:pdus_list' => 'PDUs',
'Class:PowerSource/Attribute:pdus_list+' => 'Todos os PDUs utilizando esta Fonte de energia',
-));
+]);
//
// Class: PDU
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:PDU' => 'PDU',
'Class:PDU+' => '',
'Class:PDU/ComplementaryName' => '%1$s - %2$s - %3$s - %4$s~~',
@@ -451,23 +451,23 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:PDU/Attribute:powerstart_id+' => '',
'Class:PDU/Attribute:powerstart_name' => 'Nome da fonte de energia',
'Class:PDU/Attribute:powerstart_name+' => '',
-));
+]);
//
// Class: Peripheral
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:Peripheral' => 'Periférico',
'Class:Peripheral+' => '',
'Class:Peripheral/ComplementaryName' => '%1$s - %2$s~~',
-));
+]);
//
// Class: Enclosure
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:Enclosure' => 'Gaveta',
'Class:Enclosure+' => '',
'Class:Enclosure/ComplementaryName' => '%1$s - %2$s - %3$s~~',
@@ -479,13 +479,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:Enclosure/Attribute:nb_u+' => '',
'Class:Enclosure/Attribute:device_list' => 'Dispositivos',
'Class:Enclosure/Attribute:device_list+' => 'Todos os Dispositivos presentes nesta Gaveta',
-));
+]);
//
// Class: ApplicationSolution
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:ApplicationSolution' => 'Solução de Aplicação',
'Class:ApplicationSolution+' => '',
'Class:ApplicationSolution/Attribute:functionalcis_list' => 'ICs',
@@ -502,13 +502,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:ApplicationSolution/Attribute:redundancy/disabled' => 'A Solução de aplicação está funcionando se todos os Itens de configuração (ICs) estiverem funcionando',
'Class:ApplicationSolution/Attribute:redundancy/count' => 'A Solução de aplicação está funcionando se no mínimo %1$s Item(ns) de configuração (IC(s)) estiver(em) funcionando',
'Class:ApplicationSolution/Attribute:redundancy/percent' => 'A Solução de aplicação está funcionando se no mínimo %1$s %% dos Itens de configuração (ICs) estiverem funcionando',
-));
+]);
//
// Class: BusinessProcess
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:BusinessProcess' => 'Processo de Negócio',
'Class:BusinessProcess+' => '',
'Class:BusinessProcess/Attribute:applicationsolutions_list' => 'Soluções de aplicação',
@@ -519,13 +519,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:BusinessProcess/Attribute:status/Value:active+' => '',
'Class:BusinessProcess/Attribute:status/Value:inactive' => 'Inativo',
'Class:BusinessProcess/Attribute:status/Value:inactive+' => '',
-));
+]);
//
// Class: SoftwareInstance
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:SoftwareInstance' => 'Instância de Software',
'Class:SoftwareInstance+' => '',
'Class:SoftwareInstance/Attribute:system_id' => 'Sistema',
@@ -548,64 +548,64 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:SoftwareInstance/Attribute:status/Value:active+' => 'Ativo',
'Class:SoftwareInstance/Attribute:status/Value:inactive' => 'Inativo',
'Class:SoftwareInstance/Attribute:status/Value:inactive+' => 'Inativo',
-));
+]);
//
// Class: Middleware
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:Middleware' => 'Middleware',
'Class:Middleware+' => '',
'Class:Middleware/Attribute:middlewareinstance_list' => 'Instância Middleware',
'Class:Middleware/Attribute:middlewareinstance_list+' => 'Todos as instância middleware fornecida por essa middleware',
-));
+]);
//
// Class: DBServer
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:DBServer' => 'Servidor de DB',
'Class:DBServer+' => '',
'Class:DBServer/Attribute:dbschema_list' => 'Esquemas de BD',
'Class:DBServer/Attribute:dbschema_list+' => 'Todos os Esquemas de BD para este Servidor de Banco de Dados (BD)',
-));
+]);
//
// Class: WebServer
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:WebServer' => 'Servidor Web',
'Class:WebServer+' => '',
'Class:WebServer/Attribute:webapp_list' => 'Aplicações Web',
'Class:WebServer/Attribute:webapp_list+' => 'Todas as Aplicações Web disponíveis para este Servidor Web',
-));
+]);
//
// Class: PCSoftware
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:PCSoftware' => 'Software de PC',
'Class:PCSoftware+' => '',
-));
+]);
//
// Class: OtherSoftware
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:OtherSoftware' => 'Outro Software',
'Class:OtherSoftware+' => '',
-));
+]);
//
// Class: MiddlewareInstance
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:MiddlewareInstance' => 'Instância Middleware',
'Class:MiddlewareInstance+' => '',
'Class:MiddlewareInstance/ComplementaryName' => '%1$s - %2$s~~',
@@ -613,13 +613,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:MiddlewareInstance/Attribute:middleware_id+' => '',
'Class:MiddlewareInstance/Attribute:middleware_name' => 'Nome do middleware',
'Class:MiddlewareInstance/Attribute:middleware_name+' => '',
-));
+]);
//
// Class: DatabaseSchema
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:DatabaseSchema' => 'Esquema de Banco de Dados (BD)',
'Class:DatabaseSchema+' => '',
'Class:DatabaseSchema/ComplementaryName' => '%1$s - %2$s~~',
@@ -627,13 +627,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:DatabaseSchema/Attribute:dbserver_id+' => '',
'Class:DatabaseSchema/Attribute:dbserver_name' => 'Nome do servidor de DB',
'Class:DatabaseSchema/Attribute:dbserver_name+' => '',
-));
+]);
//
// Class: WebApplication
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:WebApplication' => 'Aplicação Web',
'Class:WebApplication+' => '',
'Class:WebApplication/ComplementaryName' => '%1$s - %2$s~~',
@@ -643,14 +643,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:WebApplication/Attribute:webserver_name+' => '',
'Class:WebApplication/Attribute:url' => 'URL',
'Class:WebApplication/Attribute:url+' => '',
-));
-
+]);
//
// Class: VirtualDevice
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:VirtualDevice' => 'Dispositivo Virtual',
'Class:VirtualDevice+' => '',
'Class:VirtualDevice/Attribute:status' => 'Status',
@@ -665,24 +664,24 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:VirtualDevice/Attribute:status/Value:stock+' => 'Suporte',
'Class:VirtualDevice/Attribute:logicalvolumes_list' => 'Volume lógico',
'Class:VirtualDevice/Attribute:logicalvolumes_list+' => 'Todos os Volumes lógicos associados à este Dispositivo virtual',
-));
+]);
//
// Class: VirtualHost
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:VirtualHost' => 'Host Virtual',
'Class:VirtualHost+' => '',
'Class:VirtualHost/Attribute:virtualmachine_list' => 'Máquinas virtuais (VMs)',
'Class:VirtualHost/Attribute:virtualmachine_list+' => 'Todas as Máquinas virtuais (VMs) hospedadas neste Host virtual',
-));
+]);
//
// Class: Hypervisor
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:Hypervisor' => 'Hypervisor',
'Class:Hypervisor+' => '',
'Class:Hypervisor/Attribute:farm_id' => 'Cluster/HA',
@@ -693,13 +692,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:Hypervisor/Attribute:server_id+' => '',
'Class:Hypervisor/Attribute:server_name' => 'Nome do servidor',
'Class:Hypervisor/Attribute:server_name+' => '',
-));
+]);
//
// Class: Farm
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:Farm' => 'Cluster/HA',
'Class:Farm+' => '',
'Class:Farm/Attribute:hypervisor_list' => 'Hypervisors',
@@ -708,13 +707,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:Farm/Attribute:redundancy/disabled' => 'O farm está ativo se todos os hypervisors estiverem disponíveis',
'Class:Farm/Attribute:redundancy/count' => 'O farm está ativo se pelo menos %1$s hypervisor(s) estiver(em) disponíveis',
'Class:Farm/Attribute:redundancy/percent' => 'O farm está ativo se pelo menos %1$s %% dos hypervisors estiverem disponíveis',
-));
+]);
//
// Class: VirtualMachine
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:VirtualMachine' => 'Máquina Virtual',
'Class:VirtualMachine+' => '',
'Class:VirtualMachine/ComplementaryName' => '%1$s - %2$s~~',
@@ -742,13 +741,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:VirtualMachine/Attribute:managementip+' => '',
'Class:VirtualMachine/Attribute:logicalinterface_list' => 'Interfaces de rede',
'Class:VirtualMachine/Attribute:logicalinterface_list+' => 'Todas as interfaces de rede',
-));
+]);
//
// Class: LogicalVolume
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:LogicalVolume' => 'Volume Lógico',
'Class:LogicalVolume+' => '',
'Class:LogicalVolume/Attribute:name' => 'Nome',
@@ -769,13 +768,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:LogicalVolume/Attribute:servers_list+' => 'Todos os Servidores usando este Volume lógico',
'Class:LogicalVolume/Attribute:virtualdevices_list' => 'Dispositivos virtuais',
'Class:LogicalVolume/Attribute:virtualdevices_list+' => 'Todos os Dispositivos virtuais usando este Volume lógico',
-));
+]);
//
// Class: lnkServerToVolume
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:lnkServerToVolume' => 'Relação entre Servidor / Volume',
'Class:lnkServerToVolume+' => '',
'Class:lnkServerToVolume/Name' => '%1$s / %2$s~~',
@@ -789,13 +788,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:lnkServerToVolume/Attribute:server_name+' => '',
'Class:lnkServerToVolume/Attribute:size_used' => 'Tamanho utilizado',
'Class:lnkServerToVolume/Attribute:size_used+' => '',
-));
+]);
//
// Class: lnkVirtualDeviceToVolume
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:lnkVirtualDeviceToVolume' => 'Relação entre Dispositivo virtual / Volume',
'Class:lnkVirtualDeviceToVolume+' => '',
'Class:lnkVirtualDeviceToVolume/Name' => '%1$s / %2$s~~',
@@ -809,13 +808,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:lnkVirtualDeviceToVolume/Attribute:virtualdevice_name+' => '',
'Class:lnkVirtualDeviceToVolume/Attribute:size_used' => 'Tamanho utilizado',
'Class:lnkVirtualDeviceToVolume/Attribute:size_used+' => '',
-));
+]);
//
// Class: lnkSanToDatacenterDevice
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:lnkSanToDatacenterDevice' => 'Relação entre Switch SAN / Dispositivo de datacenter',
'Class:lnkSanToDatacenterDevice+' => '',
'Class:lnkSanToDatacenterDevice/Name' => '%1$s / %2$s~~',
@@ -831,13 +830,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:lnkSanToDatacenterDevice/Attribute:san_port+' => '',
'Class:lnkSanToDatacenterDevice/Attribute:datacenterdevice_port' => 'FC do dispositivo',
'Class:lnkSanToDatacenterDevice/Attribute:datacenterdevice_port+' => '',
-));
+]);
//
// Class: Tape
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:Tape' => 'Fita',
'Class:Tape+' => '',
'Class:Tape/Attribute:name' => 'Nome',
@@ -850,13 +849,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:Tape/Attribute:tapelibrary_id+' => '',
'Class:Tape/Attribute:tapelibrary_name' => 'Nome da biblioteca de fitas',
'Class:Tape/Attribute:tapelibrary_name+' => '',
-));
+]);
//
// Class: NASFileSystem
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:NASFileSystem' => 'Sistema de arquivos NAS',
'Class:NASFileSystem+' => '',
'Class:NASFileSystem/Attribute:name' => 'Nome',
@@ -871,13 +870,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:NASFileSystem/Attribute:nas_id+' => '',
'Class:NASFileSystem/Attribute:nas_name' => 'Nome do NAS',
'Class:NASFileSystem/Attribute:nas_name+' => '',
-));
+]);
//
// Class: Software
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:Software' => 'Software',
'Class:Software+' => '',
'Class:Software/ComplementaryName' => '%1$s - %2$s~~',
@@ -907,13 +906,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:Software/Attribute:softwarepatch_list+' => 'Todas as Atualizações para este Software',
'Class:Software/Attribute:softwarelicence_list' => 'Licenças de software',
'Class:Software/Attribute:softwarelicence_list+' => 'Todas as Licenças de software para este Software',
-));
+]);
//
// Class: Patch
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:Patch' => 'Atualização',
'Class:Patch+' => '',
'Class:Patch/Attribute:name' => 'Nome',
@@ -924,13 +923,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:Patch/Attribute:description+' => '',
'Class:Patch/Attribute:finalclass' => 'Tipo',
'Class:Patch/Attribute:finalclass+' => '',
-));
+]);
//
// Class: OSPatch
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:OSPatch' => 'Atualização de SO',
'Class:OSPatch+' => '',
'Class:OSPatch/Attribute:functionalcis_list' => 'Dispositivos',
@@ -939,13 +938,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:OSPatch/Attribute:osversion_id+' => '',
'Class:OSPatch/Attribute:osversion_name' => 'Nome da versão do SO',
'Class:OSPatch/Attribute:osversion_name+' => '',
-));
+]);
//
// Class: SoftwarePatch
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:SoftwarePatch' => 'Atualização de Software',
'Class:SoftwarePatch+' => '',
'Class:SoftwarePatch/Attribute:software_id' => 'Software',
@@ -954,13 +953,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:SoftwarePatch/Attribute:software_name+' => '',
'Class:SoftwarePatch/Attribute:softwareinstances_list' => 'Instâncias de software',
'Class:SoftwarePatch/Attribute:softwareinstances_list+' => 'Todos os sistemas onde essa Atualização de software está instalada',
-));
+]);
//
// Class: Licence
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:Licence' => 'Licença',
'Class:Licence+' => '',
'Class:Licence/Attribute:name' => 'Nome',
@@ -989,13 +988,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:Licence/Attribute:perpetual/Value:yes+' => 'Sim',
'Class:Licence/Attribute:finalclass' => 'Tipo',
'Class:Licence/Attribute:finalclass+' => '',
-));
+]);
//
// Class: OSLicence
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:OSLicence' => 'Licença de SO',
'Class:OSLicence+' => '',
'Class:OSLicence/ComplementaryName' => '%1$s - %2$s~~',
@@ -1007,13 +1006,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:OSLicence/Attribute:virtualmachines_list+' => 'Todas as Máquinas virtuais (VMs) onde essa Licença é utilizada',
'Class:OSLicence/Attribute:servers_list' => 'Servidores',
'Class:OSLicence/Attribute:servers_list+' => 'Todos os Servidores onde essa Licença é utilizada',
-));
+]);
//
// Class: SoftwareLicence
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:SoftwareLicence' => 'Licença de Software',
'Class:SoftwareLicence+' => '',
'Class:SoftwareLicence/ComplementaryName' => '%1$s - %2$s~~',
@@ -1023,13 +1022,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:SoftwareLicence/Attribute:software_name+' => '',
'Class:SoftwareLicence/Attribute:softwareinstance_list' => 'Instâncias de software',
'Class:SoftwareLicence/Attribute:softwareinstance_list+' => 'Todos os sistemas onde esta Licença é utilizada',
-));
+]);
//
// Class: lnkDocumentToLicence
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:lnkDocumentToLicence' => 'Relação entre Documento / Licença',
'Class:lnkDocumentToLicence+' => '',
'Class:lnkDocumentToLicence/Name' => '%1$s / %2$s~~',
@@ -1041,35 +1040,35 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:lnkDocumentToLicence/Attribute:document_id+' => '',
'Class:lnkDocumentToLicence/Attribute:document_name' => 'Nome do documento',
'Class:lnkDocumentToLicence/Attribute:document_name+' => '',
-));
+]);
//
// Class: OSVersion
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:OSVersion' => 'Versão do OS',
'Class:OSVersion+' => '',
'Class:OSVersion/Attribute:osfamily_id' => 'Família do SO',
'Class:OSVersion/Attribute:osfamily_id+' => '',
'Class:OSVersion/Attribute:osfamily_name' => 'Nome da família do SO',
'Class:OSVersion/Attribute:osfamily_name+' => '',
-));
+]);
//
// Class: OSFamily
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:OSFamily' => 'Família do OS',
'Class:OSFamily+' => '',
-));
+]);
//
// Class: Brand
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:Brand' => 'Fabricante',
'Class:Brand+' => '',
'Class:Brand/Attribute:logo' => 'Logo~~',
@@ -1078,13 +1077,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:Brand/Attribute:physicaldevices_list+' => 'Todos os Dispositivos físicos correspondentes a esse(a) Fabricante',
'Class:Brand/UniquenessRule:name+' => 'O nome do(a) fabricante deve ser único',
'Class:Brand/UniquenessRule:name' => 'Esse(a) fabricante já existe',
-));
+]);
//
// Class: Model
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:Model' => 'Modelo',
'Class:Model+' => '',
'Class:Model/ComplementaryName' => '%1$s - %2$s~~',
@@ -1136,37 +1135,37 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:Model/Attribute:physicaldevices_list+' => 'Todos os Dispositivos físicos correspondentes à este Modelo',
'Class:Model/UniquenessRule:name_brand+' => 'O nome do modelo deve ser único',
'Class:Model/UniquenessRule:name_brand' => 'Este modelo já existe',
-));
+]);
//
// Class: NetworkDeviceType
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:NetworkDeviceType' => 'Tipo de dispositivo de rede',
'Class:NetworkDeviceType+' => '',
'Class:NetworkDeviceType/Attribute:networkdevicesdevices_list' => 'Dispositivos de rede',
'Class:NetworkDeviceType/Attribute:networkdevicesdevices_list+' => 'Todos os Dispositivos de rede correspondentes a este Tipo',
-));
+]);
//
// Class: IOSVersion
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:IOSVersion' => 'Versão do SO',
'Class:IOSVersion+' => '',
'Class:IOSVersion/Attribute:brand_id' => 'Fabricante',
'Class:IOSVersion/Attribute:brand_id+' => '',
'Class:IOSVersion/Attribute:brand_name' => 'Nome do fabricante',
'Class:IOSVersion/Attribute:brand_name+' => '',
-));
+]);
//
// Class: lnkDocumentToPatch
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:lnkDocumentToPatch' => 'Relação entre Documento / Atualização',
'Class:lnkDocumentToPatch+' => '',
'Class:lnkDocumentToPatch/Name' => '%1$s / %2$s~~',
@@ -1178,13 +1177,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:lnkDocumentToPatch/Attribute:document_id+' => '',
'Class:lnkDocumentToPatch/Attribute:document_name' => 'Nome do documento',
'Class:lnkDocumentToPatch/Attribute:document_name+' => '',
-));
+]);
//
// Class: lnkSoftwareInstanceToSoftwarePatch
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:lnkSoftwareInstanceToSoftwarePatch' => 'Relação entre Instância de software / Atualização de software',
'Class:lnkSoftwareInstanceToSoftwarePatch+' => '',
'Class:lnkSoftwareInstanceToSoftwarePatch/Name' => '%1$s / %2$s~~',
@@ -1196,13 +1195,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:lnkSoftwareInstanceToSoftwarePatch/Attribute:softwareinstance_id+' => '',
'Class:lnkSoftwareInstanceToSoftwarePatch/Attribute:softwareinstance_name' => 'Nome da instância de software',
'Class:lnkSoftwareInstanceToSoftwarePatch/Attribute:softwareinstance_name+' => '',
-));
+]);
//
// Class: lnkFunctionalCIToOSPatch
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:lnkFunctionalCIToOSPatch' => 'Relação entre IC / Atualização de SO',
'Class:lnkFunctionalCIToOSPatch+' => '',
'Class:lnkFunctionalCIToOSPatch/Name' => '%1$s / %2$s~~',
@@ -1214,13 +1213,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:lnkFunctionalCIToOSPatch/Attribute:functionalci_id+' => '',
'Class:lnkFunctionalCIToOSPatch/Attribute:functionalci_name' => 'Nome do IC',
'Class:lnkFunctionalCIToOSPatch/Attribute:functionalci_name+' => '',
-));
+]);
//
// Class: lnkDocumentToSoftware
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:lnkDocumentToSoftware' => 'Relação entre Documento / Software',
'Class:lnkDocumentToSoftware+' => '',
'Class:lnkDocumentToSoftware/Name' => '%1$s / %2$s~~',
@@ -1232,13 +1231,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:lnkDocumentToSoftware/Attribute:document_id+' => '',
'Class:lnkDocumentToSoftware/Attribute:document_name' => 'Nome do documento',
'Class:lnkDocumentToSoftware/Attribute:document_name+' => '',
-));
+]);
//
// Class: Subnet
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:Subnet' => 'Sub-rede',
'Class:Subnet+' => '',
'Class:Subnet/Name' => '%1$s/%2$s~~',
@@ -1257,13 +1256,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:Subnet/Attribute:ip_mask+' => '',
'Class:Subnet/Attribute:vlans_list' => 'VLANs',
'Class:Subnet/Attribute:vlans_list+' => '',
-));
+]);
//
// Class: VLAN
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:VLAN' => 'VLAN',
'Class:VLAN+' => '',
'Class:VLAN/Attribute:vlan_tag' => 'Nome da VLAN',
@@ -1278,13 +1277,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:VLAN/Attribute:subnets_list+' => '',
'Class:VLAN/Attribute:physicalinterfaces_list' => 'Interfaces de rede física',
'Class:VLAN/Attribute:physicalinterfaces_list+' => '',
-));
+]);
//
// Class: lnkSubnetToVLAN
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:lnkSubnetToVLAN' => 'Relação entre Sub-rede / VLAN',
'Class:lnkSubnetToVLAN+' => '',
'Class:lnkSubnetToVLAN/Name' => '%1$s / %2$s~~',
@@ -1298,26 +1297,26 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:lnkSubnetToVLAN/Attribute:vlan_id+' => '',
'Class:lnkSubnetToVLAN/Attribute:vlan_tag' => 'Nome da VLAN',
'Class:lnkSubnetToVLAN/Attribute:vlan_tag+' => '',
-));
+]);
//
// Class: NetworkInterface
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:NetworkInterface' => 'Adaptador de Rede',
'Class:NetworkInterface+' => '',
'Class:NetworkInterface/Attribute:name' => 'Nome',
'Class:NetworkInterface/Attribute:name+' => '',
'Class:NetworkInterface/Attribute:finalclass' => 'Tipo',
'Class:NetworkInterface/Attribute:finalclass+' => '',
-));
+]);
//
// Class: IPInterface
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:IPInterface' => 'Endereço IP',
'Class:IPInterface+' => '',
'Class:IPInterface/Attribute:ipaddress' => 'Endereço IP',
@@ -1332,13 +1331,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:IPInterface/Attribute:ipmask+' => '',
'Class:IPInterface/Attribute:speed' => 'Velocidade',
'Class:IPInterface/Attribute:speed+' => '',
-));
+]);
//
// Class: PhysicalInterface
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:PhysicalInterface' => 'Placa física',
'Class:PhysicalInterface+' => '',
'Class:PhysicalInterface/Name' => '%2$s %1$s~~',
@@ -1348,13 +1347,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:PhysicalInterface/Attribute:connectableci_name+' => '',
'Class:PhysicalInterface/Attribute:vlans_list' => 'VLANs',
'Class:PhysicalInterface/Attribute:vlans_list+' => '',
-));
+]);
//
// Class: lnkPhysicalInterfaceToVLAN
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:lnkPhysicalInterfaceToVLAN' => 'Relação entre Interface física / VLAN',
'Class:lnkPhysicalInterfaceToVLAN+' => '',
'Class:lnkPhysicalInterfaceToVLAN/Name' => '%1$s %2$s / %3$s~~',
@@ -1370,27 +1369,26 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:lnkPhysicalInterfaceToVLAN/Attribute:vlan_id+' => '',
'Class:lnkPhysicalInterfaceToVLAN/Attribute:vlan_tag' => 'Nome da VLAN',
'Class:lnkPhysicalInterfaceToVLAN/Attribute:vlan_tag+' => '',
-));
-
+]);
//
// Class: LogicalInterface
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:LogicalInterface' => 'Placa lógica',
'Class:LogicalInterface+' => '',
'Class:LogicalInterface/Attribute:virtualmachine_id' => 'Máquina virtual',
'Class:LogicalInterface/Attribute:virtualmachine_id+' => '',
'Class:LogicalInterface/Attribute:virtualmachine_name' => 'Nome da máquina virtual',
'Class:LogicalInterface/Attribute:virtualmachine_name+' => '',
-));
+]);
//
// Class: FiberChannelInterface
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:FiberChannelInterface' => 'Placa Fiber Channel',
'Class:FiberChannelInterface+' => '',
'Class:FiberChannelInterface/Attribute:speed' => 'Velocidade',
@@ -1403,13 +1401,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:FiberChannelInterface/Attribute:datacenterdevice_id+' => '',
'Class:FiberChannelInterface/Attribute:datacenterdevice_name' => 'Nome do dispositivo',
'Class:FiberChannelInterface/Attribute:datacenterdevice_name+' => '',
-));
+]);
//
// Class: lnkConnectableCIToNetworkDevice
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:lnkConnectableCIToNetworkDevice' => 'Relação entre Dispositivo conectado / Dispositivo de rede',
'Class:lnkConnectableCIToNetworkDevice+' => '',
'Class:lnkConnectableCIToNetworkDevice/Name' => '%1$s / %2$s~~',
@@ -1431,13 +1429,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:lnkConnectableCIToNetworkDevice/Attribute:connection_type/Value:downlink+' => 'Link down',
'Class:lnkConnectableCIToNetworkDevice/Attribute:connection_type/Value:uplink' => 'Link up',
'Class:lnkConnectableCIToNetworkDevice/Attribute:connection_type/Value:uplink+' => 'Link up',
-));
+]);
//
// Class: lnkApplicationSolutionToFunctionalCI
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:lnkApplicationSolutionToFunctionalCI' => 'Relação entre Solução de aplicação / IC',
'Class:lnkApplicationSolutionToFunctionalCI+' => '',
'Class:lnkApplicationSolutionToFunctionalCI/Name' => '%1$s / %2$s~~',
@@ -1449,13 +1447,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:lnkApplicationSolutionToFunctionalCI/Attribute:functionalci_id+' => '',
'Class:lnkApplicationSolutionToFunctionalCI/Attribute:functionalci_name' => 'Nome do IC',
'Class:lnkApplicationSolutionToFunctionalCI/Attribute:functionalci_name+' => '',
-));
+]);
//
// Class: lnkApplicationSolutionToBusinessProcess
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:lnkApplicationSolutionToBusinessProcess' => 'Relação entre Solução de aplicação / Processo de negócio',
'Class:lnkApplicationSolutionToBusinessProcess+' => '',
'Class:lnkApplicationSolutionToBusinessProcess/Name' => '%1$s / %2$s~~',
@@ -1467,13 +1465,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:lnkApplicationSolutionToBusinessProcess/Attribute:applicationsolution_id+' => '',
'Class:lnkApplicationSolutionToBusinessProcess/Attribute:applicationsolution_name' => 'Nome da solução de aplicação',
'Class:lnkApplicationSolutionToBusinessProcess/Attribute:applicationsolution_name+' => '',
-));
+]);
//
// Class: Group
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:Group' => 'Grupo',
'Class:Group+' => '',
'Class:Group/ComplementaryName' => '%1$s - %2$s~~',
@@ -1503,13 +1501,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:Group/Attribute:ci_list+' => 'Todos os Itens de configuração (IC) associados à este Grupo',
'Class:Group/Attribute:parent_id_friendlyname' => 'Grupo pai',
'Class:Group/Attribute:parent_id_friendlyname+' => '',
-));
+]);
//
// Class: lnkGroupToCI
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:lnkGroupToCI' => 'Relação entre Grupo / IC',
'Class:lnkGroupToCI+' => '',
'Class:lnkGroupToCI/Name' => '%1$s / %2$s~~',
@@ -1523,11 +1521,11 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:lnkGroupToCI/Attribute:ci_name+' => '',
'Class:lnkGroupToCI/Attribute:reason' => 'Motivo do link',
'Class:lnkGroupToCI/Attribute:reason+' => '',
-));
+]);
// Add translation for Fieldsets
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Server:baseinfo' => 'Informações gerais',
'Server:Date' => 'Data',
'Server:moreinfo' => 'Mais informações',
@@ -1540,14 +1538,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:Subnet/Tab:FreeIPs-count' => 'IPs livres: %1$s',
'Class:Subnet/Tab:FreeIPs-explain' => 'Aqui uma faixa de 10 endereços IPs livres',
'Class:Document:PreviewTab' => 'Visualização',
-));
-
+]);
//
// Class: lnkDocumentToFunctionalCI
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:lnkDocumentToFunctionalCI' => 'Relação entre Documento / IC',
'Class:lnkDocumentToFunctionalCI+' => '',
'Class:lnkDocumentToFunctionalCI/Name' => '%1$s / %2$s~~',
@@ -1559,13 +1556,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:lnkDocumentToFunctionalCI/Attribute:document_id+' => '',
'Class:lnkDocumentToFunctionalCI/Attribute:document_name' => 'Nome do documento',
'Class:lnkDocumentToFunctionalCI/Attribute:document_name+' => '',
-));
+]);
//
// Application Menu
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Menu:Application' => 'Aplicações',
'Menu:Application+' => 'Lista de Aplicações',
'Menu:DBServer' => 'Servidores de Banco de Dados',
@@ -1610,15 +1607,15 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Menu:OSVersion+' => 'Lista de Versões do SO',
'Menu:Software' => 'Catálogo de Software',
'Menu:Software+' => '',
-));
+]);
//
// Class: PhysicalInterface
//
-Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
+Dict::Add('PT BR', 'Brazilian', 'Brazilian', [
'Class:PhysicalInterface/Attribute:org_id' => 'Org id~~',
'Class:PhysicalInterface/Attribute:org_id+' => '~~',
'Class:PhysicalInterface/Attribute:location_id' => 'Location id~~',
'Class:PhysicalInterface/Attribute:location_id+' => '~~',
-));
+]);
diff --git a/datamodels/2.x/itop-config-mgmt/module.itop-config-mgmt.php b/datamodels/2.x/itop-config-mgmt/module.itop-config-mgmt.php
index c9b87ee0c..9632bafae 100755
--- a/datamodels/2.x/itop-config-mgmt/module.itop-config-mgmt.php
+++ b/datamodels/2.x/itop-config-mgmt/module.itop-config-mgmt.php
@@ -1,10 +1,9 @@
'Configuration Management (CMDB)',
@@ -12,25 +11,25 @@ SetupWebPage::AddModule(
// Setup
//
- 'dependencies' => array(
+ 'dependencies' => [
'itop-structure/2.7.1',
- ),
+ ],
'mandatory' => false,
'visible' => true,
'installer' => 'ConfigMgmtInstaller',
// Components
//
- 'datamodel' => array(
+ 'datamodel' => [
'model.itop-config-mgmt.php',
'main.itop-config-mgmt.php',
- ),
- 'data.struct' => array(
+ ],
+ 'data.struct' => [
'data/en_us.data.itop-brand.xml',
'data/en_us.data.itop-osfamily.xml',
'data/en_us.data.itop-osversion.xml',
- ),
- 'data.sample' => array(
+ ],
+ 'data.sample' => [
'data.sample.model.xml',
'data.sample.networkdevicetype.xml',
'data.sample.servers.xml',
@@ -42,8 +41,8 @@ SetupWebPage::AddModule(
'data.sample.webapp.xml',
'data.sample.applications.xml',
'data.sample.applicationsolutionci.xml',
- ),
-
+ ],
+
// Documentation
//
'doc.manual_setup' => '',
@@ -51,13 +50,12 @@ SetupWebPage::AddModule(
// Default settings
//
- 'settings' => array(
- ),
- )
+ 'settings' => [
+ ],
+ ]
);
-if (!class_exists('ConfigMgmtInstaller'))
-{
+if (!class_exists('ConfigMgmtInstaller')) {
// Module installation handler
//
class ConfigMgmtInstaller extends ModuleInstallerAPI
@@ -76,8 +74,7 @@ if (!class_exists('ConfigMgmtInstaller'))
*/
public static function BeforeDatabaseCreation(Config $oConfiguration, $sPreviousVersion, $sCurrentVersion)
{
- if (strlen($sPreviousVersion) > 0)
- {
+ if (strlen($sPreviousVersion) > 0) {
// If you want to migrate data from one format to another, do it here
self::RenameEnumValueInDB('Software', 'type', 'DBserver', 'DBServer');
self::RenameEnumValueInDB('Software', 'type', 'Webserver', 'WebServer');
@@ -95,7 +92,7 @@ if (!class_exists('ConfigMgmtInstaller'))
self::RenameClassInDB('IPinterface', 'IPInterface');
}
}
-
+
/**
* Handler called after the creation/update of the database schema
* @param $oConfiguration Config The new configuration of the application
diff --git a/datamodels/2.x/itop-config/config.php b/datamodels/2.x/itop-config/config.php
index 5b8f2c4b3..5372d6d72 100644
--- a/datamodels/2.x/itop-config/config.php
+++ b/datamodels/2.x/itop-config/config.php
@@ -1,4 +1,5 @@
SetDefaultOperation('Edit');
$oConfigEditorController->HandleOperation();
-
diff --git a/datamodels/2.x/itop-config/dictionaries/it.dict.itop-config.php b/datamodels/2.x/itop-config/dictionaries/it.dict.itop-config.php
index 6145516c9..ba2ac0097 100644
--- a/datamodels/2.x/itop-config/dictionaries/it.dict.itop-config.php
+++ b/datamodels/2.x/itop-config/dictionaries/it.dict.itop-config.php
@@ -1,15 +1,16 @@
'Modifica file di configurazione',
'config-edit-intro' => 'Prestare molta attenzione durante la modifica del file di configurazione.',
'Menu:ConfigEditor' => 'Configurazione',
@@ -27,4 +28,4 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array(
'config-error-file-changed' => 'Errore: il file di configurazione è stato modificato da quando lo hai aperto e non può essere salvato. Aggiorna e applica nuovamente le tue modifiche.',
'config-not-allowed-in-demo' => 'Spiacente, '.ITOP_APPLICATION_SHORT.' è in modalità dimostrativa : il file di configurazione non può essere modificato.',
'config-interactive-not-allowed' => 'La modifica interattiva della configurazione di '.ITOP_APPLICATION_SHORT.' è stata disabilitata. Vedere \'config_editor\' => \'disabled\' nel file di configurazione.',
-));
+]);
diff --git a/datamodels/2.x/itop-config/dictionaries/pt_br.dict.itop-config.php b/datamodels/2.x/itop-config/dictionaries/pt_br.dict.itop-config.php
index 9625de2a7..3c4d38b79 100644
--- a/datamodels/2.x/itop-config/dictionaries/pt_br.dict.itop-config.php
+++ b/datamodels/2.x/itop-config/dictionaries/pt_br.dict.itop-config.php
@@ -1,15 +1,16 @@
'Configurações',
'itop-config/Operation:Edit/Title' => 'Editor do arquivo de configuração',
'config-edit-intro' => 'Tenha cuidado ao editar o arquivo de configuração',
@@ -28,4 +29,4 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'config-error-file-changed' => 'Error: The Configuration file has changed since you opened it and cannot be saved. Refresh and apply your changes again.~~',
'config-not-allowed-in-demo' => 'Sorry, '.ITOP_APPLICATION_SHORT.' is in demonstration mode : the configuration file cannot be edited.~~',
'config-interactive-not-allowed' => ITOP_APPLICATION_SHORT.' interactive edition of the configuration as been disabled. See \'config_editor\' => \'disabled\' in the configuration file.~~',
-));
+]);
diff --git a/datamodels/2.x/itop-config/module.itop-config.php b/datamodels/2.x/itop-config/module.itop-config.php
index 70c2882a6..941a6b0e1 100644
--- a/datamodels/2.x/itop-config/module.itop-config.php
+++ b/datamodels/2.x/itop-config/module.itop-config.php
@@ -1,10 +1,9 @@
'Configuration editor',
@@ -12,27 +11,27 @@ SetupWebPage::AddModule(
// Setup
//
- 'dependencies' => array(),
+ 'dependencies' => [],
'mandatory' => true,
'visible' => false,
// Components
//
- 'datamodel' => array(
+ 'datamodel' => [
'src/Validator/ConfigNodesVisitor.php',
'src/Validator/iTopConfigAstValidator.php',
'src/Validator/iTopConfigSyntaxValidator.php',
'src/Validator/iTopConfigValidator.php',
'src/Controller/ConfigEditorController.php',
-),
- 'webservice' => array(),
- 'dictionary' => array(
+],
+ 'webservice' => [],
+ 'dictionary' => [
'en.dict.itop-config.php',
'fr.dict.itop-config.php',
- ),
- 'data.struct' => array(),
- 'data.sample' => array(),
-
+ ],
+ 'data.struct' => [],
+ 'data.sample' => [],
+
// Documentation
//
'doc.manual_setup' => '',
@@ -40,6 +39,6 @@ SetupWebPage::AddModule(
// Default settings
//
- 'settings' => array(),
- )
+ 'settings' => [],
+ ]
);
diff --git a/datamodels/2.x/itop-config/src/Controller/ConfigEditorController.php b/datamodels/2.x/itop-config/src/Controller/ConfigEditorController.php
index 48405d694..c45c4f015 100644
--- a/datamodels/2.x/itop-config/src/Controller/ConfigEditorController.php
+++ b/datamodels/2.x/itop-config/src/Controller/ConfigEditorController.php
@@ -1,4 +1,5 @@
Get('demo_mode')) {
throw new Exception(Dict::S('config-not-allowed-in-demo'), iTopConfigValidator::CONFIG_INFO);
@@ -52,8 +54,7 @@ class ConfigEditorController extends Controller
try {
if ($sOperation == 'revert') {
$this->AddAlert(Dict::S('config-reverted'), iTopConfigValidator::CONFIG_WARNING);
- }
- else if ($sOperation == 'save') {
+ } elseif ($sOperation == 'save') {
$sTransactionId = utils::ReadParam('transaction_id', '', false, 'transaction_id');
if (!utils::IsTransactionValid($sTransactionId)) {
throw new Exception(Dict::S('config-error-transaction'), iTopConfigValidator::CONFIG_ERROR);
@@ -99,24 +100,21 @@ class ConfigEditorController extends Controller
$this->AddAlert($oValidator->CheckAsyncTasksRetryConfig($oTempConfig), iTopConfigValidator::CONFIG_WARNING);
-
// Read the config from disk after save
$sCurrentConfig = file_get_contents($sConfigFile);
$sConfigChecksum = md5($sCurrentConfig);
}
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$this->AddAlertFromException($e);
}
$this->AddAceScripts();
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$bShowEditor = false;
$this->AddAlertFromException($e);
}
- // display page
+ // display page
$this->DisplayPage([
'aErrors' => $this->aErrors,
'aWarnings' => $this->aWarnings,
@@ -127,7 +125,7 @@ class ConfigEditorController extends Controller
'sChecksum' => $sConfigChecksum,
'sPrevConfig' => $sCurrentConfig,
'sNewConfig' => $sCurrentConfig,
- ]);
+ ]);
}
/**
@@ -143,7 +141,6 @@ class ConfigEditorController extends Controller
$this->AddLinkedScript(utils::GetAbsoluteUrlAppRoot().$sAceDir.'ext-searchbox.js');
}
-
public function AddAlertFromException(Exception $e): void
{
$this->AddAlert($e->getMessage(), $e->getCode());
@@ -158,18 +155,18 @@ class ConfigEditorController extends Controller
return;
}
switch ($iLevel) {
- case iTopConfigValidator::CONFIG_SUCCESS :
+ case iTopConfigValidator::CONFIG_SUCCESS:
$this->aSuccesses[] = $sMessage;
break;
- case iTopConfigValidator::CONFIG_WARNING :
+ case iTopConfigValidator::CONFIG_WARNING:
$this->aWarnings[] = $sMessage;
break;
- case iTopConfigValidator::CONFIG_INFO :
+ case iTopConfigValidator::CONFIG_INFO:
$this->aInfo[] = $sMessage;
break;
- default :
+ default:
$this->aErrors[] = $sMessage;
}
}
-}
\ No newline at end of file
+}
diff --git a/datamodels/2.x/itop-config/src/Validator/iTopConfigAstValidator.php b/datamodels/2.x/itop-config/src/Validator/iTopConfigAstValidator.php
index 6d0fcf2fb..03400edc3 100644
--- a/datamodels/2.x/itop-config/src/Validator/iTopConfigAstValidator.php
+++ b/datamodels/2.x/itop-config/src/Validator/iTopConfigAstValidator.php
@@ -1,4 +1,5 @@
createForNewestSupportedVersion();
+ $oParser = (new ParserFactory())->createForNewestSupportedVersion();
$oNodeVisitor = new ConfigNodesVisitor();
try {
$aInitialNodes = $oParser->parse($sConfig);
} catch (\Error $e) {
- $sMessage = 'Invalid configuration: '. \Dict::Format('config-parse-error', $e->getMessage(), $e->getLine());
+ $sMessage = 'Invalid configuration: '.\Dict::Format('config-parse-error', $e->getMessage(), $e->getLine());
throw new \Exception($sMessage, iTopConfigValidator::CONFIG_ERROR, $e);
- }catch (\Exception $e) {
- $sMessage = 'Invalid configuration: '. \Dict::Format('config-parse-error', $e->getMessage(), $e->getLine());
+ } catch (\Exception $e) {
+ $sMessage = 'Invalid configuration: '.\Dict::Format('config-parse-error', $e->getMessage(), $e->getLine());
throw new \Exception($sMessage, iTopConfigValidator::CONFIG_ERROR, $e);
}
@@ -41,4 +41,4 @@ class iTopConfigAstValidator
$oTraverser->addVisitor($oNodeVisitor);
$oTraverser->traverse($aInitialNodes);
}
-}
\ No newline at end of file
+}
diff --git a/datamodels/2.x/itop-config/src/Validator/iTopConfigSyntaxValidator.php b/datamodels/2.x/itop-config/src/Validator/iTopConfigSyntaxValidator.php
index 4ecbed82e..0d61b284f 100644
--- a/datamodels/2.x/itop-config/src/Validator/iTopConfigSyntaxValidator.php
+++ b/datamodels/2.x/itop-config/src/Validator/iTopConfigSyntaxValidator.php
@@ -1,4 +1,5 @@
= 7.0.0 syntax errors are thrown as Error
- $sConfig = preg_replace(array('#^\s*<\?php#', '#\?>\s*$#'), '', $sRawConfig);
+ $sConfig = preg_replace(['#^\s*<\?php#', '#\?>\s*$#'], '', $sRawConfig);
eval('if(0){'.trim($sConfig).'}');
$sNoise = trim(ob_get_contents());
- }
- catch (\Error $e) {
+ } catch (\Error $e) {
// ParseError only thrown in PHP7
throw new \Exception('Error in configuration: '.$e->getMessage().' at line '.$e->getLine(), iTopConfigValidator::CONFIG_ERROR);
- }
- finally {
+ } finally {
ob_end_clean();
}
@@ -40,11 +38,10 @@ class iTopConfigSyntaxValidator
$sLine = $aMatches[3];
$sMessage = \Dict::Format('config-parse-error', $sMessage, $sLine);
throw new \Exception($sMessage, iTopConfigValidator::CONFIG_ERROR);
- }
- else {
+ } else {
// Note: sNoise is an html output, but so far it was ok for me (e.g. showing the entire call stack)
throw new \Exception('Syntax error in configuration file: '.$sNoise.' ', iTopConfigValidator::CONFIG_ERROR);
}
}
}
-}
\ No newline at end of file
+}
diff --git a/datamodels/2.x/itop-config/src/Validator/iTopConfigValidator.php b/datamodels/2.x/itop-config/src/Validator/iTopConfigValidator.php
index 3c5faa84a..7d83d84af 100644
--- a/datamodels/2.x/itop-config/src/Validator/iTopConfigValidator.php
+++ b/datamodels/2.x/itop-config/src/Validator/iTopConfigValidator.php
@@ -5,18 +5,19 @@ namespace Combodo\iTop\Config\Validator;
use AsyncTask;
use ReflectionClass;
-class iTopConfigValidator {
- const CONFIG_ERROR = 0;
- const CONFIG_WARNING = 1;
- const CONFIG_INFO = 2;
- const CONFIG_SUCCESS = 3;
+class iTopConfigValidator
+{
+ public const CONFIG_ERROR = 0;
+ public const CONFIG_WARNING = 1;
+ public const CONFIG_INFO = 2;
+ public const CONFIG_SUCCESS = 3;
/**
* @param $sRawConfig
*
* @throws \Exception
*/
- public function Validate($sRawConfig):void
+ public function Validate($sRawConfig): void
{
$oiTopConfigValidator = new iTopConfigAstValidator();
$oiTopConfigValidator->Validate($sRawConfig);
@@ -26,7 +27,7 @@ class iTopConfigValidator {
$oiTopConfigValidator->Validate($sRawConfig);
}
- function DBPasswordIsOk($sPassword):bool
+ public function DBPasswordIsOk($sPassword): bool
{
$bIsWindows = (array_key_exists('WINDIR', $_SERVER) || array_key_exists('windir', $_SERVER));
@@ -37,7 +38,6 @@ class iTopConfigValidator {
return true;
}
-
public function CheckAsyncTasksRetryConfig(\Config $oTempConfig): array
{
$aWarnings = [];
@@ -56,4 +56,4 @@ class iTopConfigValidator {
return $aWarnings;
}
-}
\ No newline at end of file
+}
diff --git a/datamodels/2.x/itop-core-update/dictionaries/pt_br.dict.itop-core-update.php b/datamodels/2.x/itop-core-update/dictionaries/pt_br.dict.itop-core-update.php
index 056b32700..e8bbcd378 100644
--- a/datamodels/2.x/itop-core-update/dictionaries/pt_br.dict.itop-core-update.php
+++ b/datamodels/2.x/itop-core-update/dictionaries/pt_br.dict.itop-core-update.php
@@ -1,15 +1,16 @@
'Atualização do '.ITOP_APPLICATION_SHORT,
'itop-core-update:UI:SelectUpdateFile' => 'Atualização do '.ITOP_APPLICATION_SHORT,
'itop-core-update:UI:ConfirmUpdate' => 'Atualização do '.ITOP_APPLICATION_SHORT,
@@ -95,7 +96,5 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'Class:ModuleInstallation/Attribute:installed' => 'Instalado em',
'Class:ModuleInstallation/Attribute:name' => 'Nome',
'Class:ModuleInstallation/Attribute:version' => 'Versão',
- 'Class:ModuleInstallation/Attribute:comment' => 'Comentário'
-));
-
-
+ 'Class:ModuleInstallation/Attribute:comment' => 'Comentário',
+]);
diff --git a/datamodels/2.x/itop-datacenter-mgmt/module.itop-datacenter-mgmt.php b/datamodels/2.x/itop-datacenter-mgmt/module.itop-datacenter-mgmt.php
index f3bd85bfe..30d29a8c9 100755
--- a/datamodels/2.x/itop-datacenter-mgmt/module.itop-datacenter-mgmt.php
+++ b/datamodels/2.x/itop-datacenter-mgmt/module.itop-datacenter-mgmt.php
@@ -1,9 +1,10 @@
'Datacenter Management',
@@ -27,36 +28,35 @@ SetupWebPage::AddModule(
// Setup
//
- 'dependencies' => array(
- 'itop-config-mgmt/2.2.0'
- ),
+ 'dependencies' => [
+ 'itop-config-mgmt/2.2.0',
+ ],
'mandatory' => false,
'visible' => true,
// Components
//
- 'datamodel' => array(),
- 'webservice' => array(
-
- ),
- 'data.struct' => array(
+ 'datamodel' => [],
+ 'webservice' => [
+
+ ],
+ 'data.struct' => [
// add your 'structure' definition XML files here,
- ),
- 'data.sample' => array(
+ ],
+ 'data.sample' => [
// add your sample data XML files here,
'data.sample.racks.xml',
- ),
-
+ ],
+
// Documentation
//
'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any
- 'doc.more_information' => '', // hyperlink to more information, if any
+ 'doc.more_information' => '', // hyperlink to more information, if any
// Default settings
//
- 'settings' => array(
+ 'settings' => [
// Module specific settings go here, if any
- ),
- )
+ ],
+ ]
);
-
diff --git a/datamodels/2.x/itop-endusers-devices/module.itop-endusers-devices.php b/datamodels/2.x/itop-endusers-devices/module.itop-endusers-devices.php
index 6afc623a6..162a46aed 100644
--- a/datamodels/2.x/itop-endusers-devices/module.itop-endusers-devices.php
+++ b/datamodels/2.x/itop-endusers-devices/module.itop-endusers-devices.php
@@ -1,4 +1,5 @@
'End-user Devices Management',
@@ -34,42 +35,41 @@ SetupWebPage::AddModule(
// Setup
//
- 'dependencies' => array(
- 'itop-config-mgmt/2.2.0'
- ),
+ 'dependencies' => [
+ 'itop-config-mgmt/2.2.0',
+ ],
'mandatory' => false,
'visible' => true,
'installer' => 'EndUserMgmtInstaller',
// Components
//
- 'datamodel' => array(
- ),
- 'webservice' => array(
-
- ),
- 'data.struct' => array(
+ 'datamodel' => [
+ ],
+ 'webservice' => [
+
+ ],
+ 'data.struct' => [
// add your 'structure' definition XML files here,
- ),
- 'data.sample' => array(
+ ],
+ 'data.sample' => [
// add your sample data XML files here,
- ),
-
+ ],
+
// Documentation
//
'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any
- 'doc.more_information' => '', // hyperlink to more information, if any
+ 'doc.more_information' => '', // hyperlink to more information, if any
// Default settings
//
- 'settings' => array(
+ 'settings' => [
// Module specific settings go here, if any
- ),
- )
+ ],
+ ]
);
-if (!class_exists('EndUserMgmtInstaller'))
-{
+if (!class_exists('EndUserMgmtInstaller')) {
// Module installation handler
//
class EndUserMgmtInstaller extends ModuleInstallerAPI
@@ -88,13 +88,12 @@ if (!class_exists('EndUserMgmtInstaller'))
*/
public static function BeforeDatabaseCreation(Config $oConfiguration, $sPreviousVersion, $sCurrentVersion)
{
- if (strlen($sPreviousVersion) > 0)
- {
+ if (strlen($sPreviousVersion) > 0) {
// If you want to migrate data from one format to another, do it here
self::RenameClassInDB('IpPhone', 'IPPhone');
}
}
-
+
/**
* Handler called after the creation/update of the database schema
* @param $oConfiguration Config The new configuration of the application
@@ -106,4 +105,3 @@ if (!class_exists('EndUserMgmtInstaller'))
}
}
}
-
diff --git a/datamodels/2.x/itop-faq-light/module.itop-faq-light.php b/datamodels/2.x/itop-faq-light/module.itop-faq-light.php
index d599034b2..476a797f3 100755
--- a/datamodels/2.x/itop-faq-light/module.itop-faq-light.php
+++ b/datamodels/2.x/itop-faq-light/module.itop-faq-light.php
@@ -1,10 +1,9 @@
'Frequently Asked Questions Database',
@@ -12,24 +11,24 @@ SetupWebPage::AddModule(
// Setup
//
- 'dependencies' => array(
+ 'dependencies' => [
'itop-structure/3.0.0 || itop-portal/3.0.0',
- ),
+ ],
'mandatory' => false,
'visible' => true,
'installer' => 'FAQLightInstaller',
// Components
//
- 'datamodel' => array(
- ),
- 'data.struct' => array(
+ 'datamodel' => [
+ ],
+ 'data.struct' => [
//'data.struct.itop-knownerror-mgmt.xml',
- ),
- 'data.sample' => array(
+ ],
+ 'data.sample' => [
'data.sample.faq-domains.xml',
- ),
-
+ ],
+
// Documentation
//
'doc.manual_setup' => '', // No manual installation instructions
@@ -37,13 +36,12 @@ SetupWebPage::AddModule(
// Default settings
//
- 'settings' => array(
- ),
- )
+ 'settings' => [
+ ],
+ ]
);
-if (!class_exists('FAQLightInstaller'))
-{
+if (!class_exists('FAQLightInstaller')) {
// Module installation handler
//
class FAQLightInstaller extends ModuleInstallerAPI
@@ -62,13 +60,12 @@ if (!class_exists('FAQLightInstaller'))
*/
public static function BeforeDatabaseCreation(Config $oConfiguration, $sPreviousVersion, $sCurrentVersion)
{
- if (strlen($sPreviousVersion) > 0)
- {
+ if (strlen($sPreviousVersion) > 0) {
// If you want to migrate data from one format to another, do it here
self::RenameClassInDB('FAQcategory', 'FAQCategory');
}
}
-
+
/**
* Handler called after the creation/update of the database schema
* @param $oConfiguration Config The new configuration of the application
diff --git a/datamodels/2.x/itop-files-information/module.itop-files-information.php b/datamodels/2.x/itop-files-information/module.itop-files-information.php
index 188b35aba..05d1b03c2 100644
--- a/datamodels/2.x/itop-files-information/module.itop-files-information.php
+++ b/datamodels/2.x/itop-files-information/module.itop-files-information.php
@@ -1,4 +1,5 @@
'iTop files information',
@@ -33,22 +34,22 @@ SetupWebPage::AddModule(
// Setup
//
- 'dependencies' => array(
- ),
+ 'dependencies' => [
+ ],
'mandatory' => false,
'visible' => false,
// Components
//
- 'datamodel' => array(
- 'src/Service/FilesInformation.php',
- 'src/Service/FilesInformationException.php',
+ 'datamodel' => [
+ 'src/Service/FilesInformation.php',
+ 'src/Service/FilesInformationException.php',
'src/Service/FilesInformationUtils.php',
'src/Service/FilesIntegrity.php',
- ),
- 'webservice' => array(),
- 'data.struct' => array(),
- 'data.sample' => array(),
+ ],
+ 'webservice' => [],
+ 'data.struct' => [],
+ 'data.sample' => [],
// Documentation
//
@@ -57,6 +58,6 @@ SetupWebPage::AddModule(
// Default settings
//
- 'settings' => array(),
- )
+ 'settings' => [],
+ ]
);
diff --git a/datamodels/2.x/itop-full-itil/module.itop-full-itil.php b/datamodels/2.x/itop-full-itil/module.itop-full-itil.php
index daa46e691..c69f0a01e 100644
--- a/datamodels/2.x/itop-full-itil/module.itop-full-itil.php
+++ b/datamodels/2.x/itop-full-itil/module.itop-full-itil.php
@@ -7,35 +7,35 @@
SetupWebPage::AddModule(
__FILE__, // Path to the current file, all other file names are relative to the directory containing this file
'itop-full-itil/3.3.0',
- array(
+ [
// Identification
//
'label' => 'Bridge - Request management ITIL + Incident management ITIL',
'category' => 'business',
// Setup
//
- 'dependencies' => array(
+ 'dependencies' => [
'itop-request-mgmt-itil/2.3.0',
'itop-incident-mgmt-itil/2.3.0',
- ),
+ ],
'mandatory' => false,
'visible' => false,
'auto_select' => 'SetupInfo::ModuleIsSelected("itop-request-mgmt-itil") && SetupInfo::ModuleIsSelected("itop-incident-mgmt-itil")',
// Components
//
- 'datamodel' => array(),
- 'webservice' => array(),
- 'data.struct' => array(// add your 'structure' definition XML files here,
- ),
- 'data.sample' => array(// add your sample data XML files here,
- ),
+ 'datamodel' => [],
+ 'webservice' => [],
+ 'data.struct' => [// add your 'structure' definition XML files here,
+ ],
+ 'data.sample' => [// add your sample data XML files here,
+ ],
// Documentation
//
'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any
'doc.more_information' => '', // hyperlink to more information, if any
// Default settings
//
- 'settings' => array(// Module specific settings go here, if any
- ),
- )
+ 'settings' => [// Module specific settings go here, if any
+ ],
+ ]
);
diff --git a/datamodels/2.x/itop-hub-connector/ajax.php b/datamodels/2.x/itop-hub-connector/ajax.php
index ba9ad6507..33ac5940b 100644
--- a/datamodels/2.x/itop-hub-connector/ajax.php
+++ b/datamodels/2.x/itop-hub-connector/ajax.php
@@ -1,4 +1,5 @@
SetMySQLBinDir(MetaModel::GetConfig()->GetModuleSetting('itop-backup', 'mysql_bindir', ''));
$sSourceConfigFile = APPCONF.utils::GetCurrentEnvironment().'/'.ITOP_CONFIG_FILE;
-
+
$oMutex = new iTopMutex('backup.'.utils::GetCurrentEnvironment());
$oMutex->Lock();
- try
- {
+ try {
$oBackup->CreateCompressedBackup($sTargetFile, $sSourceConfigFile);
- }
- catch (Exception $e)
- {
+ } catch (Exception $e) {
$oMutex->Unlock();
throw $e;
}
@@ -101,22 +98,22 @@ function DoBackup($sTargetFile)
/**
* Outputs the status of the current ajax execution (as a JSON structure)
- *
+ *
* @param string $sMessage
* @param bool $bSuccess
* @param number $iErrorCode
* @param array $aMoreFields
* Extra fields to pass to the caller, if needed
*/
-function ReportStatus($sMessage, $bSuccess, $iErrorCode = 0, $aMoreFields = array())
+function ReportStatus($sMessage, $bSuccess, $iErrorCode = 0, $aMoreFields = [])
{
// Do not use AjaxPage during setup phases, because it uses InterfaceDiscovery in Twig compilation
$oPage = new JsonPage();
- $aResult = array(
+ $aResult = [
'code' => $iErrorCode,
'message' => $sMessage,
- 'fields' => $aMoreFields
- );
+ 'fields' => $aMoreFields,
+ ];
$oPage->SetData($aResult);
$oPage->SetOutputDataOnly(true);
$oPage->output();
@@ -124,154 +121,137 @@ function ReportStatus($sMessage, $bSuccess, $iErrorCode = 0, $aMoreFields = arra
/**
* Helper to output the status of a successful execution
- *
+ *
* @param string $sMessage
* @param array $aMoreFields
* Extra fields to pass to the caller, if needed
*/
-function ReportSuccess($sMessage, $aMoreFields = array())
+function ReportSuccess($sMessage, $aMoreFields = [])
{
ReportStatus($sMessage, true, 0, $aMoreFields);
}
/**
* Helper to output the status of a failed execution
- *
+ *
* @param string $sMessage
* @param number $iErrorCode
* @param array $aMoreFields
* Extra fields to pass to the caller, if needed
*/
-function ReportError($sMessage, $iErrorCode, $aMoreFields = array())
+function ReportError($sMessage, $iErrorCode, $aMoreFields = [])
{
- if ($iErrorCode==0)
- {
+ if ($iErrorCode == 0) {
// 0 means no error, so change it if no meaningful error code is supplied
$iErrorCode = -1;
}
ReportStatus($sMessage, false, $iErrorCode, $aMoreFields);
}
-try
-{
+try {
SetupUtils::ExitMaintenanceMode(false); // Reset maintenance mode in case of problem
utils::PushArchiveMode(false);
-
+
ini_set('max_execution_time', max(3600, ini_get('max_execution_time'))); // Under Windows SQL/backup operations are part of the PHP timeout and require extra time
ini_set('display_errors', 1); // Make sure that fatal errors remain visible from the end-user
-
+
// Most of the ajax calls are done without the MetaModel being loaded
- // Therefore, the language must be passed as an argument,
- // and the dictionnaries be loaded here
+ // Therefore, the language must be passed as an argument,
+ // and the dictionnaries be loaded here
$sLanguage = utils::ReadParam('language', '');
- if ($sLanguage!='')
- {
- foreach (glob(APPROOT.'env-production/dictionaries/*.dict.php') as $sFilePath)
- {
- require_once ($sFilePath);
+ if ($sLanguage != '') {
+ foreach (glob(APPROOT.'env-production/dictionaries/*.dict.php') as $sFilePath) {
+ require_once($sFilePath);
}
-
+
$aLanguages = Dict::GetLanguages();
- if (array_key_exists($sLanguage, $aLanguages))
- {
+ if (array_key_exists($sLanguage, $aLanguages)) {
Dict::SetUserLanguage($sLanguage);
}
}
$sOperation = utils::ReadParam('operation', '');
- switch ($sOperation)
- {
+ switch ($sOperation) {
case 'check_before_backup':
- require_once (APPROOT.'/application/startup.inc.php');
- require_once (APPROOT.'/application/loginwebpage.class.inc.php');
+ require_once(APPROOT.'/application/startup.inc.php');
+ require_once(APPROOT.'/application/loginwebpage.class.inc.php');
LoginWebPage::DoLogin(true); // Check user rights and prompt if needed (must be admin)
$sDBBackupPath = utils::GetDataPath().'backups/manual';
$aChecks = SetupUtils::CheckBackupPrerequisites($sDBBackupPath);
$bFailed = false;
- foreach ($aChecks as $oCheckResult)
- {
- if ($oCheckResult->iSeverity==CheckResult::ERROR)
- {
+ foreach ($aChecks as $oCheckResult) {
+ if ($oCheckResult->iSeverity == CheckResult::ERROR) {
$bFailed = true;
ReportError($oCheckResult->sLabel, -2);
}
}
- if (!$bFailed)
- {
+ if (!$bFailed) {
// Continue the checks
$fFreeSpace = SetupUtils::CheckDiskSpace($sDBBackupPath);
- if ($fFreeSpace!==false)
- {
+ if ($fFreeSpace !== false) {
$sMessage = Dict::Format('iTopHub:BackupFreeDiskSpaceIn', SetupUtils::HumanReadableSize($fFreeSpace), dirname($sDBBackupPath));
ReportSuccess($sMessage);
- }
- else
- {
+ } else {
ReportError(Dict::S('iTopHub:FailedToCheckFreeDiskSpace'), -1);
}
}
- break;
-
+ break;
+
case 'do_backup':
- require_once (APPROOT.'/application/startup.inc.php');
- require_once (APPROOT.'/application/loginwebpage.class.inc.php');
+ require_once(APPROOT.'/application/startup.inc.php');
+ require_once(APPROOT.'/application/loginwebpage.class.inc.php');
LoginWebPage::DoLogin(true); // Check user rights and prompt if needed (must be admin)
- try
- {
- if (MetaModel::GetConfig()->Get('demo_mode')) throw new Exception('Sorry the installation of extensions is not allowed in demo mode');
+ try {
+ if (MetaModel::GetConfig()->Get('demo_mode')) {
+ throw new Exception('Sorry the installation of extensions is not allowed in demo mode');
+ }
SetupLog::Info('Backup starts...');
set_time_limit(0);
$sBackupPath = APPROOT.'/data/backups/manual/backup-';
$iSuffix = 1;
$sSuffix = '';
// Generate a unique name...
- do
- {
+ do {
$sBackupFile = $sBackupPath.date('Y-m-d-His').$sSuffix;
$sSuffix = '-'.$iSuffix;
$iSuffix++ ;
- }
- while (file_exists($sBackupFile));
+ } while (file_exists($sBackupFile));
$oBackup = DoBackup($sBackupFile);
$aErrors = $oBackup->GetErrors();
- if (count($aErrors)>0)
- {
+ if (count($aErrors) > 0) {
SetupLog::Error('Backup failed.');
SetupLog::Error(implode("\n", $aErrors));
- ReportError(Dict::S('iTopHub:BackupFailed'), -1, $aErrors);
- }
- else
- {
+ ReportError(Dict::S('iTopHub:BackupFailed'), -1, $aErrors);
+ } else {
SetupLog::Info('Backup successfully completed.');
ReportSuccess(Dict::S('iTopHub:BackupOk'));
}
- }
- catch (Exception $e)
- {
+ } catch (Exception $e) {
SetupLog::Error($e->getMessage());
ReportError($e->getMessage(), $e->getCode());
}
- break;
-
+ break;
+
case 'compile':
SetupLog::Info('Deployment starts...');
$sAuthent = utils::ReadParam('authent', '', false, 'raw_data');
- if (!file_exists(utils::GetDataPath().'hub/compile_authent') || $sAuthent !== file_get_contents(utils::GetDataPath().'hub/compile_authent'))
- {
- throw new SecurityException(Dict::S('iTopHub:FailAuthent'));
+ if (!file_exists(utils::GetDataPath().'hub/compile_authent') || $sAuthent !== file_get_contents(utils::GetDataPath().'hub/compile_authent')) {
+ throw new SecurityException(Dict::S('iTopHub:FailAuthent'));
}
// First step: prepare the datamodel, if it fails, roll-back
- $aSelectedExtensionCodes = utils::ReadParam('extension_codes', array());
- $aSelectedExtensionDirs = utils::ReadParam('extension_dirs', array());
+ $aSelectedExtensionCodes = utils::ReadParam('extension_codes', []);
+ $aSelectedExtensionDirs = utils::ReadParam('extension_dirs', []);
$oRuntimeEnv = new HubRunTimeEnvironment('production', false); // use a temp environment: production-build
$oRuntimeEnv->MoveSelectedExtensions(APPROOT.'/data/downloaded-extensions/', $aSelectedExtensionDirs);
$oConfig = new Config(APPCONF.'production/'.ITOP_CONFIG_FILE);
- if ($oConfig->Get('demo_mode')) throw new Exception('Sorry the installation of extensions is not allowed in demo mode');
+ if ($oConfig->Get('demo_mode')) {
+ throw new Exception('Sorry the installation of extensions is not allowed in demo mode');
+ }
$aSelectModules = $oRuntimeEnv->CompileFrom('production', false); // WARNING symlinks does not seem to be compatible with manual Commit
@@ -289,21 +269,19 @@ try
$oRuntimeEnv->Commit();
// Report the success in a way that will be detected by the ajax caller
- SetupLog::Info('Compilation completed...');
+ SetupLog::Info('Compilation completed...');
ReportSuccess('Ok'); // No access to Dict::S here
- break;
-
+ break;
+
case 'move_to_production':
// Second step: update the schema and the data
// Everything happening below is based on env-production
$oRuntimeEnv = new RunTimeEnvironment('production', true);
- try
- {
+ try {
SetupLog::Info('Move to production starts...');
- $sAuthent = utils::ReadParam('authent', '', false, 'raw_data');
- if (!file_exists(utils::GetDataPath().'hub/compile_authent') || $sAuthent !== file_get_contents(utils::GetDataPath().'hub/compile_authent'))
- {
+ $sAuthent = utils::ReadParam('authent', '', false, 'raw_data');
+ if (!file_exists(utils::GetDataPath().'hub/compile_authent') || $sAuthent !== file_get_contents(utils::GetDataPath().'hub/compile_authent')) {
throw new SecurityException(Dict::S('iTopHub:FailAuthent'));
}
unlink(utils::GetDataPath().'hub/compile_authent');
@@ -315,15 +293,11 @@ try
$aAvailableModules = $oRuntimeEnv->AnalyzeInstallation($oConfig, $oRuntimeEnv->GetBuildDir(), true);
- $aSelectedModules = array();
- foreach ($aAvailableModules as $sModuleId => $aModule)
- {
- if (($sModuleId == ROOT_MODULE) || ($sModuleId == DATAMODEL_MODULE))
- {
+ $aSelectedModules = [];
+ foreach ($aAvailableModules as $sModuleId => $aModule) {
+ if (($sModuleId == ROOT_MODULE) || ($sModuleId == DATAMODEL_MODULE)) {
continue;
- }
- else
- {
+ } else {
$aSelectedModules[] = $sModuleId;
}
}
@@ -349,17 +323,14 @@ try
// Default choices = as before
$oExtensionsMap->LoadChoicesFromDatabase($oConfig);
- foreach ($oExtensionsMap->GetAllExtensions() as $oExtension)
- {
+ foreach ($oExtensionsMap->GetAllExtensions() as $oExtension) {
// Plus all "remote" extensions
- if ($oExtension->sSource==iTopExtension::SOURCE_REMOTE)
- {
+ if ($oExtension->sSource == iTopExtension::SOURCE_REMOTE) {
$oExtensionsMap->MarkAsChosen($oExtension->sCode);
}
}
- $aSelectedExtensionCodes = array();
- foreach ($oExtensionsMap->GetChoices() as $oExtension)
- {
+ $aSelectedExtensionCodes = [];
+ foreach ($oExtensionsMap->GetChoices() as $oExtension) {
$aSelectedExtensionCodes[] = $oExtension->sCode;
}
$aSelectedExtensions = $oExtensionsMap->GetChoices();
@@ -368,34 +339,27 @@ try
// Report the success in a way that will be detected by the ajax caller
SetupLog::Info('Deployment successfully completed.');
ReportSuccess(Dict::S('iTopHub:CompiledOK'));
- }
- catch (Exception $e)
- {
- if(file_exists(utils::GetDataPath().'hub/compile_authent'))
- {
+ } catch (Exception $e) {
+ if (file_exists(utils::GetDataPath().'hub/compile_authent')) {
unlink(utils::GetDataPath().'hub/compile_authent');
}
// Note: at this point, the dictionnary is not necessarily loaded
SetupLog::Error(get_class($e).': '.Dict::S('iTopHub:ConfigurationSafelyReverted')."\n".$e->getMessage());
SetupLog::Error('Debug trace: '.$e->getTraceAsString());
ReportError($e->getMessage(), $e->getCode());
- }
- finally
- {
+ } finally {
SetupUtils::ExitReadOnlyMode();
}
- break;
-
+ break;
+
default:
ReportError("Invalid operation: '$sOperation'", -1);
}
-}
-catch (Exception $e)
-{
+} catch (Exception $e) {
SetupLog::Error(get_class($e).': '.Dict::S('iTopHub:ConfigurationSafelyReverted')."\n".$e->getMessage());
SetupLog::Error('Debug trace: '.$e->getTraceAsString());
-
+
utils::PopArchiveMode();
-
+
ReportError($e->getMessage(), $e->getCode());
}
diff --git a/datamodels/2.x/itop-hub-connector/dictionaries/pt_br.dict.itop-hub-connector.php b/datamodels/2.x/itop-hub-connector/dictionaries/pt_br.dict.itop-hub-connector.php
index 419c534a6..cc5596bd7 100644
--- a/datamodels/2.x/itop-hub-connector/dictionaries/pt_br.dict.itop-hub-connector.php
+++ b/datamodels/2.x/itop-hub-connector/dictionaries/pt_br.dict.itop-hub-connector.php
@@ -1,15 +1,16 @@
'iTop Hub',
'Menu:iTopHub:Register' => 'Conectar ao iTop Hub',
'Menu:iTopHub:Register+' => 'Vá para o iTop Hub para atualizar sua instância '.ITOP_APPLICATION_SHORT,
@@ -64,4 +65,4 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array(
'iTopHub:InstallationStatus:Installed_Version' => '%1$s versão: %2$s',
'iTopHub:InstallationStatus:Installed' => 'Instalado',
'iTopHub:InstallationStatus:Version_NotInstalled' => 'Versão %1$s NÃO instalada',
-));
+]);
diff --git a/datamodels/2.x/itop-hub-connector/land.php b/datamodels/2.x/itop-hub-connector/land.php
index 1d55e431f..2e6760c60 100644
--- a/datamodels/2.x/itop-hub-connector/land.php
+++ b/datamodels/2.x/itop-hub-connector/land.php
@@ -16,7 +16,7 @@ function DisplayStatus(WebPage $oPage)
$oPage->add('');
// Now scan the extensions and display a report of the extensions brought by the hub
$sPath = utils::GetDataPath().'downloaded-extensions/';
- $aExtraDirs = array();
+ $aExtraDirs = [];
if (is_dir($sPath)) {
$aExtraDirs[] = $sPath; // Also read the extra downloaded-modules directory
}
@@ -25,7 +25,7 @@ function DisplayStatus(WebPage $oPage)
foreach ($oExtensionsMap->GetAllExtensions() as $oExtension) {
if ($oExtension->sSource == iTopExtension::SOURCE_REMOTE) {
- $aCSSClasses = array('landing-extension');
+ $aCSSClasses = ['landing-extension'];
if ($oExtension->sInstalledVersion === '') {
$aCSSClasses[] = 'landing-installation';
$sInstallation = Dict::Format('iTopHub:InstallationStatus:Version_NotInstalled', $oExtension->sVersion);
@@ -68,12 +68,11 @@ function DoLanding(WebPage $oPage)
$oPage->add('
'.Dict::S('iTopHub:Uncompressing').' ');
-
$sProduct = utils::ReadParam('applicationName', '', false, 'raw_data');
$sVersion = utils::ReadParam('applicationVersion', '', false, 'raw_data');
$sInstanceUUID = utils::ReadParam('uuidFile', '', false, 'raw_data');
$sDatabaseUUID = utils::ReadParam('uuidBdd', '', false, 'raw_data');
- $aExtensions = utils::ReadParam('extensions', array(), false, 'raw_data');
+ $aExtensions = utils::ReadParam('extensions', [], false, 'raw_data');
// Basic consistency validation
if ($sProduct != ITOP_APPLICATION) {
@@ -128,7 +127,7 @@ function DoLanding(WebPage $oPage)
}
// Now scan the extensions and display a report of the extensions brought by the hub
- $sNextPage = utils::GetAbsoluteUrlModulePage('itop-hub-connector', 'land.php', array('operation' => 'install'));
+ $sNextPage = utils::GetAbsoluteUrlModulePage('itop-hub-connector', 'land.php', ['operation' => 'install']);
$oPage->add_ready_script("window.location.href='$sNextPage'");
}
@@ -148,11 +147,10 @@ function DoInstall(WebPage $oPage)
$oPage->set_title(Dict::S('iTopHub:Landing:Install'));
$oPage->add('
');
-
// Now scan the extensions and display a report of the extensions brought by the hub
// Now scan the extensions and display a report of the extensions brought by the hub
$sPath = utils::GetDataPath().'downloaded-extensions/';
- $aExtraDirs = array();
+ $aExtraDirs = [];
if (is_dir($sPath)) {
$aExtraDirs[] = $sPath; // Also read the extra downloaded-modules directory
}
@@ -175,14 +173,14 @@ function DoInstall(WebPage $oPage)
$oPage->add('
');
$oPage->add('
');
} else {
- $aCSSClasses = array('landing-extension');
+ $aCSSClasses = ['landing-extension'];
if ($oExtension->sInstalledVersion === '') {
$aCSSClasses[] = 'landing-installation';
$sInstallation = Dict::Format('iTopHub:InstallationEffect:Install', $oExtension->sVersion);
- } else if ($oExtension->sInstalledVersion == $oExtension->sVersion) {
+ } elseif ($oExtension->sInstalledVersion == $oExtension->sVersion) {
$aCSSClasses[] = 'landing-no-change';
$sInstallation = Dict::Format('iTopHub:InstallationEffect:NoChange', $oExtension->sVersion);
- } else if (version_compare($oExtension->sInstalledVersion, $oExtension->sVersion, '<')) {
+ } elseif (version_compare($oExtension->sInstalledVersion, $oExtension->sVersion, '<')) {
$aCSSClasses[] = 'landing-upgrade';
$sInstallation = Dict::Format('iTopHub:InstallationEffect:Upgrade', $oExtension->sInstalledVersion, $oExtension->sVersion);
} else {
@@ -213,10 +211,8 @@ function DoInstall(WebPage $oPage)
$oPage->add(''); // module-selection-body
-
$oPage->LinkStylesheetFromAppRoot('css/font-awesome/css/all.min.css');
-
$oPage->add('
');
$oPage->add(''.Dict::S('iTopHub:DBBackupLabel').' ');
$oPage->add(' '.Dict::S('iTopHub:DBBackupSentence').'
');
@@ -224,22 +220,22 @@ function DoInstall(WebPage $oPage)
$oPage->add(' ');
$oPage->add('
');
- $sIframeUrl = utils::GetAbsoluteUrlModulePage('itop-hub-connector', 'launch.php', array('target' => 'inform_after_setup'));
- $sStatusPageUrl = utils::GetAbsoluteUrlModulePage('itop-hub-connector', 'land.php', array('operation' => 'done'));
+ $sIframeUrl = utils::GetAbsoluteUrlModulePage('itop-hub-connector', 'launch.php', ['target' => 'inform_after_setup']);
+ $sStatusPageUrl = utils::GetAbsoluteUrlModulePage('itop-hub-connector', 'land.php', ['operation' => 'done']);
- $aWidgetParams = array(
- 'self_url' => utils::GetAbsoluteUrlModulePage('itop-hub-connector', 'ajax.php', array('maintenance' => true)),
+ $aWidgetParams = [
+ 'self_url' => utils::GetAbsoluteUrlModulePage('itop-hub-connector', 'ajax.php', ['maintenance' => true]),
'iframe_url' => $sIframeUrl,
'redirect_after_completion_url' => $sStatusPageUrl,
'mysql_bindir' => MetaModel::GetConfig()->GetModuleSetting('itop-backup', 'mysql_bindir', ''),
- 'labels' => array(
+ 'labels' => [
'database_backup' => Dict::S('iTopHub:InstallationProgress:DatabaseBackup'),
'extensions_installation' => Dict::S('iTopHub:InstallationProgress:ExtensionsInstallation'),
'installation_successful' => Dict::S('iTopHub:InstallationProgress:InstallationSuccessful'),
'rollback' => Dict::S('iTopHub:ConfigurationSafelyReverted'),
- ),
+ ],
'authent' => $sUID,
- );
+ ];
$sWidgetParams = json_encode($aWidgetParams);
@@ -249,7 +245,6 @@ function DoInstall(WebPage $oPage)
$oPage->add('
');
}
-
try {
require_once(APPROOT.'/application/application.inc.php');
require_once(APPROOT.'/setup/setuppage.class.inc.php');
@@ -266,7 +261,8 @@ try {
$oPage->LinkScriptFromModule('itop-hub-connector/js/hub.js');
$oPage->LinkStylesheetFromAppRoot('css/font-combodo/font-combodo.css');
- $oPage->add_style(<<add_style(
+ <<output();
-}
-catch (Exception $e) {
+} catch (Exception $e) {
require_once(APPROOT.'/setup/setuppage.class.inc.php');
$oP = new ErrorPage(Dict::S('UI:PageTitle:FatalError'));
$oP->add("".Dict::S('UI:FatalErrorMessage')." \n");
@@ -312,7 +307,7 @@ catch (Exception $e) {
$oLog->Set('issue', 'PHP Exception');
$oLog->Set('impact', 'Page could not be displayed');
$oLog->Set('callstack', $e->getTrace());
- $oLog->Set('data', array());
+ $oLog->Set('data', []);
$oLog->DBInsertNoReload();
}
diff --git a/datamodels/2.x/itop-hub-connector/launch.php b/datamodels/2.x/itop-hub-connector/launch.php
index 32c542f44..8797cf38f 100644
--- a/datamodels/2.x/itop-hub-connector/launch.php
+++ b/datamodels/2.x/itop-hub-connector/launch.php
@@ -114,7 +114,7 @@ use Combodo\iTop\Application\WebPage\NiceWebPage;
*/
function CleanVersionNumber($sString)
{
- $aMatches = array();
+ $aMatches = [];
if (preg_match("|^([0-9\\.]+)-|", $sString, $aMatches)) {
return $aMatches[1];
}
@@ -124,11 +124,11 @@ function CleanVersionNumber($sString)
function collect_configuration()
{
- $aConfiguration = array(
- 'php' => array(),
- 'mysql' => array(),
- 'apache' => array(),
- );
+ $aConfiguration = [
+ 'php' => [],
+ 'mysql' => [],
+ 'apache' => [],
+ ];
// Database information
$m_oMysqli = CMDBSource::GetMysqli();
@@ -170,7 +170,7 @@ function collect_configuration()
// PHP extensions
if (!MetaModel::GetConfig()->GetModuleSetting('itop-hub-connector', 'php_extensions_enable', true)) {
- $aConfiguration['php_extensions'] = array();
+ $aConfiguration['php_extensions'] = [];
} else {
foreach (get_loaded_extensions() as $extension) {
$aConfiguration['php_extensions'][$extension] = $extension;
@@ -178,8 +178,8 @@ function collect_configuration()
}
// Collect some PHP settings having a known impact on iTop
- $aIniGet = MetaModel::GetConfig()->GetModuleSetting('itop-hub-connector', 'php_settings_array', array()); // by default, on the time of the writting, it values are : array('post_max_size', 'upload_max_filesize', 'apc.enabled', 'timezone', 'memory_limit', 'max_execution_time');
- $aConfiguration['php_settings'] = array();
+ $aIniGet = MetaModel::GetConfig()->GetModuleSetting('itop-hub-connector', 'php_settings_array', []); // by default, on the time of the writting, it values are : array('post_max_size', 'upload_max_filesize', 'apc.enabled', 'timezone', 'memory_limit', 'max_execution_time');
+ $aConfiguration['php_settings'] = [];
foreach ($aIniGet as $iniGet) {
$aConfiguration['php_settings'][$iniGet] = (string)ini_get($iniGet);
}
@@ -197,22 +197,22 @@ function collect_configuration()
// iTop Installation Options, i.e. "Extensions"
$oExtensionMap = new iTopExtensionsMap();
$oExtensionMap->LoadChoicesFromDatabase($oConfig);
- $aConfiguration['itop_extensions'] = array();
+ $aConfiguration['itop_extensions'] = [];
foreach ($oExtensionMap->GetChoices() as $oExtension) {
switch ($oExtension->sSource) {
case iTopExtension::SOURCE_MANUAL:
case iTopExtension::SOURCE_REMOTE:
- $aConfiguration['itop_extensions'][$oExtension->sCode] = array(
+ $aConfiguration['itop_extensions'][$oExtension->sCode] = [
'label' => $oExtension->sLabel,
'value' => $oExtension->sInstalledVersion,
- );
+ ];
break;
default:
- $aConfiguration['itop_installation_options'][$oExtension->sCode] = array(
+ $aConfiguration['itop_installation_options'][$oExtension->sCode] = [
'label' => $oExtension->sLabel,
'value' => true,
- );
+ ];
}
}
@@ -223,13 +223,13 @@ function MakeDataToPost($sTargetRoute)
{
if (MetaModel::GetConfig()->Get('demo_mode')) {
// Don't expose such information in demo mode
- $aDataToPost = array('disabled' => true, 'reason' => 'demo_mode');
+ $aDataToPost = ['disabled' => true, 'reason' => 'demo_mode'];
} else {
$aConfiguration = collect_configuration();
- $aDataToPost = array(
+ $aDataToPost = [
'itop_hub_target_route' => $sTargetRoute,
- 'itop_stack' => array(
+ 'itop_stack' => [
"uuidBdd" => (string)trim(DBProperty::GetProperty('database_uuid', ''), '{}'), // TODO check if empty and... regenerate a new UUID ??
"uuidFile" => (string)trim(@file_get_contents(utils::GetDataPath()."instance.txt"), "{} \n"), // TODO check if empty and... regenerate a new UUID ??
'instance_friendly_name' => (string)$_SERVER['SERVER_NAME'],
@@ -242,8 +242,8 @@ function MakeDataToPost($sTargetRoute)
'itop_modules' => (object)$aConfiguration['itop_modules'],
'itop_extensions' => (object)$aConfiguration['itop_extensions'],
'itop_installation_options' => (object)$aConfiguration['itop_installation_options'],
- ),
- 'server_stack' => array(
+ ],
+ 'server_stack' => [
'os_name' => (string)PHP_OS,
'web_server_name' => (string)$aConfiguration['web_server_name'],
'web_server_version' => (string)$aConfiguration['web_server_version'],
@@ -253,8 +253,8 @@ function MakeDataToPost($sTargetRoute)
'php_version' => (string)CleanVersionNumber(phpversion()),
'php_settings' => (object)$aConfiguration['php_settings'],
'php_extensions' => (object)$aConfiguration['php_extensions'],
- ),
- );
+ ],
+ ];
}
return $aDataToPost;
@@ -282,21 +282,21 @@ try {
switch ($sTargetRoute) {
case 'inform_after_setup':
- // Hidden IFRAME at the end of the setup
- $sParamToken = utils::ReadParam('setup_token');
- $oTokenValidation = new TokenValidation();
- $bIsTokenValid = $oTokenValidation->isSetupTokenValid($sParamToken);
- if (UserRights::IsAdministrator() || $bIsTokenValid) {
- $oPage = new NiceWebPage('');
- $aDataToPost = MakeDataToPost($sTargetRoute);
- $oPage->add('