');
$aSubClasses = MetaModel::EnumChildClasses($this->sLinkedClass, ENUM_CHILD_CLASSES_ALL); // Including the specified class itself
- $aPossibleClasses = array();
- foreach($aSubClasses as $sCandidateClass)
- {
- if (!MetaModel::IsAbstract($sCandidateClass) && (UserRights::IsActionAllowed($sCandidateClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES))
- {
- if ($sCandidateClass == $sProposedRealClass)
- {
+ $aPossibleClasses = [];
+ foreach ($aSubClasses as $sCandidateClass) {
+ if (!MetaModel::IsAbstract($sCandidateClass) && (UserRights::IsActionAllowed($sCandidateClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES)) {
+ if ($sCandidateClass == $sProposedRealClass) {
$sRealClass = $sProposedRealClass;
}
$aPossibleClasses[$sCandidateClass] = MetaModel::GetName($sCandidateClass);
}
}
// Only one of the subclasses can be instantiated...
- if (count($aPossibleClasses) == 1)
- {
+ if (count($aPossibleClasses) == 1) {
$aKeys = array_keys($aPossibleClasses);
$sRealClass = $aKeys[0];
}
@@ -123,11 +116,11 @@ class UILinksWidgetDirect
if ($sRealClass != '') {
$oLinksetDef = MetaModel::GetAttributeDef($this->sClass, $this->sAttCode);
$sExtKeyToMe = $oLinksetDef->GetExtKeyToMe();
- $aFieldsFlags = array($sExtKeyToMe => OPT_ATT_HIDDEN);
+ $aFieldsFlags = [$sExtKeyToMe => OPT_ATT_HIDDEN];
$oObj = DBObject::MakeDefaultInstance($sRealClass);
- $aPrefillParam = array('source_obj' => $oSourceObj);
+ $aPrefillParam = ['source_obj' => $oSourceObj];
$oObj->PrefillForm('creation_from_editinplace', $aPrefillParam);
- $aFormExtraParams = array(
+ $aFormExtraParams = [
'formPrefix' => $this->sInputid,
'noRelations' => true,
'fieldsFlags' => $aFieldsFlags,
@@ -140,25 +133,22 @@ class UILinksWidgetDirect
JS
,
],
- );
+ ];
// Remove blob edition from creation form @see N°5863 to allow blob edition in modal context
FormHelper::DisableAttributeBlobInputs($sRealClass, $aFormExtraParams);
-
- if(FormHelper::HasMandatoryAttributeBlobInputs($oObj)){
+
+ if (FormHelper::HasMandatoryAttributeBlobInputs($oObj)) {
$oPage->AddUiBlock(FormHelper::GetAlertForMandatoryAttributeBlobInputsInModal(FormHelper::ENUM_MANDATORY_BLOB_MODE_CREATE));
}
- cmdbAbstractObject::DisplayCreationForm($oPage, $sRealClass, $oObj, array(), $aFormExtraParams);
- }
- else
- {
+ cmdbAbstractObject::DisplayCreationForm($oPage, $sRealClass, $oObj, [], $aFormExtraParams);
+ } else {
$sClassLabel = MetaModel::GetName($this->sLinkedClass);
$oPage->add('
'.Dict::Format('UI:SelectTheTypeOf_Class_ToCreate', $sClassLabel));
$oPage->add('');
asort($aPossibleClasses);
- foreach($aPossibleClasses as $sClassName => $sClassLabel)
- {
+ foreach ($aPossibleClasses as $sClassName => $sClassLabel) {
$oPage->add("$sClassLabel ");
}
$oPage->add(' ');
@@ -178,7 +168,7 @@ JS
* @throws \MissingQueryArgument
* @throws \OQLException
*/
- public function GetObjectsSelectionDlg($oPage, $oCurrentObj, $aAlreadyLinked, $aPrefillFormParam = array())
+ public function GetObjectsSelectionDlg($oPage, $oCurrentObj, $aAlreadyLinked, $aPrefillFormParam = [])
{
//$oPage->add("\n");
@@ -199,8 +189,7 @@ JS
$oLinkSetDef = MetaModel::GetAttributeDef($this->sClass, $this->sAttCode);
$valuesDef = $oLinkSetDef->GetValuesDef();
- if ($valuesDef === null)
- {
+ if ($valuesDef === null) {
$oFilter = new DBObjectSearch($this->sLinkedClass);
} else {
if (!$valuesDef instanceof ValueSetObjects) {
@@ -218,8 +207,10 @@ JS
$oCurrentObj->PrefillForm('search', $aPrefillFormParam);
}
$oBlock = new DisplayBlock($oFilter, 'search', false);
- $oPage->AddUiBlock($oBlock->GetDisplay($oPage, "SearchFormToAdd_{$this->sInputid}",
- array(
+ $oPage->AddUiBlock($oBlock->GetDisplay(
+ $oPage,
+ "SearchFormToAdd_{$this->sInputid}",
+ [
'result_list_outer_selector' => "SearchResultsToAdd_{$this->sInputid}",
'table_id' => "add_{$this->sInputid}",
'table_inner_id' => "ResultsToAdd_{$this->sInputid}",
@@ -227,13 +218,14 @@ JS
'cssCount' => "#count_{$this->sInputid}",
'query_params' => $oFilter->GetInternalParams(),
'hidden_criteria' => $sHiddenCriteria,
- )
+ ]
));
$sEmptyList = Dict::S('UI:Message:EmptyList:UseSearchForm');
$sCancel = Dict::S('UI:Button:Cancel');
$sAdd = Dict::S('UI:Button:Add');
- $oPage->add(<<add(
+ <<
@@ -256,52 +248,43 @@ HTML
* @throws \CoreException
* @throws \OQLException
*/
- public function SearchObjectsToAdd(WebPage $oP, $sRemoteClass = '', $aAlreadyLinked = array(), $oCurrentObj = null, $aPrefillFormParam = array())
+ public function SearchObjectsToAdd(WebPage $oP, $sRemoteClass = '', $aAlreadyLinked = [], $oCurrentObj = null, $aPrefillFormParam = [])
{
- if ($sRemoteClass == '')
- {
+ if ($sRemoteClass == '') {
$sRemoteClass = $this->sLinkedClass;
}
$oLinkSetDef = MetaModel::GetAttributeDef($this->sClass, $this->sAttCode);
$valuesDef = $oLinkSetDef->GetValuesDef();
- if ($valuesDef === null)
- {
+ if ($valuesDef === null) {
$oFilter = new DBObjectSearch($sRemoteClass);
- }
- else
- {
- if (!$valuesDef instanceof ValueSetObjects)
- {
+ } else {
+ if (!$valuesDef instanceof ValueSetObjects) {
throw new Exception('Error: only ValueSetObjects are supported for "allowed_values" in AttributeLinkedSet ('.$this->sClass.'/'.$this->sAttCode.').');
}
$oFilter = DBObjectSearch::FromOQL($valuesDef->GetFilterExpression());
}
-
- if (($oCurrentObj != null) && MetaModel::IsSameFamilyBranch($sRemoteClass, $this->sClass))
- {
+
+ if (($oCurrentObj != null) && MetaModel::IsSameFamilyBranch($sRemoteClass, $this->sClass)) {
// Prevent linking to self if the linked object is of the same family
// and already present in the database
- if (!$oCurrentObj->IsNew())
- {
+ if (!$oCurrentObj->IsNew()) {
$oFilter->AddCondition('id', $oCurrentObj->GetKey(), '!=');
}
}
- if ($oCurrentObj != null)
- {
+ if ($oCurrentObj != null) {
$this->SetSearchDefaultFromContext($oCurrentObj, $oFilter);
$aArgs = array_merge($oCurrentObj->ToArgs('this'), $oFilter->GetInternalParams());
$oFilter->SetInternalParams($aArgs);
-
+
$aPrefillFormParam['filter'] = $oFilter;
$oCurrentObj->PrefillForm('search', $aPrefillFormParam);
}
- if (count($aAlreadyLinked) > 0)
- {
+ if (count($aAlreadyLinked) > 0) {
$oFilter->AddCondition('id', $aAlreadyLinked, 'NOTIN');
}
$oBlock = new DisplayBlock($oFilter, 'list', false);
- $oBlock->Display($oP, "ResultsToAdd_{$this->sInputid}", array('menu' => false, 'cssCount'=> '#count_'.$this->sInputid , 'selection_mode' => true, 'table_id' => 'add_'.$this->sInputid)); // Don't display the 'Actions' menu on the results
+ $oBlock->Display($oP, "ResultsToAdd_{$this->sInputid}", ['menu' => false, 'cssCount' => '#count_'.$this->sInputid , 'selection_mode' => true, 'table_id' => 'add_'.$this->sInputid]); // Don't display the 'Actions' menu on the results
}
/**
@@ -311,29 +294,28 @@ HTML
public function DoAddObjects(WebPage $oP, $oFullSetFilter)
{
$aLinkedObjectIds = utils::ReadMultipleSelection($oFullSetFilter);
- foreach($aLinkedObjectIds as $iObjectId)
- {
+ foreach ($aLinkedObjectIds as $iObjectId) {
$oLinkObj = MetaModel::GetObject($this->sLinkedClass, $iObjectId);
$oP->add($this->GetObjectRow($oP, $oLinkObj, $oLinkObj->GetKey()));
}
}
-
+
public function GetObjectModificationDlg()
{
-
+
}
public function GetTableConfig()
{
- $aAttribs = array();
- $aAttribs['form::select'] = array(
+ $aAttribs = [];
+ $aAttribs['form::select'] = [
'label' => "
sInputid}:not(:disabled)', this.checked);oWidget".$this->sInputid.".directlinks('instance')._onSelectChange();\" class=\"checkAll\">",
'description' => Dict::S('UI:SelectAllToggle+'),
- );
+ ];
foreach ($this->aZlist as $sLinkedAttCode) {
$oAttDef = MetaModel::GetAttributeDef($this->sLinkedClass, $sLinkedAttCode);
- $aAttribs[$sLinkedAttCode] = array('label' => MetaModel::GetLabel($this->sLinkedClass, $sLinkedAttCode), 'description' => $oAttDef->GetOrderByHint());
+ $aAttribs[$sLinkedAttCode] = ['label' => MetaModel::GetLabel($this->sLinkedClass, $sLinkedAttCode), 'description' => $oAttDef->GetOrderByHint()];
}
return $aAttribs;
@@ -348,13 +330,12 @@ HTML
*/
public function GetRow($oPage, $sRealClass, $aValues, $iTempId)
{
- if ($sRealClass == '')
- {
+ if ($sRealClass == '') {
$sRealClass = $this->sLinkedClass;
}
$oLinkObj = new $sRealClass();
$oLinkObj->UpdateObjectFromPostedForm($this->sInputid);
-
+
return $this->GetObjectRow($oPage, $oLinkObj, $iTempId);
}
@@ -367,13 +348,12 @@ HTML
protected function GetObjectRow($oPage, $oLinkObj, $iTempId)
{
$aAttribs = $this->GetTableConfig();
- $aRow = array();
+ $aRow = [];
$aRow['form::select'] = '
';
- foreach($this->aZlist as $sLinkedAttCode)
- {
+ foreach ($this->aZlist as $sLinkedAttCode) {
$aRow[$sLinkedAttCode] = $oLinkObj->GetAsHTML($sLinkedAttCode);
}
- return $oPage->GetTableRow($aRow, $aAttribs);
+ return $oPage->GetTableRow($aRow, $aAttribs);
}
/**
@@ -386,23 +366,21 @@ HTML
*/
public function GetFormRow($oPage, $sRealClass, $aValues, $iTempId)
{
- if ($sRealClass == '')
- {
+ if ($sRealClass == '') {
$sRealClass = $this->sLinkedClass;
}
$oLinkObj = new $sRealClass();
$oLinkObj->UpdateObjectFromPostedForm($this->sInputid);
$aAttribs = $this->GetTableConfig();
- $aRow = array();
+ $aRow = [];
$aRow[] = '
';
- foreach($this->aZlist as $sLinkedAttCode)
- {
+ foreach ($this->aZlist as $sLinkedAttCode) {
$aRow[] = $oLinkObj->GetAsHTML($sLinkedAttCode);
}
return $aRow;
}
-
+
/**
* Initializes the default search parameters based on 1) a 'current' object and 2) the silos defined by the context
* @param DBObject $oSourceObj
@@ -413,27 +391,23 @@ HTML
$oAppContext = new ApplicationContext();
$sSrcClass = get_class($oSourceObj);
$sDestClass = $oSearch->GetClass();
- foreach($oAppContext->GetNames() as $key)
- {
+ foreach ($oAppContext->GetNames() as $key) {
// Find the value of the object corresponding to each 'context' parameter
- $aCallSpec = array($sSrcClass, 'MapContextParam');
+ $aCallSpec = [$sSrcClass, 'MapContextParam'];
$sAttCode = '';
- if (is_callable($aCallSpec))
- {
- $sAttCode = call_user_func($aCallSpec, $key); // Returns null when there is no mapping for this parameter
+ if (is_callable($aCallSpec)) {
+ $sAttCode = call_user_func($aCallSpec, $key); // Returns null when there is no mapping for this parameter
}
- if (MetaModel::IsValidAttCode($sSrcClass, $sAttCode))
- {
+ if (MetaModel::IsValidAttCode($sSrcClass, $sAttCode)) {
$defaultValue = $oSourceObj->Get($sAttCode);
// Find the attcode for the same 'context' parameter in the destination class
// and sets its value as the default value for the search condition
- $aCallSpec = array($sDestClass, 'MapContextParam');
+ $aCallSpec = [$sDestClass, 'MapContextParam'];
$sAttCode = '';
- if (is_callable($aCallSpec))
- {
- $sAttCode = call_user_func($aCallSpec, $key); // Returns null when there is no mapping for this parameter
+ if (is_callable($aCallSpec)) {
+ $sAttCode = call_user_func($aCallSpec, $key); // Returns null when there is no mapping for this parameter
}
if (MetaModel::IsValidAttCode($sDestClass, $sAttCode) && !empty($defaultValue)) {
@@ -443,7 +417,6 @@ HTML
}
}
-
public function GetClass(): string
{
return $this->sClass;
diff --git a/application/ui.linkswidget.class.inc.php b/application/ui.linkswidget.class.inc.php
index 0f754b84e..33e4c8eca 100644
--- a/application/ui.linkswidget.class.inc.php
+++ b/application/ui.linkswidget.class.inc.php
@@ -1,4 +1,5 @@
m_sNameSuffix = $sNameSuffix;
$this->m_bDuplicatesAllowed = $bDuplicatesAllowed;
- $this->m_aEditableFields = array();
+ $this->m_aEditableFields = [];
/** @var AttributeLinkedSetIndirect $oAttDef */
$oAttDef = MetaModel::GetAttributeDef($this->m_sClass, $this->m_sAttCode);
@@ -67,34 +68,33 @@ class UILinksWidget
$oLinkingAttDef = MetaModel::GetAttributeDef($this->m_sLinkedClass, $this->m_sExtKeyToRemote);
$this->m_sRemoteClass = $oLinkingAttDef->GetTargetClass();
- $this->m_aEditableFields = array();
- $this->m_aTableConfig = array();
- $this->m_aTableConfig['form::checkbox'] = array(
+ $this->m_aEditableFields = [];
+ $this->m_aTableConfig = [];
+ $this->m_aTableConfig['form::checkbox'] = [
'label' => "
m_sAttCode}{$this->m_sNameSuffix} .selection', this.checked); oWidget".$this->m_sInputId.".OnSelectChange();\">",
'description' => Dict::S('UI:SelectAllToggle+'),
- );
+ ];
$aLnkAttDefsToDisplay = MetaModel::GetZListAttDefsFilteredForIndirectLinkClass($sClass, $sAttCode);
- foreach ($aLnkAttDefsToDisplay as $oLnkAttDef)
- {
+ foreach ($aLnkAttDefsToDisplay as $oLnkAttDef) {
$sLnkAttCode = $oLnkAttDef->GetCode();
$this->m_aEditableFields[] = $sLnkAttCode;
- $this->m_aTableConfig[$sLnkAttCode] = array('label' => $oLnkAttDef->GetLabel(), 'description' => $oLnkAttDef->GetDescription());
+ $this->m_aTableConfig[$sLnkAttCode] = ['label' => $oLnkAttDef->GetLabel(), 'description' => $oLnkAttDef->GetDescription()];
}
- $this->m_aTableConfig['static::key'] = array(
+ $this->m_aTableConfig['static::key'] = [
'label' => MetaModel::GetName($this->m_sRemoteClass),
'description' => MetaModel::GetClassDescription($this->m_sRemoteClass),
- );
+ ];
$this->m_aEditableFields[] = $this->m_sExtKeyToRemote;
$aRemoteAttDefsToDisplay = MetaModel::GetZListAttDefsFilteredForIndirectRemoteClass($this->m_sRemoteClass);
foreach ($aRemoteAttDefsToDisplay as $oRemoteAttDef) {
$sRemoteAttCode = $oRemoteAttDef->GetCode();
- $this->m_aTableConfig['static::'.$sRemoteAttCode] = array(
+ $this->m_aTableConfig['static::'.$sRemoteAttCode] = [
'label' => $oRemoteAttDef->GetLabel(),
'description' => $oRemoteAttDef->GetDescription(),
- );
+ ];
}
}
@@ -105,7 +105,6 @@ class UILinksWidget
return ($bSafe) ? utils::GetSafeId($sFieldId) : $sFieldId;
}
-
/**
* Display the table with the form for editing all the links at once
*
@@ -119,7 +118,6 @@ class UILinksWidget
return DataTableUIBlockFactory::MakeForForm("{$this->m_sAttCode}{$this->m_sNameSuffix}", $aConfig, $aData);
}
-
/**
* Get the HTML fragment corresponding to the linkset editing widget
*
@@ -157,7 +155,7 @@ class UILinksWidget
* @throws DictExceptionMissingString
* @throws Exception
*/
- public function GetObjectPickerDialog($oPage, $oCurrentObj, $sJson, $aAlreadyLinkedIds = array(), $aPrefillFormParam = array())
+ public function GetObjectPickerDialog($oPage, $oCurrentObj, $sJson, $aAlreadyLinkedIds = [], $aPrefillFormParam = [])
{
$oAlreadyLinkedFilter = new DBObjectSearch($this->m_sRemoteClass);
if (!$this->m_bDuplicatesAllowed && count($aAlreadyLinkedIds) > 0) {
@@ -183,7 +181,9 @@ class UILinksWidget
$sLinkedSetId = $oBlock->oUILinksWidget->GetLinkedSetId();
$oDisplayBlock = new DisplayBlock($oFilter, 'search', false);
- $oBlock->AddSubBlock($oDisplayBlock->GetDisplay($oPage, "SearchFormToAdd_{$sLinkedSetId}",
+ $oBlock->AddSubBlock($oDisplayBlock->GetDisplay(
+ $oPage,
+ "SearchFormToAdd_{$sLinkedSetId}",
[
'menu' => false,
'result_list_outer_selector' => "SearchResultsToAdd_{$sLinkedSetId}",
@@ -195,7 +195,8 @@ class UILinksWidget
'query_params' => $oFilter->GetInternalParams(),
'hidden_criteria' => $sAlreadyLinkedExpression,
'submit_on_load' => false,
- ]));
+ ]
+ ));
$oBlock->AddForm();
}
@@ -212,25 +213,21 @@ class UILinksWidget
* @throws \CoreException
* @throws \Exception
*/
- public function SearchObjectsToAdd(WebPage $oP, $sRemoteClass = '', $aAlreadyLinkedIds = array(), $oCurrentObj = null)
+ public function SearchObjectsToAdd(WebPage $oP, $sRemoteClass = '', $aAlreadyLinkedIds = [], $oCurrentObj = null)
{
- if ($sRemoteClass != '')
- {
+ if ($sRemoteClass != '') {
// assert(MetaModel::IsParentClass($this->m_sRemoteClass, $sRemoteClass));
$oFilter = new DBObjectSearch($sRemoteClass);
- }
- else
- {
+ } else {
// No remote class specified use the one defined in the linkedset
- $oFilter = new DBObjectSearch($this->m_sRemoteClass);
+ $oFilter = new DBObjectSearch($this->m_sRemoteClass);
}
- if (!$this->m_bDuplicatesAllowed && count($aAlreadyLinkedIds) > 0)
- {
+ if (!$this->m_bDuplicatesAllowed && count($aAlreadyLinkedIds) > 0) {
$oFilter->AddCondition('id', $aAlreadyLinkedIds, 'NOTIN');
}
$this->SetSearchDefaultFromContext($oCurrentObj, $oFilter);
$oBlock = new DisplayBlock($oFilter, 'list', false);
- $oBlock->Display($oP, "ResultsToAdd_{$this->m_sAttCode}", array('menu' => false, 'cssCount'=> '#count_'.$this->m_sAttCode.$this->m_sNameSuffix , 'selection_mode' => true, 'table_id' => 'add_'.$this->m_sAttCode)); // Don't display the 'Actions' menu on the results
+ $oBlock->Display($oP, "ResultsToAdd_{$this->m_sAttCode}", ['menu' => false, 'cssCount' => '#count_'.$this->m_sAttCode.$this->m_sNameSuffix , 'selection_mode' => true, 'table_id' => 'add_'.$this->m_sAttCode]); // Don't display the 'Actions' menu on the results
}
/**
@@ -251,7 +248,7 @@ class UILinksWidget
$oLinkedObj = MetaModel::GetObject($this->m_sRemoteClass, $iObjectId, false);
if (is_object($oLinkedObj)) {
$oBlock = new BlockIndirectLinkSetEditTable($this);
- $aRow = $oBlock->GetFormRow($oP, $oLinkedObj, $iObjectId, array(), $oCurrentObj, $iAdditionId); // Not yet created link get negative Ids
+ $aRow = $oBlock->GetFormRow($oP, $oLinkedObj, $iObjectId, [], $oCurrentObj, $iAdditionId); // Not yet created link get negative Ids
$oRow = new FormTableRow("{$this->m_sAttCode}{$this->m_sNameSuffix}", $this->m_aTableConfig, $aRow, -$iAdditionId);
$oP->AddUiBlock($oRow);
$iAdditionId++;
@@ -280,7 +277,7 @@ class UILinksWidget
$oLinkedObj = MetaModel::GetObject($this->m_sRemoteClass, $iObjectId, false);
if (is_object($oLinkedObj)) {
$oBlock = new BlockIndirectLinkSetEditTable($this);
- $aRow = $oBlock->GetFormRow($oP, $oLinkedObj, $iObjectId, array(), $oCurrentObj, $iAdditionId, false /* Default value */, $bAllowRemoteExtKeyEdit); // Not yet created link get negative Ids
+ $aRow = $oBlock->GetFormRow($oP, $oLinkedObj, $iObjectId, [], $oCurrentObj, $iAdditionId, false /* Default value */, $bAllowRemoteExtKeyEdit); // Not yet created link get negative Ids
$aData = [];
foreach ($aRow as $item) {
$aData[] = $item;
@@ -307,37 +304,30 @@ class UILinksWidget
$oAppContext = new ApplicationContext();
$sSrcClass = get_class($oSourceObj);
$sDestClass = $oSearch->GetClass();
- foreach($oAppContext->GetNames() as $key)
- {
+ foreach ($oAppContext->GetNames() as $key) {
// Find the value of the object corresponding to each 'context' parameter
- $aCallSpec = array($sSrcClass, 'MapContextParam');
+ $aCallSpec = [$sSrcClass, 'MapContextParam'];
$sAttCode = '';
- if (is_callable($aCallSpec))
- {
- $sAttCode = call_user_func($aCallSpec, $key); // Returns null when there is no mapping for this parameter
+ if (is_callable($aCallSpec)) {
+ $sAttCode = call_user_func($aCallSpec, $key); // Returns null when there is no mapping for this parameter
}
- if (MetaModel::IsValidAttCode($sSrcClass, $sAttCode))
- {
+ if (MetaModel::IsValidAttCode($sSrcClass, $sAttCode)) {
$defaultValue = $oSourceObj->Get($sAttCode);
// Find the attcode for the same 'context' parameter in the destination class
// and sets its value as the default value for the search condition
- $aCallSpec = array($sDestClass, 'MapContextParam');
+ $aCallSpec = [$sDestClass, 'MapContextParam'];
$sAttCode = '';
- if (is_callable($aCallSpec))
- {
- $sAttCode = call_user_func($aCallSpec, $key); // Returns null when there is no mapping for this parameter
+ if (is_callable($aCallSpec)) {
+ $sAttCode = call_user_func($aCallSpec, $key); // Returns null when there is no mapping for this parameter
}
-
- if (MetaModel::IsValidAttCode($sDestClass, $sAttCode) && !empty($defaultValue))
- {
+
+ if (MetaModel::IsValidAttCode($sDestClass, $sAttCode) && !empty($defaultValue)) {
// Add Hierarchical condition if hierarchical key
$oAttDef = MetaModel::GetAttributeDef($sDestClass, $sAttCode);
- if (isset($oAttDef) && ($oAttDef->IsExternalKey()))
- {
- try
- {
+ if (isset($oAttDef) && ($oAttDef->IsExternalKey())) {
+ try {
/** @var AttributeExternalKey $oAttDef */
$sTargetClass = $oAttDef->GetTargetClass();
$sHierarchicalKeyCode = MetaModel::IsHierarchicalClass($sTargetClass);
@@ -348,8 +338,7 @@ class UILinksWidget
$oHKFilter->AddCondition_PointingTo($oFilter, $sHierarchicalKeyCode, TREE_OPERATOR_BELOW);
$oSearch->AddCondition_PointingTo($oHKFilter, $sAttCode);
}
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
}
} else {
$oSearch->AddCondition($sAttCode, $defaultValue);
diff --git a/application/ui.passwordwidget.class.inc.php b/application/ui.passwordwidget.class.inc.php
index 29315b069..138627bd0 100644
--- a/application/ui.passwordwidget.class.inc.php
+++ b/application/ui.passwordwidget.class.inc.php
@@ -1,9 +1,10 @@
sNameSuffix = $sNameSuffix;
$this->iId = $iInputId;
}
-
+
/**
* Get the HTML fragment corresponding to the linkset editing widget
* @param WebPage $oP The web page used for all the output
* @param Hash $aArgs Extra context arguments
* @return string The HTML fragment to be inserted into the page
*/
- public function Display(WebPage $oPage, $aArgs = array())
+ public function Display(WebPage $oPage, $aArgs = [])
{
$oPage->add_dict_entry('UI:Component:Input:Password:DoesNotMatch');
@@ -94,4 +95,3 @@ class UIPasswordWidget
return $sHtmlValue;
}
}
-?>
diff --git a/application/ui.searchformforeignkeys.class.inc.php b/application/ui.searchformforeignkeys.class.inc.php
index 1c140b3f8..4be179c3e 100644
--- a/application/ui.searchformforeignkeys.class.inc.php
+++ b/application/ui.searchformforeignkeys.class.inc.php
@@ -1,4 +1,5 @@
m_sRemoteClass);
$oBlock = new DisplayBlock($oFilter, 'search', false);
- $oPage->AddUiBlock($oBlock->GetDisplay($oPage, "SearchFormToAdd_{$this->m_iInputId}",
- array(
+ $oPage->AddUiBlock($oBlock->GetDisplay(
+ $oPage,
+ "SearchFormToAdd_{$this->m_iInputId}",
+ [
'menu' => false,
'result_list_outer_selector' => "SearchResultsToAdd_{$this->m_iInputId}",
'table_id' => "add_{$this->m_iInputId}",
@@ -55,12 +57,14 @@ class UISearchFormForeignKeys
'selection_mode' => true,
'cssCount' => "#count_{$this->m_iInputId}",
'query_params' => $oFilter->GetInternalParams(),
- )));
+ ]
+ ));
$sEmptyList = Dict::S('UI:Message:EmptyList:UseSearchForm');
$sCancel = Dict::S('UI:Button:Cancel');
$sAdd = Dict::S('UI:Button:Add');
- $oPage->add(<<add(
+ <<
@@ -101,20 +105,17 @@ $('#dlg_{$this->m_iInputId}').dialog('option', {title:'$sTitle'});
$('#SearchFormToAdd_{$this->m_iInputId} form').on('submit.uilinksWizard', oForeignKeysWidget{$this->m_iInputId}.SearchObjectsToAdd);
$('#SearchFormToAdd_{$this->m_iInputId}').on('resize', oForeignKeysWidget{$this->m_iInputId}.UpdateSizes);
JS
-);
+ );
}
public function GetFullListForeignKeysFromSelection($oPage, $oFullSetFilter)
{
- try
- {
+ try {
$aLinkedObjects = utils::ReadMultipleSelectionWithFriendlyname($oFullSetFilter);
$oPage->add(json_encode($aLinkedObjects));
- }
- catch (CoreException $e)
- {
+ } catch (CoreException $e) {
http_response_code(500);
- $oPage->add(json_encode(array('error' => $e->GetMessage())));
+ $oPage->add(json_encode(['error' => $e->GetMessage()]));
IssueLog::Error($e->getMessage()."\nDebug trace:\n".$e->getTraceAsString());
}
}
@@ -129,20 +130,20 @@ JS
*/
public function ListResultsSearchForeignKeys(WebPage $oP, $sRemoteClass = '')
{
- if ($sRemoteClass != '')
- {
+ if ($sRemoteClass != '') {
// assert(MetaModel::IsParentClass($this->m_sRemoteClass, $sRemoteClass));
$oFilter = new DBObjectSearch($sRemoteClass);
- }
- else
- {
+ } else {
// No remote class specified use the one defined in the linkedset
$oFilter = new DBObjectSearch($this->m_sRemoteClass);
}
$oBlock = new DisplayBlock($oFilter, 'list', false);
- $oBlock->Display($oP, "ResultsToAdd_{$this->m_iInputId}",
- array('menu' => false, 'cssCount' => "#count_{$this->m_iInputId}", 'selection_mode' => true, 'table_id' => "add_{$this->m_iInputId}"));
+ $oBlock->Display(
+ $oP,
+ "ResultsToAdd_{$this->m_iInputId}",
+ ['menu' => false, 'cssCount' => "#count_{$this->m_iInputId}", 'selection_mode' => true, 'table_id' => "add_{$this->m_iInputId}"]
+ );
}
}
diff --git a/application/uiwizard.class.inc.php b/application/uiwizard.class.inc.php
index 47472643a..a5ba088f9 100644
--- a/application/uiwizard.class.inc.php
+++ b/application/uiwizard.class.inc.php
@@ -1,9 +1,10 @@
use Combodo\iTop\Application\WebPage\iTopWebPage;
-
/**
* Class UIWizard
*
@@ -31,74 +31,73 @@ class UIWizard
protected $m_sClass;
protected $m_sTargetState;
protected $m_aWizardSteps;
-
+
public function __construct($oPage, $sClass, $sTargetState = '')
{
$this->m_oPage = $oPage;
$this->m_sClass = $sClass;
- if (empty($sTargetState))
- {
+ if (empty($sTargetState)) {
$sTargetState = MetaModel::GetDefaultState($sClass);
}
$this->m_sTargetState = $sTargetState;
$this->m_aWizardSteps = $this->ComputeWizardStructure();
}
-
- public function GetObjectClass() { return $this->m_sClass; }
- public function GetTargetState() { return $this->m_sTargetState; }
- public function GetWizardStructure() { return $this->m_aWizardSteps; }
-
+
+ public function GetObjectClass()
+ {
+ return $this->m_sClass;
+ }
+ public function GetTargetState()
+ {
+ return $this->m_sTargetState;
+ }
+ public function GetWizardStructure()
+ {
+ return $this->m_aWizardSteps;
+ }
+
/**
* Displays one step of the wizard
- */
- public function DisplayWizardStep($aStep, $iStepIndex, &$iMaxInputId, &$aFieldsMap, $bFinishEnabled = false, $aArgs = array())
+ */
+ public function DisplayWizardStep($aStep, $iStepIndex, &$iMaxInputId, &$aFieldsMap, $bFinishEnabled = false, $aArgs = [])
{
- if ($iStepIndex == 1) // one big form that contains everything, to make sure that the uploaded files are posted too
- {
+ if ($iStepIndex == 1) { // one big form that contains everything, to make sure that the uploaded files are posted too
$this->m_oPage->add("
\n");
$this->m_oPage->add("\n");
- }
+ }
/**
* Compute the order of the fields & pages in the wizard
- * @param $oPage iTopWebPage The current page (used to display error messages)
+ * @param $oPage iTopWebPage The current page (used to display error messages)
* @param $sClass string Name of the class
* @param $sStateCode string Code of the target state of the object
- * @return hash Two dimensional array: each element represents the list of fields for a given page
+ * @return hash Two dimensional array: each element represents the list of fields for a given page
*/
protected function ComputeWizardStructure()
{
- $aWizardSteps = array( 'mandatory' => array(), 'optional' => array());
- $aFieldsDone = array(); // Store all the fields that are already covered by a previous step of the wizard
-
+ $aWizardSteps = [ 'mandatory' => [], 'optional' => []];
+ $aFieldsDone = []; // Store all the fields that are already covered by a previous step of the wizard
+
$aStates = MetaModel::EnumStates($this->m_sClass);
$sStateAttCode = MetaModel::GetStateAttributeCode($this->m_sClass);
-
- $aMandatoryAttributes = array();
- // Some attributes are always mandatory independently of the state machine (if any)
- foreach(MetaModel::GetAttributesList($this->m_sClass) as $sAttCode)
- {
- $oAttDef = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
- if (!$oAttDef->IsExternalField() && !$oAttDef->IsNullAllowed() &&
- $oAttDef->IsWritable() && ($sAttCode != $sStateAttCode) )
- {
- $aMandatoryAttributes[$sAttCode] = OPT_ATT_MANDATORY;
- }
- }
- // Now check the attributes that are mandatory in the specified state
- if ( (!empty($this->m_sTargetState)) && (count($aStates[$this->m_sTargetState]['attribute_list']) > 0) )
- {
+ $aMandatoryAttributes = [];
+ // Some attributes are always mandatory independently of the state machine (if any)
+ foreach (MetaModel::GetAttributesList($this->m_sClass) as $sAttCode) {
+ $oAttDef = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
+ if (!$oAttDef->IsExternalField() && !$oAttDef->IsNullAllowed() &&
+ $oAttDef->IsWritable() && ($sAttCode != $sStateAttCode)) {
+ $aMandatoryAttributes[$sAttCode] = OPT_ATT_MANDATORY;
+ }
+ }
+
+ // Now check the attributes that are mandatory in the specified state
+ if ((!empty($this->m_sTargetState)) && (count($aStates[$this->m_sTargetState]['attribute_list']) > 0)) {
// Check all the fields that *must* be included in the wizard for this
// particular target state
- $aFields = array();
- foreach($aStates[$this->m_sTargetState]['attribute_list'] as $sAttCode => $iOptions)
- {
- if ( (isset($aMandatoryAttributes[$sAttCode])) &&
- ($aMandatoryAttributes[$sAttCode] & (OPT_ATT_MANDATORY | OPT_ATT_MUSTCHANGE | OPT_ATT_MUSTPROMPT)) )
- {
+ $aFields = [];
+ foreach ($aStates[$this->m_sTargetState]['attribute_list'] as $sAttCode => $iOptions) {
+ if ((isset($aMandatoryAttributes[$sAttCode])) &&
+ ($aMandatoryAttributes[$sAttCode] & (OPT_ATT_MANDATORY | OPT_ATT_MUSTCHANGE | OPT_ATT_MUSTPROMPT))) {
$aMandatoryAttributes[$sAttCode] |= $iOptions;
- }
- else
- {
+ } else {
$aMandatoryAttributes[$sAttCode] = $iOptions;
}
}
}
-
+
// Check all the fields that *must* be included in the wizard
// i.e. all mandatory, must-change or must-prompt fields that are
// not also read-only or hidden.
// Some fields may be required (null not allowed) from the database
- // perspective, but hidden or read-only from the user interface perspective
- $aFields = array();
- foreach($aMandatoryAttributes as $sAttCode => $iOptions)
- {
- if ( ($iOptions & (OPT_ATT_MANDATORY | OPT_ATT_MUSTCHANGE | OPT_ATT_MUSTPROMPT)) &&
- !($iOptions & (OPT_ATT_READONLY | OPT_ATT_HIDDEN)) )
- {
+ // perspective, but hidden or read-only from the user interface perspective
+ $aFields = [];
+ foreach ($aMandatoryAttributes as $sAttCode => $iOptions) {
+ if (($iOptions & (OPT_ATT_MANDATORY | OPT_ATT_MUSTCHANGE | OPT_ATT_MUSTPROMPT)) &&
+ !($iOptions & (OPT_ATT_READONLY | OPT_ATT_HIDDEN))) {
$oAttDef = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
$aPrerequisites = $oAttDef->GetPrerequisiteAttributes();
- $aFields[$sAttCode] = array();
- foreach($aPrerequisites as $sCode)
- {
+ $aFields[$sAttCode] = [];
+ foreach ($aPrerequisites as $sCode) {
$aFields[$sAttCode][$sCode] = '';
}
}
}
-
+
// Now use the dependencies between the fields to order them
// Start from the order of the 'details'
$aList = MetaModel::FlattenZlist(MetaModel::GetZListItems($this->m_sClass, 'details'));
$index = 0;
- $aOrder = array();
- foreach($aFields as $sAttCode => $void)
- {
- $aOrder[$sAttCode] = 999; // At the end of the list...
+ $aOrder = [];
+ foreach ($aFields as $sAttCode => $void) {
+ $aOrder[$sAttCode] = 999; // At the end of the list...
}
- foreach($aList as $sAttCode)
- {
- if (array_key_exists($sAttCode, $aFields))
- {
+ foreach ($aList as $sAttCode) {
+ if (array_key_exists($sAttCode, $aFields)) {
$aOrder[$sAttCode] = $index;
}
$index++;
}
- foreach($aFields as $sAttCode => $aDependencies)
- {
+ foreach ($aFields as $sAttCode => $aDependencies) {
// All fields with no remaining dependencies can be entered at this
// step of the wizard
- if (count($aDependencies) > 0)
- {
+ if (count($aDependencies) > 0) {
$iMaxPos = 0;
// Remove this field from the dependencies of the other fields
- foreach($aDependencies as $sDependentAttCode => $void)
- {
+ foreach ($aDependencies as $sDependentAttCode => $void) {
// position the current field after the ones it depends on
- $iMaxPos = max($iMaxPos, 1+$aOrder[$sDependentAttCode]);
+ $iMaxPos = max($iMaxPos, 1 + $aOrder[$sDependentAttCode]);
}
}
}
asort($aOrder);
- $aCurrentStep = array();
- foreach($aOrder as $sAttCode => $rank)
- {
+ $aCurrentStep = [];
+ foreach ($aOrder as $sAttCode => $rank) {
$aCurrentStep[] = $sAttCode;
$aFieldsDone[$sAttCode] = '';
}
$aWizardSteps['mandatory'][] = $aCurrentStep;
-
// Now computes the steps to fill the optional fields
- $aFields = array(); // reset
- foreach(MetaModel::ListAttributeDefs($this->m_sClass) as $sAttCode=>$oAttDef)
- {
+ $aFields = []; // reset
+ foreach (MetaModel::ListAttributeDefs($this->m_sClass) as $sAttCode => $oAttDef) {
$iOptions = (isset($aStates[$this->m_sTargetState]['attribute_list'][$sAttCode])) ? $aStates[$this->m_sTargetState]['attribute_list'][$sAttCode] : 0;
if (($sStateAttCode != $sAttCode) &&
(!$oAttDef->IsExternalField()) &&
@@ -282,7 +261,7 @@ $sJSHandlerCode
// are removed from the 'optional' part of the wizard
$oAttDef = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
$aPrerequisites = $oAttDef->GetPrerequisiteAttributes();
- $aFields[$sAttCode] = array();
+ $aFields[$sAttCode] = [];
foreach ($aPrerequisites as $sCode) {
if (!isset($aFieldsDone[$sCode])) {
// retain only the dependencies that were not covered
@@ -293,28 +272,23 @@ $sJSHandlerCode
}
}
// Now use the dependencies between the fields to order them
- while(count($aFields) > 0)
- {
- $aCurrentStep = array();
- foreach($aFields as $sAttCode => $aDependencies)
- {
+ while (count($aFields) > 0) {
+ $aCurrentStep = [];
+ foreach ($aFields as $sAttCode => $aDependencies) {
// All fields with no remaining dependencies can be entered at this
// step of the wizard
- if (count($aDependencies) == 0)
- {
+ if (count($aDependencies) == 0) {
$aCurrentStep[] = $sAttCode;
$aFieldsDone[$sAttCode] = '';
unset($aFields[$sAttCode]);
// Remove this field from the dependencies of the other fields
- foreach($aFields as $sUpdatedCode => $aDummy)
- {
+ foreach ($aFields as $sUpdatedCode => $aDummy) {
// remove the dependency
unset($aFields[$sUpdatedCode][$sAttCode]);
}
}
}
- if (count($aCurrentStep) == 0)
- {
+ if (count($aCurrentStep) == 0) {
// This step of the wizard would contain NO field !
$this->m_oPage->add(Dict::S('UI:Error:WizardCircularReferenceInDependencies'));
print_r($aFields);
@@ -323,7 +297,6 @@ $sJSHandlerCode
$aWizardSteps['optional'][] = $aCurrentStep;
}
return $aWizardSteps;
-
- }
+
+ }
}
-?>
diff --git a/application/user.dashboard.class.inc.php b/application/user.dashboard.class.inc.php
index 1ccc98c6e..ab3178040 100644
--- a/application/user.dashboard.class.inc.php
+++ b/application/user.dashboard.class.inc.php
@@ -1,9 +1,10 @@
"gui",
"key_type" => "autoincrement",
- "name_attcode" => array('user_id', 'menu_code'),
+ "name_attcode" => ['user_id', 'menu_code'],
"state_attcode" => "",
- "reconc_keys" => array(),
+ "reconc_keys" => [],
"db_table" => "priv_app_dashboards",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
-
- MetaModel::Init_Params($aParams);
- MetaModel::Init_AddAttribute(new AttributeExternalKey("user_id", array("targetclass"=>"User", "allowed_values"=>null, "sql"=>"user_id", "is_null_allowed"=>false, "on_target_delete"=>DEL_AUTO, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeString("menu_code", array("allowed_values"=>null, "sql"=>"menu_code", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeText("contents", array("allowed_values"=>null, "sql"=>"contents", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
+ ];
- MetaModel::Init_SetZListItems('default_search', array (
+ MetaModel::Init_Params($aParams);
+ MetaModel::Init_AddAttribute(new AttributeExternalKey("user_id", ["targetclass" => "User", "allowed_values" => null, "sql" => "user_id", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeString("menu_code", ["allowed_values" => null, "sql" => "menu_code", "default_value" => null, "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeText("contents", ["allowed_values" => null, "sql" => "contents", "default_value" => null, "is_null_allowed" => false, "depends_on" => []]));
+
+ MetaModel::Init_SetZListItems('default_search', [
0 => 'user_id',
1 => 'menu_code',
- ));
- MetaModel::Init_SetZListItems('list', array (
+ ]);
+ MetaModel::Init_SetZListItems('list', [
0 => 'user_id',
1 => 'menu_code',
- ));
+ ]);
}
/**
* Overloading this function here to secure a fix done right before the release
- * The real fix should be to implement this verb in DBObject
+ * The real fix should be to implement this verb in DBObject
*/
public function DBDeleteTracked(CMDBChange $oChange, $bSkipStrongSecurity = null, &$oDeletionPlan = null)
{
$this->DBDelete($oDeletionPlan);
}
}
-?>
diff --git a/application/user.preferences.class.inc.php b/application/user.preferences.class.inc.php
index dd1c8f322..40cc48876 100644
--- a/application/user.preferences.class.inc.php
+++ b/application/user.preferences.class.inc.php
@@ -1,9 +1,10 @@
Set('userid', $sUserId);
- $oObj->Set('preferences', array()); // Default preferences: an empty array
+ $oObj->Set('preferences', []); // Default preferences: an empty array
try {
utils::PushArchiveMode(false);
$oObj->DBInsert();
utils::PopArchiveMode();
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
// Ignore errors
}
}
@@ -245,25 +245,25 @@ class appUserPreferences extends DBObject
*/
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "gui",
"key_type" => "autoincrement",
"name_attcode" => "login",
"state_attcode" => "",
- "reconc_keys" => array("userid","login"),
+ "reconc_keys" => ["userid","login"],
"db_table" => "priv_app_preferences",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
-
+ ];
+
MetaModel::Init_Params($aParams);
- MetaModel::Init_AddAttribute(new AttributeExternalKey("userid", array("targetclass"=>"User", "allowed_values"=>null, "sql"=>"userid", "is_null_allowed"=>false, "on_target_delete"=>DEL_AUTO, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributePropertySet("preferences", array("allowed_values"=>null, "sql"=>"preferences", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeExternalField("org_id", array("allowed_values" => null, "extkey_attcode" => 'userid', "target_attcode" => "org_id")));
- MetaModel::Init_AddAttribute(new AttributeExternalField("login", array("allowed_values" => null, "extkey_attcode" => 'userid', "target_attcode" => "login")));
- MetaModel::Init_SetZListItems('list', array('org_id','preferences'));
- MetaModel::Init_SetZListItems('default_search', array('userid','login','org_id'));
+ MetaModel::Init_AddAttribute(new AttributeExternalKey("userid", ["targetclass" => "User", "allowed_values" => null, "sql" => "userid", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributePropertySet("preferences", ["allowed_values" => null, "sql" => "preferences", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeExternalField("org_id", ["allowed_values" => null, "extkey_attcode" => 'userid', "target_attcode" => "org_id"]));
+ MetaModel::Init_AddAttribute(new AttributeExternalField("login", ["allowed_values" => null, "extkey_attcode" => 'userid', "target_attcode" => "login"]));
+ MetaModel::Init_SetZListItems('list', ['org_id','preferences']);
+ MetaModel::Init_SetZListItems('default_search', ['userid','login','org_id']);
}
/**
diff --git a/application/utils.inc.php b/application/utils.inc.php
index 21d5eb1e8..ea226e995 100644
--- a/application/utils.inc.php
+++ b/application/utils.inc.php
@@ -1,4 +1,5 @@
0)
- {
+ if (count(self::$aModes) > 0) {
$bRet = end(self::$aModes);
- }
- else
- {
- if (self::$bPageMode === null)
- {
+ } else {
+ if (self::$bPageMode === null) {
self::InitArchiveMode();
}
$bRet = self::$bPageMode;
@@ -340,8 +322,7 @@ class utils
{
$bDefault = MetaModel::GetConfig()->Get('obsolescence.show_obsolete_data'); // default is false
$bShow = appUserPreferences::GetPref('show_obsolete_data', $bDefault);
- if (static::IsArchiveMode())
- {
+ if (static::IsArchiveMode()) {
$bShow = true;
}
return $bShow;
@@ -352,24 +333,17 @@ class utils
global $argv;
$retValue = $defaultValue;
- if (!is_null(self::$m_aParamsFromFile))
- {
- if (isset(self::$m_aParamsFromFile[$sName]))
- {
+ if (!is_null(self::$m_aParamsFromFile)) {
+ if (isset(self::$m_aParamsFromFile[$sName])) {
$retValue = self::$m_aParamsFromFile[$sName];
}
}
- if (isset($_REQUEST[$sName]))
- {
+ if (isset($_REQUEST[$sName])) {
$retValue = $_REQUEST[$sName];
- }
- elseif ($bAllowCLI && isset($argv))
- {
- foreach($argv as $iArg => $sArg)
- {
- if (preg_match('/^--'.$sName.'=(.*)$/', $sArg, $aMatches))
- {
+ } elseif ($bAllowCLI && isset($argv)) {
+ foreach ($argv as $iArg => $sArg) {
+ if (preg_match('/^--'.$sName.'=(.*)$/', $sArg, $aMatches)) {
$retValue = $aMatches[1];
}
}
@@ -385,16 +359,12 @@ class utils
public static function Sanitize($value, $defaultValue, $sSanitizationFilter)
{
- if ($value === $defaultValue)
- {
+ if ($value === $defaultValue) {
// Preserve the real default value (can be used to detect missing mandatory parameters)
$retValue = $value;
- }
- else
- {
+ } else {
$retValue = self::Sanitize_Internal($value, $sSanitizationFilter);
- if ($retValue === false)
- {
+ if ($retValue === false) {
$retValue = $defaultValue;
}
}
@@ -425,22 +395,18 @@ class utils
*/
protected static function Sanitize_Internal($value, $sSanitizationFilter)
{
- if (is_array($value))
- {
- $retValue = array();
- foreach ($value as $key => $val)
- {
+ if (is_array($value)) {
+ $retValue = [];
+ foreach ($value as $key => $val) {
$retValue[$key] = self::Sanitize_Internal($val, $sSanitizationFilter); // recursively check arrays
- if ($retValue[$key] === false)
- {
+ if ($retValue[$key] === false) {
return false;
}
}
return $retValue;
}
- switch ($sSanitizationFilter)
- {
+ switch ($sSanitizationFilter) {
case static::ENUM_SANITIZATION_FILTER_INTEGER:
$retValue = filter_var($value, FILTER_SANITIZE_NUMBER_INT);
break;
@@ -469,57 +435,62 @@ class utils
case static::ENUM_SANITIZATION_FILTER_PARAMETER:
case static::ENUM_SANITIZATION_FILTER_FIELD_NAME:
case static::ENUM_SANITIZATION_FILTER_TRANSACTION_ID:
- switch ($sSanitizationFilter)
- {
+ switch ($sSanitizationFilter) {
case static::ENUM_SANITIZATION_FILTER_TRANSACTION_ID:
// Same as parameter type but keep the dot character
// transaction_id, the dot is mostly for Windows servers when using file storage as the tokens are named *.tmp
// - See N°1835
// - Note: It must be included at the regexp beginning otherwise you'll get an invalid character error
- $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => '/^[\. A-Za-z0-9_=-]*$/')));
+ $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, ["options" => ["regexp" => '/^[\. A-Za-z0-9_=-]*$/']]);
break;
case static::ENUM_SANITIZATION_FILTER_ROUTE:
case static::ENUM_SANITIZATION_FILTER_OPERATION:
// - Routes should be of the "controller_namespace_code.controller_method_name" form
// - Operations should be allowed to be namespaced as well even though then don't have dedicated controller yet
- $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => '/^[\.A-Za-z0-9_-]*$/')));
+ $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, ["options" => ["regexp" => '/^[\.A-Za-z0-9_-]*$/']]);
break;
case static::ENUM_SANITIZATION_FILTER_PARAMETER:
- $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => '/^[ A-Za-z0-9_=-]*$/'))); // the '=', '%3D, '%2B', '%2F'
+ $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, ["options" => ["regexp" => '/^[ A-Za-z0-9_=-]*$/']]); // the '=', '%3D, '%2B', '%2F'
// Characters are used in serialized filters (starting 2.5, only the url encoded versions are presents, but the "=" is kept for BC)
break;
case static::ENUM_SANITIZATION_FILTER_FIELD_NAME:
- $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => '/^[A-Za-z0-9_]+(->[A-Za-z0-9_]+)*$/'))); // att_code or att_code->name or AttCode->Name or AttCode->Key2->Name
+ $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, ["options" => ["regexp" => '/^[A-Za-z0-9_]+(->[A-Za-z0-9_]+)*$/']]); // att_code or att_code->name or AttCode->Name or AttCode->Key2->Name
break;
case static::ENUM_SANITIZATION_FILTER_CONTEXT_PARAM:
- $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => '/^[ A-Za-z0-9_=%:+-]*$/')));
+ $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, ["options" => ["regexp" => '/^[ A-Za-z0-9_=%:+-]*$/']]);
break;
}
break;
- // For XML / HTML node identifiers
+ // For XML / HTML node identifiers
case static::ENUM_SANITIZATION_FILTER_ELEMENT_IDENTIFIER:
$retValue = preg_replace('/[^a-zA-Z0-9_-]/', '', $value);
- $retValue = filter_var($retValue, FILTER_VALIDATE_REGEXP,
- ['options' => ['regexp' => '/^[A-Za-z0-9][A-Za-z0-9_-]*$/']]);
+ $retValue = filter_var(
+ $retValue,
+ FILTER_VALIDATE_REGEXP,
+ ['options' => ['regexp' => '/^[A-Za-z0-9][A-Za-z0-9_-]*$/']]
+ );
break;
- // For XML / HTML node id selector
+ // For XML / HTML node id selector
case static::ENUM_SANITIZATION_FILTER_ELEMENT_SELECTOR:
- $retValue = filter_var($value, FILTER_VALIDATE_REGEXP,
- ['options' => ['regexp' => '/^[#\.][A-Za-z0-9][A-Za-z0-9_-]*$/']]);
+ $retValue = filter_var(
+ $value,
+ FILTER_VALIDATE_REGEXP,
+ ['options' => ['regexp' => '/^[#\.][A-Za-z0-9][A-Za-z0-9_-]*$/']]
+ );
break;
case static::ENUM_SANITIZATION_FILTER_VARIABLE_NAME:
$retValue = preg_replace('/[^a-zA-Z0-9_]/', '', $value);
break;
- // For URL
+ // For URL
case static::ENUM_SANITIZATION_FILTER_URL:
$retValue = filter_var($value, FILTER_SANITIZE_URL);
$retValue = filter_var($retValue, FILTER_VALIDATE_URL);
@@ -528,7 +499,7 @@ class utils
default:
case static::ENUM_SANITIZATION_FILTER_RAW_DATA:
$retValue = $value;
- // Do nothing
+ // Do nothing
}
return $retValue;
@@ -543,55 +514,53 @@ class utils
* @return ormDocument The uploaded file (can be 'empty' if nothing was uploaded)
* @throws \FileUploadException
*/
- public static function ReadPostedDocument($sName, $sIndex = null)
+ public static function ReadPostedDocument($sName, $sIndex = null)
{
$oDocument = new ormDocument(); // an empty document
- if(isset($_FILES[$sName]))
- {
+ if (isset($_FILES[$sName])) {
$aFileInfo = $_FILES[$sName];
$sError = is_null($sIndex) ? $aFileInfo['error'] : $aFileInfo['error'][$sIndex];
- switch($sError)
- {
+ switch ($sError) {
case UPLOAD_ERR_OK:
- $sTmpName = is_null($sIndex) ? $aFileInfo['tmp_name'] : $aFileInfo['tmp_name'][$sIndex];
- $sMimeType = is_null($sIndex) ? $aFileInfo['type'] : $aFileInfo['type'][$sIndex];
- $sName = is_null($sIndex) ? $aFileInfo['name'] : $aFileInfo['name'][$sIndex];
+ $sTmpName = is_null($sIndex) ? $aFileInfo['tmp_name'] : $aFileInfo['tmp_name'][$sIndex];
+ $sMimeType = is_null($sIndex) ? $aFileInfo['type'] : $aFileInfo['type'][$sIndex];
+ $sName = is_null($sIndex) ? $aFileInfo['name'] : $aFileInfo['name'][$sIndex];
- $doc_content = file_get_contents($sTmpName);
+ $doc_content = file_get_contents($sTmpName);
$sMimeType = self::GetFileMimeType($sTmpName);
$oDocument = new ormDocument($doc_content, $sMimeType, $sName);
- break;
+ break;
case UPLOAD_ERR_NO_FILE:
- // no file to load, it's a normal case, just return an empty document
- break;
+ // no file to load, it's a normal case, just return an empty document
+ break;
case UPLOAD_ERR_FORM_SIZE:
case UPLOAD_ERR_INI_SIZE:
- throw new FileUploadException(Dict::Format('UI:Error:UploadedFileTooBig', ini_get('upload_max_filesize')));
- break;
+ throw new FileUploadException(Dict::Format('UI:Error:UploadedFileTooBig', ini_get('upload_max_filesize')));
+ break;
case UPLOAD_ERR_PARTIAL:
- throw new FileUploadException(Dict::S('UI:Error:UploadedFileTruncated.'));
- break;
+ throw new FileUploadException(Dict::S('UI:Error:UploadedFileTruncated.'));
+ break;
case UPLOAD_ERR_NO_TMP_DIR:
- throw new FileUploadException(Dict::S('UI:Error:NoTmpDir'));
- break;
+ throw new FileUploadException(Dict::S('UI:Error:NoTmpDir'));
+ break;
case UPLOAD_ERR_CANT_WRITE:
- throw new FileUploadException(Dict::Format('UI:Error:CannotWriteToTmp_Dir', ini_get('upload_tmp_dir')));
- break;
+ throw new FileUploadException(Dict::Format('UI:Error:CannotWriteToTmp_Dir', ini_get('upload_tmp_dir')));
+ break;
case UPLOAD_ERR_EXTENSION:
- $sName = is_null($sIndex) ? $aFileInfo['name'] : $aFileInfo['name'][$sIndex];
- throw new FileUploadException(Dict::Format('UI:Error:UploadStoppedByExtension_FileName', $sName));
- break;
+ $sName = is_null($sIndex) ? $aFileInfo['name'] : $aFileInfo['name'][$sIndex];
+ throw new FileUploadException(Dict::Format('UI:Error:UploadStoppedByExtension_FileName', $sName));
+ break;
default:
- throw new FileUploadException(Dict::Format('UI:Error:UploadFailedUnknownCause_Code', $sError));
- break;
+ throw new FileUploadException(Dict::Format('UI:Error:UploadFailedUnknownCause_Code', $sError));
+ break;
}
}
@@ -610,26 +579,22 @@ class utils
*/
public static function ReadMultipleSelection($oFullSetFilter)
{
- $aSelectedObj = utils::ReadParam('selectObject', array());
+ $aSelectedObj = utils::ReadParam('selectObject', []);
$sSelectionMode = utils::ReadParam('selectionMode', '');
if ($sSelectionMode != '') {
// Paginated selection
- $aExceptions = utils::ReadParam('storedSelection', array());
+ $aExceptions = utils::ReadParam('storedSelection', []);
if ($sSelectionMode == 'positive') {
// Only the explicitely listed items are selected
$aSelectedObj = $aExceptions;
- }
- else
- {
+ } else {
// All items of the set are selected, except the one explicitely listed
- $aSelectedObj = array();
+ $aSelectedObj = [];
$oFullSet = new DBObjectSet($oFullSetFilter);
$sClassAlias = $oFullSetFilter->GetClassAlias();
- $oFullSet->OptimizeColumnLoad(array($sClassAlias => array('friendlyname'))); // We really need only the IDs but it does not work since id is not a real field
- while($oObj = $oFullSet->Fetch())
- {
- if (!in_array($oObj->GetKey(), $aExceptions))
- {
+ $oFullSet->OptimizeColumnLoad([$sClassAlias => ['friendlyname']]); // We really need only the IDs but it does not work since id is not a real field
+ while ($oObj = $oFullSet->Fetch()) {
+ if (!in_array($oObj->GetKey(), $aExceptions)) {
$aSelectedObj[] = $oObj->GetKey();
}
}
@@ -650,45 +615,37 @@ class utils
{
$sSelectionMode = utils::ReadParam('selectionMode', '');
- if ($sSelectionMode != 'positive' && $sSelectionMode != 'negative')
- {
+ if ($sSelectionMode != 'positive' && $sSelectionMode != 'negative') {
throw new CoreException('selectionMode must be either positive or negative');
}
// Paginated selection
- $aSelectedIds = utils::ReadParam('storedSelection', array());
- $aSelectedObjIds = utils::ReadParam('selectObject', array());
+ $aSelectedIds = utils::ReadParam('storedSelection', []);
+ $aSelectedObjIds = utils::ReadParam('selectObject', []);
//it means that the user has selected all the results of the search query
- if (count($aSelectedObjIds) > 0 )
- {
- $sFilter=utils::ReadParam("sFilter",'',false,'raw_data');
- if ($sFilter!='')
- {
- $oFullSetFilter=DBSearch::unserialize($sFilter);
+ if (count($aSelectedObjIds) > 0) {
+ $sFilter = utils::ReadParam("sFilter", '', false, 'raw_data');
+ if ($sFilter != '') {
+ $oFullSetFilter = DBSearch::unserialize($sFilter);
}
}
- if (count($aSelectedIds) > 0 )
- {
- if ($sSelectionMode == 'positive')
- {
+ if (count($aSelectedIds) > 0) {
+ if ($sSelectionMode == 'positive') {
// Only the explicitly listed items are selected
$oFullSetFilter->AddCondition('id', $aSelectedIds, 'IN');
- }
- else
- {
+ } else {
// All items of the set are selected, except the one explicitly listed
$oFullSetFilter->AddCondition('id', $aSelectedIds, 'NOTIN');
}
}
- $aSelectedObj = array();
+ $aSelectedObj = [];
$oFullSet = new DBObjectSet($oFullSetFilter);
$sClassAlias = $oFullSetFilter->GetClassAlias();
- $oFullSet->OptimizeColumnLoad(array($sClassAlias => array('friendlyname'))); // We really need only the IDs but it does not work since id is not a real field
- while ($oObj = $oFullSet->Fetch())
- {
+ $oFullSet->OptimizeColumnLoad([$sClassAlias => ['friendlyname']]); // We really need only the IDs but it does not work since id is not a real field
+ while ($oObj = $oFullSet->Fetch()) {
$aSelectedObj[$oObj->GetKey()] = $oObj->Get('friendlyname');
}
@@ -719,8 +676,7 @@ class utils
*/
public static function GetUploadTempId($sTransactionId = null)
{
- if ($sTransactionId === null)
- {
+ if ($sTransactionId === null) {
$sTransactionId = static::GetNewTransactionId();
}
return $sTransactionId;
@@ -753,8 +709,10 @@ class utils
switch ($sUnit) {
case 'G':
$iReturn *= 1024;
+ // no break
case 'M':
$iReturn *= 1024;
+ // no break
case 'K':
$iReturn *= 1024;
}
@@ -828,8 +786,7 @@ class utils
{
$sReturn = '';
// Kilobytes
- if ($value >= 1024)
- {
+ if ($value >= 1024) {
$sReturn = 'K';
$value = $value / 1024;
if ($iPrecision === 0) {
@@ -837,27 +794,24 @@ class utils
}
}
// Megabytes
- if ($value >= 1024)
- {
+ if ($value >= 1024) {
$sReturn = 'M';
$value = $value / 1024;
}
// Gigabytes
- if ($value >= 1024)
- {
+ if ($value >= 1024) {
$sReturn = 'G';
$value = $value / 1024;
}
// Terabytes
- if ($value >= 1024)
- {
+ if ($value >= 1024) {
$sReturn = 'T';
$value = $value / 1024;
}
$value = round($value, $iPrecision);
- return $value . '' . $sReturn . 'B';
+ return $value.''.$sReturn.'B';
}
/**
@@ -876,7 +830,7 @@ class utils
static $aDateTokens = null;
static $aDateRegexps = null;
if (is_null($aDateTokens)) {
- $aSpec = array(
+ $aSpec = [
'%d' => '(?
[0-9]{2})',
'%m' => '(?[0-9]{2})',
'%y' => '(?[0-9]{2})',
@@ -884,15 +838,14 @@ class utils
'%H' => '(?[0-2][0-9])',
'%i' => '(?[0-5][0-9])',
'%s' => '(?[0-5][0-9])',
- );
+ ];
$aDateTokens = array_keys($aSpec);
$aDateRegexps = array_values($aSpec);
}
- $sDateRegexp = str_replace($aDateTokens, $aDateRegexps, $sFormat);
+ $sDateRegexp = str_replace($aDateTokens, $aDateRegexps, $sFormat);
- if (preg_match('!^(?)'.$sDateRegexp.'(?)$!', $sDate, $aMatches))
- {
+ if (preg_match('!^(?)'.$sDateRegexp.'(?)$!', $sDate, $aMatches)) {
$sYear = isset($aMatches['year']) ? $aMatches['year'] : 0;
$sMonth = isset($aMatches['month']) ? $aMatches['month'] : 1;
$sDay = isset($aMatches['day']) ? $aMatches['day'] : 1;
@@ -900,12 +853,10 @@ class utils
$sMinute = isset($aMatches['minute']) ? $aMatches['minute'] : 0;
$sSecond = isset($aMatches['second']) ? $aMatches['second'] : 0;
return strtotime("$sYear-$sMonth-$sDay $sHour:$sMinute:$sSecond");
+ } else {
+ return false;
}
- else
- {
- return false;
- }
- // http://www.spaweditor.com/scripts/regex/index.php
+ // http://www.spaweditor.com/scripts/regex/index.php
}
/**
@@ -1008,8 +959,7 @@ class utils
}
$sProductionEnvConfigPath = self::GetConfigFilePath('production');
- if (file_exists($sProductionEnvConfigPath))
- {
+ if (file_exists($sProductionEnvConfigPath)) {
$oProductionEnvDiskConfig = new Config($sProductionEnvConfigPath);
self::SetConfig($oProductionEnvDiskConfig);
return self::$oConfig;
@@ -1020,13 +970,11 @@ class utils
public static function InitTimeZone($oConfig = null)
{
- if (is_null($oConfig))
- {
+ if (is_null($oConfig)) {
$oConfig = self::GetConfig();
}
$sItopTimeZone = $oConfig->Get('timezone');
- if (!empty($sItopTimeZone))
- {
+ if (!empty($sItopTimeZone)) {
date_default_timezone_set($sItopTimeZone);
}
// else
@@ -1065,21 +1013,14 @@ class utils
*/
public static function GetAbsoluteUrlAppRoot($bForceTrustProxy = false)
{
- if (static::$sAbsoluteUrlAppRootCache === null || $bForceTrustProxy)
- {
+ if (static::$sAbsoluteUrlAppRootCache === null || $bForceTrustProxy) {
static::$sAbsoluteUrlAppRootCache = self::GetConfig()->Get('app_root_url');
- if (static::$sAbsoluteUrlAppRootCache == '')
- {
+ if (static::$sAbsoluteUrlAppRootCache == '') {
static::$sAbsoluteUrlAppRootCache = self::GetDefaultUrlAppRoot($bForceTrustProxy);
- }
- elseif (strpos(static::$sAbsoluteUrlAppRootCache, SERVER_NAME_PLACEHOLDER) > -1)
- {
- if (isset($_SERVER['SERVER_NAME']))
- {
+ } elseif (strpos(static::$sAbsoluteUrlAppRootCache, SERVER_NAME_PLACEHOLDER) > -1) {
+ if (isset($_SERVER['SERVER_NAME'])) {
$sServerName = $_SERVER['SERVER_NAME'];
- }
- else
- {
+ } else {
// CLI mode ?
$sServerName = php_uname('n');
}
@@ -1112,7 +1053,6 @@ class utils
return self::GetAppRootUrl($sCurrentScript, $sAppRoot, $sAbsoluteUrl);
}
-
/**
* Build the current absolute URL from the server's variables.
*
@@ -1203,11 +1143,9 @@ class utils
{
// $_SERVER['REQUEST_URI'] is empty when running on IIS
// Let's use Ivan Tcholakov's fix (found on www.dokeos.com)
- if (empty($_SERVER['REQUEST_URI']))
- {
+ if (empty($_SERVER['REQUEST_URI'])) {
$sPath = $_SERVER['SCRIPT_NAME'];
- if (!empty($_SERVER['QUERY_STRING']))
- {
+ if (!empty($_SERVER['QUERY_STRING'])) {
$sPath .= '?'.$_SERVER['QUERY_STRING'];
}
$_SERVER['REQUEST_URI'] = $sPath;
@@ -1232,21 +1170,15 @@ class utils
$sCurrentRelativePath = str_ireplace($sAppRoot, '', $sCurrentScript);
$sAppRootPos = strpos($sAbsoluteUrl, $sCurrentRelativePath);
- if ($sAppRootPos !== false)
- {
+ if ($sAppRootPos !== false) {
$sAppRootUrl = substr($sAbsoluteUrl, 0, $sAppRootPos); // remove the current page and path
- }
- else
- {
+ } else {
// Second attempt without index.php at the end...
$sCurrentRelativePath = str_ireplace('index.php', '', $sCurrentRelativePath);
$sAppRootPos = strpos($sAbsoluteUrl, $sCurrentRelativePath);
- if ($sAppRootPos !== false)
- {
+ if ($sAppRootPos !== false) {
$sAppRootUrl = substr($sAbsoluteUrl, 0, $sAppRootPos); // remove the current page and path
- }
- else
- {
+ } else {
// No luck...
throw new Exception("Failed to determine application root path $sAbsoluteUrl ($sCurrentRelativePath) APPROOT:'$sAppRoot'");
}
@@ -1263,13 +1195,10 @@ class utils
*/
public static function GetAppRevisionNumber()
{
- if (ITOP_REVISION == 'svn')
- {
+ if (ITOP_REVISION == 'svn') {
// This is NOT a version built using the build system, just display the main version
$sRevisionNumber = Dict::Format('UI:iTopVersion:Short', ITOP_APPLICATION, ITOP_VERSION);
- }
- else
- {
+ } else {
// This is a build made from SVN, let display the full information
$sRevisionNumber = Dict::Format('UI:iTopVersion:Long', ITOP_APPLICATION, ITOP_VERSION, ITOP_REVISION, ITOP_BUILD_DATE);
}
@@ -1297,16 +1226,11 @@ class utils
$bTrustProxy = $bForceTrustProxy || self::IsProxyTrusted();
- if ($bTrustProxy && !empty($_SERVER['HTTP_X_FORWARDED_PROTO']))
- {
+ if ($bTrustProxy && !empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
$bSecured = ($_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https');
- }
- elseif ($bTrustProxy && !empty($_SERVER['HTTP_X_FORWARDED_PROTOCOL']))
- {
+ } elseif ($bTrustProxy && !empty($_SERVER['HTTP_X_FORWARDED_PROTOCOL'])) {
$bSecured = ($_SERVER['HTTP_X_FORWARDED_PROTOCOL'] === 'https');
- }
- elseif ((!empty($_SERVER['HTTPS'])) && (strtolower($_SERVER['HTTPS']) != 'off'))
- {
+ } elseif ((!empty($_SERVER['HTTPS'])) && (strtolower($_SERVER['HTTPS']) != 'off')) {
$bSecured = (strcasecmp($_SERVER['HTTPS'], 'off') !== 0);
}
@@ -1320,7 +1244,7 @@ class utils
* 2) the user did not log-in using the "basic" mode (i.e basic authentication) or by passing credentials in the URL
* @return boolean True if logoff is supported, false otherwise
*/
- static function CanLogOff()
+ public static function CanLogOff()
{
return Session::Get('can_logoff', false);
}
@@ -1334,16 +1258,15 @@ class utils
return Session::GetLog();
}
- static function DebugBacktrace($iLimit = 5)
- {
+ public static function DebugBacktrace($iLimit = 5)
+ {
$aFullTrace = debug_backtrace();
- $aLightTrace = array();
- for($i=1; ($i<=$iLimit && $i < count($aFullTrace)); $i++) // Skip the last function call... which is the call to this function !
- {
+ $aLightTrace = [];
+ for ($i = 1; ($i <= $iLimit && $i < count($aFullTrace)); $i++) { // Skip the last function call... which is the call to this function !
$aLightTrace[$i] = $aFullTrace[$i]['function'].'(), called from line '.$aFullTrace[$i]['line'].' in '.$aFullTrace[$i]['file'];
}
echo "
".print_r($aLightTrace, true)." \n";
- }
+ }
/**
* Execute the given iTop PHP script, passing it the current credentials
@@ -1385,7 +1308,7 @@ class utils
$aArguments['param_file'] = $sParamFile;
}
- $aArgs = array();
+ $aArgs = [];
foreach ($aArguments as $sName => $value) {
// Note: See comment from the 23-Apr-2004 03:30 in the PHP documentation
// It suggests to rely on pctnl_* function instead of using escapeshellargs
@@ -1416,7 +1339,7 @@ class utils
throw new Exception(Dict::S('Core:ExecProcess:Code255')." - ".$sCommand.":\n".$sErrors);
}
- return array($iRes, $aOutput);
+ return [$iRes, $aOutput];
}
/**
@@ -1434,7 +1357,7 @@ class utils
*/
public static function GetCompiledEnvironmentPath(): string
{
- return APPROOT . 'env-' . MetaModel::GetEnvironment() . '/';
+ return APPROOT.'env-'.MetaModel::GetEnvironment().'/';
}
/**
@@ -1507,8 +1430,7 @@ class utils
// 1st - add standard built-in menu items
//
- switch($iMenuId)
- {
+ switch ($iMenuId) {
case iPopupMenuExtension::MENU_OBJLIST_ACTIONS:
// No native action there yet
break;
@@ -1538,8 +1460,10 @@ class utils
if (strlen($sUrl) < SERVER_MAX_URL_LENGTH) {
// Static menus: Email this page, CSV Export & Add to Dashboard
- $aResult[] = new URLPopupMenuItem('UI:Menu:EMail', Dict::S('UI:Menu:EMail'),
- "mailto:?body=".urlencode($sUrl).' ' // Add an extra space to make it work in Outlook
+ $aResult[] = new URLPopupMenuItem(
+ 'UI:Menu:EMail',
+ Dict::S('UI:Menu:EMail'),
+ "mailto:?body=".urlencode($sUrl).' ' // Add an extra space to make it work in Outlook
);
}
@@ -1547,18 +1471,17 @@ class utils
// Bulk export actions
$aResult[] = new JSPopupMenuItem('UI:Menu:CSVExport', Dict::S('UI:Menu:CSVExport'), "ExportListDlg('$sOQL', '$sDataTableId', 'csv', ".json_encode(Dict::S('UI:Menu:CSVExport')).")");
$aResult[] = new JSPopupMenuItem('UI:Menu:ExportXLSX', Dict::S('ExcelExporter:ExportMenu'), "ExportListDlg('$sOQL', '$sDataTableId', 'xlsx', ".json_encode(Dict::S('ExcelExporter:ExportMenu')).")");
- if (extension_loaded('gd'))
- {
+ if (extension_loaded('gd')) {
// PDF export requires GD
$aResult[] = new JSPopupMenuItem('UI:Menu:ExportPDF', Dict::S('UI:Menu:ExportPDF'), "ExportListDlg('$sOQL', '$sDataTableId', 'pdf', ".json_encode(Dict::S('UI:Menu:ExportPDF')).")");
}
}
$aResult[] = new JSPopupMenuItem('UI:Menu:AddToDashboard', Dict::S('UI:Menu:AddToDashboard'), "DashletCreationDlg('$sOQL', '$sContext')");
$aResult[] = new JSPopupMenuItem('UI:Menu:ShortcutList', Dict::S('UI:Menu:ShortcutList'), "ShortcutListDlg('$sOQL', '$sDataTableId', '$sContext')");
- if (ApplicationMenu::IsMenuIdEnabled('RunQueriesMenu')) {
- $oMenuItemPlay = new JSPopupMenuItem('UI:Menu:OpenOQL', Dict::S('UI:Menu:OpenOQL'), "OpenOql('$sOQL')");
- $aResult[] = $oMenuItemPlay;
- }
+ if (ApplicationMenu::IsMenuIdEnabled('RunQueriesMenu')) {
+ $oMenuItemPlay = new JSPopupMenuItem('UI:Menu:OpenOQL', Dict::S('UI:Menu:OpenOQL'), "OpenOql('$sOQL')");
+ $aResult[] = $oMenuItemPlay;
+ }
break;
@@ -1571,7 +1494,7 @@ class utils
$oContainerBlock->AddJsFileRelPath('js/jquery.dragtable.js');
$oContainerBlock->AddCssFileRelPath('css/dragtable.css');
- $aResult = array(
+ $aResult = [
new SeparatorPopupMenuItem(),
// Static menus: Email this page & CSV Export
new URLPopupMenuItem('UI:Menu:EMail', Dict::S('UI:Menu:EMail'), "mailto:?subject=".urlencode($oObj->GetRawName())."&body=".urlencode($sUrl).' '), // Add an extra space to make it work in Outlook
@@ -1579,7 +1502,7 @@ class utils
new JSPopupMenuItem('UI:Menu:ExportXLSX', Dict::S('ExcelExporter:ExportMenu'), "ExportListDlg('$sOQL', '', 'xlsx', ".json_encode(Dict::S('ExcelExporter:ExportMenu')).")"),
new SeparatorPopupMenuItem(),
new URLPopupMenuItem('UI:Menu:PrintableVersion', Dict::S('UI:Menu:PrintableVersion'), $sUrl.'&printable=1', '_blank'),
- );
+ ];
break;
case iPopupMenuExtension::MENU_DASHBOARD_ACTIONS:
@@ -1595,11 +1518,11 @@ class utils
$sDashboardFileJS = addslashes($sDashboardFileRelative);
$sDashboardFileURL = urlencode($sDashboardFileRelative);
$sUploadDashboardTransactId = utils::GetNewTransactionId();
- $aResult = array(
+ $aResult = [
new SeparatorPopupMenuItem(),
new URLPopupMenuItem('UI:ExportDashboard', Dict::S('UI:ExportDashBoard'), utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php?operation=export_dashboard&id='.$sDashboardId.'&file='.$sDashboardFileURL),
new JSPopupMenuItem('UI:ImportDashboard', Dict::S('UI:ImportDashBoard'), "UploadDashboard({dashboard_id: '$sDashboardId', file: '$sDashboardFileJS', title: '$sDlgTitle', text: '$sDlgText', close_btn: '$sCloseBtn', transaction: '$sUploadDashboardTransactId' })"),
- );
+ ];
if ($oDashboard->GetReloadURL()) {
$aResult[] = new SeparatorPopupMenuItem();
$aResult[] = new URLPopupMenuItem('UI:Menu:PrintableVersion', Dict::S('UI:Menu:PrintableVersion'), $oDashboard->GetReloadURL().'&printable=1', '_blank');
@@ -1786,8 +1709,7 @@ SQL;
*/
public static function GetConfigFilePathRelative($sEnvironment = null)
{
- if (is_null($sEnvironment))
- {
+ if (is_null($sEnvironment)) {
$sEnvironment = self::GetCurrentEnvironment();
}
return "conf/".$sEnvironment.'/'.ITOP_CONFIG_FILE;
@@ -1824,7 +1746,7 @@ SQL;
*
* @throws \Exception
*/
- public static function GetAbsoluteUrlModulePage($sModule, $sPage, $aArguments = array(), $sEnvironment = null)
+ public static function GetAbsoluteUrlModulePage($sModule, $sPage, $aArguments = [], $sEnvironment = null)
{
$aArgs = self::GetExecPageArguments($sModule, $sPage, $aArguments, $sEnvironment);
$sArgs = http_build_query($aArgs);
@@ -1841,17 +1763,15 @@ SQL;
* @return string[] key/value pair for the exec page query string. Warning : values are not url encoded !
* @throws \Exception if one of the argument has a reserved name
*/
- public static function GetExecPageArguments($sModule, $sPage, $aArguments = array(), $sEnvironment = null)
+ public static function GetExecPageArguments($sModule, $sPage, $aArguments = [], $sEnvironment = null)
{
$sEnvironment = is_null($sEnvironment) ? self::GetCurrentEnvironment() : $sEnvironment;
- $aArgs = array();
+ $aArgs = [];
$aArgs['exec_module'] = $sModule;
$aArgs['exec_page'] = $sPage;
$aArgs['exec_env'] = $sEnvironment;
- foreach($aArguments as $sName => $sValue)
- {
- if (($sName == 'exec_module') || ($sName == 'exec_page') || ($sName == 'exec_env'))
- {
+ foreach ($aArguments as $sName => $sValue) {
+ if (($sName == 'exec_module') || ($sName == 'exec_page') || ($sName == 'exec_env')) {
throw new Exception("Module page: $sName is a reserved page argument name");
}
$aArgs[$sName] = $sValue;
@@ -1877,17 +1797,13 @@ SQL;
*/
public static function MakeUniqueName($sProposed, $aExisting)
{
- if (in_array($sProposed, $aExisting))
- {
+ if (in_array($sProposed, $aExisting)) {
$i = 1;
- while (in_array($sProposed.$i, $aExisting) && ($i < 50))
- {
+ while (in_array($sProposed.$i, $aExisting) && ($i < 50)) {
$i++;
}
return $sProposed.$i;
- }
- else
- {
+ } else {
return $sProposed;
}
}
@@ -1899,7 +1815,7 @@ SQL;
*/
public static function GetSafeId($sId)
{
- return str_replace(array(':', '[', ']', '+', '-', ' '), '_', $sId);
+ return str_replace([':', '[', ']', '+', '-', ' '], '_', $sId);
}
/**
@@ -1925,7 +1841,7 @@ SQL;
*
* @since 3.1.0 N°6172 as curl ext is now mandatory, method will crash with a ApplicationException if this PHP extension isn't available
*/
- public static function DoPostRequest($sUrl, $aData, $sOptionnalHeaders = null, &$aResponseHeaders = null, $aCurlOptions = array())
+ public static function DoPostRequest($sUrl, $aData, $sOptionnalHeaders = null, &$aResponseHeaders = null, $aCurlOptions = [])
{
if (false === function_exists('curl_init')) {
throw new ApplicationException('\utils::DoPostRequest method called whereas the CURL PHP extension isn\'t available !');
@@ -1938,12 +1854,12 @@ SQL;
$aHeaders = explode("\n", $sOptionnalHeaders ?? '');
// N°3267 - Webservices: Fix optional headers not being taken into account
// See https://www.php.net/curl_setopt CURLOPT_HTTPHEADER
- $aHTTPHeaders = array();
+ $aHTTPHeaders = [];
foreach ($aHeaders as $sHeaderString) {
$aHTTPHeaders[] = trim($sHeaderString);
}
// Default options, can be overloaded/extended with the 4th parameter of this method, see above $aCurlOptions
- $aOptions = array(
+ $aOptions = [
CURLOPT_RETURNTRANSFER => true, // return the content of the request
CURLOPT_HEADER => false, // don't return the headers in the output
CURLOPT_FOLLOWLOCATION => true, // follow redirects
@@ -1960,7 +1876,7 @@ SQL;
CURLOPT_POST => count($aData),
CURLOPT_POSTFIELDS => http_build_query($aData),
CURLOPT_HTTPHEADER => $aHTTPHeaders,
- );
+ ];
$aAllOptions = $aCurlOptions + $aOptions;
$ch = curl_init($sUrl);
@@ -1987,22 +1903,22 @@ SQL;
/**
* Get a standard list of character sets
*
- * @param array $aAdditionalEncodings Additional values
+ * @param array $aAdditionalEncodings Additional values
* @return array of iconv code => english label, sorted by label
*/
- public static function GetPossibleEncodings($aAdditionalEncodings = array())
+ public static function GetPossibleEncodings($aAdditionalEncodings = [])
{
// Encodings supported:
// ICONV_CODE => Display Name
// Each iconv installation supports different encodings
// Some reasonably common and useful encodings are listed here
- $aPossibleEncodings = array(
+ $aPossibleEncodings = [
'UTF-8' => 'Unicode (UTF-8)',
'ISO-8859-1' => 'Western (ISO-8859-1)',
'WINDOWS-1251' => 'Cyrilic (Windows 1251)',
'WINDOWS-1252' => 'Western (Windows 1252)',
'ISO-8859-15' => 'Western (ISO-8859-15)',
- );
+ ];
$aPossibleEncodings = array_merge($aPossibleEncodings, $aAdditionalEncodings);
asort($aPossibleEncodings);
return $aPossibleEncodings;
@@ -2134,7 +2050,7 @@ SQL;
}
// else log the error if needed
if ($bLogErrors) {
- IssueLog::Warning("Format string requires $iExpectedCount arguments, but only $iActualCount provided. Format: '$sFormat'" );
+ IssueLog::Warning("Format string requires $iExpectedCount arguments, but only $iActualCount provided. Format: '$sFormat'");
}
// Create a replacement map
@@ -2159,7 +2075,7 @@ SQL;
}
// Remove any remaining nulls (for positions that weren't referenced)
- $aReplacements = array_filter($aReplacements, static function($val) { return $val !== null; });
+ $aReplacements = array_filter($aReplacements, static function ($val) { return $val !== null; });
} else {
// For non-positional, we need to map each position
$aReplacements = [];
@@ -2209,8 +2125,7 @@ SQL;
try {
//return ''.$sHtml;
return Html2Text::convert(''.$sHtml, ['ignore_errors' => true]);
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
return $e->getMessage();
}
}
@@ -2223,7 +2138,7 @@ SQL;
*/
public static function TextToHtml($sText)
{
- if (static::IsNullOrEmptyString($sText)){
+ if (static::IsNullOrEmptyString($sText)) {
return '';
}
$sText = str_replace("\r\n", "\n", $sText);
@@ -2242,24 +2157,21 @@ SQL;
public static function GetCSSFromSASS($sSassRelPath, $aImportPaths = null)
{
// Avoiding compilation if file is already a css file.
- if (preg_match('/\.css(\?.*)?$/', $sSassRelPath))
- {
+ if (preg_match('/\.css(\?.*)?$/', $sSassRelPath)) {
return $sSassRelPath;
}
// Setting import paths
- if ($aImportPaths === null)
- {
- $aImportPaths = array();
+ if ($aImportPaths === null) {
+ $aImportPaths = [];
}
- $aImportPaths[] = APPROOT . '/css';
+ $aImportPaths[] = APPROOT.'/css';
$sSassPath = APPROOT.$sSassRelPath;
$sCssRelPath = preg_replace('/\.scss$/', '.css', $sSassRelPath);
$sCssPath = APPROOT.$sCssRelPath;
clearstatcache();
- if (!file_exists($sCssPath) || (is_writable($sCssPath) && (filemtime($sCssPath) < filemtime($sSassPath))))
- {
+ if (!file_exists($sCssPath) || (is_writable($sCssPath) && (filemtime($sCssPath) < filemtime($sSassPath)))) {
$sCss = static::CompileCSSFromSASS(file_get_contents($sSassPath), $aImportPaths);
file_put_contents($sCssPath, $sCss);
}
@@ -2277,7 +2189,7 @@ SQL;
*
* @since 2.7.0
*/
- public static function CompileCSSFromSASS($sSassContent, $aImportPaths = array(), $aVariables = array())
+ public static function CompileCSSFromSASS($sSassContent, $aImportPaths = [], $aVariables = [])
{
$oSass = new Compiler();
$oSass->setOutputStyle(OutputStyle::COMPRESSED);
@@ -2327,17 +2239,17 @@ SQL;
$data = $sPrefix;
$data .= __FILE__;
$data .= mt_rand();
- $hash = strtoupper(hash('ripemd128', $uid . md5($data)));
- $sUUID = '{' .
- substr($hash, 0, 8) .
- '-' .
- substr($hash, 8, 4) .
- '-' .
- substr($hash, 12, 4) .
- '-' .
- substr($hash, 16, 4) .
- '-' .
- substr($hash, 20, 12) .
+ $hash = strtoupper(hash('ripemd128', $uid.md5($data)));
+ $sUUID = '{'.
+ substr($hash, 0, 8).
+ '-'.
+ substr($hash, 8, 4).
+ '-'.
+ substr($hash, 12, 4).
+ '-'.
+ substr($hash, 16, 4).
+ '-'.
+ substr($hash, 20, 12).
'}';
return $sUUID;
}
@@ -2350,7 +2262,7 @@ SQL;
*/
public static function GetCurrentModuleName($iCallDepth = 0)
{
- return ModuleService::GetInstance()->GetCurrentModuleName($iCallDepth + 1);
+ return ModuleService::GetInstance()->GetCurrentModuleName($iCallDepth + 1);
}
/**
@@ -2397,7 +2309,7 @@ SQL;
*/
public static function GetCurrentModuleSetting($sProperty, $defaultvalue = null)
{
- return ModuleService::GetInstance()->GetCurrentModuleSetting($sProperty, $defaultvalue);
+ return ModuleService::GetInstance()->GetCurrentModuleSetting($sProperty, $defaultvalue);
}
/**
@@ -2406,7 +2318,7 @@ SQL;
*/
public static function GetCompiledModuleVersion($sModuleName)
{
- return ModuleService::GetInstance()->GetCompiledModuleVersion($sModuleName);
+ return ModuleService::GetInstance()->GetCompiledModuleVersion($sModuleName);
}
/**
@@ -2417,8 +2329,7 @@ SQL;
public static function IsURL($sPath)
{
$bRet = false;
- if ((substr($sPath, 0, 7) == 'http://') || (substr($sPath, 0, 8) == 'https://') || (substr($sPath, 0, 8) == 'ftp://'))
- {
+ if ((substr($sPath, 0, 7) == 'http://') || (substr($sPath, 0, 8) == 'https://') || (substr($sPath, 0, 8) == 'ftp://')) {
$bRet = true;
}
return $bRet;
@@ -2442,7 +2353,7 @@ SQL;
// extract the "query" part of the URL and analyze it
$sQuery = parse_url($sPath, PHP_URL_QUERY);
if ($sQuery !== null) {
- $aParams = array();
+ $aParams = [];
foreach (explode('&', $sQuery) as $sChunk) {
$aParts = explode('=', $sChunk ?? '');
if (count($aParts) != 2) {
@@ -2555,22 +2466,17 @@ TXT
protected static function ParseHeaders($aHeaders)
{
- $aCleanHeaders = array();
- foreach( $aHeaders as $sKey => $sValue )
- {
+ $aCleanHeaders = [];
+ foreach ($aHeaders as $sKey => $sValue) {
$aTokens = explode(':', $sValue ?? '', 2);
- if(isset($aTokens[1]))
- {
+ if (isset($aTokens[1])) {
$aCleanHeaders[trim($aTokens[0])] = trim($aTokens[1]);
- }
- else
- {
+ } else {
// The header is not in the form Header-Code: Value
$aCleanHeaders[] = $sValue; // Store the value as-is
- $aMatches = array();
+ $aMatches = [];
// Check if it's not the HTTP response code
- if( preg_match("|HTTP/[0-9\.]+\s+([0-9]+)|", $sValue, $aMatches) )
- {
+ if (preg_match("|HTTP/[0-9\.]+\s+([0-9]+)|", $sValue, $aMatches)) {
$aCleanHeaders['reponse_code'] = intval($aMatches[1]);
}
}
@@ -2619,8 +2525,7 @@ TXT
*/
public static function IsHighCardinality($sClass)
{
- if (utils::GetConfig()->Get('search_manual_submit'))
- {
+ if (utils::GetConfig()->Get('search_manual_submit')) {
return true;
}
$aHugeClasses = MetaModel::GetConfig()->Get('high_cardinality_classes');
@@ -2639,20 +2544,17 @@ TXT
*/
public static function GetFileMimeType($sFilePath, $sDefaultMimeType = 'application/octet-stream')
{
- if (!function_exists('finfo_file'))
- {
+ if (!function_exists('finfo_file')) {
return $sDefaultMimeType;
}
$sMimeType = $sDefaultMimeType;
$rInfo = @finfo_open(FILEINFO_MIME_TYPE);
- if ($rInfo !== false)
- {
+ if ($rInfo !== false) {
$sType = @finfo_file($rInfo, $sFilePath);
if (($sType !== false)
&& is_string($sType)
- && ($sType !== ''))
- {
+ && ($sType !== '')) {
$sMimeType = $sType;
}
}
@@ -2682,14 +2584,12 @@ TXT
final public static function RealPath($sPath, $sBasePath)
{
$sFileRealPath = realpath($sPath);
- if ($sFileRealPath === false)
- {
+ if ($sFileRealPath === false) {
return false;
}
$sRealBasePath = realpath($sBasePath); // avoid problems when having '/' on Windows for example
- if (!self::StartsWith($sFileRealPath, $sRealBasePath))
- {
+ if (!self::StartsWith($sFileRealPath, $sRealBasePath)) {
return false;
}
@@ -2710,8 +2610,7 @@ TXT
{
$sRootPath = realpath($sBasePath);
$sFullPath = realpath($sAbsolutePath);
- if (($sFullPath === false) || !self::StartsWith($sFullPath, $sRootPath))
- {
+ if (($sFullPath === false) || !self::StartsWith($sFullPath, $sRootPath)) {
return false;
}
$sLocalPath = substr($sFullPath, strlen($sRootPath.DIRECTORY_SEPARATOR));
@@ -2730,8 +2629,7 @@ TXT
{
$sRootPath = realpath(APPROOT);
$sFullPath = realpath($sRootPath.DIRECTORY_SEPARATOR.$sPath);
- if (($sFullPath === false) || !self::StartsWith($sFullPath, $sRootPath))
- {
+ if (($sFullPath === false) || !self::StartsWith($sFullPath, $sRootPath)) {
return false;
}
return $sFullPath;
@@ -2744,8 +2642,7 @@ TXT
public static function GetCurrentUserName()
{
- if (function_exists('posix_getpwuid'))
- {
+ if (function_exists('posix_getpwuid')) {
return posix_getpwuid(posix_geteuid())['name'];
}
@@ -2767,13 +2664,12 @@ TXT
public static function EnrichRaisedException($oCmdbAbstract, $oException)
{
if (is_null($oCmdbAbstract) ||
- ! is_a($oCmdbAbstract, \cmdbAbstractObject::class))
- {
+ ! is_a($oCmdbAbstract, \cmdbAbstractObject::class)) {
throw $oException;
}
- $sCmdbAbstractInfo = str_replace("\n", '', "" . $oCmdbAbstract);
- $sMessage = $oException->getMessage() . " (" . $sCmdbAbstractInfo . ")";
+ $sCmdbAbstractInfo = str_replace("\n", '', "".$oCmdbAbstract);
+ $sMessage = $oException->getMessage()." (".$sCmdbAbstractInfo.")";
$e = new CoreException($sMessage, null, '', $oException);
throw $e;
@@ -3119,7 +3015,7 @@ TXT
// Prepare array for matched class if not already present
if (!array_key_exists($sMatchedClass, $aMentionedObjects)) {
- $aMentionedObjects[$sMatchedClass] = array();
+ $aMentionedObjects[$sMatchedClass] = [];
}
// Add matched ID if not already there
if (!in_array($sMatchedId, $aMentionedObjects[$sMatchedClass])) {
diff --git a/application/wizardhelper.class.inc.php b/application/wizardhelper.class.inc.php
index 020227b51..866cfa2ce 100644
--- a/application/wizardhelper.class.inc.php
+++ b/application/wizardhelper.class.inc.php
@@ -1,4 +1,5 @@
-
/**
* Class WizardHelper
*
@@ -42,23 +42,17 @@ class WizardHelper
*/
public function GetTargetObject($bReadUploadedFiles = false)
{
- if (isset($this->m_aData['m_oCurrentValues']['id']))
- {
+ if (isset($this->m_aData['m_oCurrentValues']['id'])) {
$oObj = MetaModel::GetObject($this->m_aData['m_sClass'], $this->m_aData['m_oCurrentValues']['id']);
- }
- else
- {
+ } else {
$oObj = MetaModel::NewObject($this->m_aData['m_sClass']);
}
- foreach($this->m_aData['m_oCurrentValues'] as $sAttCode => $value)
- {
+ foreach ($this->m_aData['m_oCurrentValues'] as $sAttCode => $value) {
// Because this is stored in a Javascript array, unused indexes
// are filled with null values and unused keys (stored as strings) contain $$NULL$$
- if ( ($sAttCode !='id') && ($value !== '$$NULL$$'))
- {
+ if (($sAttCode != 'id') && ($value !== '$$NULL$$')) {
$oAttDef = MetaModel::GetAttributeDef($this->m_aData['m_sClass'], $sAttCode);
- if (($oAttDef->IsLinkSet()) && ($value != '') )
- {
+ if (($oAttDef->IsLinkSet()) && ($value != '')) {
// special handling for lists
// assumes this is handled as an array of objects
// thus encoded in json like: [ { name:'link1', 'id': 123}, { name:'link2', 'id': 124}...]
@@ -71,47 +65,35 @@ class WizardHelper
// Check what are the meaningful attributes
$aFields = $this->GetLinkedWizardStructure($oAttDef);
$sLinkedClass = $oAttDef->GetLinkedClass();
- $aLinkedObjectsArray = array();
+ $aLinkedObjectsArray = [];
if (!is_array($aData)) {
echo("aData: '$aData' (value: '$value')\n");
}
- foreach ($aData as $aLinkedObject)
- {
+ foreach ($aData as $aLinkedObject) {
$oLinkedObj = MetaModel::NewObject($sLinkedClass);
- foreach($aFields as $sLinkedAttCode)
- {
- if ( isset($aLinkedObject[$sLinkedAttCode]) && ($aLinkedObject[$sLinkedAttCode] !== null) )
- {
+ foreach ($aFields as $sLinkedAttCode) {
+ if (isset($aLinkedObject[$sLinkedAttCode]) && ($aLinkedObject[$sLinkedAttCode] !== null)) {
$sLinkedAttDef = MetaModel::GetAttributeDef($sLinkedClass, $sLinkedAttCode);
- if (($sLinkedAttDef->IsExternalKey()) && ($aLinkedObject[$sLinkedAttCode] != '') && ($aLinkedObject[$sLinkedAttCode] > 0) )
- {
+ if (($sLinkedAttDef->IsExternalKey()) && ($aLinkedObject[$sLinkedAttCode] != '') && ($aLinkedObject[$sLinkedAttCode] > 0)) {
// For external keys: load the target object so that external fields
// get filled too
$oTargetObj = MetaModel::GetObject($sLinkedAttDef->GetTargetClass(), $aLinkedObject[$sLinkedAttCode]);
$oLinkedObj->Set($sLinkedAttCode, $oTargetObj);
- }
- elseif($sLinkedAttDef instanceof AttributeDateTime)
- {
- $sDateClass = get_class($sLinkedAttDef);
- $sDate = $aLinkedObject[$sLinkedAttCode];
- if($sDate !== null && $sDate !== '')
- {
- $oDateTimeFormat = $sDateClass::GetFormat();
- $oDate = $oDateTimeFormat->Parse($sDate);
- if ($sDateClass == "AttributeDate")
- {
- $sDate = $oDate->format('Y-m-d');
- }
- else
- {
- $sDate = $oDate->format('Y-m-d H:i:s');
- }
- }
+ } elseif ($sLinkedAttDef instanceof AttributeDateTime) {
+ $sDateClass = get_class($sLinkedAttDef);
+ $sDate = $aLinkedObject[$sLinkedAttCode];
+ if ($sDate !== null && $sDate !== '') {
+ $oDateTimeFormat = $sDateClass::GetFormat();
+ $oDate = $oDateTimeFormat->Parse($sDate);
+ if ($sDateClass == "AttributeDate") {
+ $sDate = $oDate->format('Y-m-d');
+ } else {
+ $sDate = $oDate->format('Y-m-d H:i:s');
+ }
+ }
- $oLinkedObj->Set($sLinkedAttCode, $sDate);
- }
- else
- {
+ $oLinkedObj->Set($sLinkedAttCode, $sDate);
+ } else {
$oLinkedObj->Set($sLinkedAttCode, $aLinkedObject[$sLinkedAttCode]);
}
}
@@ -120,98 +102,67 @@ class WizardHelper
}
$oSet = DBObjectSet::FromArray($sLinkedClass, $aLinkedObjectsArray);
$oObj->Set($sAttCode, $oSet);
- }
- else if ( $oAttDef->GetEditClass() == 'Document' )
- {
- if ($bReadUploadedFiles)
- {
+ } elseif ($oAttDef->GetEditClass() == 'Document') {
+ if ($bReadUploadedFiles) {
$oDocument = utils::ReadPostedDocument('attr_'.$sAttCode, 'fcontents');
$oObj->Set($sAttCode, $oDocument);
- }
- else
- {
+ } else {
// Create a new empty document, just for displaying the file name
$oDocument = new ormDocument(null, '', $value);
$oObj->Set($sAttCode, $oDocument);
}
- }
- else if ( $oAttDef->GetEditClass() == 'Image' )
- {
- if ($bReadUploadedFiles)
- {
+ } elseif ($oAttDef->GetEditClass() == 'Image') {
+ if ($bReadUploadedFiles) {
$oDocument = utils::ReadPostedDocument('attr_'.$sAttCode, 'fcontents');
$oObj->Set($sAttCode, $oDocument);
- }
- else
- {
+ } else {
// Create a new empty document, just for displaying the file name
$oDocument = new ormDocument(null, '', $value);
$oObj->Set($sAttCode, $oDocument);
}
- }
- else if (($oAttDef->IsExternalKey()) && (!empty($value)) && ($value > 0) )
- {
+ } elseif (($oAttDef->IsExternalKey()) && (!empty($value)) && ($value > 0)) {
// For external keys: load the target object so that external fields
// get filled too
$oTargetObj = MetaModel::GetObject($oAttDef->GetTargetClass(), $value, false);
- if ($oTargetObj)
- {
+ if ($oTargetObj) {
$oObj->Set($sAttCode, $oTargetObj);
- }
- else
- {
+ } else {
// May happen for security reasons (portal, see ticket N°1074)
$oObj->Set($sAttCode, $value);
}
- }
- else if ($oAttDef instanceof AttributeDateTime) // AttributeDate is derived from AttributeDateTime
- {
- if ($value != null)
- {
+ } elseif ($oAttDef instanceof AttributeDateTime) { // AttributeDate is derived from AttributeDateTime
+ if ($value != null) {
$oDate = $oAttDef->GetFormat()->Parse($value);
- if ($oDate instanceof DateTime)
- {
+ if ($oDate instanceof DateTime) {
$value = $oDate->format($oAttDef->GetInternalFormat());
- }
- else
- {
+ } else {
$value = null;
}
}
$oObj->Set($sAttCode, $value);
- }
- else if ($oAttDef instanceof AttributeTagSet) // AttributeDate is derived from AttributeDateTime
- {
- if (is_null($value))
- {
+ } elseif ($oAttDef instanceof AttributeTagSet) { // AttributeDate is derived from AttributeDateTime
+ if (is_null($value)) {
// happens if field is hidden (see N°1827)
- $value = array();
- }
- else
- {
+ $value = [];
+ } else {
$value = json_decode($value, true);
}
$oTagSet = new ormTagSet(get_class($oObj), $sAttCode, $oAttDef->GetMaxItems());
$oTagSet->SetValues($value['orig_value']);
$oTagSet->ApplyDelta($value);
$oObj->Set($sAttCode, $oTagSet);
- }
- else if ($oAttDef instanceof AttributeSet) // AttributeDate is derived from AttributeDateTime
- {
+ } elseif ($oAttDef instanceof AttributeSet) { // AttributeDate is derived from AttributeDateTime
$value = json_decode($value, true);
$oTagSet = new ormSet(get_class($oObj), $sAttCode, $oAttDef->GetMaxItems());
$oTagSet->SetValues($value['orig_value']);
$oTagSet->ApplyDelta($value);
$oObj->Set($sAttCode, $oTagSet);
- }
- else
- {
+ } else {
$oObj->Set($sAttCode, $value);
}
}
}
- if (isset($this->m_aData['m_sState']) && !empty($this->m_aData['m_sState']))
- {
+ if (isset($this->m_aData['m_sState']) && !empty($this->m_aData['m_sState'])) {
$oObj->Set(MetaModel::GetStateAttributeCode($this->m_aData['m_sClass']), $this->m_aData['m_sState']);
}
$oObj->DoComputeValues();
@@ -226,31 +177,25 @@ class WizardHelper
public function SetDefaultValue($sAttCode, $value)
{
// Protect against a request for a non existing field
- if (isset($this->m_aData['m_oFieldsMap'][$sAttCode]))
- {
+ if (isset($this->m_aData['m_oFieldsMap'][$sAttCode])) {
$oAttDef = MetaModel::GetAttributeDef($this->m_aData['m_sClass'], $sAttCode);
- if ($oAttDef->GetEditClass() == 'List')
- {
+ if ($oAttDef->GetEditClass() == 'List') {
// special handling for lists
// this as to be handled as an array of objects
// thus encoded in json like: [ { name:'link1', 'id': 123}, { name:'link2', 'id': 124}...]
// NOT YET IMPLEMENTED !!
$oSet = $value;
- $aData = array();
+ $aData = [];
$aFields = $this->GetLinkedWizardStructure($oAttDef);
- while($oLinkedObj = $oSet->fetch())
- {
- foreach($aFields as $sLinkedAttCode)
- {
+ while ($oLinkedObj = $oSet->fetch()) {
+ foreach ($aFields as $sLinkedAttCode) {
$aRow[$sAttCode] = $oLinkedObj->Get($sLinkedAttCode);
}
$aData[] = $aRow;
}
$this->m_aData['m_oDefaultValue'][$sAttCode] = json_encode($aData);
- }
- else
- {
+ } else {
// Normal handling for all other scalar attributes
$this->m_aData['m_oDefaultValue'][$sAttCode] = $value;
}
@@ -265,8 +210,7 @@ class WizardHelper
public function SetAllowedValuesHtml($sAttCode, $sHtml)
{
// Protect against a request for a non existing field
- if (isset($this->m_aData['m_oFieldsMap'][$sAttCode]))
- {
+ if (isset($this->m_aData['m_oFieldsMap'][$sAttCode])) {
$this->m_aData['m_oAllowedValues'][$sAttCode] = $sHtml;
}
}
@@ -276,7 +220,7 @@ class WizardHelper
return json_encode($this->m_aData);
}
- static public function FromJSON($sJSON)
+ public static function FromJSON($sJSON)
{
$oWizHelper = new WizardHelper();
$aData = json_decode($sJSON, true); // true means hash array instead of object
@@ -288,21 +232,17 @@ class WizardHelper
{
$oWizard = new UIWizard(null, $oAttDef->GetLinkedClass());
$aWizardSteps = $oWizard->GetWizardStructure();
- $aFields = array();
+ $aFields = [];
$sExtKeyToMeCode = $oAttDef->GetExtKeyToMe();
// Retrieve as a flat list, all the attributes that are needed to create
// an object of the linked class and put them into a flat array, except
// the attribute 'ext_key_to_me' which is a constant in our case
- foreach($aWizardSteps as $sDummy => $aMainSteps)
- {
+ foreach ($aWizardSteps as $sDummy => $aMainSteps) {
// 2 entries: 'mandatory' and 'optional'
- foreach($aMainSteps as $aSteps)
- {
+ foreach ($aMainSteps as $aSteps) {
// One entry for each step of the wizard
- foreach($aSteps as $sAttCode)
- {
- if ($sAttCode != $sExtKeyToMeCode)
- {
+ foreach ($aSteps as $sAttCode) {
+ if ($sAttCode != $sExtKeyToMeCode) {
$aFields[] = $sAttCode;
}
}
@@ -316,20 +256,20 @@ class WizardHelper
return $this->m_aData['m_sClass'];
}
- public function GetFormPrefix()
- {
- return $this->m_aData['m_sFormPrefix'];
- }
+ public function GetFormPrefix()
+ {
+ return $this->m_aData['m_sFormPrefix'];
+ }
- public function GetInitialState()
- {
- return isset($this->m_aData['m_sInitialState']) ? $this->m_aData['m_sInitialState'] : null;
- }
+ public function GetInitialState()
+ {
+ return isset($this->m_aData['m_sInitialState']) ? $this->m_aData['m_sInitialState'] : null;
+ }
- public function GetStimulus()
- {
- return isset($this->m_aData['m_sStimulus']) ? $this->m_aData['m_sStimulus'] : null;
- }
+ public function GetStimulus()
+ {
+ return isset($this->m_aData['m_sStimulus']) ? $this->m_aData['m_sStimulus'] : null;
+ }
public function GetIdForField($sFieldName)
{
@@ -337,8 +277,7 @@ class WizardHelper
// It may happen that the field we'd like to update does not
// exist in the form. For example, if the field should be hidden/read-only
// in the current state of the object
- if (isset($this->m_aData['m_oFieldsMap'][$sFieldName]))
- {
+ if (isset($this->m_aData['m_oFieldsMap'][$sFieldName])) {
$sResult = $this->m_aData['m_oFieldsMap'][$sFieldName];
}
@@ -362,12 +301,14 @@ class WizardHelper
$sWizardHelperJsVar = (!is_null($this->m_aData['m_sWizHelperJsVarName'])) ? utils::Sanitize($this->m_aData['m_sWizHelperJsVarName'], '', utils::ENUM_SANITIZATION_FILTER_PARAMETER) : 'oWizardHelper'.$this->GetFormPrefix();
$sWizardHelperJson = $this->ToJSON();
- $oPage->add_script(<<add_script(
+ <<add_ready_script(<<add_ready_script(
+ <<author=$author; }
+ public function __construct()
+ {
+ }
+ public function setAuthor($author = '')
+ {
+ $this->author = $author;
+ }
public function __destruct()
{
if (!empty($this->temp_files)) {
- foreach($this->temp_files as $temp_file) {
+ foreach ($this->temp_files as $temp_file) {
@unlink($temp_file);
}
}
}
-
+
public function setDateFormat($date_format)
{
$this->date_format = $date_format;
}
-
+
public function setDateTimeFormat($date_time_format)
{
$this->date_time_format = $date_time_format;
}
-
+
protected function tempFilename()
{
$filename = tempnam(SetupUtils::GettmpDir(), 'xlsx_writer_');
@@ -64,120 +72,123 @@ Class XLSXWriter
{
@unlink($filename);//if the zip already exists, overwrite it
$zip = new ZipArchive();
- if (empty($this->sheets_meta)) { self::log("Error in ".__CLASS__."::".__FUNCTION__.", no worksheets defined."); return; }
- if (!$zip->open($filename, ZipArchive::CREATE)) { self::log("Error in ".__CLASS__."::".__FUNCTION__.", unable to create zip."); return; }
-
+ if (empty($this->sheets_meta)) {
+ self::log("Error in ".__CLASS__."::".__FUNCTION__.", no worksheets defined.");
+ return;
+ }
+ if (!$zip->open($filename, ZipArchive::CREATE)) {
+ self::log("Error in ".__CLASS__."::".__FUNCTION__.", unable to create zip.");
+ return;
+ }
+
$zip->addEmptyDir("docProps/");
- $zip->addFromString("docProps/app.xml" , self::buildAppXML() );
+ $zip->addFromString("docProps/app.xml", self::buildAppXML());
$zip->addFromString("docProps/core.xml", self::buildCoreXML());
$zip->addEmptyDir("_rels/");
$zip->addFromString("_rels/.rels", self::buildRelationshipsXML());
$zip->addEmptyDir("xl/worksheets/");
- foreach($this->sheets_meta as $sheet_meta) {
- $zip->addFile($sheet_meta['filename'], "xl/worksheets/".$sheet_meta['xmlname'] );
+ foreach ($this->sheets_meta as $sheet_meta) {
+ $zip->addFile($sheet_meta['filename'], "xl/worksheets/".$sheet_meta['xmlname']);
}
if (!empty($this->shared_strings)) {
- $zip->addFile($this->writeSharedStringsXML(), "xl/sharedStrings.xml" ); //$zip->addFromString("xl/sharedStrings.xml", self::buildSharedStringsXML() );
+ $zip->addFile($this->writeSharedStringsXML(), "xl/sharedStrings.xml"); //$zip->addFromString("xl/sharedStrings.xml", self::buildSharedStringsXML() );
}
- $zip->addFromString("xl/workbook.xml" , self::buildWorkbookXML() );
- $zip->addFile($this->writeStylesXML(), "xl/styles.xml" ); //$zip->addFromString("xl/styles.xml" , self::buildStylesXML() );
- $zip->addFromString("[Content_Types].xml" , self::buildContentTypesXML() );
+ $zip->addFromString("xl/workbook.xml", self::buildWorkbookXML());
+ $zip->addFile($this->writeStylesXML(), "xl/styles.xml"); //$zip->addFromString("xl/styles.xml" , self::buildStylesXML() );
+ $zip->addFromString("[Content_Types].xml", self::buildContentTypesXML());
$zip->addEmptyDir("xl/_rels/");
- $zip->addFromString("xl/_rels/workbook.xml.rels", self::buildWorkbookRelsXML() );
+ $zip->addFromString("xl/_rels/workbook.xml.rels", self::buildWorkbookRelsXML());
$zip->close();
}
-
- public function writeSheet(array $data, $sheet_name='', array $header_types=array(), array $header_row=array() )
+ public function writeSheet(array $data, $sheet_name = '', array $header_types = [], array $header_row = [])
{
- $data = empty($data) ? array( array('') ) : $data;
-
+ $data = empty($data) ? [ [''] ] : $data;
+
$sheet_filename = $this->tempFilename();
- $sheet_default = 'Sheet'.(count($this->sheets_meta)+1);
+ $sheet_default = 'Sheet'.(count($this->sheets_meta) + 1);
$sheet_name = !empty($sheet_name) ? $sheet_name : $sheet_default;
- $this->sheets_meta[] = array('filename'=>$sheet_filename, 'sheetname'=>$sheet_name ,'xmlname'=>strtolower($sheet_default).".xml" );
+ $this->sheets_meta[] = ['filename' => $sheet_filename, 'sheetname' => $sheet_name ,'xmlname' => strtolower($sheet_default).".xml" ];
$header_offset = empty($header_types) ? 0 : 1;
$row_count = count($data) + $header_offset;
$column_count = count($data[self::array_first_key($data)]);
- $max_cell = self::xlsCell( $row_count-1, $column_count-1 );
+ $max_cell = self::xlsCell($row_count - 1, $column_count - 1);
- $tabselected = count($this->sheets_meta)==1 ? 'true' : 'false';//only first sheet is selected
+ $tabselected = count($this->sheets_meta) == 1 ? 'true' : 'false';//only first sheet is selected
$cell_formats_arr = empty($header_types) ? array_fill(0, $column_count, 'string') : array_values($header_types);
- if (empty($header_row) && !empty($header_types))
- {
- $header_row = empty($header_types) ? array() : array_keys($header_types);
+ if (empty($header_row) && !empty($header_types)) {
+ $header_row = empty($header_types) ? [] : array_keys($header_types);
}
$fd = fopen($sheet_filename, "w+");
- if ($fd===false) { self::log("write failed in ".__CLASS__."::".__FUNCTION__."."); return; }
-
- fwrite($fd,''."\n");
- fwrite($fd,'');
- fwrite($fd, '');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, '');
- fwrite($fd, '');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, '');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, '');
- if (!empty($header_row))
- {
+ if ($fd === false) {
+ self::log("write failed in ".__CLASS__."::".__FUNCTION__.".");
+ return;
+ }
+
+ fwrite($fd, ''."\n");
+ fwrite($fd, '');
+ fwrite($fd, '');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, '');
+ fwrite($fd, '');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, '');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, '');
+ if (!empty($header_row)) {
fwrite($fd, '');
- foreach($header_row as $k=>$v)
- {
- $this->writeCell($fd, 0, $k, $v, $cell_format='string');
+ foreach ($header_row as $k => $v) {
+ $this->writeCell($fd, 0, $k, $v, $cell_format = 'string');
}
fwrite($fd, '
');
}
- foreach($data as $i=>$row)
- {
- fwrite($fd, '');
- foreach($row as $k=>$v)
- {
- $this->writeCell($fd, $i+$header_offset, $k, $v, $cell_formats_arr[$k]);
+ foreach ($data as $i => $row) {
+ fwrite($fd, '');
+ foreach ($row as $k => $v) {
+ $this->writeCell($fd, $i + $header_offset, $k, $v, $cell_formats_arr[$k]);
}
fwrite($fd, '
');
}
- fwrite($fd, '
');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, '');
- fwrite($fd, '&C&"Times New Roman,Regular"&12&A ');
- fwrite($fd, '&C&"Times New Roman,Regular"&12Page &P ');
- fwrite($fd, ' ');
- fwrite($fd,' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, '');
+ fwrite($fd, '&C&"Times New Roman,Regular"&12&A ');
+ fwrite($fd, '&C&"Times New Roman,Regular"&12Page &P ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
fclose($fd);
}
protected function writeCell($fd, $row_number, $column_number, $value, $cell_format)
{
- static $styles = array('money'=>1,'dollar'=>1,'datetime'=>2,'date'=>3,'string'=>0);
+ static $styles = ['money' => 1,'dollar' => 1,'datetime' => 2,'date' => 3,'string' => 0];
$cell = self::xlsCell($row_number, $column_number);
$s = isset($styles[$cell_format]) && ($value !== '') ? $styles[$cell_format] : '0';
-
+
if (is_int($value) || is_float($value)) {
- fwrite($fd,''.($value*1).' ');//int,float, etc
- } else if (($cell_format=='date') && ($value != '')) {
- fwrite($fd,''.intval(self::convert_date_time($value)).' ');
- } else if (($cell_format=='datetime') && ($value != '')) {
- fwrite($fd,''.self::convert_date_time($value).' ');
- } else if ($value==''){
- fwrite($fd,' ');
- } else if ($value[0]=='='){
- fwrite($fd,''.self::xmlspecialchars($value).' ');
- } else if ($value!==''){
- fwrite($fd,''.self::xmlspecialchars($this->setSharedString($value)).' ');
+ fwrite($fd, ''.($value * 1).' ');//int,float, etc
+ } elseif (($cell_format == 'date') && ($value != '')) {
+ fwrite($fd, ''.intval(self::convert_date_time($value)).' ');
+ } elseif (($cell_format == 'datetime') && ($value != '')) {
+ fwrite($fd, ''.self::convert_date_time($value).' ');
+ } elseif ($value == '') {
+ fwrite($fd, ' ');
+ } elseif ($value[0] == '=') {
+ fwrite($fd, ''.self::xmlspecialchars($value).' ');
+ } elseif ($value !== '') {
+ fwrite($fd, ''.self::xmlspecialchars($this->setSharedString($value)).' ');
}
}
@@ -185,62 +196,65 @@ Class XLSXWriter
{
$tempfile = $this->tempFilename();
$fd = fopen($tempfile, "w+");
- if ($fd===false) { self::log("write failed in ".__CLASS__."::".__FUNCTION__."."); return; }
+ if ($fd === false) {
+ self::log("write failed in ".__CLASS__."::".__FUNCTION__.".");
+ return;
+ }
fwrite($fd, ''."\n");
fwrite($fd, '');
fwrite($fd, '');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
fwrite($fd, ' ');
fwrite($fd, '');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
fwrite($fd, ' ');
fwrite($fd, ' ');
fwrite($fd, ' ');
- fwrite($fd, '');
- fwrite($fd, '');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
+ fwrite($fd, '');
+ fwrite($fd, '');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
//fwrite($fd, ' ');
//fwrite($fd, ' ');
//fwrite($fd, ' ');
//fwrite($fd, ' ');
//fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, '');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, ' ');
- fwrite($fd, '');
- fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, '');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, ' ');
+ fwrite($fd, '');
+ fwrite($fd, ' ');
//fwrite($fd, ' ');
//fwrite($fd, ' ');
//fwrite($fd, ' ');
//fwrite($fd, ' ');
//fwrite($fd, ' ');
- fwrite($fd, ' ');
+ fwrite($fd, '');
fwrite($fd, ' ');
fclose($fd);
return $tempfile;
@@ -250,12 +264,9 @@ Class XLSXWriter
{
// Strip control characters which Excel does not seem to like...
$v = preg_replace('/[\x00-\x09\x0B\x0C\x0E-\x1F]/u', '', $v);
- if (isset($this->shared_strings[$v]))
- {
+ if (isset($this->shared_strings[$v])) {
$string_value = $this->shared_strings[$v];
- }
- else
- {
+ } else {
$string_value = count($this->shared_strings);
$this->shared_strings[$v] = $string_value;
}
@@ -267,13 +278,15 @@ Class XLSXWriter
{
$tempfile = $this->tempFilename();
$fd = fopen($tempfile, "w+");
- if ($fd===false) { self::log("write failed in ".__CLASS__."::".__FUNCTION__."."); return; }
-
- fwrite($fd,''."\n");
- fwrite($fd,'');
- foreach($this->shared_strings as $s=>$c)
- {
- fwrite($fd,''.self::xmlspecialchars($s).' ');
+ if ($fd === false) {
+ self::log("write failed in ".__CLASS__."::".__FUNCTION__.".");
+ return;
+ }
+
+ fwrite($fd, ''."\n");
+ fwrite($fd, '');
+ foreach ($this->shared_strings as $s => $c) {
+ fwrite($fd, ''.self::xmlspecialchars($s).' ');
}
fwrite($fd, ' ');
fclose($fd);
@@ -282,89 +295,89 @@ Class XLSXWriter
protected function buildAppXML()
{
- $app_xml="";
- $app_xml.=''."\n";
- $app_xml.='0 ';
+ $app_xml = "";
+ $app_xml .= ''."\n";
+ $app_xml .= '0 ';
return $app_xml;
}
protected function buildCoreXML()
{
- $core_xml="";
- $core_xml.=''."\n";
- $core_xml.='';
- $core_xml.=''.date("Y-m-d\TH:i:s.00\Z").' ';//$date_time = '2013-07-25T15:54:37.00Z';
- $core_xml.=''.self::xmlspecialchars($this->author).' ';
- $core_xml.='0 ';
- $core_xml.=' ';
+ $core_xml = "";
+ $core_xml .= ''."\n";
+ $core_xml .= '';
+ $core_xml .= ''.date("Y-m-d\TH:i:s.00\Z").' ';//$date_time = '2013-07-25T15:54:37.00Z';
+ $core_xml .= ''.self::xmlspecialchars($this->author).' ';
+ $core_xml .= '0 ';
+ $core_xml .= ' ';
return $core_xml;
}
protected function buildRelationshipsXML()
{
- $rels_xml="";
- $rels_xml.=''."\n";
- $rels_xml.='';
- $rels_xml.=' ';
- $rels_xml.=' ';
- $rels_xml.=' ';
- $rels_xml.="\n";
- $rels_xml.=' ';
+ $rels_xml = "";
+ $rels_xml .= ''."\n";
+ $rels_xml .= '';
+ $rels_xml .= ' ';
+ $rels_xml .= ' ';
+ $rels_xml .= ' ';
+ $rels_xml .= "\n";
+ $rels_xml .= ' ';
return $rels_xml;
}
protected function buildWorkbookXML()
{
- $workbook_xml="";
- $workbook_xml.=''."\n";
- $workbook_xml.='';
- $workbook_xml.=' ';
- $workbook_xml.=' ';
- $workbook_xml.='';
- foreach($this->sheets_meta as $i=>$sheet_meta) {
- $workbook_xml.=' ';
+ $workbook_xml = "";
+ $workbook_xml .= ''."\n";
+ $workbook_xml .= '';
+ $workbook_xml .= ' ';
+ $workbook_xml .= ' ';
+ $workbook_xml .= '';
+ foreach ($this->sheets_meta as $i => $sheet_meta) {
+ $workbook_xml .= ' ';
}
- $workbook_xml.=' ';
- $workbook_xml.=' ';
+ $workbook_xml .= ' ';
+ $workbook_xml .= ' ';
return $workbook_xml;
}
protected function buildWorkbookRelsXML()
{
- $wkbkrels_xml="";
- $wkbkrels_xml.=''."\n";
- $wkbkrels_xml.='';
- $wkbkrels_xml.=' ';
- foreach($this->sheets_meta as $i=>$sheet_meta) {
- $wkbkrels_xml.=' ';
+ $wkbkrels_xml = "";
+ $wkbkrels_xml .= ''."\n";
+ $wkbkrels_xml .= '';
+ $wkbkrels_xml .= ' ';
+ foreach ($this->sheets_meta as $i => $sheet_meta) {
+ $wkbkrels_xml .= ' ';
}
if (!empty($this->shared_strings)) {
- $wkbkrels_xml.=' ';
+ $wkbkrels_xml .= ' ';
}
- $wkbkrels_xml.="\n";
- $wkbkrels_xml.=' ';
+ $wkbkrels_xml .= "\n";
+ $wkbkrels_xml .= ' ';
return $wkbkrels_xml;
}
protected function buildContentTypesXML()
{
- $content_types_xml="";
- $content_types_xml.=''."\n";
- $content_types_xml.='';
- $content_types_xml.=' ';
- $content_types_xml.=' ';
- foreach($this->sheets_meta as $i=>$sheet_meta) {
- $content_types_xml.=' ';
+ $content_types_xml = "";
+ $content_types_xml .= ''."\n";
+ $content_types_xml .= '';
+ $content_types_xml .= ' ';
+ $content_types_xml .= ' ';
+ foreach ($this->sheets_meta as $i => $sheet_meta) {
+ $content_types_xml .= ' ';
}
if (!empty($this->shared_strings)) {
- $content_types_xml.=' ';
+ $content_types_xml .= ' ';
}
- $content_types_xml.=' ';
- $content_types_xml.=' ';
- $content_types_xml.=' ';
- $content_types_xml.=' ';
- $content_types_xml.="\n";
- $content_types_xml.=' ';
+ $content_types_xml .= ' ';
+ $content_types_xml .= ' ';
+ $content_types_xml .= ' ';
+ $content_types_xml .= ' ';
+ $content_types_xml .= "\n";
+ $content_types_xml .= ' ';
return $content_types_xml;
}
@@ -377,10 +390,10 @@ Class XLSXWriter
public static function xlsCell($row_number, $column_number)
{
$n = $column_number;
- for($r = ""; $n >= 0; $n = intval($n / 26) - 1) {
- $r = chr($n%26 + 0x41) . $r;
+ for ($r = ""; $n >= 0; $n = intval($n / 26) - 1) {
+ $r = chr($n % 26 + 0x41).$r;
}
- return $r . ($row_number+1);
+ return $r.($row_number + 1);
}
//------------------------------------------------------------------
public static function log($string)
@@ -404,26 +417,30 @@ Class XLSXWriter
{
$days = 0; # Number of days since epoch
$seconds = 0; # Time expressed as fraction of 24h hours in seconds
- $year=$month=$day=0;
- $hour=$min =$sec=0;
+ $year = $month = $day = 0;
+ $hour = $min = $sec = 0;
$date_time = $date_input;
- if (preg_match("/(\d{4})\-(\d{2})\-(\d{2})/", $date_time, $matches))
- {
- list($junk,$year,$month,$day) = $matches;
+ if (preg_match("/(\d{4})\-(\d{2})\-(\d{2})/", $date_time, $matches)) {
+ list($junk, $year, $month, $day) = $matches;
}
- if (preg_match("/(\d{2}):(\d{2}):(\d{2})/", $date_time, $matches))
- {
- list($junk,$hour,$min,$sec) = $matches;
- $seconds = ( $hour * 60 * 60 + $min * 60 + $sec ) / ( 24 * 60 * 60 );
+ if (preg_match("/(\d{2}):(\d{2}):(\d{2})/", $date_time, $matches)) {
+ list($junk, $hour, $min, $sec) = $matches;
+ $seconds = ($hour * 60 * 60 + $min * 60 + $sec) / (24 * 60 * 60);
}
//using 1900 as epoch, not 1904, ignoring 1904 special case
-
+
# Special cases for Excel.
- if ("$year-$month-$day"=='1899-12-31') return $seconds ; # Excel 1900 epoch
- if ("$year-$month-$day"=='1900-01-00') return $seconds ; # Excel 1900 epoch
- if ("$year-$month-$day"=='1900-02-29') return 60 + $seconds ; # Excel false leapday
+ if ("$year-$month-$day" == '1899-12-31') {
+ return $seconds ;
+ } # Excel 1900 epoch
+ if ("$year-$month-$day" == '1900-01-00') {
+ return $seconds ;
+ } # Excel 1900 epoch
+ if ("$year-$month-$day" == '1900-02-29') {
+ return 60 + $seconds ;
+ } # Excel false leapday
# We calculate the date by calculating the number of days since the epoch
# and adjust for the number of leap days. We calculate the number of leap
@@ -435,33 +452,35 @@ Class XLSXWriter
$range = $year - $epoch;
# Set month days and check for leap year.
- $leap = (($year % 400 == 0) || (($year % 4 == 0) && ($year % 100)) ) ? 1 : 0;
- $mdays = array( 31, ($leap ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
+ $leap = (($year % 400 == 0) || (($year % 4 == 0) && ($year % 100))) ? 1 : 0;
+ $mdays = [ 31, ($leap ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
# Some boundary checks
- if($year < $epoch || $year > 9999) return 0;
- if($month < 1 || $month > 12) return 0;
- if($day < 1 || $day > $mdays[ $month - 1 ]) return 0;
+ if ($year < $epoch || $year > 9999) {
+ return 0;
+ }
+ if ($month < 1 || $month > 12) {
+ return 0;
+ }
+ if ($day < 1 || $day > $mdays[ $month - 1 ]) {
+ return 0;
+ }
# Accumulate the number of days since the epoch.
$days = $day; # Add days for current month
- $days += array_sum( array_slice($mdays, 0, $month-1 ) ); # Add days for past months
+ $days += array_sum(array_slice($mdays, 0, $month - 1)); # Add days for past months
$days += $range * 365; # Add days for past years
- $days += intval( ( $range ) / 4 ); # Add leapdays
- $days -= intval( ( $range + $offset ) / 100 ); # Subtract 100 year leapdays
- $days += intval( ( $range + $offset + $norm ) / 400 ); # Add 400 year leapdays
+ $days += intval(($range) / 4); # Add leapdays
+ $days -= intval(($range + $offset) / 100); # Subtract 100 year leapdays
+ $days += intval(($range + $offset + $norm) / 400); # Add 400 year leapdays
$days -= $leap; # Already counted above
# Adjust for Excel erroneously treating 1900 as a leap year.
- if ($days > 59) { $days++;}
+ if ($days > 59) {
+ $days++;
+ }
return $days + $seconds;
}
//------------------------------------------------------------------
}
-
-
-
-
-
-
diff --git a/bootstrap.inc.php b/bootstrap.inc.php
index 8e64d8163..29dacb113 100644
--- a/bootstrap.inc.php
+++ b/bootstrap.inc.php
@@ -18,7 +18,6 @@
* You should have received a copy of the GNU Affero General Public License
*/
-
/**
* Checks PHP version
*
@@ -39,7 +38,6 @@ if (PHP_MAJOR_VERSION >= 7) {
exit(-1);
}
-
define('ITOP_DEFAULT_ENV', 'production');
define('MAINTENANCE_MODE_FILE', APPROOT.'data/.maintenance');
define('READONLY_MODE_FILE', APPROOT.'data/.readonly');
@@ -60,8 +58,7 @@ if (!isset($bBypassMaintenance)) {
$bBypassMaintenance = isset($_REQUEST['maintenance']) ? boolval($_REQUEST['maintenance']) : false;
}
-if (file_exists(MAINTENANCE_MODE_FILE) && !$bBypassMaintenance)
-{
+if (file_exists(MAINTENANCE_MODE_FILE) && !$bBypassMaintenance) {
$sTitle = 'Maintenance';
$sMessage = 'This application is currently under maintenance.';
@@ -70,8 +67,7 @@ if (file_exists(MAINTENANCE_MODE_FILE) && !$bBypassMaintenance)
include(APPROOT.'application/maintenancemsg.php');
$sSAPIName = strtoupper(trim(PHP_SAPI));
- switch (true)
- {
+ switch (true) {
case isset($_SERVER['REQUEST_URI']) && EndsWith($_SERVER['REQUEST_URI'], '/pages/ajax.searchform.php'):
_MaintenanceHtmlMessage($sMessage);
break;
@@ -102,6 +98,7 @@ if (file_exists(MAINTENANCE_MODE_FILE) && !$bBypassMaintenance)
*
* @return bool
*/
-function EndsWith($haystack, $needle) {
+function EndsWith($haystack, $needle)
+{
return substr_compare($haystack, $needle, -strlen($needle)) === 0;
}
diff --git a/conf/index.php b/conf/index.php
index 112807643..fcb6f20af 100644
--- a/conf/index.php
+++ b/conf/index.php
@@ -1,2 +1,3 @@
-
/**
* Various dev/debug helpers
* TODO: cleanup or at least re-organize
@@ -25,7 +25,6 @@
* @license http://opensource.org/licenses/AGPL-3.0
*/
-
/**
* MyHelpers
*
@@ -35,28 +34,23 @@ class MyHelpers
{
public static function CheckValueInArray($sDescription, $value, $aData)
{
- if (!in_array($value, $aData))
- {
+ if (!in_array($value, $aData)) {
self::HandleWrongValue($sDescription, $value, $aData);
}
}
public static function CheckKeyInArray($sDescription, $key, $aData)
{
- if (!array_key_exists($key, $aData))
- {
+ if (!array_key_exists($key, $aData)) {
self::HandleWrongValue($sDescription, $key, array_keys($aData));
}
}
public static function HandleWrongValue($sDescription, $value, $aData)
{
- if (count($aData) == 0)
- {
+ if (count($aData) == 0) {
$sArrayDesc = "{}";
- }
- else
- {
+ } else {
$sArrayDesc = "{".implode(", ", $aData)."}";
}
// exit!
@@ -64,7 +58,7 @@ class MyHelpers
}
// getmicrotime()
- // format sss.mmmuuupppnnn
+ // format sss.mmmuuupppnnn
public static function getmicrotime()
{
return microtime(true);
@@ -74,14 +68,15 @@ class MyHelpers
* MakeSQLComment
* converts hash into text comment which we can use in a (mySQL) query
*/
- public static function MakeSQLComment ($aHash)
+ public static function MakeSQLComment($aHash)
{
- if (empty($aHash)) return "";
+ if (empty($aHash)) {
+ return "";
+ }
$sComment = "";
{
- foreach($aHash as $sKey=>$sValue)
- {
- $sComment .= "\n-- ". $sKey ."=>" . $sValue;
+ foreach ($aHash as $sKey => $sValue) {
+ $sComment .= "\n-- ".$sKey."=>".$sValue;
}
}
return $sComment;
@@ -90,12 +85,9 @@ class MyHelpers
public static function var_dump_html($aWords, $bFullDisplay = false)
{
echo "\n";
- if ($bFullDisplay)
- {
+ if ($bFullDisplay) {
print_r($aWords); // full dump!
- }
- else
- {
+ } else {
var_dump($aWords); // truncate things when they are too big
}
echo "\n \n";
@@ -123,9 +115,10 @@ class MyHelpers
{
$aLines1 = explode("\n", $s1);
$aLines2 = explode("\n", $s2);
- for ($i = 0 ; $i < min(count($aLines1), count($aLines2)) ; $i++)
- {
- if ($aLines1[$i] != $aLines2[$i]) return $i;
+ for ($i = 0 ; $i < min(count($aLines1), count($aLines2)) ; $i++) {
+ if ($aLines1[$i] != $aLines2[$i]) {
+ return $i;
+ }
}
return false;
}
@@ -142,9 +135,10 @@ class MyHelpers
// do not work fine with multiline strings
$iLen1 = strlen($s1);
$iLen2 = strlen($s2);
- for ($i = 0 ; $i < min($iLen1, $iLen2) ; $i++)
- {
- if ($s1[$i] !== $s2[$i]) return $i;
+ for ($i = 0 ; $i < min($iLen1, $iLen2) ; $i++) {
+ if ($s1[$i] !== $s2[$i]) {
+ return $i;
+ }
}
return false;
}
@@ -154,9 +148,10 @@ class MyHelpers
// do not work fine with multiline strings
$iLen1 = strlen($s1);
$iLen2 = strlen($s2);
- for ($i = 0 ; $i < min(strlen($s1), strlen($s2)) ; $i++)
- {
- if ($s1[$iLen1 - $i - 1] !== $s2[$iLen2 - $i - 1]) return array($iLen1 - $i, $iLen2 - $i);
+ for ($i = 0 ; $i < min(strlen($s1), strlen($s2)) ; $i++) {
+ if ($s1[$iLen1 - $i - 1] !== $s2[$iLen2 - $i - 1]) {
+ return [$iLen1 - $i, $iLen2 - $i];
+ }
}
return false;
}
@@ -177,8 +172,7 @@ class MyHelpers
protected static function string_cmp_html($s1, $s2, $sHighlight)
{
$iDiffPos = self::first_diff($s1, $s2);
- if ($iDiffPos === false)
- {
+ if ($iDiffPos === false) {
echo "strings are identical";
return;
}
@@ -189,7 +183,7 @@ class MyHelpers
$sMiddle1 = substr($s1, $iDiffPos, $aLastDiff[0] - $iDiffPos);
$sMiddle2 = substr($s2, $iDiffPos, $aLastDiff[1] - $iDiffPos);
-
+
echo "$sStart$sMiddle1 $sEnd
\n";
echo "$sStart$sMiddle2 $sEnd
\n";
}
@@ -203,40 +197,34 @@ class MyHelpers
public static function var_cmp_html($var1, $var2, $sHighlight = 'color:red; font-weight:bold;')
{
- if (is_object($var1))
- {
+ if (is_object($var1)) {
return self::object_cmp_html($var1, $var2, $sHighlight);
- }
- else if (count(explode("\n", $var1)) > 1)
- {
+ } elseif (count(explode("\n", $var1)) > 1) {
// multiline string
return self::text_cmp_html($var1, $var2, $sHighlight);
- }
- else
- {
+ } else {
return self::string_cmp_html($var1, $var2, $sHighlight);
}
}
public static function get_callstack($iLevelsToIgnore = 0, $aCallStack = null)
{
- if ($aCallStack == null) $aCallStack = debug_backtrace();
-
+ if ($aCallStack == null) {
+ $aCallStack = debug_backtrace();
+ }
+
$aCallStack = array_slice($aCallStack, $iLevelsToIgnore);
-
- $aDigestCallStack = array();
- $bFirstLine = true;
- foreach ($aCallStack as $aCallInfo)
- {
+
+ $aDigestCallStack = [];
+ $bFirstLine = true;
+ foreach ($aCallStack as $aCallInfo) {
$sLine = empty($aCallInfo['line']) ? "" : $aCallInfo['line'];
$sFile = empty($aCallInfo['file']) ? "" : $aCallInfo['file'];
- if ($sFile != '')
- {
+ if ($sFile != '') {
$sFile = str_replace('\\', '/', $sFile);
$sAppRoot = str_replace('\\', '/', APPROOT);
$iPos = strpos($sFile, $sAppRoot);
- if ($iPos !== false)
- {
+ if ($iPos !== false) {
$sFile = substr($sFile, strlen($sAppRoot));
}
}
@@ -244,55 +232,51 @@ class MyHelpers
$sType = empty($aCallInfo['type']) ? "" : $aCallInfo['type'];
$sFunction = empty($aCallInfo['function']) ? "" : $aCallInfo['function'];
- if ($bFirstLine)
- {
+ if ($bFirstLine) {
$bFirstLine = false;
// For this line do not display the "function name" because
// that will be the name of our error handler for sure !
$sFunctionInfo = "N/A";
- }
- else
- {
+ } else {
$args = '';
- if (empty($aCallInfo['args'])) $aCallInfo['args'] = array();
- foreach ($aCallInfo['args'] as $a)
- {
- if (!empty($args))
- {
+ if (empty($aCallInfo['args'])) {
+ $aCallInfo['args'] = [];
+ }
+ foreach ($aCallInfo['args'] as $a) {
+ if (!empty($args)) {
$args .= ', ';
}
- switch (gettype($a))
- {
+ switch (gettype($a)) {
case 'integer':
case 'double':
- $args .= $a;
- break;
+ $args .= $a;
+ break;
case 'string':
- $a = Str::pure2html(self::beautifulstr($a, 64, true, false));
- $args .= "\"$a\"";
- break;
- case 'array':
- $args .= 'array('.count($a).')';
- break;
- case 'object':
- $args .= 'Object('.get_class($a).')';
- break;
- case 'resource':
- $args .= 'Resource('.strstr($a, '#').')';
- break;
- case 'boolean':
- $args .= $a ? 'true' : 'false';
- break;
- case 'NULL':
- $args .= 'null';
- break;
- default:
- $args .= 'Unknown';
+ $a = Str::pure2html(self::beautifulstr($a, 64, true, false));
+ $args .= "\"$a\"";
+ break;
+ case 'array':
+ $args .= 'array('.count($a).')';
+ break;
+ case 'object':
+ $args .= 'Object('.get_class($a).')';
+ break;
+ case 'resource':
+ $args .= 'Resource('.strstr($a, '#').')';
+ break;
+ case 'boolean':
+ $args .= $a ? 'true' : 'false';
+ break;
+ case 'NULL':
+ $args .= 'null';
+ break;
+ default:
+ $args .= 'Unknown';
}
}
$sFunctionInfo = "$sClass$sType$sFunction($args)";
}
- $aDigestCallStack[] = array('File'=>$sFile, 'Line'=>$sLine, 'Function'=>$sFunctionInfo);
+ $aDigestCallStack[] = ['File' => $sFile, 'Line' => $sLine, 'Function' => $sFunctionInfo];
}
return $aDigestCallStack;
}
@@ -311,9 +295,8 @@ class MyHelpers
public static function get_callstack_text($iLevelsToIgnore = 0, $aCallStack = null)
{
$aDigestCallStack = self::get_callstack($iLevelsToIgnore, $aCallStack);
- $aRes = array();
- foreach ($aDigestCallStack as $aCall)
- {
+ $aRes = [];
+ foreach ($aDigestCallStack as $aCall) {
$aRes[] = $aCall['File'].' at '.$aCall['Line'].', '.$aCall['Function'];
}
return implode("\n", $aRes);
@@ -325,21 +308,27 @@ class MyHelpers
///////////////////////////////////////////////////////////////////////////////
public static function make_table_from_assoc_array(&$aData)
{
- if (!is_array($aData)) throw new CoreException("make_table_from_assoc_array: Error - the passed argument is not an array");
+ if (!is_array($aData)) {
+ throw new CoreException("make_table_from_assoc_array: Error - the passed argument is not an array");
+ }
$aFirstRow = reset($aData);
- if (count($aData) == 0) return '';
- if (!is_array($aFirstRow)) throw new CoreException("make_table_from_assoc_array: Error - the passed argument is not a bi-dimensional array");
+ if (count($aData) == 0) {
+ return '';
+ }
+ if (!is_array($aFirstRow)) {
+ throw new CoreException("make_table_from_assoc_array: Error - the passed argument is not a bi-dimensional array");
+ }
$sOutput = "";
$sOutput .= "\n";
-
+
// Table header
//
$sOutput .= " \n";
- foreach ($aFirstRow as $fieldname=>$trash) {
+ foreach ($aFirstRow as $fieldname => $trash) {
$sOutput .= " ".$fieldname." \n";
}
$sOutput .= " \n";
-
+
// Table contents
//
$iCount = 0;
@@ -354,7 +343,7 @@ class MyHelpers
}
$sOutput .= " \n";
}
-
+
$sOutput .= "
\n";
return $sOutput;
}
@@ -368,7 +357,9 @@ class MyHelpers
}
public static function debug_breakpoint_notempty($arg)
{
- if (empty($arg)) return;
+ if (empty($arg)) {
+ return;
+ }
echo " Debug breakpoint (triggered on non-empty value) \n";
MyHelpers::var_dump_html($arg);
MyHelpers::dump_callstack();
@@ -381,7 +372,7 @@ class MyHelpers
*/
public static function xmlentities($string)
{
- return str_replace( array( '&', '"', "'", '<', '>' ), array ( '&' , '"', ''' , '<' , '>' ), $string );
+ return str_replace([ '&', '"', "'", '<', '>' ], [ '&' , '"', ''' , '<' , '>' ], $string);
}
/**
@@ -390,20 +381,24 @@ class MyHelpers
*/
public static function xmlencode($string)
{
- return xmlentities(iconv("UTF-8", "UTF-8//IGNORE",$string));
+ return xmlentities(iconv("UTF-8", "UTF-8//IGNORE", $string));
}
///////////////////////////////////////////////////////////////////////////////
// Source: New - format strings for output
// Last modif: 2005/01/18 RQU
///////////////////////////////////////////////////////////////////////////////
- public static function beautifulstr($sLongString, $iMaxLen, $bShowLen=false, $bShowTooltip=true)
+ public static function beautifulstr($sLongString, $iMaxLen, $bShowLen = false, $bShowTooltip = true)
{
- if (!is_string($sLongString)) throw new CoreException("beautifulstr: expect a string as 1st argument");
-
+ if (!is_string($sLongString)) {
+ throw new CoreException("beautifulstr: expect a string as 1st argument");
+ }
+
// Nothing to do if the string is short
- if (strlen($sLongString) <= $iMaxLen) return $sLongString;
-
+ if (strlen($sLongString) <= $iMaxLen) {
+ return $sLongString;
+ }
+
// Truncate the string
$sSuffix = "...";
if ($bShowLen) {
@@ -411,7 +406,7 @@ class MyHelpers
}
$sOutput = substr($sLongString, 0, $iMaxLen - strlen($sSuffix)).$sSuffix;
$sOutput = htmlspecialchars($sOutput);
-
+
// Add tooltip if required
//if ($bShowTooltip) {
// $oTooltip = new gui_tooltip($sLongString);
@@ -427,11 +422,11 @@ Utility class: static methods for cleaning & escaping untrusted (i.e.
user-supplied) strings.
Any string can (usually) be thought of as being in one of these 'modes':
pure = what the user actually typed / what you want to see on the page /
- what is actually stored in the DB
+ what is actually stored in the DB
gpc = incoming GET, POST or COOKIE data
sql = escaped for passing safely to RDBMS via SQL (also, data from DB
- queries and file reads if you have magic_quotes_runtime on--which
- is rare)
+ queries and file reads if you have magic_quotes_runtime on--which
+ is rare)
html = safe for html display (htmlentities applied)
Always knowing what mode your string is in--using these methods to
convert between modes--will prevent SQL injection and cross-site scripting.
@@ -456,8 +451,11 @@ class Str
}
public static function gpc2pure($gpc)
{
- if (ini_get('magic_quotes_sybase')) $pure = str_replace("''", "'", $gpc);
- else $pure = $gpc;
+ if (ini_get('magic_quotes_sybase')) {
+ $pure = str_replace("''", "'", $gpc);
+ } else {
+ $pure = $gpc;
+ }
return $pure;
}
public static function html2pure($html)
@@ -477,7 +475,9 @@ class Str
}
public static function pure2sql($pure, $maxLength = false)
{
- if ($maxLength) $pure = substr($pure, 0, $maxLength);
+ if ($maxLength) {
+ $pure = substr($pure, 0, $maxLength);
+ }
return (STR_SYBASE)
? str_replace("'", "''", $pure)
: addslashes($pure);
@@ -485,7 +485,9 @@ class Str
public static function sql2html($sql, $maxLength = false)
{
$pure = self::sql2pure($sql);
- if ($maxLength) $pure = substr($pure, 0, $maxLength);
+ if ($maxLength) {
+ $pure = substr($pure, 0, $maxLength);
+ }
return self::pure2html($pure);
}
public static function sql2pure($sql)
@@ -507,7 +509,7 @@ class Str
protected static function xmlentities($string)
{
- return str_replace( array( '&', '"', "'", '<', '>' ), array ( '&' , '"', ''' , '<' , '>' ), $string );
+ return str_replace([ '&', '"', "'", '<', '>' ], [ '&' , '"', ''' , '<' , '>' ], $string);
}
/**
@@ -516,7 +518,7 @@ class Str
*/
protected static function xmlencode($string)
{
- return self::xmlentities(iconv("UTF-8", "UTF-8//IGNORE",$string));
+ return self::xmlentities(iconv("UTF-8", "UTF-8//IGNORE", $string));
}
public static function islowcase($sString)
diff --git a/core/TemporaryObjectDescriptor.php b/core/TemporaryObjectDescriptor.php
index 9631fe2e6..5a0fd3a48 100644
--- a/core/TemporaryObjectDescriptor.php
+++ b/core/TemporaryObjectDescriptor.php
@@ -1,4 +1,5 @@
'core',
'key_type' => 'autoincrement',
- 'name_attcode' => array('item_class', 'temp_id'),
+ 'name_attcode' => ['item_class', 'temp_id'],
'image_attcode' => '',
'state_attcode' => '',
- 'reconc_keys' => array(''),
+ 'reconc_keys' => [''],
'db_table' => 'priv_temporary_object_descriptor',
'db_key_field' => 'id',
'db_finalclass_field' => '',
'style' => new ormStyle(null, null, null, null, null, null),
- 'indexes' => array(
+ 'indexes' => [
1 =>
- array(
+ [
0 => 'temp_id',
- ),
+ ],
2 =>
- array(
+ [
0 => 'item_class',
1 => 'item_id',
- ),
- ),
- );
+ ],
+ ],
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeDateTime('expiration_date', array('sql' => 'expiration_date', 'is_null_allowed' => false, 'default_value' => '', 'allowed_values' => null, 'depends_on' => array(), 'always_load_in_tables' => false)));
- MetaModel::Init_AddAttribute(new AttributeString('temp_id', array('sql' => 'temp_id', 'is_null_allowed' => true, 'default_value' => '', 'allowed_values' => null, 'depends_on' => array(), 'always_load_in_tables' => false)));
- MetaModel::Init_AddAttribute(new AttributeString('item_class', array('sql' => 'item_class', 'is_null_allowed' => false, 'default_value' => '', 'allowed_values' => null, 'depends_on' => array(), 'always_load_in_tables' => false)));
- MetaModel::Init_AddAttribute(new AttributeObjectKey('item_id', array('class_attcode' => 'item_class', 'sql' => 'item_id', 'is_null_allowed' => true, 'allowed_values' => null, 'depends_on' => array(), 'always_load_in_tables' => false)));
- MetaModel::Init_AddAttribute(new AttributeDateTime('creation_date', array('sql' => 'creation_date', 'is_null_allowed' => true, 'default_value' => '', 'allowed_values' => null, 'depends_on' => array(), 'always_load_in_tables' => false)));
- MetaModel::Init_AddAttribute(new AttributeString('host_class', array('sql' => 'host_class', 'is_null_allowed' => true, 'default_value' => '', 'allowed_values' => null, 'depends_on' => array(), 'always_load_in_tables' => false)));
- MetaModel::Init_AddAttribute(new AttributeObjectKey('host_id', array('class_attcode' => 'host_class', 'sql' => 'host_id', 'is_null_allowed' => true, 'allowed_values' => null, 'depends_on' => array(), 'always_load_in_tables' => false)));
- MetaModel::Init_AddAttribute(new AttributeString('host_att_code', array('sql' => 'host_att_code', 'is_null_allowed' => true, 'default_value' => '', 'allowed_values' => null, 'depends_on' => array(), 'always_load_in_tables' => false)));
- MetaModel::Init_AddAttribute(new AttributeEnum("operation", array("allowed_values" => new ValueSetEnum('create,delete'), "sql" => "operation", "default_value" => "create", "is_null_allowed" => true, "depends_on" => array())));
+ MetaModel::Init_AddAttribute(new AttributeDateTime('expiration_date', ['sql' => 'expiration_date', 'is_null_allowed' => false, 'default_value' => '', 'allowed_values' => null, 'depends_on' => [], 'always_load_in_tables' => false]));
+ MetaModel::Init_AddAttribute(new AttributeString('temp_id', ['sql' => 'temp_id', 'is_null_allowed' => true, 'default_value' => '', 'allowed_values' => null, 'depends_on' => [], 'always_load_in_tables' => false]));
+ MetaModel::Init_AddAttribute(new AttributeString('item_class', ['sql' => 'item_class', 'is_null_allowed' => false, 'default_value' => '', 'allowed_values' => null, 'depends_on' => [], 'always_load_in_tables' => false]));
+ MetaModel::Init_AddAttribute(new AttributeObjectKey('item_id', ['class_attcode' => 'item_class', 'sql' => 'item_id', 'is_null_allowed' => true, 'allowed_values' => null, 'depends_on' => [], 'always_load_in_tables' => false]));
+ MetaModel::Init_AddAttribute(new AttributeDateTime('creation_date', ['sql' => 'creation_date', 'is_null_allowed' => true, 'default_value' => '', 'allowed_values' => null, 'depends_on' => [], 'always_load_in_tables' => false]));
+ MetaModel::Init_AddAttribute(new AttributeString('host_class', ['sql' => 'host_class', 'is_null_allowed' => true, 'default_value' => '', 'allowed_values' => null, 'depends_on' => [], 'always_load_in_tables' => false]));
+ MetaModel::Init_AddAttribute(new AttributeObjectKey('host_id', ['class_attcode' => 'host_class', 'sql' => 'host_id', 'is_null_allowed' => true, 'allowed_values' => null, 'depends_on' => [], 'always_load_in_tables' => false]));
+ MetaModel::Init_AddAttribute(new AttributeString('host_att_code', ['sql' => 'host_att_code', 'is_null_allowed' => true, 'default_value' => '', 'allowed_values' => null, 'depends_on' => [], 'always_load_in_tables' => false]));
+ MetaModel::Init_AddAttribute(new AttributeEnum("operation", ["allowed_values" => new ValueSetEnum('create,delete'), "sql" => "operation", "default_value" => "create", "is_null_allowed" => true, "depends_on" => []]));
- MetaModel::Init_SetZListItems('details', array(
+ MetaModel::Init_SetZListItems('details', [
0 => 'temp_id',
1 => 'item_class',
2 => 'item_id',
3 => 'creation_date',
4 => 'expiration_date',
5 => 'meta',
- ));
- MetaModel::Init_SetZListItems('standard_search', array(
+ ]);
+ MetaModel::Init_SetZListItems('standard_search', [
0 => 'temp_id',
1 => 'item_class',
2 => 'item_id',
- ));
- MetaModel::Init_SetZListItems('list', array(
+ ]);
+ MetaModel::Init_SetZListItems('list', [
0 => 'temp_id',
1 => 'item_class',
2 => 'item_id',
3 => 'creation_date',
4 => 'expiration_date',
- ));;
+ ]);
+ ;
}
-
public function DBInsertNoReload()
{
$this->SetCurrentDateIfNull('creation_date');
@@ -82,7 +83,6 @@ class TemporaryObjectDescriptor extends DBObject
return parent::DBInsertNoReload();
}
-
/**
* Set/Update all of the '_item' fields
*
diff --git a/core/action.class.inc.php b/core/action.class.inc.php
index 62f2e8ad5..74820bcf9 100644
--- a/core/action.class.inc.php
+++ b/core/action.class.inc.php
@@ -1,9 +1,10 @@
"grant_by_profile,core/cmdb",
"key_type" => "autoincrement",
"name_attcode" => "name",
@@ -59,14 +59,14 @@ abstract class Action extends cmdbAbstractObject
"db_key_field" => "id",
"db_finalclass_field" => "realclass",
"style" => new ormStyle("ibo-dm-class--Action", "ibo-dm-class-alt--Action", "var(--ibo-dm-class--Action--main-color)", "var(--ibo-dm-class--Action--complementary-color)", null, '../images/icons/icons8-in-transit.svg'),
- );
+ ];
MetaModel::Init_Params($aParams);
//MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeString("name", array("allowed_values" => null, "sql" => "name", "default_value" => null, "is_null_allowed" => false, "depends_on" => array())));
- MetaModel::Init_AddAttribute(new AttributeString("description", array("allowed_values" => null, "sql" => "description", "default_value" => null, "is_null_allowed" => true, "depends_on" => array())));
+ MetaModel::Init_AddAttribute(new AttributeString("name", ["allowed_values" => null, "sql" => "name", "default_value" => null, "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeString("description", ["allowed_values" => null, "sql" => "description", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
- MetaModel::Init_AddAttribute(new AttributeEnum("status", array(
- "allowed_values" => new ValueSetEnum(array('test' => 'Being tested', 'enabled' => 'In production', 'disabled' => 'Inactive')),
+ MetaModel::Init_AddAttribute(new AttributeEnum("status", [
+ "allowed_values" => new ValueSetEnum(['test' => 'Being tested', 'enabled' => 'In production', 'disabled' => 'Inactive']),
"styled_values" => [
'test' => new ormStyle('ibo-dm-enum--Action-status-test', 'ibo-dm-enum-alt--Action-status-test', 'var(--ibo-dm-enum--Action-status-test--main-color)', 'var(--ibo-dm-enum--Action-status-test--complementary-color)', null, null),
'enabled' => new ormStyle('ibo-dm-enum--Action-status-enabled', 'ibo-dm-enum-alt--Action-status-enabled', 'var(--ibo-dm-enum--Action-status-enabled--main-color)', 'var(--ibo-dm-enum--Action-status-enabled--complementary-color)', 'fas fa-check', null),
@@ -76,21 +76,23 @@ abstract class Action extends cmdbAbstractObject
"sql" => "status",
"default_value" => "test",
"is_null_allowed" => false,
- "depends_on" => array(),
- )));
+ "depends_on" => [],
+ ]));
- MetaModel::Init_AddAttribute(new AttributeLinkedSetIndirect("trigger_list",
- array("linked_class" => "lnkTriggerAction", "ext_key_to_me" => "action_id", "ext_key_to_remote" => "trigger_id", "allowed_values" => null, "count_min" => 0, "count_max" => 0, "depends_on" => array(), "display_style" => 'property')));
- MetaModel::Init_AddAttribute(new AttributeEnum("asynchronous", array("allowed_values" => new ValueSetEnum(['use_global_setting' => 'Use global settings','yes' => 'Yes' ,'no' => 'No']), "sql" => "asynchronous", "default_value" => 'use_global_setting', "is_null_allowed" => false, "depends_on" => array())));
+ MetaModel::Init_AddAttribute(new AttributeLinkedSetIndirect(
+ "trigger_list",
+ ["linked_class" => "lnkTriggerAction", "ext_key_to_me" => "action_id", "ext_key_to_remote" => "trigger_id", "allowed_values" => null, "count_min" => 0, "count_max" => 0, "depends_on" => [], "display_style" => 'property']
+ ));
+ MetaModel::Init_AddAttribute(new AttributeEnum("asynchronous", ["allowed_values" => new ValueSetEnum(['use_global_setting' => 'Use global settings','yes' => 'Yes' ,'no' => 'No']), "sql" => "asynchronous", "default_value" => 'use_global_setting', "is_null_allowed" => false, "depends_on" => []]));
// Display lists
// - Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('details', array('name', 'description', 'status', 'trigger_list'));
+ MetaModel::Init_SetZListItems('details', ['name', 'description', 'status', 'trigger_list']);
// - Attributes to be displayed for a list
- MetaModel::Init_SetZListItems('list', array('finalclass', 'name', 'description', 'status'));
+ MetaModel::Init_SetZListItems('list', ['finalclass', 'name', 'description', 'status']);
// Search criteria
// - Default criteria of the search form
- MetaModel::Init_SetZListItems('default_search', array('name', 'description', 'status'));
+ MetaModel::Init_SetZListItems('default_search', ['name', 'description', 'status']);
}
@@ -111,8 +113,7 @@ abstract class Action extends cmdbAbstractObject
*/
public function IsActive()
{
- switch($this->Get('status'))
- {
+ switch ($this->Get('status')) {
case 'enabled':
case 'test':
return true;
@@ -131,8 +132,7 @@ abstract class Action extends cmdbAbstractObject
*/
public function IsBeingTested()
{
- switch($this->Get('status'))
- {
+ switch ($this->Get('status')) {
case 'test':
return true;
@@ -220,7 +220,7 @@ abstract class Action extends cmdbAbstractObject
$iLastExecutionDays = $oConfig->Get($sLastExecutionDaysConfigParamName);
if ($iLastExecutionDays < 0) {
- throw new InvalidConfigParamException("Invalid value for {$sLastExecutionDaysConfigParamName} config parameter. Param desc: " . $oConfig->GetDescription($sLastExecutionDaysConfigParamName));
+ throw new InvalidConfigParamException("Invalid value for {$sLastExecutionDaysConfigParamName} config parameter. Param desc: ".$oConfig->GetDescription($sLastExecutionDaysConfigParamName));
}
$sActionQueryOql = 'SELECT EventNotification WHERE action_id = :action_id';
@@ -250,7 +250,7 @@ abstract class Action extends cmdbAbstractObject
*/
public static function GetAsynchronousGlobalSetting(): bool
{
- return false;
+ return false;
}
/**
@@ -270,7 +270,7 @@ abstract class Action extends cmdbAbstractObject
}
/**
- * A notification
+ * A notification
*
* @package iTopORM
*/
@@ -282,8 +282,8 @@ abstract class ActionNotification extends Action
*/
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "grant_by_profile,core/cmdb",
"key_type" => "autoincrement",
"name_attcode" => "name",
@@ -293,22 +293,22 @@ abstract class ActionNotification extends Action
"db_table" => "priv_action_notification",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
// Display lists
// - Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('details', array('name', 'description', 'status', 'trigger_list'));
+ MetaModel::Init_SetZListItems('details', ['name', 'description', 'status', 'trigger_list']);
// - Attributes to be displayed for a list
- MetaModel::Init_SetZListItems('list', array('finalclass', 'description', 'status'));
- MetaModel::Init_AddAttribute(new AttributeApplicationLanguage("language", array("sql"=>"language", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
+ MetaModel::Init_SetZListItems('list', ['finalclass', 'description', 'status']);
+ MetaModel::Init_AddAttribute(new AttributeApplicationLanguage("language", ["sql" => "language", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
// Search criteria
// - Criteria of the std search form
-// MetaModel::Init_SetZListItems('standard_search', array('name'));
+ // MetaModel::Init_SetZListItems('standard_search', array('name'));
// - Default criteria of the search form
-// MetaModel::Init_SetZListItems('default_search', array('name'));
+ // MetaModel::Init_SetZListItems('default_search', array('name'));
}
/**
@@ -321,7 +321,8 @@ abstract class ActionNotification extends Action
* @throws \DictExceptionUnknownLanguage
* @since 3.2.0
*/
- public function SetNotificationLanguage($sLanguage = null, $sLanguageCode = null){
+ public function SetNotificationLanguage($sLanguage = null, $sLanguageCode = null)
+ {
$sPreviousLanguage = Dict::GetUserLanguage();
$aPreviousPluginProperties = ApplicationContext::GetPluginProperties('QueryLocalizerPlugin');
$sLanguage = $sLanguage ?? $this->Get('language');
@@ -338,7 +339,7 @@ abstract class ActionNotification extends Action
}
/**
- * An email notification
+ * An email notification
*
* @package iTopORM
*/
@@ -348,69 +349,68 @@ class ActionEmail extends ActionNotification
* @var string
* @since 3.0.1
*/
- const ENUM_HEADER_NAME_MESSAGE_ID = 'Message-ID';
+ public const ENUM_HEADER_NAME_MESSAGE_ID = 'Message-ID';
/**
* @var string
* @since 3.0.1
*/
- const ENUM_HEADER_NAME_REFERENCES = 'References';
+ public const ENUM_HEADER_NAME_REFERENCES = 'References';
/**
* @var string
* @since 3.1.0
*/
- const TEMPLATE_BODY_CONTENT = '$content$';
+ public const TEMPLATE_BODY_CONTENT = '$content$';
/**
* Wraps the 'body' of the message for previewing inside an IFRAME -- i.e. without any of the iTop stylesheets being applied
* @var string
* @since 3.1.0
*/
- const CONTENT_HIGHLIGHT = '';
+ public const CONTENT_HIGHLIGHT = '';
/**
* Wraps a placeholder of the email's body for previewing inside an IFRAME -- i.e. without any of the iTop stylesheets being applied
* @var string
*/
- const FIELD_HIGHLIGHT = '\\$$1\\$ ';
+ public const FIELD_HIGHLIGHT = '\\$$1\\$ ';
/**
* @inheritDoc
*/
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "grant_by_profile,core/cmdb,application",
"key_type" => "autoincrement",
"name_attcode" => "name",
"state_attcode" => "",
- "reconc_keys" => array('name'),
+ "reconc_keys" => ['name'],
"db_table" => "priv_action_email",
"db_key_field" => "id",
"db_finalclass_field" => "",
'style' => new ormStyle(null, null, null, null, null, '../images/icons/icons8-mailing.svg'),
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeEmailAddress("test_recipient", array("allowed_values" => null, "sql" => "test_recipient", "default_value" => "", "is_null_allowed" => true, "depends_on" => array())));
+ MetaModel::Init_AddAttribute(new AttributeEmailAddress("test_recipient", ["allowed_values" => null, "sql" => "test_recipient", "default_value" => "", "is_null_allowed" => true, "depends_on" => []]));
- MetaModel::Init_AddAttribute(new AttributeString("from", array("allowed_values" => null, "sql" => "from", "default_value" => null, "is_null_allowed" => false, "depends_on" => array())));
- MetaModel::Init_AddAttribute(new AttributeString("from_label", array("allowed_values" => null, "sql" => "from_label", "default_value" => null, "is_null_allowed" => true, "depends_on" => array())));
- MetaModel::Init_AddAttribute(new AttributeString("reply_to", array("allowed_values" => null, "sql" => "reply_to", "default_value" => null, "is_null_allowed" => true, "depends_on" => array())));
- MetaModel::Init_AddAttribute(new AttributeString("reply_to_label", array("allowed_values" => null, "sql" => "reply_to_label", "default_value" => null, "is_null_allowed" => true, "depends_on" => array())));
- MetaModel::Init_AddAttribute(new AttributeOQL("to", array("allowed_values" => null, "sql" => "to", "default_value" => null, "is_null_allowed" => true, "depends_on" => array())));
- MetaModel::Init_AddAttribute(new AttributeOQL("cc", array("allowed_values" => null, "sql" => "cc", "default_value" => null, "is_null_allowed" => true, "depends_on" => array())));
- MetaModel::Init_AddAttribute(new AttributeOQL("bcc", array("allowed_values" => null, "sql" => "bcc", "default_value" => null, "is_null_allowed" => true, "depends_on" => array())));
- MetaModel::Init_AddAttribute(new AttributeTemplateString("subject", array("allowed_values" => null, "sql" => "subject", "default_value" => null, "is_null_allowed" => false, "depends_on" => array())));
- MetaModel::Init_AddAttribute(new AttributeTemplateHTML("body", array("allowed_values" => null, "sql" => "body", "default_value" => null, "is_null_allowed" => false, "depends_on" => array())));
- MetaModel::Init_AddAttribute(new AttributeEnum("importance", array("allowed_values" => new ValueSetEnum('low,normal,high'), "sql" => "importance", "default_value" => 'normal', "is_null_allowed" => false, "depends_on" => array())));
- MetaModel::Init_AddAttribute(new AttributeBlob("html_template", array("is_null_allowed"=>true, "depends_on"=>array(), "always_load_in_tables"=>false)));
- MetaModel::Init_AddAttribute(new AttributeEnum("ignore_notify", array("allowed_values" => new ValueSetEnum('yes,no'), "sql" => "ignore_notify", "default_value" => 'yes', "is_null_allowed" => false, "depends_on" => array())));
-
+ MetaModel::Init_AddAttribute(new AttributeString("from", ["allowed_values" => null, "sql" => "from", "default_value" => null, "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeString("from_label", ["allowed_values" => null, "sql" => "from_label", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeString("reply_to", ["allowed_values" => null, "sql" => "reply_to", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeString("reply_to_label", ["allowed_values" => null, "sql" => "reply_to_label", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeOQL("to", ["allowed_values" => null, "sql" => "to", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeOQL("cc", ["allowed_values" => null, "sql" => "cc", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeOQL("bcc", ["allowed_values" => null, "sql" => "bcc", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeTemplateString("subject", ["allowed_values" => null, "sql" => "subject", "default_value" => null, "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeTemplateHTML("body", ["allowed_values" => null, "sql" => "body", "default_value" => null, "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeEnum("importance", ["allowed_values" => new ValueSetEnum('low,normal,high'), "sql" => "importance", "default_value" => 'normal', "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeBlob("html_template", ["is_null_allowed" => true, "depends_on" => [], "always_load_in_tables" => false]));
+ MetaModel::Init_AddAttribute(new AttributeEnum("ignore_notify", ["allowed_values" => new ValueSetEnum('yes,no'), "sql" => "ignore_notify", "default_value" => 'yes', "is_null_allowed" => false, "depends_on" => []]));
// Display lists
// - Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('details', array(
- 'col:col1' => array(
- 'fieldset:ActionEmail:main' => array(
+ MetaModel::Init_SetZListItems('details', [
+ 'col:col1' => [
+ 'fieldset:ActionEmail:main' => [
0 => 'name',
1 => 'description',
2 => 'status',
@@ -419,14 +419,14 @@ class ActionEmail extends ActionNotification
5 => 'subject',
6 => 'body',
// 5 => 'importance', not handled when sending the mail, better hide it then
- ),
- 'fieldset:ActionEmail:trigger' => array(
+ ],
+ 'fieldset:ActionEmail:trigger' => [
0 => 'trigger_list',
- 1 => 'asynchronous'
- ),
- ),
- 'col:col2' => array(
- 'fieldset:ActionEmail:recipients' => array(
+ 1 => 'asynchronous',
+ ],
+ ],
+ 'col:col2' => [
+ 'fieldset:ActionEmail:recipients' => [
0 => 'from',
1 => 'from_label',
2 => 'reply_to',
@@ -436,17 +436,17 @@ class ActionEmail extends ActionNotification
6 => 'to',
7 => 'cc',
8 => 'bcc',
- ),
- ),
- ));
+ ],
+ ],
+ ]);
// - Attributes to be displayed for a list
- MetaModel::Init_SetZListItems('list', array('status', 'to', 'subject', 'language'));
+ MetaModel::Init_SetZListItems('list', ['status', 'to', 'subject', 'language']);
// Search criteria
// - Standard criteria of the search
- MetaModel::Init_SetZListItems('standard_search', array('name', 'description', 'status', 'subject', 'language'));
+ MetaModel::Init_SetZListItems('standard_search', ['name', 'description', 'status', 'subject', 'language']);
// - Default criteria for the search
- MetaModel::Init_SetZListItems('default_search', array('name', 'description', 'status', 'subject', 'language'));
+ MetaModel::Init_SetZListItems('default_search', ['name', 'description', 'status', 'subject', 'language']);
}
// count the recipients found
@@ -477,10 +477,11 @@ class ActionEmail extends ActionNotification
{
$oTrigger = $aArgs['trigger->object()'] ?? null;
$sOQL = $this->Get($sRecipAttCode);
- if (utils::IsNullOrEmptyString($sOQL)) return '';
+ if (utils::IsNullOrEmptyString($sOQL)) {
+ return '';
+ }
- try
- {
+ try {
$oSearch = DBObjectSearch::FromOQL($sOQL);
if ($this->Get('ignore_notify') === 'no') {
// In theory, it is possible to notify *any* kind of object,
@@ -492,31 +493,26 @@ class ActionEmail extends ActionNotification
}
}
$oSearch->AllowAllData();
- }
- catch (OQLException $e)
- {
+ } catch (OQLException $e) {
$this->m_aMailErrors[] = "query syntax error for recipient '$sRecipAttCode'";
return $e->getMessage();
}
$sClass = $oSearch->GetClass();
// Determine the email attribute (the first one will be our choice)
- foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
- {
- if ($oAttDef instanceof AttributeEmailAddress)
- {
+ foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) {
+ if ($oAttDef instanceof AttributeEmailAddress) {
$sEmailAttCode = $sAttCode;
// we've got one, exit the loop
break;
}
}
- if (!isset($sEmailAttCode))
- {
+ if (!isset($sEmailAttCode)) {
$this->m_aMailErrors[] = "wrong target for recipient '$sRecipAttCode'";
return "The objects of the class '$sClass' do not have any email attribute";
}
- if($oTrigger !== null && in_array('Contact', MetaModel::EnumParentClasses($sClass, ENUM_CHILD_CLASSES_ALL), true)) {
+ if ($oTrigger !== null && in_array('Contact', MetaModel::EnumParentClasses($sClass, ENUM_CHILD_CLASSES_ALL), true)) {
$aArgs['trigger_id'] = $oTrigger->GetKey();
$aArgs['action_id'] = $this->GetKey();
@@ -526,13 +522,11 @@ class ActionEmail extends ActionNotification
$oSearch->AddConditionExpression(Expression::FromOQL("`$sAlias`.id NOT IN ($sSubscribedContactsOQL)"));
}
- $oSet = new DBObjectSet($oSearch, array() /* order */, $aArgs);
- $aRecipients = array();
- while ($oObj = $oSet->Fetch())
- {
+ $oSet = new DBObjectSet($oSearch, [] /* order */, $aArgs);
+ $aRecipients = [];
+ while ($oObj = $oSet->Fetch()) {
$sAddress = trim($oObj->Get($sEmailAttCode));
- if (utils::IsNotNullOrEmptyString($sAddress))
- {
+ if (utils::IsNotNullOrEmptyString($sAddress)) {
$aRecipients[] = $sAddress;
$this->m_iRecipients++;
}
@@ -551,68 +545,51 @@ class ActionEmail extends ActionNotification
*/
public function DoExecute($oTrigger, $aContextArgs)
{
- if (MetaModel::IsLogEnabledNotification())
- {
+ if (MetaModel::IsLogEnabledNotification()) {
$oLog = new EventNotificationEmail();
- if ($this->IsBeingTested())
- {
+ if ($this->IsBeingTested()) {
$oLog->Set('message', 'TEST - Notification sent ('.$this->Get('test_recipient').')');
- }
- else
- {
+ } else {
$oLog->Set('message', 'Notification pending');
}
$oLog->Set('userinfo', UserRights::GetUser());
$oLog->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();
- }
- else
- {
+ } else {
$oLog = null;
}
- try
- {
+ try {
$sRes = $this->_DoExecute($oTrigger, $aContextArgs, $oLog);
- if ($this->IsBeingTested())
- {
+ if ($this->IsBeingTested()) {
$sPrefix = 'TEST ('.$this->Get('test_recipient').') - ';
- }
- else
- {
+ } else {
$sPrefix = '';
}
- if ($oLog)
- {
- $oLog->Set('message', $sPrefix . $sRes);
- $oLog->DBUpdate();
- }
+ if ($oLog) {
+ $oLog->Set('message', $sPrefix.$sRes);
+ $oLog->DBUpdate();
+ }
- }
- catch (Exception $e)
- {
- if ($oLog)
- {
+ } catch (Exception $e) {
+ if ($oLog) {
$oLog->Set('message', 'Error: '.$e->getMessage());
- try
- {
- $oLog->DBUpdate();
- }
- catch (Exception $eSecondTryUpdate)
- {
- IssueLog::Error("Failed to process email ".$oLog->GetKey()." - reason: ".$e->getMessage()."\nTrace:\n".$e->getTraceAsString());
+ try {
+ $oLog->DBUpdate();
+ } catch (Exception $eSecondTryUpdate) {
+ IssueLog::Error("Failed to process email ".$oLog->GetKey()." - reason: ".$e->getMessage()."\nTrace:\n".$e->getTraceAsString());
- $oLog->Set('message', 'Error: more details in the log for email "'.$oLog->GetKey().'"');
- $oLog->DBUpdate();
- }
+ $oLog->Set('message', 'Error: more details in the log for email "'.$oLog->GetKey().'"');
+ $oLog->DBUpdate();
+ }
}
}
@@ -629,11 +606,11 @@ class ActionEmail extends ActionNotification
*/
protected function _DoExecute($oTrigger, $aContextArgs, &$oLog)
{
- $sStyles = file_get_contents(APPROOT . utils::GetCSSFromSASS("css/email.scss"));
+ $sStyles = file_get_contents(APPROOT.utils::GetCSSFromSASS("css/email.scss"));
$sStyles .= MetaModel::GetConfig()->Get('email_css');
-
+
$oEmail = new EMail();
-
+
$aEmailContent = $this->PrepareMessageContent($aContextArgs, $oLog);
$oEmail->SetSubject($aEmailContent['subject']);
$oEmail->SetBody($aEmailContent['body'], 'text/html', $sStyles);
@@ -645,23 +622,18 @@ class ActionEmail extends ActionNotification
$oEmail->SetReferences($aEmailContent['references']);
$oEmail->SetMessageId($aEmailContent['message_id']);
$oEmail->SetInReplyTo($aEmailContent['in_reply_to']);
-
- foreach($aEmailContent['attachments'] as $aAttachment) {
+
+ foreach ($aEmailContent['attachments'] as $aAttachment) {
$oEmail->AddAttachment($aAttachment['data'], $aAttachment['filename'], $aAttachment['mime_type']);
}
-
- if (empty($this->m_aMailErrors))
- {
- if ($this->m_iRecipients == 0)
- {
+
+ if (empty($this->m_aMailErrors)) {
+ if ($this->m_iRecipients == 0) {
return 'No recipient';
- }
- else
- {
+ } else {
$aErrors = [];
$iRes = $oEmail->Send($aErrors, $this->IsAsynchronous() ? Email::ENUM_SEND_FORCE_ASYNCHRONOUS : Email::ENUM_SEND_FORCE_SYNCHRONOUS, $oLog);
- switch ($iRes)
- {
+ switch ($iRes) {
case EMAIL_SEND_OK:
return "Sent";
@@ -721,39 +693,36 @@ class ActionEmail extends ActionNotification
$sPreviousUrlMaker = ApplicationContext::SetUrlMakerClass();
[$sPreviousLanguage, $aPreviousPluginProperties] = $this->SetNotificationLanguage();
- try
- {
+ try {
$this->m_iRecipients = 0;
- $this->m_aMailErrors = array();
-
+ $this->m_aMailErrors = [];
+
// Determine recipients
//
$aMessageContent['to'] = $this->FindRecipients('to', $aContextArgs);
$aMessageContent['cc'] = $this->FindRecipients('cc', $aContextArgs);
$aMessageContent['bcc'] = $this->FindRecipients('bcc', $aContextArgs);
-
+
$aMessageContent['from'] = MetaModel::ApplyParams($this->Get('from'), $aContextArgs);
$aMessageContent['from_label'] = MetaModel::ApplyParams($this->Get('from_label'), $aContextArgs);
$aMessageContent['reply_to'] = MetaModel::ApplyParams($this->Get('reply_to'), $aContextArgs);
$aMessageContent['reply_to_label'] = MetaModel::ApplyParams($this->Get('reply_to_label'), $aContextArgs);
-
+
$aMessageContent['subject'] = MetaModel::ApplyParams($this->Get('subject'), $aContextArgs);
$sBody = $this->BuildMessageBody(false);
$aMessageContent['body'] = MetaModel::ApplyParams($sBody, $aContextArgs);
-
+
$oObj = $aContextArgs['this->object()'];
$aMessageContent['message_id'] = $this->GenerateIdentifierForHeaders($oObj, static::ENUM_HEADER_NAME_MESSAGE_ID);
$aMessageContent['references'] = $this->GenerateIdentifierForHeaders($oObj, static::ENUM_HEADER_NAME_REFERENCES);
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
/** @noinspection PhpUnhandledExceptionInspection */
throw $e;
- }
- finally {
+ } finally {
ApplicationContext::SetUrlMakerClass($sPreviousUrlMaker);
$this->SetNotificationLanguage($sPreviousLanguage, $aPreviousPluginProperties['language_code'] ?? null);
}
-
+
if (!is_null($oLog)) {
// Note: we have to secure this because those values are calculated
// inside the try statement, and we would like to keep track of as
@@ -802,19 +771,17 @@ class ActionEmail extends ActionNotification
}
// Note: N°4849 We pass the "References" identifier instead of the "Message-ID" on purpose as we want notifications emails to group around the triggering iTop object, not just the users' replies to the notification
$aMessageContent['in_reply_to'] = $aMessageContent['references'];
-
- if (isset($aContextArgs['attachments']))
- {
- $aAttachmentReport = array();
+
+ if (isset($aContextArgs['attachments'])) {
+ $aAttachmentReport = [];
/** @var \ormDocument $oDocument */
- foreach($aContextArgs['attachments'] as $oDocument)
- {
+ foreach ($aContextArgs['attachments'] as $oDocument) {
$aMessageContent['attachments'][] = ['data' => $oDocument->GetData(), 'filename' => $oDocument->GetFileName(), 'mime_type' => $oDocument->GetMimeType()];
- $aAttachmentReport[] = array($oDocument->GetFileName(), $oDocument->GetMimeType(), strlen($oDocument->GetData() ?? ''));
+ $aAttachmentReport[] = [$oDocument->GetFileName(), $oDocument->GetMimeType(), strlen($oDocument->GetData() ?? '')];
}
$oLog->Set('attachments', $aAttachmentReport);
}
-
+
return $aMessageContent;
}
@@ -859,11 +826,11 @@ class ActionEmail extends ActionNotification
]);
throw new Exception($sErrorMessage);
}
-
+
/**
* Compose the body of the message from the 'body' attribute and the HTML template (if any)
* @since 3.1.0 N°4849
- * @param bool $bHighlightPlaceholders If true add some extra HTML around placeholders to highlight them
+ * @param bool $bHighlightPlaceholders If true add some extra HTML around placeholders to highlight them
* @return string
*/
protected function BuildMessageBody(bool $bHighlightPlaceholders = false): string
@@ -889,13 +856,13 @@ HTML;
$sBody = $oHtmlTemplate->GetData();
}
}
- if($bHighlightPlaceholders) {
+ if ($bHighlightPlaceholders) {
// Highlight all placeholders
$sBody = preg_replace('/\\$([^$]+)\\$/', static::FIELD_HIGHLIGHT, $sBody);
}
return $sBody;
}
-
+
/**
* @since 3.1.0 N°4849
* @inheritDoc
diff --git a/core/apc-compat.php b/core/apc-compat.php
index 6412a2673..0e0488fc9 100644
--- a/core/apc-compat.php
+++ b/core/apc-compat.php
@@ -1,9 +1,10 @@
getNumberOfParameters() != 2)
- {
+ if ($oFunction->getNumberOfParameters() != 2) {
// Beware: APCu behaves slightly differently from APC !!
// Worse: the compatibility layer integrated into APC differs from apcu-bc (testing the number of parameters is a must)
// In CLI mode (PHP > 7) apc_cache_info returns null and outputs an error message.
$aCacheUserData = @apc_cache_info();
- }
- else
- {
+ } else {
$aCacheUserData = @apc_cache_info('user');
}
return $aCacheUserData;
}
// Cache emulation
-if (!function_exists('apc_store'))
-{
+if (!function_exists('apc_store')) {
require_once(APPROOT.'core/apc-emulation.php');
-}
\ No newline at end of file
+}
diff --git a/core/apc-emulation.php b/core/apc-emulation.php
index 33214a911..a1bcad7bb 100644
--- a/core/apc-emulation.php
+++ b/core/apc-emulation.php
@@ -1,4 +1,5 @@
$value)
- {
+ if (is_array($key)) {
+ $aResult = [];
+ foreach ($key as $sKey => $value) {
$aResult[] = apcFile::StoreOneFile($sKey, $value, $ttl);
}
return $aResult;
@@ -89,8 +88,7 @@ function apc_clear_cache($cache_type = '')
*/
function apc_delete($key)
{
- if (empty($key))
- {
+ if (empty($key)) {
return false;
}
$bRet1 = apcFile::DeleteEntry(apcFile::GetCacheFileName($key));
@@ -126,17 +124,17 @@ function apc_exists($keys)
class apcFile
{
// Check only once per request
- static public $aFilesByTime = null;
- static public $iFileCount = 0;
+ public static $aFilesByTime = null;
+ public static $iFileCount = 0;
/** Get the file name corresponding to the cache entry.
* If an empty key is provided, the root of the cache is returned.
* @param $sKey
* @return string
*/
- static public function GetCacheFileName($sKey = '')
+ public static function GetCacheFileName($sKey = '')
{
- $sPath = str_replace(array(' ', '/', '\\', '.'), '-', $sKey ?? '');
+ $sPath = str_replace([' ', '/', '\\', '.'], '-', $sKey ?? '');
return utils::GetCachePath().'apc-emul/'.$sPath;
}
@@ -144,26 +142,21 @@ class apcFile
* @param $sEntry string starting folder.
* @return array list of entries stored into array of key 'info'
*/
- static public function GetCacheEntries($sEntry)
+ public static function GetCacheEntries($sEntry)
{
- $aResult = array();
- if (is_dir($sEntry))
- {
- $aFiles = array_diff(scandir($sEntry), array('.', '..'));
- foreach($aFiles as $sFile)
- {
+ $aResult = [];
+ if (is_dir($sEntry)) {
+ $aFiles = array_diff(scandir($sEntry), ['.', '..']);
+ foreach ($aFiles as $sFile) {
$sSubFile = $sEntry.'/'.$sFile;
$aResult = array_merge($aResult, self::GetCacheEntries($sSubFile));
}
- }
- else
- {
+ } else {
$sKey = basename($sEntry);
- if (strpos($sKey, '-') === 0)
- {
+ if (strpos($sKey, '-') === 0) {
$sKey = substr($sKey, 1);
}
- $aResult[] = array('info' => $sKey);
+ $aResult[] = ['info' => $sKey];
}
return $aResult;
}
@@ -172,35 +165,25 @@ class apcFile
* @param $sCache
* @return bool true if the entry was deleted false if error occurs (like entry did not exist).
*/
- static public function DeleteEntry($sCache)
+ public static function DeleteEntry($sCache)
{
- if (is_dir($sCache))
- {
- $aFiles = array_diff(scandir($sCache), array('.', '..'));
- foreach($aFiles as $sFile)
- {
+ if (is_dir($sCache)) {
+ $aFiles = array_diff(scandir($sCache), ['.', '..']);
+ foreach ($aFiles as $sFile) {
$sSubFile = $sCache.'/'.$sFile;
- if (!self::DeleteEntry($sSubFile))
- {
+ if (!self::DeleteEntry($sSubFile)) {
return false;
}
}
- if (!@rmdir($sCache))
- {
+ if (!@rmdir($sCache)) {
return false;
}
- }
- else
- {
- if (is_file($sCache))
- {
- if (!@unlink($sCache))
- {
+ } else {
+ if (is_file($sCache)) {
+ if (!@unlink($sCache)) {
return false;
}
- }
- else
- {
+ } else {
return false;
}
}
@@ -215,23 +198,22 @@ class apcFile
* @return bool
* @since 3.2.0 N°7068
*/
- static public function ExistsOneFile($sKey) {
- return is_file(self::GetCacheFileName('-' . $sKey)) || is_file(self::GetCacheFileName($sKey));
+ public static function ExistsOneFile($sKey)
+ {
+ return is_file(self::GetCacheFileName('-'.$sKey)) || is_file(self::GetCacheFileName($sKey));
}
/** Get one cache entry content.
* @param $sKey
* @return bool|mixed
*/
- static public function FetchOneFile($sKey)
+ public static function FetchOneFile($sKey)
{
// Try the 'TTLed' version
$sValue = self::ReadCacheLocked(self::GetCacheFileName('-'.$sKey));
- if ($sValue === false)
- {
+ if ($sValue === false) {
$sValue = self::ReadCacheLocked(self::GetCacheFileName($sKey));
- if ($sValue === false)
- {
+ if ($sValue === false) {
return false;
}
}
@@ -245,7 +227,7 @@ class apcFile
* @param int $iTTL time to live
* @return bool
*/
- static public function StoreOneFile($sKey, $value, $iTTL)
+ public static function StoreOneFile($sKey, $value, $iTTL)
{
if (empty($sKey)) {
return false;
@@ -279,40 +261,31 @@ class apcFile
* remove older files if the mamximum is reached.
* @param $sNewFilename
*/
- static protected function AddFile($sNewFilename)
+ protected static function AddFile($sNewFilename)
{
- if (strpos(basename($sNewFilename), '-') !== 0)
- {
+ if (strpos(basename($sNewFilename), '-') !== 0) {
return;
}
$iMaxFiles = MetaModel::GetConfig()->Get('apc_cache_emulation.max_entries');
- if ($iMaxFiles == 0)
- {
+ if ($iMaxFiles == 0) {
return;
}
- if (!self::$aFilesByTime)
- {
+ if (!self::$aFilesByTime) {
self::ListFilesByTime();
self::$iFileCount = count(self::$aFilesByTime);
- if ($iMaxFiles !== 0)
- {
+ if ($iMaxFiles !== 0) {
asort(self::$aFilesByTime);
}
- }
- else
- {
+ } else {
self::$aFilesByTime[$sNewFilename] = time();
self::$iFileCount++;
}
- if (self::$iFileCount > $iMaxFiles)
- {
+ if (self::$iFileCount > $iMaxFiles) {
$iFileNbToRemove = self::$iFileCount - $iMaxFiles;
- foreach(self::$aFilesByTime as $sFileToRemove => $iTime)
- {
+ foreach (self::$aFilesByTime as $sFileToRemove => $iTime) {
@unlink($sFileToRemove);
- if (--$iFileNbToRemove === 0)
- {
+ if (--$iFileNbToRemove === 0) {
break;
}
}
@@ -324,25 +297,19 @@ class apcFile
/** Get the list of files with their associated access time
* @param string $sCheck Directory to scan
*/
- static protected function ListFilesByTime($sCheck = null)
+ protected static function ListFilesByTime($sCheck = null)
{
- if (empty($sCheck))
- {
+ if (empty($sCheck)) {
$sCheck = self::GetCacheFileName();
}
// Garbage collection
- $aFiles = array_diff(@scandir($sCheck), array('.', '..'));
- foreach($aFiles as $sFile)
- {
+ $aFiles = array_diff(@scandir($sCheck), ['.', '..']);
+ foreach ($aFiles as $sFile) {
$sSubFile = $sCheck.'/'.$sFile;
- if (is_dir($sSubFile))
- {
+ if (is_dir($sSubFile)) {
self::ListFilesByTime($sSubFile);
- }
- else
- {
- if (strpos(basename($sSubFile), '-') === 0)
- {
+ } else {
+ if (strpos(basename($sSubFile), '-') === 0) {
self::$aFilesByTime[$sSubFile] = @fileatime($sSubFile);
}
}
@@ -353,7 +320,7 @@ class apcFile
* @param $sFilename
* @return bool|string the content of the cache entry or false if error
*/
- static protected function ReadCacheLocked($sFilename)
+ protected static function ReadCacheLocked($sFilename)
{
$sContent = false;
$file = @fopen($sFilename, 'r');
@@ -367,7 +334,7 @@ class apcFile
return $sContent;
}
- static protected function ResetFileCount()
+ protected static function ResetFileCount()
{
self::$aFilesByTime = null;
self::$iFileCount = 0;
diff --git a/core/apc-service.class.inc.php b/core/apc-service.class.inc.php
index ca541eb84..c7922f0d9 100644
--- a/core/apc-service.class.inc.php
+++ b/core/apc-service.class.inc.php
@@ -4,8 +4,10 @@
* Class ApcService
* @since 2.7.6 N°4125
*/
-class ApcService {
- public function __construct() {
+class ApcService
+{
+ public function __construct()
+ {
}
/**
@@ -13,7 +15,8 @@ class ApcService {
* @return bool
* @see function_exists()
*/
- public function function_exists($function_name) {
+ public function function_exists($function_name)
+ {
return function_exists($function_name);
}
@@ -22,7 +25,7 @@ class ApcService {
* @return mixed
* @see apc_fetch()
*/
- function apc_fetch($key)
+ public function apc_fetch($key)
{
return apc_fetch($key);
}
@@ -34,9 +37,8 @@ class ApcService {
* @return array|bool
* @see apc_store()
*/
- function apc_store($key, $var = NULL, $ttl = 0)
+ public function apc_store($key, $var = null, $ttl = 0)
{
return apc_store($key, $var, $ttl);
}
}
-?>
\ No newline at end of file
diff --git a/core/asynctask.class.inc.php b/core/asynctask.class.inc.php
index c8a3a417d..aaf55b0cf 100644
--- a/core/asynctask.class.inc.php
+++ b/core/asynctask.class.inc.php
@@ -1,9 +1,10 @@
use Combodo\iTop\Service\Notification\Event\EventNotificationNewsroomService;
-
/**
* Persistent classes (internal): user defined actions
*
@@ -25,11 +25,10 @@ use Combodo\iTop\Service\Notification\Event\EventNotificationNewsroomService;
* @license http://opensource.org/licenses/AGPL-3.0
*/
-
class ExecAsyncTask implements iBackgroundProcess
{
public function GetPeriodicity()
- {
+ {
return 2; // seconds
}
@@ -39,19 +38,16 @@ class ExecAsyncTask implements iBackgroundProcess
// Criteria: planned, and expected to occur... ASAP or in the past
$sOQL = "SELECT AsyncTask WHERE (status = 'planned') AND (ISNULL(planned) OR (planned < '$sNow'))";
$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 = new CMDBObjectSet(DBObjectSearch::FromOQL($sOQL), ['created' => true] /* order by*/, [], null, 1 /* limit count */);
$oTask = $oSet->Fetch();
- if (is_null($oTask))
- {
+ if (is_null($oTask)) {
// Nothing to be done
break;
}
$iProcessed++;
- if ($oTask->Process())
- {
+ if ($oTask->Process()) {
$oTask->DBDelete();
}
}
@@ -60,7 +56,7 @@ class ExecAsyncTask implements iBackgroundProcess
}
/**
- * A
+ * A
*
* @package iTopORM
*/
@@ -72,79 +68,72 @@ abstract class AsyncTask extends DBObject
*/
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "core/cmdb",
"key_type" => "autoincrement",
- "name_attcode" => array('created'),
+ "name_attcode" => ['created'],
"state_attcode" => "",
- "reconc_keys" => array(),
+ "reconc_keys" => [],
"db_table" => "priv_async_task",
"db_key_field" => "id",
"db_finalclass_field" => "realclass",
- );
+ ];
MetaModel::Init_Params($aParams);
// Null is allowed to ease the migration from iTop 2.0.2 and earlier, when the status did not exist, and because the default value is not taken into account in the SQL definition
// The value is set from null to planned in the setup program
- MetaModel::Init_AddAttribute(new AttributeEnum("status", array("allowed_values"=>new ValueSetEnum('planned,running,idle,error'), "sql"=>"status", "default_value"=>"planned", "is_null_allowed"=>true, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeEnum("status", ["allowed_values" => new ValueSetEnum('planned,running,idle,error'), "sql" => "status", "default_value" => "planned", "is_null_allowed" => true, "depends_on" => []]));
- 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 AttributeDateTime("started", array("allowed_values"=>null, "sql"=>"started", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeDateTime("planned", array("allowed_values"=>null, "sql"=>"planned", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeExternalKey("event_id", array("targetclass"=>"Event", "jointype"=> "", "allowed_values"=>null, "sql"=>"event_id", "is_null_allowed"=>true, "on_target_delete"=>DEL_SILENT, "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 AttributeDateTime("started", ["allowed_values" => null, "sql" => "started", "default_value" => "", "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeDateTime("planned", ["allowed_values" => null, "sql" => "planned", "default_value" => "", "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeExternalKey("event_id", ["targetclass" => "Event", "jointype" => "", "allowed_values" => null, "sql" => "event_id", "is_null_allowed" => true, "on_target_delete" => DEL_SILENT, "depends_on" => []]));
- MetaModel::Init_AddAttribute(new AttributeInteger("remaining_retries", array("allowed_values"=>null, "sql"=>"remaining_retries", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeInteger("last_error_code", array("allowed_values"=>null, "sql"=>"last_error_code", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeString("last_error", array("allowed_values"=>null, "sql"=>"last_error", "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeDateTime("last_attempt", array("allowed_values"=>null, "sql"=>"last_attempt", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeInteger("remaining_retries", ["allowed_values" => null, "sql" => "remaining_retries", "default_value" => 0, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeInteger("last_error_code", ["allowed_values" => null, "sql" => "last_error_code", "default_value" => 0, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeString("last_error", ["allowed_values" => null, "sql" => "last_error", "default_value" => '', "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeDateTime("last_attempt", ["allowed_values" => null, "sql" => "last_attempt", "default_value" => "", "is_null_allowed" => true, "depends_on" => []]));
}
/**
* Every is fine
*/
- const OK = 0;
+ public const OK = 0;
/**
* The task no longer exists
*/
- const DELETED = 1;
+ public const DELETED = 1;
/**
* The task is already being executed
*/
- const ALREADY_RUNNING = 2;
+ public const ALREADY_RUNNING = 2;
/**
* The current process requests the ownership on the task.
* In case the task can be accessed concurrently, this function can be overloaded to add a critical section.
- * The function must not block the caller if another process is already owning the task
- *
- * @return integer A code among OK/DELETED/ALREADY_RUNNING.
- */
+ * The function must not block the caller if another process is already owning the task
+ *
+ * @return integer A code among OK/DELETED/ALREADY_RUNNING.
+ */
public function MarkAsRunning()
{
- try
- {
- if ($this->Get('status') == 'running')
- {
+ try {
+ if ($this->Get('status') == 'running') {
return self::ALREADY_RUNNING;
- }
- else
- {
+ } else {
$this->Set('status', 'running');
$this->Set('started', time());
$this->DBUpdate();
return self::OK;
}
- }
- catch(Exception $e)
- {
+ } catch (Exception $e) {
// Corrupted task !! (for example: "Failed to reload object")
IssueLog::Error('Failed to process async task #'.$this->GetKey().' - reason: '.$e->getMessage().' - fatal error, deleting the task.');
- if ($this->Get('event_id') != 0)
- {
- $oEventLog = MetaModel::GetObject('Event', $this->Get('event_id'));
- $oEventLog->Set('message', 'Failed, corrupted data: '.$e->getMessage());
- $oEventLog->DBUpdate();
+ if ($this->Get('event_id') != 0) {
+ $oEventLog = MetaModel::GetObject('Event', $this->Get('event_id'));
+ $oEventLog->Set('message', 'Failed, corrupted data: '.$e->getMessage());
+ $oEventLog->DBUpdate();
}
$this->DBDelete();
return self::DELETED;
@@ -155,8 +144,7 @@ abstract class AsyncTask extends DBObject
{
$iRetryDelay = 600;
$aRetries = MetaModel::GetConfig()->Get('async_task_retries');
- if (is_array($aRetries) && array_key_exists(get_class($this), $aRetries))
- {
+ if (is_array($aRetries) && array_key_exists(get_class($this), $aRetries)) {
$aConfig = $aRetries[get_class($this)];
$iRetryDelay = $aConfig['retry_delay'] ?? $iRetryDelay;
}
@@ -167,8 +155,7 @@ abstract class AsyncTask extends DBObject
{
$iMaxRetries = 0;
$aRetries = MetaModel::GetConfig()->Get('async_task_retries');
- if (is_array($aRetries) && array_key_exists(get_class($this), $aRetries))
- {
+ if (is_array($aRetries) && array_key_exists(get_class($this), $aRetries)) {
$aConfig = $aRetries[get_class($this)];
$iMaxRetries = $aConfig['max_retries'] ?? $iMaxRetries;
}
@@ -177,40 +164,33 @@ abstract class AsyncTask extends DBObject
public function IsRetryDelayExponential()
{
- $bExponential = false;
- $aRetries = MetaModel::GetConfig()->Get('async_task_retries');
- if (is_array($aRetries) && array_key_exists(get_class($this), $aRetries))
- {
- $aConfig = $aRetries[get_class($this)];
- $bExponential = (bool) ($aConfig['exponential_delay'] ?? $bExponential);
- }
- return $bExponential;
+ $bExponential = false;
+ $aRetries = MetaModel::GetConfig()->Get('async_task_retries');
+ if (is_array($aRetries) && array_key_exists(get_class($this), $aRetries)) {
+ $aConfig = $aRetries[get_class($this)];
+ $bExponential = (bool) ($aConfig['exponential_delay'] ?? $bExponential);
+ }
+ return $bExponential;
}
public static function CheckRetryConfig(Config $oConfig, $sAsyncTaskClass)
{
- $aMessages = [];
- $aRetries = $oConfig->Get('async_task_retries');
- if (is_array($aRetries) && array_key_exists($sAsyncTaskClass, $aRetries))
- {
- $aValidKeys = array("retry_delay", "max_retries", "exponential_delay");
- $aConfig = $aRetries[$sAsyncTaskClass];
- if (!is_array($aConfig))
- {
- $aMessages[] = Dict::Format('Class:AsyncTask:InvalidConfig_Class_Keys', $sAsyncTaskClass, implode(', ', $aValidKeys));
- }
- else
- {
- foreach($aConfig as $key => $value)
- {
- if (!in_array($key, $aValidKeys))
- {
- $aMessages[] = Dict::Format('Class:AsyncTask:InvalidConfig_Class_InvalidKey_Keys', $sAsyncTaskClass, $key, implode(', ', $aValidKeys));
- }
- }
- }
- }
- return $aMessages;
+ $aMessages = [];
+ $aRetries = $oConfig->Get('async_task_retries');
+ if (is_array($aRetries) && array_key_exists($sAsyncTaskClass, $aRetries)) {
+ $aValidKeys = ["retry_delay", "max_retries", "exponential_delay"];
+ $aConfig = $aRetries[$sAsyncTaskClass];
+ if (!is_array($aConfig)) {
+ $aMessages[] = Dict::Format('Class:AsyncTask:InvalidConfig_Class_Keys', $sAsyncTaskClass, implode(', ', $aValidKeys));
+ } else {
+ foreach ($aConfig as $key => $value) {
+ if (!in_array($key, $aValidKeys)) {
+ $aMessages[] = Dict::Format('Class:AsyncTask:InvalidConfig_Class_InvalidKey_Keys', $sAsyncTaskClass, $key, implode(', ', $aValidKeys));
+ }
+ }
+ }
+ }
+ return $aMessages;
}
/**
@@ -223,16 +203,15 @@ abstract class AsyncTask extends DBObject
*/
public static function GetNextRetryDelay($bIsExponential, $iRetryDelay, $iMaxRetries, $iRemainingRetries)
{
- if ($bIsExponential)
- {
- $iExponent = $iMaxRetries - $iRemainingRetries;
- if ($iExponent < 0) $iExponent = 0; // Safety net in case on configuration change in the middle of retries
- return $iRetryDelay * (2 ** $iExponent);
- }
- else
- {
- return $iRetryDelay;
- }
+ if ($bIsExponential) {
+ $iExponent = $iMaxRetries - $iRemainingRetries;
+ if ($iExponent < 0) {
+ $iExponent = 0;
+ } // Safety net in case on configuration change in the middle of retries
+ return $iRetryDelay * (2 ** $iExponent);
+ } else {
+ return $iRetryDelay;
+ }
}
/**
@@ -242,14 +221,14 @@ abstract class AsyncTask extends DBObject
{
}
- protected function OnInsert()
+ protected function OnInsert()
{
$this->Set('created', time());
}
- /**
- * @return boolean True if the task record can be deleted
- */
+ /**
+ * @return boolean True if the task record can be deleted
+ */
public function Process()
{
// By default: consider that the task is not completed
@@ -257,25 +236,19 @@ abstract class AsyncTask extends DBObject
// Attempt to take the ownership
$iStatus = $this->MarkAsRunning();
- if ($iStatus == self::OK)
- {
- try
- {
+ if ($iStatus == self::OK) {
+ try {
$sStatus = $this->DoProcess();
- if ($this->Get('event_id') != 0)
- {
+ if ($this->Get('event_id') != 0) {
$oEventLog = MetaModel::GetObject('Event', $this->Get('event_id'));
$oEventLog->Set('message', $sStatus);
$oEventLog->DBUpdate();
}
$bRet = true;
- } catch (Exception $e)
- {
+ } catch (Exception $e) {
$this->HandleError($e->getMessage(), $e->getCode());
}
- }
- else
- {
+ } else {
// Already done or being handled by another process... skip...
$bRet = false;
}
@@ -288,8 +261,7 @@ abstract class AsyncTask extends DBObject
*/
protected function HandleError($sErrorMessage, $iErrorCode)
{
- if ($this->Get('last_attempt') == '')
- {
+ if ($this->Get('last_attempt') == '') {
// First attempt
$this->Set('remaining_retries', $this->GetMaxRetries($iErrorCode));
}
@@ -299,45 +271,34 @@ abstract class AsyncTask extends DBObject
$this->Set('last_attempt', time());
$iRemaining = $this->Get('remaining_retries');
- if ($iRemaining > 0)
- {
+ if ($iRemaining > 0) {
$iRetryDelay = $this->GetRetryDelay($iErrorCode);
$iNextRetryDelay = static::GetNextRetryDelay($this->IsRetryDelayExponential(), $iRetryDelay, $this->GetMaxRetries($iErrorCode), $iRemaining);
IssueLog::Info('Failed to process async task #'.$this->GetKey().' - reason: '.$sErrorMessage.' - remaining retries: '.$iRemaining.' - next retry in '.$iNextRetryDelay.'s');
- if ($this->Get('event_id') != 0)
- {
+ if ($this->Get('event_id') != 0) {
$oEventLog = MetaModel::GetObject('Event', $this->Get('event_id'));
$oEventLog->Set('message', "$sErrorMessage\nFailed to process async task. Remaining retries: $iRemaining. Next retry in {$iNextRetryDelay}s");
- try
- {
- $oEventLog->DBUpdate();
- }
- catch (Exception $e)
- {
- $oEventLog->Set('message', "Failed to process async task. Remaining retries: $iRemaining. Next retry in {$iNextRetryDelay}s, more details in the log");
- $oEventLog->DBUpdate();
- }
+ try {
+ $oEventLog->DBUpdate();
+ } catch (Exception $e) {
+ $oEventLog->Set('message', "Failed to process async task. Remaining retries: $iRemaining. Next retry in {$iNextRetryDelay}s, more details in the log");
+ $oEventLog->DBUpdate();
+ }
}
$this->Set('remaining_retries', $iRemaining - 1);
$this->Set('status', 'planned');
$this->Set('started', null);
$this->Set('planned', time() + $iNextRetryDelay);
- }
- else
- {
+ } else {
IssueLog::Error('Failed to process async task #'.$this->GetKey().' - reason: '.$sErrorMessage);
- if ($this->Get('event_id') != 0)
- {
+ if ($this->Get('event_id') != 0) {
$oEventLog = MetaModel::GetObject('Event', $this->Get('event_id'));
$oEventLog->Set('message', "$sErrorMessage\nFailed to process async task.");
- try
- {
- $oEventLog->DBUpdate();
- }
- catch (Exception $e)
- {
- $oEventLog->Set('message', 'Failed to process async task, more details in the log');
- $oEventLog->DBUpdate();
+ try {
+ $oEventLog->DBUpdate();
+ } catch (Exception $e) {
+ $oEventLog->Set('message', 'Failed to process async task, more details in the log');
+ $oEventLog->DBUpdate();
}
}
$this->Set('status', 'error');
@@ -352,20 +313,20 @@ abstract class AsyncTask extends DBObject
* Throws an exception (message and code)
*
* @return string
- */
+ */
abstract public function DoProcess();
/**
* Describes the error codes that DoProcess can return by the mean of exceptions
- */
- static public function EnumErrorCodes()
+ */
+ public static function EnumErrorCodes()
{
- return array();
+ return [];
}
}
/**
- * An email notification
+ * An email notification
*
* @package iTopORM
*/
@@ -373,38 +334,37 @@ class AsyncSendEmail extends AsyncTask
{
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "core/cmdb",
"key_type" => "autoincrement",
"name_attcode" => "created",
"state_attcode" => "",
- "reconc_keys" => array(),
+ "reconc_keys" => [],
"db_table" => "priv_async_send_email",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeInteger("version", array("allowed_values"=>null, "sql"=>"version", "default_value"=>Email::ORIGINAL_FORMAT, "is_null_allowed"=>false, "depends_on"=>array())));
- 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("subject", array("allowed_values"=>null, "sql"=>"subject", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeLongText("message", array("allowed_values"=>null, "sql"=>"message", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeInteger("version", ["allowed_values" => null, "sql" => "version", "default_value" => Email::ORIGINAL_FORMAT, "is_null_allowed" => false, "depends_on" => []]));
+ 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("subject", ["allowed_values" => null, "sql" => "subject", "default_value" => null, "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeLongText("message", ["allowed_values" => null, "sql" => "message", "default_value" => null, "is_null_allowed" => false, "depends_on" => []]));
// Display lists
-// MetaModel::Init_SetZListItems('details', array('name', 'description', 'status', 'test_recipient', 'from', 'reply_to', 'to', 'cc', 'bcc', 'subject', 'body', 'importance', 'trigger_list')); // Attributes to be displayed for the complete details
-// MetaModel::Init_SetZListItems('list', array('name', 'status', 'to', 'subject')); // Attributes to be displayed for a list
+ // MetaModel::Init_SetZListItems('details', array('name', 'description', 'status', 'test_recipient', 'from', 'reply_to', 'to', 'cc', 'bcc', 'subject', 'body', 'importance', 'trigger_list')); // Attributes to be displayed for the complete details
+ // MetaModel::Init_SetZListItems('list', array('name', 'status', 'to', 'subject')); // 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
}
- static public function AddToQueue(EMail $oEMail, $oLog)
+ public static function AddToQueue(EMail $oEMail, $oLog)
{
$oNew = MetaModel::NewObject(__class__);
- if ($oLog)
- {
+ if ($oLog) {
$oNew->Set('event_id', $oLog->GetKey());
}
$oNew->Set('to', $oEMail->GetRecipientTO(true /* string */));
@@ -425,35 +385,33 @@ class AsyncSendEmail extends AsyncTask
{
$sMessage = $this->Get('message');
$iVersion = (int) $this->Get('version');
- switch($iVersion)
- {
+ switch ($iVersion) {
case Email::FORMAT_V2:
- $oEMail = Email::UnSerializeV2($sMessage);
- break;
-
+ $oEMail = Email::UnSerializeV2($sMessage);
+ break;
+
case Email::ORIGINAL_FORMAT:
- $oEMail = unserialize($sMessage);
- break;
-
+ $oEMail = unserialize($sMessage);
+ break;
+
default:
- return 'Unknown version of the serialization format: '.$iVersion;
+ return 'Unknown version of the serialization format: '.$iVersion;
}
$iRes = $oEMail->Send($aIssues, true /* force synchro !!!!! */);
- switch ($iRes)
- {
- case EMAIL_SEND_OK:
- return "Sent";
+ switch ($iRes) {
+ case EMAIL_SEND_OK:
+ return "Sent";
- case EMAIL_SEND_PENDING:
- return "Bug - the email should be sent in synchronous mode";
+ case EMAIL_SEND_PENDING:
+ return "Bug - the email should be sent in synchronous mode";
- case EMAIL_SEND_ERROR:
- if (is_array($aIssues)) {
- $sMessage = "Sending eMail failed: ".implode(', ', $aIssues);
- } else {
- $sMessage = "Sending eMail failed.";
- }
- throw new Exception($sMessage);
+ case EMAIL_SEND_ERROR:
+ if (is_array($aIssues)) {
+ $sMessage = "Sending eMail failed: ".implode(', ', $aIssues);
+ } else {
+ $sMessage = "Sending eMail failed.";
+ }
+ throw new Exception($sMessage);
}
return '';
}
@@ -463,33 +421,33 @@ class AsyncSendEmail extends AsyncTask
* An async notification to be sent to iTop users through the newsroom
* @since 3.2.0
*/
-class AsyncSendNewsroom extends AsyncTask {
-
+class AsyncSendNewsroom extends AsyncTask
+{
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "core/cmdb",
"key_type" => "autoincrement",
"name_attcode" => "created",
"state_attcode" => "",
- "reconc_keys" => array(),
+ "reconc_keys" => [],
"db_table" => "priv_async_send_newsroom",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeText("recipients", array("allowed_values"=>null, "sql"=>"recipients", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeExternalKey("action_id", array("targetclass"=>"Action", "allowed_values"=>null, "sql"=>"action_id", "default_value"=>null, "is_null_allowed"=>false, "on_target_delete"=>DEL_AUTO, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeExternalKey("trigger_id", array("targetclass"=>"Trigger", "allowed_values"=>null, "sql"=>"trigger_id", "default_value"=>null, "is_null_allowed"=>false, "on_target_delete"=>DEL_AUTO, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeText("title", array("allowed_values"=>null, "sql"=>"title", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
- 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 AttributeInteger("object_id", array("allowed_values"=>null, "sql"=>"object_id", "default_value"=>null, "is_null_allowed"=>false, "on_target_delete"=>DEL_AUTO, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeString("object_class", array("allowed_values"=>null, "sql"=>"object_class", "default_value"=>null, "is_null_allowed"=>false, "on_target_delete"=>DEL_AUTO, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeText("url", array("allowed_values"=>null, "sql"=>"url", "default_value"=>null, "is_null_allowed"=>false, "on_target_delete"=>DEL_AUTO, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeDateTime("date", array("allowed_values"=>null, "sql"=>"date", "default_value"=>'NOW()', "is_null_allowed"=>false, "on_target_delete"=>DEL_AUTO, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeText("recipients", ["allowed_values" => null, "sql" => "recipients", "default_value" => null, "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeExternalKey("action_id", ["targetclass" => "Action", "allowed_values" => null, "sql" => "action_id", "default_value" => null, "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeExternalKey("trigger_id", ["targetclass" => "Trigger", "allowed_values" => null, "sql" => "trigger_id", "default_value" => null, "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeText("title", ["allowed_values" => null, "sql" => "title", "default_value" => null, "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeText("message", ["allowed_values" => null, "sql" => "message", "default_value" => null, "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeInteger("object_id", ["allowed_values" => null, "sql" => "object_id", "default_value" => null, "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeString("object_class", ["allowed_values" => null, "sql" => "object_class", "default_value" => null, "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeText("url", ["allowed_values" => null, "sql" => "url", "default_value" => null, "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeDateTime("date", ["allowed_values" => null, "sql" => "date", "default_value" => 'NOW()', "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => []]));
}
@@ -514,7 +472,7 @@ class AsyncSendNewsroom extends AsyncTask {
$oNew->Set('object_id', $iObjectId);
$oNew->Set('object_class', $sObjectClass);
$oNew->SetCurrentDate('date');
-
+
$oNew->DBInsert();
}
@@ -532,13 +490,12 @@ class AsyncSendNewsroom extends AsyncTask {
$iObjectId = $this->Get('object_id');
$sObjectClass = $this->Get('object_class');
$sDate = $this->Get('date');
-
- foreach ($aRecipients as $iRecipientId)
- {
+
+ foreach ($aRecipients as $iRecipientId) {
$oEvent = EventNotificationNewsroomService::MakeEventFromAction($oAction, $iRecipientId, $iTriggerId, $sMessage, $sTitle, $sUrl, $iObjectId, $sObjectClass, $sDate);
$oEvent->DBInsertNoReload();
}
-
+
return "Sent";
}
-}
\ No newline at end of file
+}
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 @@
-
/**
* Tasks performed in the background
*
@@ -24,7 +24,6 @@
* @license http://opensource.org/licenses/AGPL-3.0
*/
-
class ObsolescenceDateUpdater implements iBackgroundProcess
{
public function GetPeriodicity()
@@ -37,18 +36,17 @@ class ObsolescenceDateUpdater implements iBackgroundProcess
$iCountSet = 0;
$iCountReset = 0;
$iClasses = 0;
- foreach (MetaModel::EnumObsoletableClasses() as $sClass)
- {
+ foreach (MetaModel::EnumObsoletableClasses() as $sClass) {
$oObsoletedToday = new DBObjectSearch($sClass);
$oObsoletedToday->AddCondition('obsolescence_flag', 1, '=');
$oObsoletedToday->AddCondition('obsolescence_date', null, '=');
$sToday = date(AttributeDate::GetSQLFormat());
- $iCountSet += MetaModel::BulkUpdate($oObsoletedToday, array('obsolescence_date' => $sToday));
+ $iCountSet += MetaModel::BulkUpdate($oObsoletedToday, ['obsolescence_date' => $sToday]);
$oObsoletedToday = new DBObjectSearch($sClass);
$oObsoletedToday->AddCondition('obsolescence_flag', 1, '!=');
$oObsoletedToday->AddCondition('obsolescence_date', null, '!=');
- $iCountReset += MetaModel::BulkUpdate($oObsoletedToday, array('obsolescence_date' => null));
+ $iCountReset += MetaModel::BulkUpdate($oObsoletedToday, ['obsolescence_date' => null]);
}
return "Obsolescence date updated (classes: $iClasses ; set: $iCountSet ; reset: $iCountReset)\n";
}
diff --git a/core/backgroundprocess.inc.php b/core/backgroundprocess.inc.php
index 46b4490f3..3e05348ed 100644
--- a/core/backgroundprocess.inc.php
+++ b/core/backgroundprocess.inc.php
@@ -1,4 +1,5 @@
oConfig))
- {
+ if (!isset($this->oConfig)) {
$this->oConfig = MetaModel::GetConfig();
}
return $this->oConfig;
}
-
/**
* Interpret current setting for the week days
*
@@ -128,7 +125,7 @@ abstract class AbstractWeeklyScheduledProcess implements iScheduledProcess
*/
public function InterpretWeekDays()
{
- static $aWEEKDAYTON = array(
+ static $aWEEKDAYTON = [
'monday' => 1,
'tuesday' => 2,
'wednesday' => 3,
@@ -136,32 +133,26 @@ abstract class AbstractWeeklyScheduledProcess implements iScheduledProcess
'friday' => 5,
'saturday' => 6,
'sunday' => 7,
- );
- $aDays = array();
+ ];
+ $aDays = [];
$sWeekDays = $this->getOConfig()->GetModuleSetting(
$this->GetModuleName(),
static::MODULE_SETTING_WEEKDAYS,
static::DEFAULT_MODULE_SETTING_WEEKDAYS
);
- if ($sWeekDays !== '')
- {
+ if ($sWeekDays !== '') {
$aWeekDaysRaw = explode(',', $sWeekDays);
- foreach ($aWeekDaysRaw as $sWeekDay)
- {
+ foreach ($aWeekDaysRaw as $sWeekDay) {
$sWeekDay = strtolower(trim($sWeekDay));
- if (array_key_exists($sWeekDay, $aWEEKDAYTON))
- {
+ if (array_key_exists($sWeekDay, $aWEEKDAYTON)) {
$aDays[] = $aWEEKDAYTON[$sWeekDay];
- }
- else
- {
+ } else {
throw new ProcessInvalidConfigException($this->GetModuleName().": wrong format for setting '".static::MODULE_SETTING_WEEKDAYS."' (found '$sWeekDay')");
}
}
}
- if (count($aDays) === 0)
- {
+ if (count($aDays) === 0) {
throw new ProcessInvalidConfigException($this->GetModuleName().': missing setting \''.static::MODULE_SETTING_WEEKDAYS.'\'');
}
$aDays = array_unique($aDays);
@@ -185,8 +176,7 @@ abstract class AbstractWeeklyScheduledProcess implements iScheduledProcess
static::DEFAULT_MODULE_SETTING_ENABLED
);
- if (!$bEnabled)
- {
+ if (!$bEnabled) {
return new DateTime('3000-01-01');
}
@@ -202,21 +192,17 @@ abstract class AbstractWeeklyScheduledProcess implements iScheduledProcess
static::GetDefaultModuleSettingTime()
);
$sProcessTime = trim($sProcessTime);
- if (!preg_match('/[0-2]\d:[0-5]\d/', $sProcessTime))
- {
+ if (!preg_match('/[0-2]\d:[0-5]\d/', $sProcessTime)) {
throw new ProcessInvalidConfigException($this->GetModuleName().": wrong format for setting '".static::MODULE_SETTING_TIME."' (found '$sProcessTime')");
}
$oNow = new DateTime($sCurrentTime);
$iNextPos = false;
$sDay = $oNow->format('N');
- for ($iDay = (int) $sDay; $iDay <= 7; $iDay++)
- {
+ for ($iDay = (int) $sDay; $iDay <= 7; $iDay++) {
$iNextPos = array_search($iDay, $aDays, true);
- if ($iNextPos !== false)
- {
- if (($iDay > $oNow->format('N')) || ($oNow->format('H:i') < $sProcessTime))
- {
+ if ($iNextPos !== false) {
+ if (($iDay > $oNow->format('N')) || ($oNow->format('H:i') < $sProcessTime)) {
break;
}
$iNextPos = false; // necessary on sundays
@@ -225,17 +211,14 @@ abstract class AbstractWeeklyScheduledProcess implements iScheduledProcess
// 3rd - Compute the result
//
- if ($iNextPos === false)
- {
+ if ($iNextPos === false) {
// Jump to the first day within the next week
$iFirstDayOfWeek = $aDays[0];
$iDayMove = $oNow->format('N') - $iFirstDayOfWeek;
$oRet = clone $oNow;
$oRet->modify(-$iDayMove.' days');
$oRet->modify('+1 weeks');
- }
- else
- {
+ } else {
$iNextDayOfWeek = $aDays[$iNextPos];
$iMove = $iNextDayOfWeek - $oNow->format('N');
$oRet = clone $oNow;
diff --git a/core/backgroundtask.class.inc.php b/core/backgroundtask.class.inc.php
index 6c6736819..bfc843f98 100644
--- a/core/backgroundtask.class.inc.php
+++ b/core/backgroundtask.class.inc.php
@@ -1,9 +1,10 @@
-
/**
* Class BackgroundTask
* A class to record information about the execution of background processes ({@link iProcess} impl)
@@ -46,49 +46,47 @@ class BackgroundTask extends DBObject
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "core/cmdb",
"key_type" => "autoincrement",
"name_attcode" => "class_name",
"state_attcode" => "",
- "reconc_keys" => array(),
+ "reconc_keys" => [],
"db_table" => "priv_backgroundtask",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
- MetaModel::Init_AddAttribute(new AttributeString("class_name", array("allowed_values"=>null, "sql"=>"class_name", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeDateTime("first_run_date", array("allowed_values"=>null, "sql"=>"first_run_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeDateTime("latest_run_date", array("allowed_values"=>null, "sql"=>"latest_run_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeDateTime("next_run_date", array("allowed_values"=>null, "sql"=>"next_run_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
-
- MetaModel::Init_AddAttribute(new AttributeInteger("total_exec_count", array("allowed_values"=>null, "sql"=>"total_exec_count", "default_value"=>"0", "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeDecimal("latest_run_duration", array("allowed_values"=>null, "sql"=>"latest_run_duration", "digits"=> 8, "decimals"=> 3, "default_value"=>"0", "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeDecimal("min_run_duration", array("allowed_values"=>null, "sql"=>"min_run_duration", "digits"=> 8, "decimals"=> 3, "default_value"=>"0", "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeDecimal("max_run_duration", array("allowed_values"=>null, "sql"=>"max_run_duration", "digits"=> 8, "decimals"=> 3, "default_value"=>"0", "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeDecimal("average_run_duration", array("allowed_values"=>null, "sql"=>"average_run_duration", "digits"=> 8, "decimals"=> 3, "default_value"=>"0", "is_null_allowed"=>true, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeString("class_name", ["allowed_values" => null, "sql" => "class_name", "default_value" => null, "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeDateTime("first_run_date", ["allowed_values" => null, "sql" => "first_run_date", "default_value" => "", "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeDateTime("latest_run_date", ["allowed_values" => null, "sql" => "latest_run_date", "default_value" => "", "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeDateTime("next_run_date", ["allowed_values" => null, "sql" => "next_run_date", "default_value" => "", "is_null_allowed" => true, "depends_on" => []]));
- MetaModel::Init_AddAttribute(new AttributeBoolean("running", array("allowed_values"=>null, "sql"=>"running", "default_value"=>false, "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeEnum("status", array("allowed_values"=>new ValueSetEnum('active,paused,removed'), "sql"=>"status", "default_value"=>'active', "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeString("system_user", array("allowed_values"=>null, "sql"=>"system_user", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeInteger("total_exec_count", ["allowed_values" => null, "sql" => "total_exec_count", "default_value" => "0", "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeDecimal("latest_run_duration", ["allowed_values" => null, "sql" => "latest_run_duration", "digits" => 8, "decimals" => 3, "default_value" => "0", "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeDecimal("min_run_duration", ["allowed_values" => null, "sql" => "min_run_duration", "digits" => 8, "decimals" => 3, "default_value" => "0", "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeDecimal("max_run_duration", ["allowed_values" => null, "sql" => "max_run_duration", "digits" => 8, "decimals" => 3, "default_value" => "0", "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeDecimal("average_run_duration", ["allowed_values" => null, "sql" => "average_run_duration", "digits" => 8, "decimals" => 3, "default_value" => "0", "is_null_allowed" => true, "depends_on" => []]));
+
+ MetaModel::Init_AddAttribute(new AttributeBoolean("running", ["allowed_values" => null, "sql" => "running", "default_value" => false, "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeEnum("status", ["allowed_values" => new ValueSetEnum('active,paused,removed'), "sql" => "status", "default_value" => 'active', "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeString("system_user", ["allowed_values" => null, "sql" => "system_user", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
}
-
+
public function ComputeDurations($fLatestDuration)
{
$iTotalRun = $this->Get('total_exec_count');
- $fAverageDuration = ($this->Get('average_run_duration') * $iTotalRun + $fLatestDuration) / (1+$iTotalRun);
- $this->Set('average_run_duration', sprintf('%.3f',$fAverageDuration));
- $this->Set('total_exec_count', 1+$iTotalRun);
- if ($fLatestDuration < $this->Get('min_run_duration'))
- {
- $this->Set('min_run_duration', sprintf('%.3f',$fLatestDuration));
+ $fAverageDuration = ($this->Get('average_run_duration') * $iTotalRun + $fLatestDuration) / (1 + $iTotalRun);
+ $this->Set('average_run_duration', sprintf('%.3f', $fAverageDuration));
+ $this->Set('total_exec_count', 1 + $iTotalRun);
+ if ($fLatestDuration < $this->Get('min_run_duration')) {
+ $this->Set('min_run_duration', sprintf('%.3f', $fLatestDuration));
}
- if ($fLatestDuration > $this->Get('max_run_duration'))
- {
- $this->Set('max_run_duration', sprintf('%.3f',$fLatestDuration));
+ if ($fLatestDuration > $this->Get('max_run_duration')) {
+ $this->Set('max_run_duration', sprintf('%.3f', $fLatestDuration));
}
- $this->Set('latest_run_duration', sprintf('%.3f',$fLatestDuration));
+ $this->Set('latest_run_duration', sprintf('%.3f', $fLatestDuration));
}
}
diff --git a/core/bulkchange.class.inc.php b/core/bulkchange.class.inc.php
index 1865fafc4..8dd01b6ec 100644
--- a/core/bulkchange.class.inc.php
+++ b/core/bulkchange.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/cmdbchange.class.inc.php b/core/cmdbchange.class.inc.php
index e69673e22..0ea64f595 100644
--- a/core/cmdbchange.class.inc.php
+++ b/core/cmdbchange.class.inc.php
@@ -1,4 +1,5 @@
"core/cmdb, grant_by_profile",
"key_type" => "autoincrement",
"name_attcode" => "date",
"state_attcode" => "",
- "reconc_keys" => array(),
+ "reconc_keys" => [],
"db_table" => "priv_change",
"db_key_field" => "id",
"db_finalclass_field" => "",
- 'indexes' => array(
- array('origin'),
- ),
- );
+ 'indexes' => [
+ ['origin'],
+ ],
+ ];
MetaModel::Init_Params($aParams);
//MetaModel::Init_InheritAttributes();
- 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 AttributeExternalKey("user_id", array("allowed_values"=>null, "sql"=>"user_id", "targetclass"=>"User", "is_null_allowed"=>true, "on_target_delete"=>DEL_MANUAL, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeEnum("origin", array("allowed_values"=>new ValueSetEnum(implode(',', [CMDBChangeOrigin::INTERACTIVE, CMDBChangeOrigin::CSV_INTERACTIVE, CMDBChangeOrigin::CSV_IMPORT, CMDBChangeOrigin::WEBSERVICE_SOAP, CMDBChangeOrigin::WEBSERVICE_REST, CMDBChangeOrigin::SYNCHRO_DATA_SOURCE, CMDBChangeOrigin::EMAIL_PROCESSING, CMDBChangeOrigin::CUSTOM_EXTENSION])), "sql"=>"origin", "default_value"=>CMDBChangeOrigin::INTERACTIVE, "is_null_allowed"=>true, "depends_on"=>array())));
+ 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 AttributeExternalKey("user_id", ["allowed_values" => null, "sql" => "user_id", "targetclass" => "User", "is_null_allowed" => true, "on_target_delete" => DEL_MANUAL, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeEnum("origin", ["allowed_values" => new ValueSetEnum(implode(',', [CMDBChangeOrigin::INTERACTIVE, CMDBChangeOrigin::CSV_INTERACTIVE, CMDBChangeOrigin::CSV_IMPORT, CMDBChangeOrigin::WEBSERVICE_SOAP, CMDBChangeOrigin::WEBSERVICE_REST, CMDBChangeOrigin::SYNCHRO_DATA_SOURCE, CMDBChangeOrigin::EMAIL_PROCESSING, CMDBChangeOrigin::CUSTOM_EXTENSION])), "sql" => "origin", "default_value" => CMDBChangeOrigin::INTERACTIVE, "is_null_allowed" => true, "depends_on" => []]));
}
/**
@@ -48,12 +49,9 @@ class CMDBChange extends DBObject
*/
public static function GetCurrentUserName()
{
- if (UserRights::IsImpersonated())
- {
+ if (UserRights::IsImpersonated()) {
$sUserString = Dict::Format('UI:Archive_User_OnBehalfOf_User', UserRights::GetRealUserFriendlyName(), UserRights::GetUserFriendlyName());
- }
- else
- {
+ } else {
$sUserString = UserRights::GetUserFriendlyName();
}
return $sUserString;
@@ -74,12 +72,9 @@ class CMDBChange extends DBObject
public function GetUserName()
{
- if (preg_match('/^(.*)\\(CSV\\)$/i', $this->Get('userinfo'), $aMatches))
- {
+ if (preg_match('/^(.*)\\(CSV\\)$/i', $this->Get('userinfo'), $aMatches)) {
$sUser = $aMatches[1];
- }
- else
- {
+ } else {
$sUser = $this->Get('userinfo');
}
return $sUser;
diff --git a/core/cmdbchangeop.class.inc.php b/core/cmdbchangeop.class.inc.php
index 26703dc62..c3add281e 100644
--- a/core/cmdbchangeop.class.inc.php
+++ b/core/cmdbchangeop.class.inc.php
@@ -1,9 +1,10 @@
-
/**
* Persistent classes (internal) : cmdbChangeOp and derived
*
@@ -24,9 +24,8 @@
* @license http://opensource.org/licenses/AGPL-3.0
*/
-
/**
- * Various atomic change operations, to be tracked
+ * Various atomic change operations, to be tracked
*
* @package iTopORM
*/
@@ -50,31 +49,31 @@ class CMDBChangeOp extends DBObject implements iCMDBChangeOp
{
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "core/cmdb, grant_by_profile",
"key_type" => "autoincrement",
"name_attcode" => "change",
"state_attcode" => "",
- "reconc_keys" => array(),
+ "reconc_keys" => [],
"db_table" => "priv_changeop",
"db_key_field" => "id",
"db_finalclass_field" => "optype",
- 'indexes' => array(
- array('objclass', 'objkey'),
- ),
- );
+ 'indexes' => [
+ ['objclass', 'objkey'],
+ ],
+ ];
MetaModel::Init_Params($aParams);
//MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeExternalKey("change", array("allowed_values"=>null, "sql"=>"changeid", "targetclass"=>"CMDBChange", "is_null_allowed"=>false, "on_target_delete"=>DEL_MANUAL, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeExternalField("date", array("allowed_values"=>null, "extkey_attcode"=>"change", "target_attcode"=>"date")));
- MetaModel::Init_AddAttribute(new AttributeExternalField("userinfo", array("allowed_values"=>null, "extkey_attcode"=>"change", "target_attcode"=>"userinfo")));
- MetaModel::Init_AddAttribute(new AttributeExternalField("user_id", array("allowed_values"=>null, "extkey_attcode"=>"change", "target_attcode"=>"user_id")));
- MetaModel::Init_AddAttribute(new AttributeString("objclass", array("allowed_values"=>null, "sql"=>"objclass", "default_value"=>"", "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeObjectKey("objkey", array("allowed_values"=>null, "class_attcode"=>"objclass", "sql"=>"objkey", "is_null_allowed"=>false, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeExternalKey("change", ["allowed_values" => null, "sql" => "changeid", "targetclass" => "CMDBChange", "is_null_allowed" => false, "on_target_delete" => DEL_MANUAL, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeExternalField("date", ["allowed_values" => null, "extkey_attcode" => "change", "target_attcode" => "date"]));
+ MetaModel::Init_AddAttribute(new AttributeExternalField("userinfo", ["allowed_values" => null, "extkey_attcode" => "change", "target_attcode" => "userinfo"]));
+ MetaModel::Init_AddAttribute(new AttributeExternalField("user_id", ["allowed_values" => null, "extkey_attcode" => "change", "target_attcode" => "user_id"]));
+ MetaModel::Init_AddAttribute(new AttributeString("objclass", ["allowed_values" => null, "sql" => "objclass", "default_value" => "", "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeObjectKey("objkey", ["allowed_values" => null, "class_attcode" => "objclass", "sql" => "objkey", "is_null_allowed" => false, "depends_on" => []]));
- MetaModel::Init_SetZListItems('details', array('change', 'date', 'userinfo')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('change', 'date', 'userinfo')); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('details', ['change', 'date', 'userinfo']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['change', 'date', 'userinfo']); // Attributes to be displayed for the complete details
}
/**
@@ -108,7 +107,7 @@ class CMDBChangeOp extends DBObject implements iCMDBChangeOp
}
/**
- * Record the creation of an object
+ * Record the creation of an object
*
* @package iTopORM
*/
@@ -119,24 +118,24 @@ class CMDBChangeOpCreate 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_create",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
}
-
+
/**
* @inheritDoc
- */
+ */
public function GetDescription()
{
return Dict::S('Change:ObjectCreated');
@@ -144,7 +143,7 @@ class CMDBChangeOpCreate extends CMDBChangeOp
}
/**
- * Record the deletion of an object
+ * Record the deletion of an object
*
* @package iTopORM
*/
@@ -155,24 +154,24 @@ class CMDBChangeOpDelete 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_delete",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
// Final class of the object (objclass must be set to the root class for efficiency purposes)
- MetaModel::Init_AddAttribute(new AttributeString("fclass", array("allowed_values"=>null, "sql"=>"fclass", "default_value"=>"", "is_null_allowed"=>false, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeString("fclass", ["allowed_values" => null, "sql" => "fclass", "default_value" => "", "is_null_allowed" => false, "depends_on" => []]));
// Last friendly name of the object
- MetaModel::Init_AddAttribute(new AttributeString("fname", array("allowed_values"=>null, "sql"=>"fname", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeString("fname", ["allowed_values" => null, "sql" => "fname", "default_value" => "", "is_null_allowed" => true, "depends_on" => []]));
}
/**
@@ -196,29 +195,29 @@ class CMDBChangeOpSetAttribute 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_setatt",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeString("attcode", array("allowed_values"=>null, "sql"=>"attcode", "default_value"=>"", "is_null_allowed"=>false, "depends_on"=>array())));
-
+ MetaModel::Init_AddAttribute(new AttributeString("attcode", ["allowed_values" => null, "sql" => "attcode", "default_value" => "", "is_null_allowed" => false, "depends_on" => []]));
+
// Display lists
- MetaModel::Init_SetZListItems('details', array('date', 'userinfo', 'attcode')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('date', 'userinfo', 'attcode')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['date', 'userinfo', 'attcode']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['date', 'userinfo', 'attcode']); // Attributes to be displayed for a list
}
}
/**
- * Record the modification of a scalar attribute
+ * Record the modification of a scalar attribute
*
* @package iTopORM
*/
@@ -229,25 +228,25 @@ class CMDBChangeOpSetAttributeScalar extends CMDBChangeOpSetAttribute
*/
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_setatt_scalar",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeString("oldvalue", array("allowed_values"=>null, "sql"=>"oldvalue", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeString("newvalue", array("allowed_values"=>null, "sql"=>"newvalue", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
-
+ MetaModel::Init_AddAttribute(new AttributeString("oldvalue", ["allowed_values" => null, "sql" => "oldvalue", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeString("newvalue", ["allowed_values" => null, "sql" => "newvalue", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+
// Display lists
- MetaModel::Init_SetZListItems('details', array('date', 'userinfo', 'attcode', 'oldvalue', 'newvalue')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('date', 'userinfo', 'attcode', 'oldvalue', 'newvalue')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['date', 'userinfo', 'attcode', 'oldvalue', 'newvalue']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['date', 'userinfo', 'attcode', 'oldvalue', 'newvalue']); // Attributes to be displayed for a list
}
/**
@@ -262,9 +261,10 @@ class CMDBChangeOpSetAttributeScalar extends CMDBChangeOpSetAttribute
$oTargetSearch->AddCondition('id', $oTargetObjectKey, '=');
$oMonoObjectSet = new DBObjectSet($oTargetSearch);
- if (UserRights::IsActionAllowedOnAttribute($this->Get('objclass'), $this->Get('attcode'), UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES)
- {
- if (!MetaModel::IsValidAttCode($this->Get('objclass'), $this->Get('attcode'))) return ''; // Protects against renamed attributes...
+ if (UserRights::IsActionAllowedOnAttribute($this->Get('objclass'), $this->Get('attcode'), UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES) {
+ if (!MetaModel::IsValidAttCode($this->Get('objclass'), $this->Get('attcode'))) {
+ return '';
+ } // Protects against renamed attributes...
$oAttDef = MetaModel::GetAttributeDef($this->Get('objclass'), $this->Get('attcode'));
$sAttName = $oAttDef->GetLabel();
@@ -287,57 +287,58 @@ class CMDBChangeOpSetAttributeTagSet extends CMDBChangeOpSetAttribute
* @inheritDoc
*/
public static function Init()
- {
- $aParams = array
- (
- "category" => "core/cmdb, grant_by_profile",
- "key_type" => "",
- "name_attcode" => "change",
- "state_attcode" => "",
- "reconc_keys" => array(),
- "db_table" => "priv_changeop_setatt_tagset",
- "db_key_field" => "id",
- "db_finalclass_field" => "",
- );
- MetaModel::Init_Params($aParams);
- MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeText("oldvalue", array("allowed_values"=>null, "sql"=>"oldvalue", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeText("newvalue", array("allowed_values"=>null, "sql"=>"newvalue", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
+ {
+ $aParams =
+ [
+ "category" => "core/cmdb, grant_by_profile",
+ "key_type" => "",
+ "name_attcode" => "change",
+ "state_attcode" => "",
+ "reconc_keys" => [],
+ "db_table" => "priv_changeop_setatt_tagset",
+ "db_key_field" => "id",
+ "db_finalclass_field" => "",
+ ];
+ MetaModel::Init_Params($aParams);
+ MetaModel::Init_InheritAttributes();
+ MetaModel::Init_AddAttribute(new AttributeText("oldvalue", ["allowed_values" => null, "sql" => "oldvalue", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeText("newvalue", ["allowed_values" => null, "sql" => "newvalue", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
- // Display lists
- MetaModel::Init_SetZListItems('details', array('date', 'userinfo', 'attcode', 'oldvalue', 'newvalue')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('date', 'userinfo', 'attcode', 'oldvalue', 'newvalue')); // Attributes to be displayed for a list
- }
+ // Display lists
+ MetaModel::Init_SetZListItems('details', ['date', 'userinfo', 'attcode', 'oldvalue', 'newvalue']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['date', 'userinfo', 'attcode', 'oldvalue', 'newvalue']); // Attributes to be displayed for a list
+ }
/**
* @inheritDoc
*/
public function GetDescription()
- {
- $sResult = '';
- $sTargetObjectClass = $this->Get('objclass');
- $oTargetObjectKey = $this->Get('objkey');
- $sAttCode = $this->Get('attcode');
- $oTargetSearch = new DBObjectSearch($sTargetObjectClass);
- $oTargetSearch->AddCondition('id', $oTargetObjectKey, '=');
+ {
+ $sResult = '';
+ $sTargetObjectClass = $this->Get('objclass');
+ $oTargetObjectKey = $this->Get('objkey');
+ $sAttCode = $this->Get('attcode');
+ $oTargetSearch = new DBObjectSearch($sTargetObjectClass);
+ $oTargetSearch->AddCondition('id', $oTargetObjectKey, '=');
- $oMonoObjectSet = new DBObjectSet($oTargetSearch);
- if (UserRights::IsActionAllowedOnAttribute($sTargetObjectClass, $sAttCode, UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES)
- {
- if (!MetaModel::IsValidAttCode($this->Get('objclass'), $this->Get('attcode'))) return ''; // Protects against renamed attributes...
+ $oMonoObjectSet = new DBObjectSet($oTargetSearch);
+ if (UserRights::IsActionAllowedOnAttribute($sTargetObjectClass, $sAttCode, UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES) {
+ if (!MetaModel::IsValidAttCode($this->Get('objclass'), $this->Get('attcode'))) {
+ return '';
+ } // Protects against renamed attributes...
- $oAttDef = MetaModel::GetAttributeDef($this->Get('objclass'), $this->Get('attcode'));
- $sAttName = $oAttDef->GetLabel();
- $sNewValue = $this->Get('newvalue');
- $sOldValue = $this->Get('oldvalue');
- $sResult = $oAttDef->DescribeChangeAsHTML($sOldValue, $sNewValue);
- }
- return $sResult;
- }
+ $oAttDef = MetaModel::GetAttributeDef($this->Get('objclass'), $this->Get('attcode'));
+ $sAttName = $oAttDef->GetLabel();
+ $sNewValue = $this->Get('newvalue');
+ $sOldValue = $this->Get('oldvalue');
+ $sResult = $oAttDef->DescribeChangeAsHTML($sOldValue, $sNewValue);
+ }
+ return $sResult;
+ }
}
/**
- * Record the modification of an URL
+ * Record the modification of an URL
*
* @package iTopORM
*/
@@ -348,17 +349,17 @@ class CMDBChangeOpSetAttributeURL extends CMDBChangeOpSetAttribute
*/
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_setatt_url",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
@@ -371,12 +372,12 @@ class CMDBChangeOpSetAttributeURL extends CMDBChangeOpSetAttribute
// 2. from the iTop config
// 3. config parameter default value
// see \AttributeURL::GetValidationPattern
- MetaModel::Init_AddAttribute(new AttributeURL("oldvalue", array("allowed_values" => null, "sql" => "oldvalue", "target" => '_blank', "default_value" => null, "is_null_allowed" => true, "depends_on" => array(), "validation_pattern" => '.*')));
- MetaModel::Init_AddAttribute(new AttributeURL("newvalue", array("allowed_values" => null, "sql" => "newvalue", "target" => '_blank', "default_value" => null, "is_null_allowed" => true, "depends_on" => array(), "validation_pattern" => '.*')));
+ MetaModel::Init_AddAttribute(new AttributeURL("oldvalue", ["allowed_values" => null, "sql" => "oldvalue", "target" => '_blank', "default_value" => null, "is_null_allowed" => true, "depends_on" => [], "validation_pattern" => '.*']));
+ MetaModel::Init_AddAttribute(new AttributeURL("newvalue", ["allowed_values" => null, "sql" => "newvalue", "target" => '_blank', "default_value" => null, "is_null_allowed" => true, "depends_on" => [], "validation_pattern" => '.*']));
// Display lists
- MetaModel::Init_SetZListItems('details', array('date', 'userinfo', 'attcode', 'oldvalue', 'newvalue')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('date', 'userinfo', 'attcode', 'oldvalue', 'newvalue')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['date', 'userinfo', 'attcode', 'oldvalue', 'newvalue']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['date', 'userinfo', 'attcode', 'oldvalue', 'newvalue']); // Attributes to be displayed for a list
}
/**
@@ -391,9 +392,10 @@ class CMDBChangeOpSetAttributeURL extends CMDBChangeOpSetAttribute
$oTargetSearch->AddCondition('id', $oTargetObjectKey, '=');
$oMonoObjectSet = new DBObjectSet($oTargetSearch);
- if (UserRights::IsActionAllowedOnAttribute($this->Get('objclass'), $this->Get('attcode'), UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES)
- {
- if (!MetaModel::IsValidAttCode($this->Get('objclass'), $this->Get('attcode'))) return ''; // Protects against renamed attributes...
+ if (UserRights::IsActionAllowedOnAttribute($this->Get('objclass'), $this->Get('attcode'), UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES) {
+ if (!MetaModel::IsValidAttCode($this->Get('objclass'), $this->Get('attcode'))) {
+ return '';
+ } // Protects against renamed attributes...
$oAttDef = MetaModel::GetAttributeDef($this->Get('objclass'), $this->Get('attcode'));
$sAttName = $oAttDef->GetLabel();
@@ -417,24 +419,24 @@ class CMDBChangeOpSetAttributeBlob extends CMDBChangeOpSetAttribute
*/
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_setatt_data",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeBlob("prevdata", array("depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeBlob("prevdata", ["depends_on" => []]));
// Display lists
- MetaModel::Init_SetZListItems('details', array('date', 'userinfo', 'attcode')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('date', 'userinfo', 'attcode')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['date', 'userinfo', 'attcode']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['date', 'userinfo', 'attcode']); // Attributes to be displayed for a list
}
/**
@@ -444,7 +446,7 @@ class CMDBChangeOpSetAttributeBlob extends CMDBChangeOpSetAttribute
{
// Temporary, until we change the options of GetDescription() -needs a more global revision
$bIsHtml = true;
-
+
$sResult = '';
$oTargetObjectClass = $this->Get('objclass');
$oTargetObjectKey = $this->Get('objkey');
@@ -452,8 +454,7 @@ class CMDBChangeOpSetAttributeBlob extends CMDBChangeOpSetAttribute
$oTargetSearch->AddCondition('id', $oTargetObjectKey, '=');
$oMonoObjectSet = new DBObjectSet($oTargetSearch);
- if (UserRights::IsActionAllowedOnAttribute($this->Get('objclass'), $this->Get('attcode'), UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES)
- {
+ if (UserRights::IsActionAllowedOnAttribute($this->Get('objclass'), $this->Get('attcode'), UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES) {
if (MetaModel::IsValidAttCode($this->Get('objclass'), $this->Get('attcode'))) {
$oAttDef = MetaModel::GetAttributeDef($this->Get('objclass'), $this->Get('attcode'));
$sAttName = $oAttDef->GetLabel();
@@ -496,24 +497,24 @@ class CMDBChangeOpSetAttributeOneWayPassword extends CMDBChangeOpSetAttribute
*/
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_setatt_pwd",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeOneWayPassword("prev_pwd", array("sql" => 'data', "default_value" => '', "is_null_allowed"=> true, "allowed_values" => null, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeOneWayPassword("prev_pwd", ["sql" => 'data', "default_value" => '', "is_null_allowed" => true, "allowed_values" => null, "depends_on" => []]));
// Display lists
- MetaModel::Init_SetZListItems('details', array('date', 'userinfo', 'attcode')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('date', 'userinfo', 'attcode')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['date', 'userinfo', 'attcode']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['date', 'userinfo', 'attcode']); // Attributes to be displayed for a list
}
/**
@@ -523,7 +524,7 @@ class CMDBChangeOpSetAttributeOneWayPassword extends CMDBChangeOpSetAttribute
{
// Temporary, until we change the options of GetDescription() -needs a more global revision
$bIsHtml = true;
-
+
$sResult = '';
$oTargetObjectClass = $this->Get('objclass');
$oTargetObjectKey = $this->Get('objkey');
@@ -531,15 +532,11 @@ class CMDBChangeOpSetAttributeOneWayPassword extends CMDBChangeOpSetAttribute
$oTargetSearch->AddCondition('id', $oTargetObjectKey, '=');
$oMonoObjectSet = new DBObjectSet($oTargetSearch);
- if (UserRights::IsActionAllowedOnAttribute($this->Get('objclass'), $this->Get('attcode'), UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES)
- {
- if (MetaModel::IsValidAttCode($this->Get('objclass'), $this->Get('attcode')))
- {
+ if (UserRights::IsActionAllowedOnAttribute($this->Get('objclass'), $this->Get('attcode'), UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES) {
+ if (MetaModel::IsValidAttCode($this->Get('objclass'), $this->Get('attcode'))) {
$oAttDef = MetaModel::GetAttributeDef($this->Get('objclass'), $this->Get('attcode'));
$sAttName = $oAttDef->GetLabel();
- }
- else
- {
+ } else {
// The attribute was renamed or removed from the object ?
$sAttName = $this->Get('attcode');
}
@@ -559,24 +556,24 @@ class CMDBChangeOpSetAttributeEncrypted extends CMDBChangeOpSetAttribute
*/
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_setatt_encrypted",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeEncryptedString("prevstring", array("sql" => 'data', "default_value" => '', "is_null_allowed"=> true, "allowed_values" => null, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeEncryptedString("prevstring", ["sql" => 'data', "default_value" => '', "is_null_allowed" => true, "allowed_values" => null, "depends_on" => []]));
// Display lists
- MetaModel::Init_SetZListItems('details', array('date', 'userinfo', 'attcode')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('date', 'userinfo', 'attcode')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['date', 'userinfo', 'attcode']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['date', 'userinfo', 'attcode']); // Attributes to be displayed for a list
}
/**
@@ -586,7 +583,7 @@ class CMDBChangeOpSetAttributeEncrypted extends CMDBChangeOpSetAttribute
{
// Temporary, until we change the options of GetDescription() -needs a more global revision
$bIsHtml = true;
-
+
$sResult = '';
$oTargetObjectClass = $this->Get('objclass');
$oTargetObjectKey = $this->Get('objkey');
@@ -594,15 +591,11 @@ class CMDBChangeOpSetAttributeEncrypted extends CMDBChangeOpSetAttribute
$oTargetSearch->AddCondition('id', $oTargetObjectKey, '=');
$oMonoObjectSet = new DBObjectSet($oTargetSearch);
- if (UserRights::IsActionAllowedOnAttribute($this->Get('objclass'), $this->Get('attcode'), UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES)
- {
- if (MetaModel::IsValidAttCode($this->Get('objclass'), $this->Get('attcode')))
- {
+ if (UserRights::IsActionAllowedOnAttribute($this->Get('objclass'), $this->Get('attcode'), UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES) {
+ if (MetaModel::IsValidAttCode($this->Get('objclass'), $this->Get('attcode'))) {
$oAttDef = MetaModel::GetAttributeDef($this->Get('objclass'), $this->Get('attcode'));
$sAttName = $oAttDef->GetLabel();
- }
- else
- {
+ } else {
// The attribute was renamed or removed from the object ?
$sAttName = $this->Get('attcode');
}
@@ -625,24 +618,24 @@ class CMDBChangeOpSetAttributeText extends CMDBChangeOpSetAttribute
*/
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_setatt_text",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeText("prevdata", array("allowed_values"=>null, "sql"=>"prevdata", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeText("prevdata", ["allowed_values" => null, "sql" => "prevdata", "default_value" => "", "is_null_allowed" => true, "depends_on" => []]));
// Display lists
- MetaModel::Init_SetZListItems('details', array('date', 'userinfo', 'attcode')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('date', 'userinfo', 'attcode')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['date', 'userinfo', 'attcode']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['date', 'userinfo', 'attcode']); // Attributes to be displayed for a list
}
/**
@@ -652,7 +645,7 @@ class CMDBChangeOpSetAttributeText extends CMDBChangeOpSetAttribute
{
// Temporary, until we change the options of GetDescription() -needs a more global revision
$bIsHtml = true;
-
+
$sResult = '';
$oTargetObjectClass = $this->Get('objclass');
$oTargetObjectKey = $this->Get('objkey');
@@ -660,15 +653,11 @@ class CMDBChangeOpSetAttributeText extends CMDBChangeOpSetAttribute
$oTargetSearch->AddCondition('id', $oTargetObjectKey, '=');
$oMonoObjectSet = new DBObjectSet($oTargetSearch);
- if (UserRights::IsActionAllowedOnAttribute($this->Get('objclass'), $this->Get('attcode'), UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES)
- {
- if (MetaModel::IsValidAttCode($this->Get('objclass'), $this->Get('attcode')))
- {
+ if (UserRights::IsActionAllowedOnAttribute($this->Get('objclass'), $this->Get('attcode'), UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES) {
+ if (MetaModel::IsValidAttCode($this->Get('objclass'), $this->Get('attcode'))) {
$oAttDef = MetaModel::GetAttributeDef($this->Get('objclass'), $this->Get('attcode'));
$sAttName = $oAttDef->GetLabel();
- }
- else
- {
+ } else {
// The attribute was renamed or removed from the object ?
$sAttName = $this->Get('attcode');
}
@@ -693,24 +682,24 @@ class CMDBChangeOpSetAttributeLongText extends CMDBChangeOpSetAttribute
*/
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_setatt_longtext",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeLongText("prevdata", array("allowed_values"=>null, "sql"=>"prevdata", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeLongText("prevdata", ["allowed_values" => null, "sql" => "prevdata", "default_value" => "", "is_null_allowed" => true, "depends_on" => []]));
// Display lists
- MetaModel::Init_SetZListItems('details', array('date', 'userinfo', 'attcode')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('date', 'userinfo', 'attcode')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['date', 'userinfo', 'attcode']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['date', 'userinfo', 'attcode']); // Attributes to be displayed for a list
}
/**
@@ -725,15 +714,11 @@ class CMDBChangeOpSetAttributeLongText extends CMDBChangeOpSetAttribute
$oTargetSearch->AddCondition('id', $oTargetObjectKey, '=');
$oMonoObjectSet = new DBObjectSet($oTargetSearch);
- if (UserRights::IsActionAllowedOnAttribute($this->Get('objclass'), $this->Get('attcode'), UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES)
- {
- if (MetaModel::IsValidAttCode($this->Get('objclass'), $this->Get('attcode')))
- {
+ if (UserRights::IsActionAllowedOnAttribute($this->Get('objclass'), $this->Get('attcode'), UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES) {
+ if (MetaModel::IsValidAttCode($this->Get('objclass'), $this->Get('attcode'))) {
$oAttDef = MetaModel::GetAttributeDef($this->Get('objclass'), $this->Get('attcode'));
$sAttName = $oAttDef->GetLabel();
- }
- else
- {
+ } else {
// The attribute was renamed or removed from the object ?
$sAttName = $this->Get('attcode');
}
@@ -758,23 +743,23 @@ class CMDBChangeOpSetAttributeHTML extends CMDBChangeOpSetAttributeLongText
*/
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_setatt_html",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
-
+
// Display lists
- MetaModel::Init_SetZListItems('details', array('date', 'userinfo', 'attcode')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('date', 'userinfo', 'attcode')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['date', 'userinfo', 'attcode']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['date', 'userinfo', 'attcode']); // Attributes to be displayed for a list
}
/**
@@ -787,10 +772,9 @@ class CMDBChangeOpSetAttributeHTML extends CMDBChangeOpSetAttributeLongText
$oTargetObjectKey = $this->Get('objkey');
$oTargetSearch = new DBObjectSearch($oTargetObjectClass);
$oTargetSearch->AddCondition('id', $oTargetObjectKey, '=');
-
+
$oMonoObjectSet = new DBObjectSet($oTargetSearch);
- if (UserRights::IsActionAllowedOnAttribute($this->Get('objclass'), $this->Get('attcode'), UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES)
- {
+ if (UserRights::IsActionAllowedOnAttribute($this->Get('objclass'), $this->Get('attcode'), UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES) {
if (MetaModel::IsValidAttCode($this->Get('objclass'), $this->Get('attcode'))) {
$oAttDef = MetaModel::GetAttributeDef($this->Get('objclass'), $this->Get('attcode'));
$sAttName = $oAttDef->GetLabel();
@@ -804,7 +788,7 @@ class CMDBChangeOpSetAttributeHTML extends CMDBChangeOpSetAttributeLongText
$sResult = Dict::Format('Change:AttName_Changed_PreviousValue_OldValue', $sAttName, $sTextView);
}
return $sResult;
- }
+ }
}
/**
@@ -822,24 +806,24 @@ class CMDBChangeOpSetAttributeCaseLog extends CMDBChangeOpSetAttribute
*/
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_setatt_log",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeInteger("lastentry", array("allowed_values"=>null, "sql"=>"lastentry", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeInteger("lastentry", ["allowed_values" => null, "sql" => "lastentry", "default_value" => 0, "is_null_allowed" => true, "depends_on" => []]));
// Display lists
- MetaModel::Init_SetZListItems('details', array('date', 'userinfo', 'attcode')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('date', 'userinfo', 'attcode')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['date', 'userinfo', 'attcode']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['date', 'userinfo', 'attcode']); // Attributes to be displayed for a list
}
/**
@@ -849,7 +833,7 @@ class CMDBChangeOpSetAttributeCaseLog extends CMDBChangeOpSetAttribute
{
// Temporary, until we change the options of GetDescription() -needs a more global revision
$bIsHtml = true;
-
+
$sResult = '';
$oTargetObjectClass = $this->Get('objclass');
$oTargetObjectKey = $this->Get('objkey');
@@ -857,15 +841,11 @@ class CMDBChangeOpSetAttributeCaseLog extends CMDBChangeOpSetAttribute
$oTargetSearch->AddCondition('id', $oTargetObjectKey, '=');
$oMonoObjectSet = new DBObjectSet($oTargetSearch);
- if (UserRights::IsActionAllowedOnAttribute($this->Get('objclass'), $this->Get('attcode'), UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES)
- {
- if (MetaModel::IsValidAttCode($this->Get('objclass'), $this->Get('attcode')))
- {
+ if (UserRights::IsActionAllowedOnAttribute($this->Get('objclass'), $this->Get('attcode'), UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES) {
+ if (MetaModel::IsValidAttCode($this->Get('objclass'), $this->Get('attcode'))) {
$oAttDef = MetaModel::GetAttributeDef($this->Get('objclass'), $this->Get('attcode'));
$sAttName = $oAttDef->GetLabel();
- }
- else
- {
+ } else {
// The attribute was renamed or removed from the object ?
$sAttName = $this->Get('attcode');
}
@@ -885,12 +865,12 @@ class CMDBChangeOpSetAttributeCaseLog extends CMDBChangeOpSetAttribute
*/
protected function ToHtml($sRawText)
{
- return str_replace(array("\r\n", "\n", "\r"), " ", utils::EscapeHtml($sRawText));
+ return str_replace(["\r\n", "\n", "\r"], " ", utils::EscapeHtml($sRawText));
}
}
/**
- * Record an action made by a plug-in
+ * Record an action made by a plug-in
*
* @package iTopORM
*/
@@ -901,19 +881,19 @@ class CMDBChangeOpPlugin 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_plugin",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
- MetaModel::Init_AddAttribute(new AttributeString("description", array("allowed_values"=>null, "sql"=>"description", "default_value"=>'', "is_null_allowed"=>false, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeString("description", ["allowed_values" => null, "sql" => "description", "default_value" => '', "is_null_allowed" => false, "depends_on" => []]));
/* May be used later when implementing an extension mechanism that will allow the plug-ins to store some extra information and still degrades gracefully when the plug-in is desinstalled
MetaModel::Init_AddAttribute(new AttributeString("extension_class", array("allowed_values"=>null, "sql"=>"extension_class", "default_value"=>'', "is_null_allowed"=>false, "depends_on"=>array())));
MetaModel::Init_AddAttribute(new AttributeInteger("extension_id", array("allowed_values"=>null, "sql"=>"extension_id", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
@@ -931,7 +911,7 @@ class CMDBChangeOpPlugin extends CMDBChangeOp
}
/**
- * Record added/removed objects from within a link set
+ * Record added/removed objects from within a link set
*
* @package iTopORM
*/
@@ -942,29 +922,29 @@ abstract class CMDBChangeOpSetAttributeLinks extends CMDBChangeOpSetAttribute
*/
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_links",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
// Note: item class/id points to the link class itself in case of a direct link set (e.g. Server::interface_list => Interface)
// item class/id points to the remote class in case of a indirect link set (e.g. Server::contract_list => Contract)
- MetaModel::Init_AddAttribute(new AttributeString("item_class", array("allowed_values"=>null, "sql"=>"item_class", "default_value"=>'', "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeInteger("item_id", array("allowed_values"=>null, "sql"=>"item_id", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeString("item_class", ["allowed_values" => null, "sql" => "item_class", "default_value" => '', "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeInteger("item_id", ["allowed_values" => null, "sql" => "item_id", "default_value" => 0, "is_null_allowed" => false, "depends_on" => []]));
}
}
/**
- * Record added/removed objects from within a link set
+ * Record added/removed objects from within a link set
*
* @package iTopORM
*/
@@ -975,21 +955,21 @@ class CMDBChangeOpSetAttributeLinksAddRemove extends CMDBChangeOpSetAttributeLin
*/
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_links_addremove",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeEnum("type", array("allowed_values"=>new ValueSetEnum('added,removed'), "sql"=>"type", "default_value"=>"added", "is_null_allowed"=>false, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeEnum("type", ["allowed_values" => new ValueSetEnum('added,removed'), "sql" => "type", "default_value" => "added", "is_null_allowed" => false, "depends_on" => []]));
}
/**
@@ -1004,9 +984,10 @@ class CMDBChangeOpSetAttributeLinksAddRemove extends CMDBChangeOpSetAttributeLin
$oTargetSearch->AddCondition('id', $oTargetObjectKey, '=');
$oMonoObjectSet = new DBObjectSet($oTargetSearch);
- if (UserRights::IsActionAllowedOnAttribute($this->Get('objclass'), $this->Get('attcode'), UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES)
- {
- if (!MetaModel::IsValidAttCode($this->Get('objclass'), $this->Get('attcode'))) return ''; // Protects against renamed attributes...
+ if (UserRights::IsActionAllowedOnAttribute($this->Get('objclass'), $this->Get('attcode'), UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES) {
+ if (!MetaModel::IsValidAttCode($this->Get('objclass'), $this->Get('attcode'))) {
+ return '';
+ } // Protects against renamed attributes...
$oAttDef = MetaModel::GetAttributeDef($this->Get('objclass'), $this->Get('attcode'));
$sAttName = $oAttDef->GetLabel();
@@ -1014,15 +995,14 @@ class CMDBChangeOpSetAttributeLinksAddRemove extends CMDBChangeOpSetAttributeLin
$sItemDesc = MetaModel::GetHyperLink($this->Get('item_class'), $this->Get('item_id'));
$sResult = $sAttName.' - ';
- switch ($this->Get('type'))
- {
- case 'added':
- $sResult .= Dict::Format('Change:LinkSet:Added', $sItemDesc);
- break;
+ switch ($this->Get('type')) {
+ case 'added':
+ $sResult .= Dict::Format('Change:LinkSet:Added', $sItemDesc);
+ break;
- case 'removed':
- $sResult .= Dict::Format('Change:LinkSet:Removed', $sItemDesc);
- break;
+ case 'removed':
+ $sResult .= Dict::Format('Change:LinkSet:Removed', $sItemDesc);
+ break;
}
}
return $sResult;
@@ -1031,7 +1011,7 @@ class CMDBChangeOpSetAttributeLinksAddRemove extends CMDBChangeOpSetAttributeLin
/**
* Record attribute changes from within a link set
- * A single record redirects to the modifications made within the same change
+ * A single record redirects to the modifications made within the same change
*
* @package iTopORM
*/
@@ -1042,21 +1022,21 @@ class CMDBChangeOpSetAttributeLinksTune extends CMDBChangeOpSetAttributeLinks
*/
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_links_tune",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeInteger("link_id", array("allowed_values"=>null, "sql"=>"link_id", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeInteger("link_id", ["allowed_values" => null, "sql" => "link_id", "default_value" => 0, "is_null_allowed" => false, "depends_on" => []]));
}
/**
@@ -1071,9 +1051,10 @@ class CMDBChangeOpSetAttributeLinksTune extends CMDBChangeOpSetAttributeLinks
$oTargetSearch->AddCondition('id', $oTargetObjectKey, '=');
$oMonoObjectSet = new DBObjectSet($oTargetSearch);
- if (UserRights::IsActionAllowedOnAttribute($this->Get('objclass'), $this->Get('attcode'), UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES)
- {
- if (!MetaModel::IsValidAttCode($this->Get('objclass'), $this->Get('attcode'))) return ''; // Protects against renamed attributes...
+ if (UserRights::IsActionAllowedOnAttribute($this->Get('objclass'), $this->Get('attcode'), UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES) {
+ if (!MetaModel::IsValidAttCode($this->Get('objclass'), $this->Get('attcode'))) {
+ return '';
+ } // Protects against renamed attributes...
$oAttDef = MetaModel::GetAttributeDef($this->Get('objclass'), $this->Get('attcode'));
$sAttName = $oAttDef->GetLabel();
@@ -1086,27 +1067,22 @@ class CMDBChangeOpSetAttributeLinksTune extends CMDBChangeOpSetAttributeLinks
$oSearch = new DBObjectSearch('CMDBChangeOpSetAttribute');
$oSearch->AddCondition('change', $this->Get('change'), '=');
$oSearch->AddCondition('objkey', $this->Get('link_id'), '=');
- if (count($aLinkClasses) == 1)
- {
+ if (count($aLinkClasses) == 1) {
// Faster than the whole building of the expression below for just one value ??
$oSearch->AddCondition('objclass', $sLinkClass, '=');
- }
- else
- {
- $oField = new FieldExpression('objclass', $oSearch->GetClassAlias());
+ } else {
+ $oField = new FieldExpression('objclass', $oSearch->GetClassAlias());
$sListExpr = '('.implode(', ', CMDBSource::Quote($aLinkClasses)).')';
$sOQLCondition = $oField->RenderExpression()." IN $sListExpr";
$oNewCondition = Expression::FromOQL($sOQLCondition);
$oSearch->AddConditionExpression($oNewCondition);
}
$oSet = new DBObjectSet($oSearch);
- $aChanges = array();
- while ($oChangeOp = $oSet->Fetch())
- {
+ $aChanges = [];
+ while ($oChangeOp = $oSet->Fetch()) {
$aChanges[] = $oChangeOp->GetDescription();
}
- if (count($aChanges) == 0)
- {
+ if (count($aChanges) == 0) {
return '';
}
@@ -1132,24 +1108,24 @@ class CMDBChangeOpSetAttributeCustomFields extends CMDBChangeOpSetAttribute
*/
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_setatt_custfields",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeLongText("prevdata", array("allowed_values"=>null, "sql"=>"prevdata", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeLongText("prevdata", ["allowed_values" => null, "sql" => "prevdata", "default_value" => "", "is_null_allowed" => true, "depends_on" => []]));
// Display lists
- MetaModel::Init_SetZListItems('details', array('date', 'userinfo', 'attcode')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('date', 'userinfo', 'attcode')); // Attributes to be displayed for a list
+ MetaModel::Init_SetZListItems('details', ['date', 'userinfo', 'attcode']); // Attributes to be displayed for the complete details
+ MetaModel::Init_SetZListItems('list', ['date', 'userinfo', 'attcode']); // Attributes to be displayed for a list
}
/**
@@ -1158,26 +1134,22 @@ class CMDBChangeOpSetAttributeCustomFields extends CMDBChangeOpSetAttribute
public function GetDescription()
{
$sResult = '';
- if (MetaModel::IsValidAttCode($this->Get('objclass'), $this->Get('attcode')))
- {
+ if (MetaModel::IsValidAttCode($this->Get('objclass'), $this->Get('attcode'))) {
$oTargetObjectClass = $this->Get('objclass');
$oTargetObjectKey = $this->Get('objkey');
$oTargetSearch = new DBObjectSearch($oTargetObjectClass);
$oTargetSearch->AddCondition('id', $oTargetObjectKey, '=');
$oMonoObjectSet = new DBObjectSet($oTargetSearch);
- if (UserRights::IsActionAllowedOnAttribute($this->Get('objclass'), $this->Get('attcode'), UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES)
- {
+ if (UserRights::IsActionAllowedOnAttribute($this->Get('objclass'), $this->Get('attcode'), UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES) {
$aValues = json_decode($this->Get('prevdata'), true);
$oAttDef = MetaModel::GetAttributeDef($this->Get('objclass'), $this->Get('attcode'));
$sAttName = $oAttDef->GetLabel();
- try
- {
+ try {
$oHandler = $oAttDef->GetHandler($aValues);
$sValueDesc = $oHandler->GetAsHTML($aValues);
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
$sValueDesc = 'Custom field error: '.utils::EscapeHtml($e->getMessage());
}
$sTextView = ''.$sValueDesc.'
';
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..8b17a931d 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, 'stack' => $e->getTraceAsString()]);
} finally {
- $oKPI->ComputeStats('Query exec (mySQL)', $sSql);
- }
+ $oKPI->ComputeStats('Query exec (mySQL)', $sSql);
+ }
if ($oResult === false) {
- $aContext = array('query' => $sSql);
+ $aContext = ["\nstack" => (new Exception(''))->getTraceAsString(), "\nquery" => $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/computing.inc.php b/core/computing.inc.php
index f183e737c..88283492c 100644
--- a/core/computing.inc.php
+++ b/core/computing.inc.php
@@ -1,4 +1,5 @@
*/
-
/**
* Any extension to compute things like a stop watch deadline or working hours
*
@@ -29,7 +29,7 @@
/**
* Metric computing for stop watches.
* Can be used for AttributeStopWatch goal (iTop XML node xpath: /itop_design/classes/class/fields/field/goal)
- */
+ */
interface iMetricComputer
{
public static function GetDescription();
@@ -44,7 +44,7 @@ interface iMetricComputer
/**
* Working time computing for stop watches
- */
+ */
interface iWorkingTimeComputer
{
public static function GetDescription();
@@ -58,7 +58,7 @@ interface iWorkingTimeComputer
* considering only the valid (open) hours for a specified object
*/
public function GetDeadline($oObject, $iDuration, DateTime $oStartDate);
-
+
/**
* @param DBObject $oObject The object for which to compute the duration
* @param DateTime $oStartDate The starting point for the computation (default = now)
@@ -87,7 +87,7 @@ class DefaultMetricComputer implements iMetricComputer
/**
* Default implementation of working time computing
- */
+ */
class DefaultWorkingTimeComputer implements iWorkingTimeComputer
{
public static function GetDescription()
@@ -100,8 +100,7 @@ class DefaultWorkingTimeComputer implements iWorkingTimeComputer
*/
public function GetDeadline($oObject, $iDuration, DateTime $oStartDate)
{
- if (class_exists('WorkingTimeRecorder'))
- {
+ if (class_exists('WorkingTimeRecorder')) {
WorkingTimeRecorder::Trace(WorkingTimeRecorder::TRACE_DEBUG, __class__.'::'.__function__);
}
//echo "GetDeadline - default: ".$oStartDate->format('Y-m-d H:i:s')." + $iDuration \n";
@@ -109,26 +108,23 @@ class DefaultWorkingTimeComputer implements iWorkingTimeComputer
// the specified duration to the given date/time
$oResult = clone $oStartDate;
$oResult->modify($iDuration.' seconds');
- if (class_exists('WorkingTimeRecorder'))
- {
+ if (class_exists('WorkingTimeRecorder')) {
WorkingTimeRecorder::SetValues($oStartDate->format('U'), $oResult->format('U'), $iDuration, WorkingTimeRecorder::COMPUTED_END);
}
return $oResult;
}
-
+
/**
* @inheritDoc
*/
public function GetOpenDuration($oObject, DateTime $oStartDate, DateTime $oEndDate)
{
- if (class_exists('WorkingTimeRecorder'))
- {
+ if (class_exists('WorkingTimeRecorder')) {
WorkingTimeRecorder::Trace(WorkingTimeRecorder::TRACE_DEBUG, __class__.'::'.__function__);
}
//echo "GetOpenDuration - default: ".$oStartDate->format('Y-m-d H:i:s')." to ".$oEndDate->format('Y-m-d H:i:s')." \n";
$iDuration = abs($oEndDate->format('U') - $oStartDate->format('U'));
- if (class_exists('WorkingTimeRecorder'))
- {
+ if (class_exists('WorkingTimeRecorder')) {
WorkingTimeRecorder::SetValues($oStartDate->format('U'), $oEndDate->format('U'), $iDuration, WorkingTimeRecorder::COMPUTED_DURATION);
}
return $iDuration;
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/contexttag.class.inc.php b/core/contexttag.class.inc.php
index 760df778c..698a21d00 100644
--- a/core/contexttag.class.inc.php
+++ b/core/contexttag.class.inc.php
@@ -1,4 +1,5 @@
-
/**
* Simple helper class for keeping track of the context inside the call stack
*
@@ -63,7 +63,7 @@ class ContextTag
* @since 3.1.0 N°6047
*/
public const TAG_IMPORT = 'Import';
- /**
+ /**
* @since 3.1.0 N°6047
*/
public const TAG_EXPORT = 'Export';
@@ -74,7 +74,7 @@ class ContextTag
*/
public const TAG_OBJECT_SEARCH = 'ObjectSearch';
- protected static $aStack = array();
+ protected static $aStack = [];
/**
* Store a context tag on the stack
@@ -124,33 +124,29 @@ class ContextTag
*/
public static function GetTags()
{
- $aRawTags = array(
+ $aRawTags = [
ContextTag::TAG_REST,
ContextTag::TAG_SYNCHRO,
ContextTag::TAG_SETUP,
ContextTag::TAG_CONSOLE,
ContextTag::TAG_CRON,
- ContextTag::TAG_PORTAL);
+ ContextTag::TAG_PORTAL];
- $aTags = array();
+ $aTags = [];
- foreach ($aRawTags as $sRawTag)
- {
+ foreach ($aRawTags as $sRawTag) {
$aTags[$sRawTag] = Dict::S("Core:Context={$sRawTag}");
}
$aPortalsConf = PortalDispatcherData::GetData();
- $aDispatchers = array();
- foreach ($aPortalsConf as $sPortalId => $aConf)
- {
+ $aDispatchers = [];
+ foreach ($aPortalsConf as $sPortalId => $aConf) {
$sHandlerClass = $aConf['handler'];
$aDispatchers[$sPortalId] = new $sHandlerClass($sPortalId);
}
- foreach ($aDispatchers as $sPortalId => $oDispatcher)
- {
- if ($sPortalId != 'backoffice')
- {
+ foreach ($aDispatchers as $sPortalId => $oDispatcher) {
+ if ($sPortalId != 'backoffice') {
$aTags['Portal:'.$sPortalId] = $oDispatcher->GetLabel();
}
}
diff --git a/core/counter.class.inc.php b/core/counter.class.inc.php
index 69ec0a2eb..ad53e03ca 100644
--- a/core/counter.class.inc.php
+++ b/core/counter.class.inc.php
@@ -1,4 +1,5 @@
Lock();
$bIsInsideTransaction = CMDBSource::IsInsideTransaction();
- if ($bIsInsideTransaction)
- {
+ if ($bIsInsideTransaction) {
// # Transaction isolation hack:
// When inside a transaction, we need to open a new connection for the counter.
// So it is visible immediately to the connections outside of the transaction.
@@ -59,75 +57,61 @@ final class ItopCounter
// we did not wanted this! As opening a short connection is less prone to starving than a long running one.
// Plus it would trigger way more deadlocks!
$hDBLink = self::InitMySQLSession();
- }
- else
- {
+ } else {
$hDBLink = CMDBSource::GetMysqli();
}
- try
- {
- $oFilter = DBObjectSearch::FromOQL('SELECT KeyValueStore WHERE key_name=:key_name AND namespace=:namespace', array(
+ try {
+ $oFilter = DBObjectSearch::FromOQL('SELECT KeyValueStore WHERE key_name=:key_name AND namespace=:namespace', [
'key_name' => $sCounterName,
'namespace' => $sSelfClassName,
- ));
+ ]);
$oAttDef = MetaModel::GetAttributeDef(KeyValueStore::class, 'value');
- $aAttToLoad = array(KeyValueStore::class => array('value' => $oAttDef));
- $sSql = $oFilter->MakeSelectQuery(array(), array(), $aAttToLoad);
+ $aAttToLoad = [KeyValueStore::class => ['value' => $oAttDef]];
+ $sSql = $oFilter->MakeSelectQuery([], [], $aAttToLoad);
$hResult = mysqli_query($hDBLink, $sSql);
$aCounter = mysqli_fetch_array($hResult, MYSQLI_NUM);
mysqli_free_result($hResult);
//Rebuild the filter, as the MakeSelectQuery polluted the orignal and it cannot be reused
- $oFilter = DBObjectSearch::FromOQL('SELECT KeyValueStore WHERE key_name=:key_name AND namespace=:namespace', array(
+ $oFilter = DBObjectSearch::FromOQL('SELECT KeyValueStore WHERE key_name=:key_name AND namespace=:namespace', [
'key_name' => $sCounterName,
'namespace' => $sSelfClassName,
- ));
+ ]);
- if (is_null($aCounter))
- {
- if (null != $oNewObjectValueProvider)
- {
+ if (is_null($aCounter)) {
+ if (null != $oNewObjectValueProvider) {
$iComputedValue = $oNewObjectValueProvider();
- }
- else
- {
+ } else {
$iComputedValue = 0;
}
$iCurrentValue = $iComputedValue + 1;
- $aQueryParams = array(
+ $aQueryParams = [
'key_name' => $sCounterName,
'value' => "$iCurrentValue",
'namespace' => $sSelfClassName,
- );
+ ];
$sSql = $oFilter->MakeInsertQuery($aQueryParams);
- }
- else
- {
+ } else {
$iCurrentValue = (int) $aCounter[1];
$iCurrentValue++;
- $aQueryParams = array(
+ $aQueryParams = [
'value' => "$iCurrentValue",
- );
+ ];
$sSql = $oFilter->MakeUpdateQuery($aQueryParams);
}
$hResult = mysqli_query($hDBLink, $sSql);
- }
- catch(Exception $e)
- {
+ } catch (Exception $e) {
IssueLog::Error($e->getMessage());
throw $e;
- }
- finally
- {
- if ($bIsInsideTransaction)
- {
+ } finally {
+ if ($bIsInsideTransaction) {
mysqli_close($hDBLink);
}
$oiTopMutex->Unlock();
@@ -157,8 +141,7 @@ final class ItopCounter
{
$sRootClass = MetaModel::GetRootClass($sLeafClass);
- $oNewObjectCallback = function() use ($sRootClass)
- {
+ $oNewObjectCallback = function () use ($sRootClass) {
$sRootTable = MetaModel::DBGetTable($sRootClass);
$sIdField = MetaModel::DBGetKey($sRootClass);
@@ -186,17 +169,14 @@ final class ItopCounter
$hDBLink = CMDBSource::GetMysqliInstance($sDBHost, $sDBUser, $sDBPwd, $sDBName, $bDBTlsEnabled, $sDBTlsCA, false);
- if (!$hDBLink)
- {
- throw new MySQLException('Could not connect to the DB server '.mysqli_connect_error().' (mysql errno: '.mysqli_connect_errno(), array('host' => $sDBHost, 'user' => $sDBUser));
- }
+ if (!$hDBLink) {
+ throw new MySQLException('Could not connect to the DB server '.mysqli_connect_error().' (mysql errno: '.mysqli_connect_errno(), ['host' => $sDBHost, 'user' => $sDBUser]);
+ }
return $hDBLink;
}
}
-
-
/**
* Persistent classes for a CMDB
*
@@ -208,44 +188,43 @@ class KeyValueStore extends DBObject
{
public static function Init()
{
- $aParams = array(
+ $aParams = [
'category' => '',
'key_type' => 'autoincrement',
- 'name_attcode' => array('key_name'),
+ 'name_attcode' => ['key_name'],
'state_attcode' => '',
- 'reconc_keys' => array(''),
+ 'reconc_keys' => [''],
'db_table' => 'key_value_store',
'db_key_field' => 'id',
'db_finalclass_field' => '',
- 'indexes' => array (
- array (
+ 'indexes' => [
+ [
0 => 'key_name',
1 => 'namespace',
- ),
- ),);
+ ],
+ ],];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeString("namespace", array("allowed_values"=>null, "sql"=>'namespace', "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array(), "always_load_in_tables"=>false)));
- MetaModel::Init_AddAttribute(new AttributeString("key_name", array("allowed_values"=>null, "sql"=>'key_name', "default_value"=>'', "is_null_allowed"=>false, "depends_on"=>array(), "always_load_in_tables"=>false)));
- MetaModel::Init_AddAttribute(new AttributeString("value", array("allowed_values"=>null, "sql"=>'value', "default_value"=>'0', "is_null_allowed"=>false, "depends_on"=>array(), "always_load_in_tables"=>false)));
+ MetaModel::Init_AddAttribute(new AttributeString("namespace", ["allowed_values" => null, "sql" => 'namespace', "default_value" => null, "is_null_allowed" => true, "depends_on" => [], "always_load_in_tables" => false]));
+ MetaModel::Init_AddAttribute(new AttributeString("key_name", ["allowed_values" => null, "sql" => 'key_name', "default_value" => '', "is_null_allowed" => false, "depends_on" => [], "always_load_in_tables" => false]));
+ MetaModel::Init_AddAttribute(new AttributeString("value", ["allowed_values" => null, "sql" => 'value', "default_value" => '0', "is_null_allowed" => false, "depends_on" => [], "always_load_in_tables" => false]));
- MetaModel::Init_SetZListItems('details', array (
+ MetaModel::Init_SetZListItems('details', [
0 => 'key_name',
1 => 'value',
2 => 'namespace',
- ));
- MetaModel::Init_SetZListItems('standard_search', array (
+ ]);
+ MetaModel::Init_SetZListItems('standard_search', [
0 => 'key_name',
1 => 'value',
2 => 'namespace',
- ));
- MetaModel::Init_SetZListItems('list', array (
+ ]);
+ MetaModel::Init_SetZListItems('list', [
0 => 'key_name',
1 => 'value',
2 => 'namespace',
- ));
+ ]);
;
}
-
-}
\ No newline at end of file
+}
diff --git a/core/csvbulkexport.class.inc.php b/core/csvbulkexport.class.inc.php
index 62d4e990b..bc0d957ac 100644
--- a/core/csvbulkexport.class.inc.php
+++ b/core/csvbulkexport.class.inc.php
@@ -1,4 +1,5 @@
aStatusInfo['separator'] = utils::ReadParam('separator', ',', true, 'raw_data');
- if (strtolower($this->aStatusInfo['separator']) == 'tab')
- {
+ if (strtolower($this->aStatusInfo['separator']) == 'tab') {
$this->aStatusInfo['separator'] = "\t";
- }
- else if (strtolower($this->aStatusInfo['separator']) == 'other')
- {
+ } elseif (strtolower($this->aStatusInfo['separator']) == 'other') {
$this->aStatusInfo['separator'] = utils::ReadParam('other-separator', ',', true, 'raw_data');
}
-
+
$this->aStatusInfo['text_qualifier'] = utils::ReadParam('text-qualifier', '"', true, 'raw_data');
- if (strtolower($this->aStatusInfo['text_qualifier']) == 'other')
- {
+ if (strtolower($this->aStatusInfo['text_qualifier']) == 'other') {
$this->aStatusInfo['text_qualifier'] = utils::ReadParam('other-text-qualifier', '"', true, 'raw_data');
}
$this->aStatusInfo['charset'] = strtoupper(utils::ReadParam('charset', 'UTF-8', true, 'raw_data'));
$this->aStatusInfo['formatted_text'] = (bool)utils::ReadParam('formatted_text', 0, true);
-
+
$sDateFormatRadio = utils::ReadParam('csv_date_format_radio', '');
- switch($sDateFormatRadio)
- {
+ switch ($sDateFormatRadio) {
case 'default':
- // Export from the UI => format = same as is the UI
- $this->aStatusInfo['date_format'] = (string)AttributeDateTime::GetFormat();
- break;
-
+ // Export from the UI => format = same as is the UI
+ $this->aStatusInfo['date_format'] = (string)AttributeDateTime::GetFormat();
+ break;
+
case 'custom':
- // Custom format specified from the UI
- $this->aStatusInfo['date_format'] = utils::ReadParam('date_format', (string)AttributeDateTime::GetFormat(), true, 'raw_data');
- break;
-
+ // Custom format specified from the UI
+ $this->aStatusInfo['date_format'] = utils::ReadParam('date_format', (string)AttributeDateTime::GetFormat(), true, 'raw_data');
+ break;
+
default:
- // Export from the command line (or scripted) => default format is SQL, as in previous versions of iTop, unless specified otherwise
- $this->aStatusInfo['date_format'] = utils::ReadParam('date_format', (string)AttributeDateTime::GetSQLFormat(), true, 'raw_data');
+ // Export from the command line (or scripted) => default format is SQL, as in previous versions of iTop, unless specified otherwise
+ $this->aStatusInfo['date_format'] = utils::ReadParam('date_format', (string)AttributeDateTime::GetSQLFormat(), true, 'raw_data');
}
}
-
protected function SuggestField($sClass, $sAttCode)
{
- switch($sAttCode)
- {
+ switch ($sAttCode) {
case 'id': // replace 'id' by 'friendlyname'
$sAttCode = 'friendlyname';
break;
-
+
default:
$oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
- if ($oAttDef instanceof AttributeExternalKey)
- {
+ if ($oAttDef instanceof AttributeExternalKey) {
$sAttCode .= '_friendlyname';
}
}
@@ -99,7 +92,7 @@ class CSVBulkExport extends TabularBulkExport
public function EnumFormParts()
{
- return array_merge(parent::EnumFormParts(), array('csv_options' => array('separator', 'charset', 'text-qualifier', 'no_localize', 'formatted_text'), 'interactive_fields_csv' => array('interactive_fields_csv')));
+ return array_merge(parent::EnumFormParts(), ['csv_options' => ['separator', 'charset', 'text-qualifier', 'no_localize', 'formatted_text'], 'interactive_fields_csv' => ['interactive_fields_csv']]);
}
/**
@@ -128,11 +121,11 @@ class CSVBulkExport extends TabularBulkExport
$sRawSeparator = utils::ReadParam('separator', ',', true, 'raw_data');
$sCustomDateTimeFormat = utils::ReadParam('', ',', true, 'raw_data');
- $aSep = array(
+ $aSep = [
';' => Dict::S('UI:CSVImport:SeparatorSemicolon+'),
',' => Dict::S('UI:CSVImport:SeparatorComma+'),
'tab' => Dict::S('UI:CSVImport:SeparatorTab+'),
- );
+ ];
$sOtherSeparator = '';
if (!array_key_exists($sRawSeparator, $aSep)) {
$sOtherSeparator = $sRawSeparator;
@@ -155,10 +148,10 @@ class CSVBulkExport extends TabularBulkExport
$oMulticolumn->AddColumn(ColumnUIBlockFactory::MakeForBlock($oFieldSetTextQualifier));
$sRawQualifier = utils::ReadParam('text-qualifier', '"', true, 'raw_data');
- $aQualifiers = array(
+ $aQualifiers = [
'"' => Dict::S('UI:CSVImport:QualifierDoubleQuote+'),
'\'' => Dict::S('UI:CSVImport:QualifierSimpleQuote+'),
- );
+ ];
$sOtherQualifier = '';
if (!array_key_exists($sRawQualifier, $aQualifiers)) {
$sOtherQualifier = $sRawQualifier;
@@ -230,7 +223,6 @@ class CSVBulkExport extends TabularBulkExport
$oRadioCustom->GetInput()->AddCSSClass('ibo-input-checkbox');
$oFieldSetDate->AddSubBlock($oRadioCustom);
-
$oP->add_ready_script(
<<'.utils::EscapeHtml($oAttDef->GetEditValue($oObj->Get($sAttCode), $oObj)).' ';
@@ -266,14 +256,13 @@ EOF
protected function GetValue($oObj, $sAttCode)
{
- switch($sAttCode)
- {
+ switch ($sAttCode) {
case 'id':
$sRet = $oObj->GetKey();
break;
-
+
default:
- $sRet = trim($oObj->GetAsCSV($sAttCode), '"');
+ $sRet = trim($oObj->GetAsCSV($sAttCode), '"');
}
return $sRet;
}
@@ -285,20 +274,17 @@ EOF
$this->aStatusInfo['position'] = 0;
$this->aStatusInfo['total'] = $oSet->Count();
- $aData = array();
- foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
- {
+ $aData = [];
+ foreach ($this->aStatusInfo['fields'] as $iCol => $aFieldSpec) {
$aData[] = $aFieldSpec['sColLabel'];
}
- $sFrom = array("\r\n", $this->aStatusInfo['text_qualifier']);
- $sTo = array("\n", $this->aStatusInfo['text_qualifier'].$this->aStatusInfo['text_qualifier']);
- foreach($aData as $idx => $sData)
- {
+ $sFrom = ["\r\n", $this->aStatusInfo['text_qualifier']];
+ $sTo = ["\n", $this->aStatusInfo['text_qualifier'].$this->aStatusInfo['text_qualifier']];
+ foreach ($aData as $idx => $sData) {
// Escape and encode (if needed) the headers
$sEscaped = str_replace($sFrom, $sTo, (string)$sData);
$aData[$idx] = $this->aStatusInfo['text_qualifier'].$sEscaped.$this->aStatusInfo['text_qualifier'];
- if ($this->aStatusInfo['charset'] != 'UTF-8')
- {
+ if ($this->aStatusInfo['charset'] != 'UTF-8') {
// Note: due to bugs in the glibc library it's safer to call iconv on the smallest possible string
// and thus to convert field by field and not the whole row or file at once (see ticket N°991)
$aData[$idx] = @iconv('UTF-8', $this->aStatusInfo['charset'].'//IGNORE//TRANSLIT', $aData[$idx]);
@@ -325,45 +311,37 @@ EOF
$sExportDateTimeFormat = $this->aStatusInfo['date_format'];
$oPrevDateTimeFormat = AttributeDateTime::GetFormat();
$oPrevDateFormat = AttributeDate::GetFormat();
- if ($sExportDateTimeFormat !== (string)$oPrevDateTimeFormat)
- {
+ if ($sExportDateTimeFormat !== (string)$oPrevDateTimeFormat) {
// Change date & time formats
$oDateTimeFormat = new DateTimeFormat($sExportDateTimeFormat);
$oDateFormat = new DateTimeFormat($oDateTimeFormat->ToDateFormat());
AttributeDateTime::SetFormat($oDateTimeFormat);
AttributeDate::SetFormat($oDateFormat);
}
- while($aRow = $oSet->FetchAssoc())
- {
+ while ($aRow = $oSet->FetchAssoc()) {
set_time_limit(intval($iLoopTimeLimit));
- $aData = array();
- foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
- {
+ $aData = [];
+ foreach ($this->aStatusInfo['fields'] as $iCol => $aFieldSpec) {
$sAlias = $aFieldSpec['sAlias'];
$sAttCode = $aFieldSpec['sAttCode'];
$sField = '';
$oObj = $aRow[$sAlias];
- if ($oObj != null)
- {
- switch($sAttCode)
- {
+ if ($oObj != null) {
+ switch ($sAttCode) {
case 'id':
$sField = $oObj->GetKey();
break;
-
+
default:
$sField = $oObj->GetAsCSV($sAttCode, $this->aStatusInfo['separator'], $this->aStatusInfo['text_qualifier'], $this->bLocalizeOutput, !$this->aStatusInfo['formatted_text']);
}
}
- if ($this->aStatusInfo['charset'] != 'UTF-8')
- {
+ if ($this->aStatusInfo['charset'] != 'UTF-8') {
// Note: due to bugs in the glibc library it's safer to call iconv on the smallest possible string
// and thus to convert field by field and not the whole row or file at once (see ticket N°991)
$aData[] = @iconv('UTF-8', $this->aStatusInfo['charset'].'//IGNORE//TRANSLIT', $sField);
- }
- else
- {
+ } else {
$aData[] = $sField;
}
}
@@ -375,27 +353,23 @@ EOF
AttributeDate::SetFormat($oPrevDateFormat);
set_time_limit(intval($iPreviousTimeLimit));
$this->aStatusInfo['position'] += $this->iChunkSize;
- if ($this->aStatusInfo['total'] == 0)
- {
+ if ($this->aStatusInfo['total'] == 0) {
$iPercentage = 100;
- }
- else
- {
- $iPercentage = floor(min(100.0, 100.0*$this->aStatusInfo['position']/$this->aStatusInfo['total']));
+ } else {
+ $iPercentage = floor(min(100.0, 100.0 * $this->aStatusInfo['position'] / $this->aStatusInfo['total']));
}
- if ($iCount < $this->iChunkSize)
- {
+ if ($iCount < $this->iChunkSize) {
$sRetCode = 'done';
}
- $aStatus = array('code' => $sRetCode, 'message' => Dict::S('Core:BulkExport:RetrievingData'), 'percentage' => $iPercentage);
+ $aStatus = ['code' => $sRetCode, 'message' => Dict::S('Core:BulkExport:RetrievingData'), 'percentage' => $iPercentage];
return $sData;
}
public function GetSupportedFormats()
{
- return array('csv' => Dict::S('Core:BulkExport:CSVFormat'));
+ return ['csv' => Dict::S('Core:BulkExport:CSVFormat')];
}
public function GetMimeType()
diff --git a/core/csvparser.class.inc.php b/core/csvparser.class.inc.php
index 2ba7ac21a..0af23a685 100644
--- a/core/csvparser.class.inc.php
+++ b/core/csvparser.class.inc.php
@@ -1,10 +1,10 @@
');
-
/**
* CSVParser
*
@@ -41,9 +40,9 @@ class CSVParser
}
protected $m_sCurrCell = '';
- protected $m_aCurrRow = array();
+ protected $m_aCurrRow = [];
protected $m_iToSkip = 0;
- protected $m_aDataSet = array();
+ protected $m_aDataSet = [];
protected function __AddChar($c)
{
@@ -55,27 +54,20 @@ class CSVParser
}
protected function __AddCell($c = null, $aFieldMap = null, $bTrimSpaces = false)
{
- if ($bTrimSpaces)
- {
+ if ($bTrimSpaces) {
$sCell = trim($this->m_sCurrCell);
- }
- else
- {
+ } else {
$sCell = $this->m_sCurrCell;
}
- if ($sCell == NULL_VALUE)
- {
+ if ($sCell == NULL_VALUE) {
$sCell = null;
}
- if (!is_null($aFieldMap))
- {
+ if (!is_null($aFieldMap)) {
$iNextCol = count($this->m_aCurrRow);
$iNextName = $aFieldMap[$iNextCol];
$this->m_aCurrRow[$iNextName] = $sCell;
- }
- else
- {
+ } else {
$this->m_aCurrRow[] = $sCell;
}
$this->m_sCurrCell = '';
@@ -84,33 +76,24 @@ class CSVParser
{
$this->__AddCell($c, $aFieldMap, $bTrimSpaces);
- if ($this->m_iToSkip > 0)
- {
+ if ($this->m_iToSkip > 0) {
$this->m_iToSkip--;
- }
- elseif (count($this->m_aCurrRow) > 1)
- {
+ } elseif (count($this->m_aCurrRow) > 1) {
$this->m_aDataSet[] = $this->m_aCurrRow;
- }
- elseif (count($this->m_aCurrRow) == 1)
- {
+ } elseif (count($this->m_aCurrRow) == 1) {
// Get the unique value
$aValues = array_values($this->m_aCurrRow);
- $sValue = $aValues[0];
- if (strlen($sValue) > 0)
- {
+ $sValue = $aValues[0];
+ if (strlen($sValue) > 0) {
$this->m_aDataSet[] = $this->m_aCurrRow;
}
- }
- else
- {
+ } else {
// blank line, skip silently
}
- $this->m_aCurrRow = array();
-
+ $this->m_aCurrRow = [];
+
// More time for the next row
- if ($this->m_iTimeLimitPerRow !== null)
- {
+ if ($this->m_iTimeLimitPerRow !== null) {
set_time_limit(intval($this->m_iTimeLimitPerRow));
}
}
@@ -124,87 +107,71 @@ class CSVParser
$this->__AddRow($c, $aFieldMap, true);
}
- function ToArray($iToSkip = 1, $aFieldMap = null, $iMax = 0)
+ public function ToArray($iToSkip = 1, $aFieldMap = null, $iMax = 0)
{
- $aTransitions = array();
+ $aTransitions = [];
- $aTransitions[stSTARTING][evBLANK] = array('', stSTARTING);
- $aTransitions[stSTARTING][evSEPARATOR] = array('__AddCell', stSTARTING);
- $aTransitions[stSTARTING][evNEWLINE] = array('__AddRow', stSTARTING);
- $aTransitions[stSTARTING][evTEXTQUAL] = array('', stQUALIFIED);
- $aTransitions[stSTARTING][evOTHERCHAR] = array('__AddChar', stRAW);
- $aTransitions[stSTARTING][evEND] = array('__AddRow', stSTARTING);
+ $aTransitions[stSTARTING][evBLANK] = ['', stSTARTING];
+ $aTransitions[stSTARTING][evSEPARATOR] = ['__AddCell', stSTARTING];
+ $aTransitions[stSTARTING][evNEWLINE] = ['__AddRow', stSTARTING];
+ $aTransitions[stSTARTING][evTEXTQUAL] = ['', stQUALIFIED];
+ $aTransitions[stSTARTING][evOTHERCHAR] = ['__AddChar', stRAW];
+ $aTransitions[stSTARTING][evEND] = ['__AddRow', stSTARTING];
- $aTransitions[stRAW][evBLANK] = array('__AddChar', stRAW);
- $aTransitions[stRAW][evSEPARATOR] = array('__AddCellTrimmed', stSTARTING);
- $aTransitions[stRAW][evNEWLINE] = array('__AddRowTrimmed', stSTARTING);
- $aTransitions[stRAW][evTEXTQUAL] = array('__AddChar', stRAW);
- $aTransitions[stRAW][evOTHERCHAR] = array('__AddChar', stRAW);
- $aTransitions[stRAW][evEND] = array('__AddRowTrimmed', stSTARTING);
+ $aTransitions[stRAW][evBLANK] = ['__AddChar', stRAW];
+ $aTransitions[stRAW][evSEPARATOR] = ['__AddCellTrimmed', stSTARTING];
+ $aTransitions[stRAW][evNEWLINE] = ['__AddRowTrimmed', stSTARTING];
+ $aTransitions[stRAW][evTEXTQUAL] = ['__AddChar', stRAW];
+ $aTransitions[stRAW][evOTHERCHAR] = ['__AddChar', stRAW];
+ $aTransitions[stRAW][evEND] = ['__AddRowTrimmed', stSTARTING];
- $aTransitions[stQUALIFIED][evBLANK] = array('__AddChar', stQUALIFIED);
- $aTransitions[stQUALIFIED][evSEPARATOR] = array('__AddChar', stQUALIFIED);
- $aTransitions[stQUALIFIED][evNEWLINE] = array('__AddChar', stQUALIFIED);
- $aTransitions[stQUALIFIED][evTEXTQUAL] = array('', stESCAPED);
- $aTransitions[stQUALIFIED][evOTHERCHAR] = array('__AddChar', stQUALIFIED);
- $aTransitions[stQUALIFIED][evEND] = array('__AddRow', stSTARTING);
+ $aTransitions[stQUALIFIED][evBLANK] = ['__AddChar', stQUALIFIED];
+ $aTransitions[stQUALIFIED][evSEPARATOR] = ['__AddChar', stQUALIFIED];
+ $aTransitions[stQUALIFIED][evNEWLINE] = ['__AddChar', stQUALIFIED];
+ $aTransitions[stQUALIFIED][evTEXTQUAL] = ['', stESCAPED];
+ $aTransitions[stQUALIFIED][evOTHERCHAR] = ['__AddChar', stQUALIFIED];
+ $aTransitions[stQUALIFIED][evEND] = ['__AddRow', stSTARTING];
- $aTransitions[stESCAPED][evBLANK] = array('', stESCAPED);
- $aTransitions[stESCAPED][evSEPARATOR] = array('__AddCell', stSTARTING);
- $aTransitions[stESCAPED][evNEWLINE] = array('__AddRow', stSTARTING);
- $aTransitions[stESCAPED][evTEXTQUAL] = array('__AddChar', stQUALIFIED);
- $aTransitions[stESCAPED][evOTHERCHAR] = array('__AddChar', stSTARTING);
- $aTransitions[stESCAPED][evEND] = array('__AddRow', stSTARTING);
+ $aTransitions[stESCAPED][evBLANK] = ['', stESCAPED];
+ $aTransitions[stESCAPED][evSEPARATOR] = ['__AddCell', stSTARTING];
+ $aTransitions[stESCAPED][evNEWLINE] = ['__AddRow', stSTARTING];
+ $aTransitions[stESCAPED][evTEXTQUAL] = ['__AddChar', stQUALIFIED];
+ $aTransitions[stESCAPED][evOTHERCHAR] = ['__AddChar', stSTARTING];
+ $aTransitions[stESCAPED][evEND] = ['__AddRow', stSTARTING];
// Reset parser variables
$this->m_sCurrCell = '';
- $this->m_aCurrRow = array();
+ $this->m_aCurrRow = [];
$this->m_iToSkip = $iToSkip;
- $this->m_aDataSet = array();
+ $this->m_aDataSet = [];
$iDataLength = strlen($this->m_sCSVData);
$iState = stSTARTING;
$iTimeLimit = null;
- if ($this->m_iTimeLimitPerRow !== null)
- {
+ if ($this->m_iTimeLimitPerRow !== null) {
// Give some time for the first row
$iTimeLimit = ini_get('max_execution_time');
set_time_limit(intval($this->m_iTimeLimitPerRow));
}
- for($i = 0; $i <= $iDataLength ; $i++)
- {
- if ($i == $iDataLength)
- {
+ for ($i = 0; $i <= $iDataLength ; $i++) {
+ if ($i == $iDataLength) {
$c = null;
$iEvent = evEND;
- }
- else
- {
+ } else {
$c = $this->m_sCSVData[$i];
- if ($c == $this->m_sSep)
- {
+ if ($c == $this->m_sSep) {
$iEvent = evSEPARATOR;
- }
- elseif ($c == ' ')
- {
+ } elseif ($c == ' ') {
$iEvent = evBLANK;
- }
- elseif ($c == "\t")
- {
+ } elseif ($c == "\t") {
$iEvent = evBLANK;
- }
- elseif ($c == "\n")
- {
+ } elseif ($c == "\n") {
$iEvent = evNEWLINE;
- }
- elseif ($c == $this->m_sTextQualifier)
- {
+ } elseif ($c == $this->m_sTextQualifier) {
$iEvent = evTEXTQUAL;
- }
- else
- {
+ } else {
$iEvent = evOTHERCHAR;
}
}
@@ -212,24 +179,21 @@ class CSVParser
$sAction = $aTransitions[$iState][$iEvent][0];
$iState = $aTransitions[$iState][$iEvent][1];
- if (!empty($sAction))
- {
- $aCallSpec = array($this, $sAction);
- if (is_callable($aCallSpec))
- {
+ if (!empty($sAction)) {
+ $aCallSpec = [$this, $sAction];
+ if (is_callable($aCallSpec)) {
call_user_func($aCallSpec, $c, $aFieldMap);
- }
- else
- {
+ } else {
throw new CSVParserException("CSVParser: unknown verb '$sAction'");
}
}
$iLineCount = count($this->m_aDataSet);
- if (($iMax > 0) && ($iLineCount >= $iMax)) break;
+ if (($iMax > 0) && ($iLineCount >= $iMax)) {
+ break;
+ }
}
- if ($iTimeLimit !== null)
- {
+ if ($iTimeLimit !== null) {
// Restore the previous time limit
set_time_limit(intval($iTimeLimit));
}
@@ -242,6 +206,3 @@ class CSVParser
return $aHeader[0];
}
}
-
-
-?>
diff --git a/core/customfieldshandler.class.inc.php b/core/customfieldshandler.class.inc.php
index 6aa3a0033..10a14ad2a 100644
--- a/core/customfieldshandler.class.inc.php
+++ b/core/customfieldshandler.class.inc.php
@@ -1,4 +1,5 @@
sAttCode = $sAttCode;
$this->aValues = null;
}
@@ -59,7 +62,8 @@ abstract class CustomFieldsHandler {
* @throws \ApplicationException if {@link static::$oForm} attribute not initialized yet
* @since 3.1.0 N°6322 N°1150 Add template_id checks
*/
- public function Validate(DBObject $oHostObject) {
+ public function Validate(DBObject $oHostObject)
+ {
if (false === isset($this->oForm)) {
throw new ApplicationException('oForm attribute not init yet. You must call BuildForm before this method !');
}
@@ -68,9 +72,8 @@ abstract class CustomFieldsHandler {
$this->oForm->Validate();
if ($this->oForm->GetValid()) {
$ret = true;
- }
- else {
- $aMessages = array();
+ } else {
+ $aMessages = [];
foreach ($this->oForm->GetErrorMessages() as $sFieldId => $aFieldMessages) {
$aMessages[] = $sFieldId.': '.implode(', ', $aFieldMessages);
}
@@ -87,7 +90,8 @@ abstract class CustomFieldsHandler {
*
* @return \Combodo\iTop\Form\Form
*/
- public function GetForm() {
+ public function GetForm()
+ {
return $this->oForm;
}
@@ -96,15 +100,17 @@ abstract class CustomFieldsHandler {
$this->aValues = $aValues;
}
- public static function GetPrerequisiteAttributes($sClass = null) {
- return array();
+ public static function GetPrerequisiteAttributes($sClass = null)
+ {
+ return [];
}
/**
* List the available verbs for 'GetForTemplate'
*/
- public static function EnumTemplateVerbs() {
- return array();
+ public static function EnumTemplateVerbs()
+ {
+ return [];
}
/**
@@ -169,7 +175,6 @@ abstract class CustomFieldsHandler {
return null;
}
-
/**
* @param DBObject $oHostObject
*
diff --git a/core/data.generator.class.inc.php b/core/data.generator.class.inc.php
index 7883ac17e..7e1d56eaf 100644
--- a/core/data.generator.class.inc.php
+++ b/core/data.generator.class.inc.php
@@ -1,9 +1,10 @@
-
/**
* data generator
- * helps the consultants in creating dummy data sets, for various test purposes (validation, usability, scalability)
+ * helps the consultants in creating dummy data sets, for various test purposes (validation, usability, scalability)
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -37,60 +37,50 @@ class cmdbDataGenerator
protected $m_sOrganizationCode;
protected $m_sOrganizationName;
protected $m_OrganizationDomains;
-
+
/**
* Constructor
*/
public function __construct($sOrganizationId = "")
{
global $aCompanies, $aCompaniesCode;
- if ($sOrganizationId == '')
- {
+ if ($sOrganizationId == '') {
// No organization provided, pick a random and unused one from our predefined list
- $retries = 5*count($aCompanies);
- while ( ($retries > 0) && !isset($this->m_sOrganizationCode)) // Stupid algorithm, but I'm too lazy to do something bulletproof tonight
- {
+ $retries = 5 * count($aCompanies);
+ while (($retries > 0) && !isset($this->m_sOrganizationCode)) { // Stupid algorithm, but I'm too lazy to do something bulletproof tonight
$index = rand(0, count($aCompanies) - 1);
- if (!$this->OrganizationExists($aCompanies[$index]['code']))
- {
+ if (!$this->OrganizationExists($aCompanies[$index]['code'])) {
$this->m_sOrganizationCode = $aCompanies[$index]['code'];
$this->m_sOrganizationName = $aCompanies[$index]['name'];
$this->m_OrganizationDomains = $aCompanies[$index]['domain'];
}
$retries--;
}
- }
- else
- {
+ } else {
// A code has been provided, let's take the information we need from the organization itself
$this->m_sOrganizationId = $sOrganizationId;
$oOrg = $this->GetOrganization($sOrganizationId);
- if ($oOrg == null)
- {
+ if ($oOrg == null) {
echo "Unable to find the organization '$sOrganisationCode' in the database... can not add objects into this organization.
\n";
exit();
}
$this->m_sOrganizationCode = $oOrg->Get('code');
$this->m_sOrganizationName = $oOrg->Get('name');
- if (!isset($aCompaniesCode[$this->m_sOrganizationCode]['domain']))
- {
+ if (!isset($aCompaniesCode[$this->m_sOrganizationCode]['domain'])) {
// Generate some probable domain names for this organization
- $this->m_OrganizationDomains = array(strtolower($this->m_sOrganizationCode).".com", strtolower($this->m_sOrganizationCode).".org", strtolower($this->m_sOrganizationCode)."corp.net",);
- }
- else
- {
+ $this->m_OrganizationDomains = [strtolower($this->m_sOrganizationCode).".com", strtolower($this->m_sOrganizationCode).".org", strtolower($this->m_sOrganizationCode)."corp.net",];
+ } else {
// Pick the domain names for this organization from the predefined list
$this->m_OrganizationDomains = $aCompaniesCode[$this->m_sOrganizationCode]['domain'];
}
}
-
- if (!isset($this->m_sOrganizationCode))
- {
+
+ if (!isset($this->m_sOrganizationCode)) {
echo "Unable to find an organization code which is not already used... can not create a new organization. Enhance the list of fake organizations (\$aCompanies in data_sample.inc.php).
\n";
exit();
}
}
-
+
/**
* Get the current organization id used by the generator
*
@@ -100,7 +90,7 @@ class cmdbDataGenerator
{
return $this->m_sOrganizationId;
}
-
+
/**
* Get the current organization id used by the generator
*
@@ -111,7 +101,7 @@ class cmdbDataGenerator
{
$this->m_sOrganizationId = $sId;
}
-
+
/**
* Get the current organization code used by the generator
*
@@ -127,69 +117,66 @@ class cmdbDataGenerator
*
* @return string The organization name
*/
- function GetOrganizationName()
+ public function GetOrganizationName()
{
return $this->m_sOrganizationName;
}
-
+
/**
* Get a pseudo random first name taken from a (big) prefedined list
*
* @return string A random first name
*/
- function GenerateFirstName()
+ public function GenerateFirstName()
{
global $aFirstNames;
return $aFirstNames[rand(0, count($aFirstNames) - 1)];
}
-
+
/**
* Get a pseudo random last name taken from a (big) prefedined list
*
* @return string A random last name
*/
- function GenerateLastName()
+ public function GenerateLastName()
{
global $aNames;
return $aNames[rand(0, count($aNames) - 1)];
}
-
+
/**
* Get a pseudo random country name taken from a prefedined list
*
* @return string A random city name
*/
- function GenerateCountryName()
+ public function GenerateCountryName()
{
global $aCountries;
return $aCountries[rand(0, count($aCountries) - 1)];
}
-
+
/**
* Get a pseudo random city name taken from a (big) prefedined list
*
* @return string A random city name
*/
- function GenerateCityName()
+ public function GenerateCityName()
{
global $aCities;
return $aCities[rand(0, count($aCities) - 1)];
}
-
+
/**
* Get a pseudo random email address made of the first name, last name and organization's domain
*
* @return string A random email address
*/
- function GenerateEmail($sFirstName, $sLastName)
+ public function GenerateEmail($sFirstName, $sLastName)
{
- if (rand(1, 20) > 18)
- {
+ if (rand(1, 20) > 18) {
// some people (let's say 5~10%) have an irregular email address
$sEmail = strtolower($this->CleanForEmail($sLastName))."@".strtolower($this->GenerateDomain());
- }
- else
- {
+ } else {
$sEmail = strtolower($this->CleanForEmail($sFirstName)).".".strtolower($this->CleanForEmail($sLastName))."@".strtolower($this->GenerateDomain());
}
return $sEmail;
@@ -203,7 +190,7 @@ class cmdbDataGenerator
* - domain() => returns a domain name for the current organization
* - enum(aaa,bb,c,dddd) => returns randomly one of aaa,bb,c or dddd with the same
* probability of occurence. If you want to change the probability you can repeat some values
- * i.e enum(most probable,most probable,most probable,most probable,most probable,rare)
+ * i.e enum(most probable,most probable,most probable,most probable,most probable,rare)
* - number(xxx-yyy) => a random number between xxx and yyy (bounds included)
* note that if the first number (xxx) begins with a zero, then the result will zero padded
* to the same number of digits as xxx.
@@ -215,39 +202,28 @@ class cmdbDataGenerator
* @param string $sTemplate The template used for generating the string
* @return string The generated pseudo random the string
*/
- function GenerateString($sTemplate)
+ public function GenerateString($sTemplate)
{
$sResult = "";
$aParts = explode("\|", $sTemplate);
- foreach($aParts as $sPart)
- {
- if (preg_match("/domain\(\)/", $sPart, $aMatches))
- {
+ foreach ($aParts as $sPart) {
+ if (preg_match("/domain\(\)/", $sPart, $aMatches)) {
$sResult .= strtolower($this->GenerateDomain());
- }
- elseif (preg_match("/enum\((.+)\)/", $sPart, $aMatches))
- {
+ } elseif (preg_match("/enum\((.+)\)/", $sPart, $aMatches)) {
$sEnumValues = $aMatches[1];
$aEnumValues = explode(",", $sEnumValues);
$sResult .= $aEnumValues[rand(0, count($aEnumValues) - 1)];
- }
- elseif (preg_match("/number\((\d+)-(\d+)\)/", $sPart, $aMatches))
- {
+ } elseif (preg_match("/number\((\d+)-(\d+)\)/", $sPart, $aMatches)) {
$sStartNumber = $aMatches[1];
- if ($sStartNumber[0] == '0')
- {
+ if ($sStartNumber[0] == '0') {
// number must be zero padded
$sFormat = "%0".strlen($sStartNumber)."d";
- }
- else
- {
+ } else {
$sFormat = "%d";
}
$sEndNumber = $aMatches[2];
$sResult .= sprintf($sFormat, rand($sStartNumber, $sEndNumber));
- }
- else
- {
+ } else {
$sResult .= $sPart;
}
}
@@ -264,27 +240,22 @@ class cmdbDataGenerator
* @param string $aFilterCriteria A hash array of filterCOde => FilterValue (the strict operator '=' is used )
* @return mixed The key to an object of the given class, or null if none are found
*/
- function GenerateKey($sClass, $aFilterCriteria)
+ public function GenerateKey($sClass, $aFilterCriteria)
{
$retKey = null;
$oFilter = new DBObjectSearch($sClass);
- foreach($aFilterCriteria as $sFilterCode => $filterValue)
- {
+ foreach ($aFilterCriteria as $sFilterCode => $filterValue) {
$oFilter->AddCondition($sFilterCode, $filterValue, '=');
}
$oSet = new CMDBObjectSet($oFilter);
- if ($oSet->Count() > 0)
- {
+ if ($oSet->Count() > 0) {
$max_count = $index = rand(1, $oSet->Count());
- do
- {
+ do {
$oObj = $oSet->Fetch();
$index--;
- }
- while($index > 0);
-
- if (!is_object($oObj))
- {
+ } while ($index > 0);
+
+ if (!is_object($oObj)) {
echo "
";
echo "ERROR: non empty set, but invalid object picked! class='$sClass'\n";
echo "Index chosen: $max_count\n";
@@ -292,9 +263,7 @@ class cmdbDataGenerator
echo "Filter criteria:\n";
print_r($aFilterCriteria);
echo " ";
- }
- else
- {
+ } else {
$retKey = $oObj->GetKey();
}
}
@@ -305,7 +274,7 @@ class cmdbDataGenerator
// Protected methods
//
///////////////////////////////////////////////////////////////////////////////
-
+
/**
* Generate a (random) domain name consistent with the organization name & code
*
@@ -316,17 +285,14 @@ class cmdbDataGenerator
*/
protected function GenerateDomain()
{
- if (is_array($this->m_OrganizationDomains))
- {
- $sDomain = $this->m_OrganizationDomains[rand(0, count($this->m_OrganizationDomains)-1)];
- }
- else
- {
+ if (is_array($this->m_OrganizationDomains)) {
+ $sDomain = $this->m_OrganizationDomains[rand(0, count($this->m_OrganizationDomains) - 1)];
+ } else {
$sDomain = $this->m_OrganizationDomains;
}
return $sDomain;
}
-
+
/**
* Strips accented characters from a string in order to produce a suitable email address
*
@@ -335,7 +301,7 @@ class cmdbDataGenerator
*/
protected function CleanForEmail($sText)
{
- return str_replace(array("'", "ļæ½", "ļæ½", "ļæ½", "ļæ½", "ļæ½", "ļæ½", "ļæ½", "ļæ½", "ļæ½"), array("", "e", "e", "e", "c", "a", "a", "n", "oe", "ae"), $sText);
+ return str_replace(["'", "ļæ½", "ļæ½", "ļæ½", "ļæ½", "ļæ½", "ļæ½", "ļæ½", "ļæ½", "ļæ½"], ["", "e", "e", "e", "c", "a", "a", "n", "oe", "ae"], $sText);
}
/**
@@ -364,11 +330,9 @@ class cmdbDataGenerator
$oFilter = new DBObjectSearch('Organization');
$oFilter->AddCondition('id', $sId, '=');
$oSet = new CMDBObjectSet($oFilter);
- if ($oSet->Count() > 0)
- {
+ if ($oSet->Count() > 0) {
$oOrg = $oSet->Fetch(); // Let's take the first one found
}
return $oOrg;
}
}
-?>
diff --git a/core/datamodel.core.xml b/core/datamodel.core.xml
index cdbcaf002..872b4cef8 100644
--- a/core/datamodel.core.xml
+++ b/core/datamodel.core.xml
@@ -2,9 +2,10 @@
- cmdbAbstractObject
+ DBObject
- core/cmdb,application
+ 1
+ core/cmdb,view_in_gui
false
autoincrement
priv_lnk_action_notif_to_contact
@@ -42,18 +43,21 @@
ActionNotification
false
+ DEL_AUTO
contact_id
Contact
false
+ DEL_AUTO
trigger_id
Trigger
false
+ DEL_AUTO
subscribed
@@ -66,18 +70,17 @@
-
- -
-
- -
-
10
-
- -
-
20
-
- -
-
30
-
-
+ -
+
10
+
+ -
+
20
+
+ -
+
30
+
+ -
+
40
@@ -91,11 +94,30 @@
-
20
- -
+
-
30
+ -
+
40
+
+
+
+ -
+
10
+
+ -
+
20
+
+ -
+
30
+
+ -
+
40
+
+
+
diff --git a/core/datetimeformat.class.inc.php b/core/datetimeformat.class.inc.php
index bf8921723..f4e7f9215 100644
--- a/core/datetimeformat.class.inc.php
+++ b/core/datetimeformat.class.inc.php
@@ -1,9 +1,10 @@
-
/**
* Helper class to generate Date & Time formatting strings in the various conventions
* from the PHP DateTime::createFromFormat convention.
- *
+ *
* Example:
- *
+ *
* $oFormat = new DateTimeFormat('m/d/Y H:i');
* $oFormat->ToExcel();
* >> 'MM/dd/YYYY HH:mm'
- *
+ *
* @author Denis Flaven
*
*/
class DateTimeFormat
{
protected $sPHPFormat;
-
+
/**
* Constructs the DateTimeFormat object
* @param string $sPHPFormat A format string using the PHP 'DateTime::createFromFormat' convention
@@ -42,7 +42,7 @@ class DateTimeFormat
{
$this->sPHPFormat = (string)$sPHPFormat;
}
-
+
/**
* @return string
*/
@@ -50,34 +50,34 @@ class DateTimeFormat
{
return $this->sPHPFormat;
}
-
+
/**
* Return the mapping table for converting between various conventions for date/time formats
*/
protected static function GetFormatMapping()
{
- return array(
+ return [
// Days
- 'd' => array('regexpr' => '(0[1-9]|[1-2][0-9]|3[0-1])', 'datepicker' => 'dd', 'excel' => 'dd', 'moment' => 'DD'), // Day of the month: 2 digits (with leading zero)
- 'j' => array('regexpr' => '([1-9]|[1-2][0-9]|3[0-1])', 'datepicker' => 'd', 'excel' => 'd', 'moment' => 'D'), // Day of the month: 1 or 2 digits (without leading zero)
+ 'd' => ['regexpr' => '(0[1-9]|[1-2][0-9]|3[0-1])', 'datepicker' => 'dd', 'excel' => 'dd', 'moment' => 'DD'], // Day of the month: 2 digits (with leading zero)
+ 'j' => ['regexpr' => '([1-9]|[1-2][0-9]|3[0-1])', 'datepicker' => 'd', 'excel' => 'd', 'moment' => 'D'], // Day of the month: 1 or 2 digits (without leading zero)
// Months
- 'm' => array('regexpr' => '(0[1-9]|1[0-2])', 'datepicker' => 'mm', 'excel' => 'MM', 'moment' => 'MM' ), // Month on 2 digits i.e. 01-12
- 'n' => array('regexpr' => '([1-9]|1[0-2])', 'datepicker' => 'm', 'excel' => 'm', 'moment' => 'M'), // Month on 1 or 2 digits 1-12
+ 'm' => ['regexpr' => '(0[1-9]|1[0-2])', 'datepicker' => 'mm', 'excel' => 'MM', 'moment' => 'MM' ], // Month on 2 digits i.e. 01-12
+ 'n' => ['regexpr' => '([1-9]|1[0-2])', 'datepicker' => 'm', 'excel' => 'm', 'moment' => 'M'], // Month on 1 or 2 digits 1-12
// Years
- 'Y' => array('regexpr' => '([0-9]{4})', 'datepicker' => 'yy', 'excel' => 'YYYY', 'moment' => 'YYYY'), // Year on 4 digits
- 'y' => array('regexpr' => '([0-9]{2})', 'datepicker' => 'y', 'excel' => 'YY', 'moment' => 'YY'), // Year on 2 digits
+ 'Y' => ['regexpr' => '([0-9]{4})', 'datepicker' => 'yy', 'excel' => 'YYYY', 'moment' => 'YYYY'], // Year on 4 digits
+ 'y' => ['regexpr' => '([0-9]{2})', 'datepicker' => 'y', 'excel' => 'YY', 'moment' => 'YY'], // Year on 2 digits
// Hours
- 'H' => array('regexpr' => '([0-1][0-9]|2[0-3])', 'datepicker' => 'HH', 'excel' => 'HH', 'moment' => 'HH'), // Hour 00..23
- 'h' => array('regexpr' => '(0[1-9]|1[0-2])', 'datepicker' => 'hh', 'excel' => 'hh', 'moment' => 'hh'), // Hour 01..12
- 'G' => array('regexpr' => '([0-9]|1[0-9]|2[0-3])', 'datepicker' => 'H', 'excel' => 'H', 'moment' => 'H'), // Hour 0..23
- 'g' => array('regexpr' => '([1-9]|1[0-2])', 'datepicker' => 'h', 'excel' => 'h', 'moment' => 'h'), // Hour 1..12
- 'a' => array('regexpr' => '(am|pm)', 'datepicker' => 'tt', 'excel' => 'am/pm', 'moment' => 'a'),
- 'A' => array('regexpr' => '(AM|PM)', 'datepicker' => 'TT', 'excel' => 'AM/PM', 'moment' => 'A'),
+ 'H' => ['regexpr' => '([0-1][0-9]|2[0-3])', 'datepicker' => 'HH', 'excel' => 'HH', 'moment' => 'HH'], // Hour 00..23
+ 'h' => ['regexpr' => '(0[1-9]|1[0-2])', 'datepicker' => 'hh', 'excel' => 'hh', 'moment' => 'hh'], // Hour 01..12
+ 'G' => ['regexpr' => '([0-9]|1[0-9]|2[0-3])', 'datepicker' => 'H', 'excel' => 'H', 'moment' => 'H'], // Hour 0..23
+ 'g' => ['regexpr' => '([1-9]|1[0-2])', 'datepicker' => 'h', 'excel' => 'h', 'moment' => 'h'], // Hour 1..12
+ 'a' => ['regexpr' => '(am|pm)', 'datepicker' => 'tt', 'excel' => 'am/pm', 'moment' => 'a'],
+ 'A' => ['regexpr' => '(AM|PM)', 'datepicker' => 'TT', 'excel' => 'AM/PM', 'moment' => 'A'],
// Minutes
- 'i' => array('regexpr' => '([0-5][0-9])', 'datepicker' => 'mm', 'excel' => 'mm', 'moment' => 'mm'),
+ 'i' => ['regexpr' => '([0-5][0-9])', 'datepicker' => 'mm', 'excel' => 'mm', 'moment' => 'mm'],
// Seconds
- 's' => array('regexpr' => '([0-5][0-9])', 'datepicker' => 'ss', 'excel' => 'ss', 'moment' => 'ss'),
- );
+ 's' => ['regexpr' => '([0-5][0-9])', 'datepicker' => 'ss', 'excel' => 'ss', 'moment' => 'ss'],
+ ];
}
/**
@@ -87,57 +87,44 @@ class DateTimeFormat
* @param string $sEscapePattern The replacement string for escaping characters in the output string. %s is the source char.
* @param string $bEscapeAll True to systematically escape all litteral characters
* @param array $sSpecialChars A string containing the only characters to escape in the output
- * @return string The string in the requested format
+ * @return string The string in the requested format
*/
protected function Transform($sOutputFormatCode, $sEscapePattern, $bEscapeAll = false, $sSpecialChars = '')
{
$aMappings = static::GetFormatMapping();
$sResult = '';
-
+
$bEscaping = false;
- for($i=0; $i < strlen($this->sPHPFormat); $i++)
- {
- if (($this->sPHPFormat[$i] == '\\'))
- {
+ for ($i = 0; $i < strlen($this->sPHPFormat); $i++) {
+ if (($this->sPHPFormat[$i] == '\\')) {
$bEscaping = true;
continue;
}
-
- if ($bEscaping)
- {
- if (($sSpecialChars === '') || (strpos($sSpecialChars, $this->sPHPFormat[$i]) !== false))
- {
+
+ if ($bEscaping) {
+ if (($sSpecialChars === '') || (strpos($sSpecialChars, $this->sPHPFormat[$i]) !== false)) {
$sResult .= sprintf($sEscapePattern, $this->sPHPFormat[$i]);
- }
- else
- {
+ } else {
$sResult .= $this->sPHPFormat[$i];
}
-
+
$bEscaping = false;
- }
- else if(array_key_exists($this->sPHPFormat[$i], $aMappings))
- {
+ } elseif (array_key_exists($this->sPHPFormat[$i], $aMappings)) {
// Not a litteral value, must be replaced by its regular expression pattern
$sResult .= $aMappings[$this->sPHPFormat[$i]][$sOutputFormatCode];
- }
- else
- {
- if ($bEscapeAll || (strpos($sSpecialChars, $this->sPHPFormat[$i]) !== false))
- {
+ } else {
+ if ($bEscapeAll || (strpos($sSpecialChars, $this->sPHPFormat[$i]) !== false)) {
$sResult .= sprintf($sEscapePattern, $this->sPHPFormat[$i]);
- }
- else
- {
+ } else {
// Normal char with no special meaning, no need to escape it
$sResult .= $this->sPHPFormat[$i];
}
}
}
-
- return $sResult;
- }
-
+
+ return $sResult;
+ }
+
/**
* Format a date into the supplied format string
* @param mixed $date An int, string, DateTime object or null !!
@@ -146,38 +133,27 @@ class DateTimeFormat
*/
public function Format($date)
{
- if ($date == null)
- {
+ if ($date == null) {
$sDate = '';
- }
- else if (($date === '0000-00-00') || ($date === '0000-00-00 00:00:00'))
- {
+ } elseif (($date === '0000-00-00') || ($date === '0000-00-00 00:00:00')) {
$sDate = '';
- }
- else if ($date instanceof DateTime)
- {
+ } elseif ($date instanceof DateTime) {
// Parameter is a DateTime
$sDate = $date->format($this->sPHPFormat);
- }
- else if (is_int($date))
- {
+ } elseif (is_int($date)) {
// Parameter is a Unix timestamp
$oDate = new DateTime();
$oDate->setTimestamp($date);
$sDate = $oDate->format($this->sPHPFormat);
- }
- else if (is_string($date))
- {
+ } elseif (is_string($date)) {
$oDate = new DateTime($date);
$sDate = $oDate->format($this->sPHPFormat);
- }
- else
- {
+ } else {
throw new Exception(__CLASS__."::Format: Unexpected date value: ".print_r($date, true));
}
return $sDate;
}
-
+
/**
* Parse a date in the supplied format and return the date as a string in the internal format
* @param string $sDate The string to parse
@@ -187,22 +163,18 @@ class DateTimeFormat
*/
public function Parse($sDate)
{
- if (($sDate == null) || ($sDate == '0000-00-00 00:00:00') || ($sDate == '0000-00-00'))
- {
- return null;
- }
- else
- {
+ if (($sDate == null) || ($sDate == '0000-00-00 00:00:00') || ($sDate == '0000-00-00')) {
+ return null;
+ } else {
$sFormat = preg_replace('/\\?/', '', $this->sPHPFormat); // replace escaped characters by a wildcard for parsing
$oDate = DateTime::createFromFormat($this->sPHPFormat, $sDate);
- if ($oDate === false)
- {
+ if ($oDate === false) {
throw new Exception(__CLASS__."::Parse: Unable to parse the date: '$sDate' using the format: '{$this->sPHPFormat}'");
}
return $oDate;
}
}
-
+
/**
* Get the date or datetime format string in the jQuery UI date picker format
* @return string The format string using the date picker convention
@@ -211,7 +183,7 @@ class DateTimeFormat
{
return $this->Transform('datepicker', "'%s'");
}
-
+
/**
* Get a date or datetime format string in the Excel format
* @return string The format string using the Excel convention
@@ -220,7 +192,7 @@ class DateTimeFormat
{
return $this->Transform('excel', "%s");
}
-
+
/**
* Get a date or datetime format string in the moment.js format
* @return string The format string using the moment.js convention
@@ -229,16 +201,15 @@ class DateTimeFormat
{
return $this->Transform('moment', "[%s]", true /* escape all */);
}
-
+
public static function GetJSSQLToCustomFormat()
{
- $aPHPToMoment = array();
- foreach(self::GetFormatMapping() as $sPHPCode => $aMapping)
- {
+ $aPHPToMoment = [];
+ foreach (self::GetFormatMapping() as $sPHPCode => $aMapping) {
$aPHPToMoment[$sPHPCode] = $aMapping['moment'];
}
$sJSMapping = json_encode($aPHPToMoment);
-
+
$sFunction =
<<sPHPFormat); $i++)
- {
- if (($this->sPHPFormat[$i] == '\\'))
- {
+ for ($i = 0; $i < strlen($this->sPHPFormat); $i++) {
+ if (($this->sPHPFormat[$i] == '\\')) {
$bEscaping = true;
continue;
}
-
- if ($bEscaping)
- {
+
+ if ($bEscaping) {
$sResult .= $this->sPHPFormat[$i]; // No need to escape characters in the placeholder
$bEscaping = false;
- }
- else if(array_key_exists($this->sPHPFormat[$i], $aMappings))
- {
+ } elseif (array_key_exists($this->sPHPFormat[$i], $aMappings)) {
// Not a litteral value, must be replaced by Dict equivalent
$sResult .= Dict::S('Core:DateTime:Placeholder_'.$this->sPHPFormat[$i]);
- }
- else
- {
+ } else {
// Normal char with no special meaning
$sResult .= $this->sPHPFormat[$i];
}
}
-
+
return $sResult;
}
@@ -373,14 +337,11 @@ EOF
{
$iStart = 999;
$iEnd = 0;
-
- foreach($aPlaceholders as $sChar)
- {
+
+ foreach ($aPlaceholders as $sChar) {
$iPos = strpos($this->sPHPFormat, $sChar);
- if ($iPos !== false)
- {
- if (($iPos > 0) && ($this->sPHPFormat[$iPos-1] == '\\'))
- {
+ if ($iPos !== false) {
+ if (($iPos > 0) && ($this->sPHPFormat[$iPos - 1] == '\\')) {
// The placeholder is actually escaped, it's a litteral character, ignore it
continue;
}
@@ -391,25 +352,25 @@ EOF
$sFormat = substr($this->sPHPFormat, $iStart, $iEnd - $iStart + 1);
return $sFormat;
}
-
+
/**
* Produces the Date format string by extracting only the date part of the date and time format string
* @return string
*/
public function ToDateFormat()
{
- return $this->ToSubFormat(array('Y', 'y', 'd', 'j', 'm', 'n'));
+ return $this->ToSubFormat(['Y', 'y', 'd', 'j', 'm', 'n']);
}
-
+
/**
* Produces the Time format string by extracting only the time part of the date and time format string
* @return string
*/
public function ToTimeFormat()
{
- return $this->ToSubFormat(array('H', 'h', 'G', 'g', 'i', 's', 'a', 'A'));
+ return $this->ToSubFormat(['H', 'h', 'G', 'g', 'i', 's', 'a', 'A']);
}
-
+
/**
* Get the regular expression to (approximately) validate a date/time for the current format
* The validation does not take into account the number of days in a month (i.e. June 31st will pass, as well as Feb 30th!)
@@ -419,8 +380,7 @@ EOF
public function ToRegExpr($sDelimiter = null)
{
$sRet = '^'.$this->Transform('regexpr', "\\%s", false /* escape all */, '.?*$^()[]:').'$';
- if ($sDelimiter !== null)
- {
+ if ($sDelimiter !== null) {
$sRet = $sDelimiter.str_replace($sDelimiter, '\\'.$sDelimiter, $sRet).$sDelimiter;
}
return $sRet;
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/dbobjectiterator.php b/core/dbobjectiterator.php
index 98519f9ed..eb5845c8d 100644
--- a/core/dbobjectiterator.php
+++ b/core/dbobjectiterator.php
@@ -1,9 +1,10 @@
-
/**
- * A set of persistent objects, could be heterogeneous as long as the objects in the set have a common ancestor class
+ * A set of persistent objects, could be heterogeneous as long as the objects in the set have a common ancestor class
*
* @package iTopORM
* @copyright Copyright (C) 2010-2024 Combodo SAS
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/dbobjectset.class.php b/core/dbobjectset.class.php
index 12783ce6f..6d25134cf 100644
--- a/core/dbobjectset.class.php
+++ b/core/dbobjectset.class.php
@@ -1,4 +1,5 @@
.]attcode' => bAscending (true for ASC, false, for DESC)
* Example : array('name' => true, 'id' => false)
@@ -97,10 +97,10 @@ class DBObjectSet implements iDBObjectSetIterator
* @param int $iLimitStart Index of the first row to load (i.e. equivalent to MySQL's LIMIT start, count)
* @param bool $bSort if false no order by is done
*/
- public function __construct(DBSearch $oFilter, $aOrderBy = array(), $aArgs = array(), $aExtendedDataSpec = null, $iLimitCount = 0, $iLimitStart = 0, $bSort = true)
+ public function __construct(DBSearch $oFilter, $aOrderBy = [], $aArgs = [], $aExtendedDataSpec = null, $iLimitCount = 0, $iLimitStart = 0, $bSort = true)
{
$this->m_oFilter = $oFilter->DeepClone();
- $this->m_aAddedIds = array();
+ $this->m_aAddedIds = [];
$this->m_aOrderBy = $aOrderBy;
$this->m_aArgs = $aArgs;
$this->m_aAttToLoad = null;
@@ -112,44 +112,41 @@ class DBObjectSet implements iDBObjectSetIterator
$this->m_iNumTotalDBRows = null;
$this->m_iNumLoadedDBRows = 0;
$this->m_bLoaded = false;
- $this->m_aAddedObjects = array();
+ $this->m_aAddedObjects = [];
$this->m_iCurrRow = 0;
$this->m_oSQLResult = null;
}
- /**
- * @internal
- */
+ /**
+ * @internal
+ */
public function __destruct()
{
- if (is_object($this->m_oSQLResult))
- {
+ if (is_object($this->m_oSQLResult)) {
$this->m_oSQLResult->free();
}
}
- /**
- * @internal
- *
- * @return string
- *
- * @throws \Exception
- * @throws \CoreException
- * @throws \MissingQueryArgument
- */
+ /**
+ * @internal
+ *
+ * @return string
+ *
+ * @throws \Exception
+ * @throws \CoreException
+ * @throws \MissingQueryArgument
+ */
public function __toString()
{
$sRet = '';
$this->Rewind();
$sRet .= "Set (".$this->m_oFilter->ToOQL(true).") \n";
- $sRet .= "Query: ".$this->m_oFilter->MakeSelectQuery().") \n";
-
+ $sRet .= "Query: ".$this->m_oFilter->MakeSelectQuery().") \n";
+
$sRet .= $this->Count()." records \n";
- if ($this->Count() > 0)
- {
+ if ($this->Count() > 0) {
$sRet .= "\n";
- while ($oObj = $this->Fetch())
- {
+ while ($oObj = $this->Fetch()) {
$sRet .= "".$oObj->__toString()." \n";
}
$sRet .= " \n";
@@ -158,9 +155,9 @@ class DBObjectSet implements iDBObjectSetIterator
return $sRet;
}
- /**
- * @internal
- */
+ /**
+ * @internal
+ */
public function __clone()
{
$this->m_oFilter = $this->m_oFilter->DeepClone();
@@ -174,7 +171,7 @@ class DBObjectSet implements iDBObjectSetIterator
/**
* Called when unserializing a DBObjectSet
- * @internal
+ * @internal
*/
public function __wakeup()
{
@@ -185,84 +182,75 @@ class DBObjectSet implements iDBObjectSetIterator
$this->m_oSQLResult = null;
}
- /**
- * @internal
- * @param $bShow
- */
+ /**
+ * @internal
+ * @param $bShow
+ */
public function SetShowObsoleteData($bShow)
{
$this->m_oFilter->SetShowObsoleteData($bShow);
}
- /**
- * @internal
- * @return bool
- */
+ /**
+ * @internal
+ * @return bool
+ */
public function GetShowObsoleteData()
{
return $this->m_oFilter->GetShowObsoleteData();
}
- /**
- * Specify the subset of attributes to load
- * this subset is specified for each class of objects,
- * this has to be done before the actual fetch.
- *
- * @api
- *
- * @param array $aAttToLoad Format: alias => array of attribute_codes
- *
- * @return void
- *
- * @throws \Exception
- * @throws \CoreException
- */
+ /**
+ * Specify the subset of attributes to load
+ * this subset is specified for each class of objects,
+ * this has to be done before the actual fetch.
+ *
+ * @api
+ *
+ * @param array $aAttToLoad Format: alias => array of attribute_codes
+ *
+ * @return void
+ *
+ * @throws \Exception
+ * @throws \CoreException
+ */
public function OptimizeColumnLoad($aAttToLoad)
{
// Check that the structure is an array of array
- if (!is_array($aAttToLoad))
- {
+ if (!is_array($aAttToLoad)) {
$this->m_aAttToLoad = null;
- trigger_error ( "OptimizeColumnLoad : wrong format actual :(".print_r($aAttToLoad, true)."). should be [alias=>[attributes]]", E_USER_WARNING );
+ trigger_error("OptimizeColumnLoad : wrong format actual :(".print_r($aAttToLoad, true)."). should be [alias=>[attributes]]", E_USER_WARNING);
return;
}
- foreach ($aAttToLoad as $sAlias => $aAttCodes)
- {
- if (!is_array($aAttCodes))
- {
+ foreach ($aAttToLoad as $sAlias => $aAttCodes) {
+ if (!is_array($aAttCodes)) {
$this->m_aAttToLoad = null;
- trigger_error ( "OptimizeColumnLoad : wrong format actual :(".print_r($aAttToLoad, true)."). should be [alias=>[attributes]]", E_USER_WARNING );
+ trigger_error("OptimizeColumnLoad : wrong format actual :(".print_r($aAttToLoad, true)."). should be [alias=>[attributes]]", E_USER_WARNING);
return;
}
}
// Complete the attribute list with the attribute codes
- $aAttToLoadWithAttDef = array();
- foreach($this->m_oFilter->GetSelectedClasses() as $sClassAlias => $sClass)
- {
- $aAttToLoadWithAttDef[$sClassAlias] = array();
- if (array_key_exists($sClassAlias, $aAttToLoad))
- {
+ $aAttToLoadWithAttDef = [];
+ foreach ($this->m_oFilter->GetSelectedClasses() as $sClassAlias => $sClass) {
+ $aAttToLoadWithAttDef[$sClassAlias] = [];
+ if (array_key_exists($sClassAlias, $aAttToLoad)) {
$aAttList = $aAttToLoad[$sClassAlias];
- foreach($aAttList as $sAttToLoad)
- {
+ foreach ($aAttList as $sAttToLoad) {
$oAttDef = MetaModel::GetAttributeDef($sClass, $sAttToLoad);
$aAttToLoadWithAttDef[$sClassAlias][$sAttToLoad] = $oAttDef;
- if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
- {
+ if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) {
// Add the external key friendly name anytime
$oFriendlyNameAttDef = MetaModel::GetAttributeDef($sClass, $sAttToLoad.'_friendlyname');
$aAttToLoadWithAttDef[$sClassAlias][$sAttToLoad.'_friendlyname'] = $oFriendlyNameAttDef;
- if (MetaModel::IsArchivable($oAttDef->GetTargetClass(EXTKEY_ABSOLUTE)))
- {
+ if (MetaModel::IsArchivable($oAttDef->GetTargetClass(EXTKEY_ABSOLUTE))) {
// Add the archive flag if necessary
$oArchiveFlagAttDef = MetaModel::GetAttributeDef($sClass, $sAttToLoad.'_archive_flag');
$aAttToLoadWithAttDef[$sClassAlias][$sAttToLoad.'_archive_flag'] = $oArchiveFlagAttDef;
}
- if (MetaModel::IsObsoletable($oAttDef->GetTargetClass(EXTKEY_ABSOLUTE)))
- {
+ if (MetaModel::IsObsoletable($oAttDef->GetTargetClass(EXTKEY_ABSOLUTE))) {
// Add the obsolescence flag if necessary
$oObsoleteFlagAttDef = MetaModel::GetAttributeDef($sClass, $sAttToLoad.'_obsolescence_flag');
$aAttToLoadWithAttDef[$sClassAlias][$sAttToLoad.'_obsolescence_flag'] = $oObsoleteFlagAttDef;
@@ -275,23 +263,20 @@ class DBObjectSet implements iDBObjectSetIterator
$oFriendlyNameAttDef = MetaModel::GetAttributeDef($sClass, 'friendlyname');
$aAttToLoadWithAttDef[$sClassAlias]['friendlyname'] = $oFriendlyNameAttDef;
- if (MetaModel::IsArchivable($sClass))
- {
+ if (MetaModel::IsArchivable($sClass)) {
// Add the archive flag if necessary
$oArchiveFlagAttDef = MetaModel::GetAttributeDef($sClass, 'archive_flag');
$aAttToLoadWithAttDef[$sClassAlias]['archive_flag'] = $oArchiveFlagAttDef;
}
- if (MetaModel::IsObsoletable($sClass))
- {
+ if (MetaModel::IsObsoletable($sClass)) {
// Add the obsolescence flag if necessary
$oObsoleteFlagAttDef = MetaModel::GetAttributeDef($sClass, 'obsolescence_flag');
$aAttToLoadWithAttDef[$sClassAlias]['obsolescence_flag'] = $oObsoleteFlagAttDef;
}
// Make sure that the final class is requested anytime, whatever the specification (needed for object construction!)
- if (!MetaModel::IsStandaloneClass($sClass) && !array_key_exists('finalclass', $aAttToLoadWithAttDef[$sClassAlias]))
- {
+ if (!MetaModel::IsStandaloneClass($sClass) && !array_key_exists('finalclass', $aAttToLoadWithAttDef[$sClassAlias])) {
$aAttToLoadWithAttDef[$sClassAlias]['finalclass'] = MetaModel::GetAttributeDef($sClass, 'finalclass');
}
}
@@ -299,36 +284,36 @@ class DBObjectSet implements iDBObjectSetIterator
$this->m_aAttToLoad = $aAttToLoadWithAttDef;
}
- /**
- * Create a set (in-memory) containing just the given object
- *
- * @internal
- *
- * @param \DBobject $oObject
- *
- * @return \DBObjectSet The singleton set
- *
- * @throws \Exception
- */
- static public function FromObject($oObject)
+ /**
+ * Create a set (in-memory) containing just the given object
+ *
+ * @internal
+ *
+ * @param \DBobject $oObject
+ *
+ * @return \DBObjectSet The singleton set
+ *
+ * @throws \Exception
+ */
+ public static function FromObject($oObject)
{
$oRetSet = self::FromScratch(get_class($oObject));
$oRetSet->AddObject($oObject);
return $oRetSet;
}
- /**
- * Create an empty set (in-memory), for the given class (and its subclasses) of objects
- *
- * @internal
- *
- * @param string $sClass The class (or an ancestor) for the objects to be added in this set
- *
- * @return \DBObjectSet The empty set
- *
- * @throws \Exception
- */
- static public function FromScratch($sClass)
+ /**
+ * Create an empty set (in-memory), for the given class (and its subclasses) of objects
+ *
+ * @internal
+ *
+ * @param string $sClass The class (or an ancestor) for the objects to be added in this set
+ *
+ * @return \DBObjectSet The empty set
+ *
+ * @throws \Exception
+ */
+ public static function FromScratch($sClass)
{
$oFilter = new DBObjectSearch($sClass);
$oFilter->AddConditionExpression(new FalseExpression());
@@ -338,41 +323,41 @@ class DBObjectSet implements iDBObjectSetIterator
return $oRetSet;
}
- /**
- * Create a set (in-memory) with just one column (i.e. one object per row) and filled with the given array of objects
- *
- * @internal
- *
- * @param string $sClass The class of the objects (must be a common ancestor to all objects in the set)
- * @param array $aObjects The list of objects to add into the set
- *
- * @return \DBObjectSet
- *
- * @throws \Exception
- */
- static public function FromArray($sClass, $aObjects)
+ /**
+ * Create a set (in-memory) with just one column (i.e. one object per row) and filled with the given array of objects
+ *
+ * @internal
+ *
+ * @param string $sClass The class of the objects (must be a common ancestor to all objects in the set)
+ * @param array $aObjects The list of objects to add into the set
+ *
+ * @return \DBObjectSet
+ *
+ * @throws \Exception
+ */
+ public static function FromArray($sClass, $aObjects)
{
$oRetSet = self::FromScratch($sClass);
$oRetSet->AddObjectArray($aObjects, $sClass);
return $oRetSet;
}
- /**
- * Create a set in-memory with several classes of objects per row (with one alias per "column")
- *
- * **Limitation:**
- * The filter/OQL query representing such a set can not be rebuilt (only the first column will be taken into account)
- *
- * @internal
- *
- * @param array $aClasses Format: array of (alias => class)
- * @param array $aObjects Format: array of (array of (classalias => object))
- *
- * @return \DBObjectSet
- *
- * @throws \Exception
- */
- static public function FromArrayAssoc($aClasses, $aObjects)
+ /**
+ * Create a set in-memory with several classes of objects per row (with one alias per "column")
+ *
+ * **Limitation:**
+ * The filter/OQL query representing such a set can not be rebuilt (only the first column will be taken into account)
+ *
+ * @internal
+ *
+ * @param array $aClasses Format: array of (alias => class)
+ * @param array $aObjects Format: array of (array of (classalias => object))
+ *
+ * @return \DBObjectSet
+ *
+ * @throws \Exception
+ */
+ 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,
@@ -384,132 +369,115 @@ class DBObjectSet implements iDBObjectSetIterator
$oRetSet = new self($oFilter);
$oRetSet->m_bLoaded = true; // no DB load
$oRetSet->m_iNumTotalDBRows = 0; // Nothing from the DB
-
- foreach($aObjects as $rowIndex => $aObjectsByClassAlias)
- {
+
+ foreach ($aObjects as $rowIndex => $aObjectsByClassAlias) {
$oRetSet->AddObjectExtended($aObjectsByClassAlias);
}
return $oRetSet;
}
- /**
- *
- * @internal
- *
- * @param $oObject
- * @param string $sLinkSetAttCode
- * @param string $sExtKeyToRemote
- *
- * @return \DBObjectSet
- *
- * @throws \Exception
- * @throws \ArchivedObjectException
- * @throws \CoreException
- */static public function FromLinkSet($oObject, $sLinkSetAttCode, $sExtKeyToRemote)
+ /**
+ *
+ * @internal
+ *
+ * @param $oObject
+ * @param string $sLinkSetAttCode
+ * @param string $sExtKeyToRemote
+ *
+ * @return \DBObjectSet
+ *
+ * @throws \Exception
+ * @throws \ArchivedObjectException
+ * @throws \CoreException
+ */public static function FromLinkSet($oObject, $sLinkSetAttCode, $sExtKeyToRemote)
{
$oLinkAttCode = MetaModel::GetAttributeDef(get_class($oObject), $sLinkSetAttCode);
$oExtKeyAttDef = MetaModel::GetAttributeDef($oLinkAttCode->GetLinkedClass(), $sExtKeyToRemote);
$sTargetClass = $oExtKeyAttDef->GetTargetClass();
$oLinkSet = $oObject->Get($sLinkSetAttCode);
- $aTargets = array();
- while ($oLink = $oLinkSet->Fetch())
- {
+ $aTargets = [];
+ while ($oLink = $oLinkSet->Fetch()) {
$aTargets[] = MetaModel::GetObject($sTargetClass, $oLink->Get($sExtKeyToRemote));
}
return self::FromArray($sTargetClass, $aTargets);
}
- /**
- * Fetch all as array of DBObject
- *
- * Note: After calling this method, the set cursor will be at the end of the set. You might want to rewind it.
- *
- * @api
- *
- * @param bool $bWithId if true array key will be set to object id
- *
- * @return DBObject[]
- *
- * @throws \Exception
- * @throws \CoreException
- * @throws \CoreUnexpectedValue
- * @throws \MySQLException
- */
+ /**
+ * Fetch all as array of DBObject
+ *
+ * Note: After calling this method, the set cursor will be at the end of the set. You might want to rewind it.
+ *
+ * @api
+ *
+ * @param bool $bWithId if true array key will be set to object id
+ *
+ * @return DBObject[]
+ *
+ * @throws \Exception
+ * @throws \CoreException
+ * @throws \CoreUnexpectedValue
+ * @throws \MySQLException
+ */
public function ToArray($bWithId = true)
{
- $aRet = array();
+ $aRet = [];
$this->Rewind();
- while ($oObject = $this->Fetch())
- {
- if ($bWithId)
- {
+ while ($oObject = $this->Fetch()) {
+ if ($bWithId) {
$aRet[$oObject->GetKey()] = $oObject;
- }
- else
- {
+ } else {
$aRet[] = $oObject;
}
}
return $aRet;
}
- /**
- * Fetch all as a structured array
- *
- * Unlike ToArray, ToArrayOfValues return the objects as an array.
- * Only the scalar values will be presents (see AttributeDefinition::IsScalar())
- *
- * @api
- *
- * @return array[]
- *
- * @throws \Exception
- * @throws \CoreException
- * @throws \CoreUnexpectedValue
- * @throws \MySQLException
- */
+ /**
+ * Fetch all as a structured array
+ *
+ * Unlike ToArray, ToArrayOfValues return the objects as an array.
+ * Only the scalar values will be presents (see AttributeDefinition::IsScalar())
+ *
+ * @api
+ *
+ * @return array[]
+ *
+ * @throws \Exception
+ * @throws \CoreException
+ * @throws \CoreUnexpectedValue
+ * @throws \MySQLException
+ */
public function ToArrayOfValues()
{
- if (!$this->m_bLoaded) $this->Load();
+ if (!$this->m_bLoaded) {
+ $this->Load();
+ }
$this->Rewind();
$aSelectedClasses = $this->m_oFilter->GetSelectedClasses();
- $aRet = array();
+ $aRet = [];
$iRow = 0;
- while($aObjects = $this->FetchAssoc())
- {
- foreach($aObjects as $sClassAlias => $oObject)
- {
- if (is_null($oObject))
- {
+ while ($aObjects = $this->FetchAssoc()) {
+ foreach ($aObjects as $sClassAlias => $oObject) {
+ if (is_null($oObject)) {
$aRet[$iRow][$sClassAlias.'.'.'id'] = null;
- }
- else
- {
+ } else {
$aRet[$iRow][$sClassAlias.'.'.'id'] = $oObject->GetKey();
- }
- if (is_null($oObject))
- {
- $sClass = $aSelectedClasses[$sClassAlias];
}
- else
- {
+ if (is_null($oObject)) {
+ $sClass = $aSelectedClasses[$sClassAlias];
+ } else {
$sClass = get_class($oObject);
}
- foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
- {
- if ($oAttDef->IsScalar())
- {
+ foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) {
+ if ($oAttDef->IsScalar()) {
$sAttName = $sClassAlias.'.'.$sAttCode;
- if (is_null($oObject))
- {
+ if (is_null($oObject)) {
$aRet[$iRow][$sAttName] = null;
- }
- else
- {
+ } else {
$aRet[$iRow][$sAttName] = $oObject->Get($sAttCode);
}
}
@@ -520,45 +488,41 @@ class DBObjectSet implements iDBObjectSetIterator
return $aRet;
}
- /**
- * Note: After calling this method, the set cursor will be at the end of the set. You might want to rewind it.
- *
- * @param string $sAttCode
- * @param bool $bWithId
- *
- * @return array
- *
- * @throws \Exception
- * @throws \CoreException
- */
+ /**
+ * Note: After calling this method, the set cursor will be at the end of the set. You might want to rewind it.
+ *
+ * @param string $sAttCode
+ * @param bool $bWithId
+ *
+ * @return array
+ *
+ * @throws \Exception
+ * @throws \CoreException
+ */
public function GetColumnAsArray($sAttCode, $bWithId = true)
{
- $aRet = array();
+ $aRet = [];
$this->Rewind();
- while ($oObject = $this->Fetch())
- {
- if ($bWithId)
- {
+ while ($oObject = $this->Fetch()) {
+ if ($bWithId) {
$aRet[$oObject->GetKey()] = $oObject->Get($sAttCode);
- }
- else
- {
+ } else {
$aRet[] = $oObject->Get($sAttCode);
}
}
return $aRet;
}
- /**
- * Retrieve the DBSearch corresponding to the objects present in this set
- *
- * Limitation:
- * This method will NOT work for sets with several columns (i.e. several objects per row)
- *
- * @return \DBObjectSearch
- *
- * @throws \CoreException
- */
+ /**
+ * Retrieve the DBSearch corresponding to the objects present in this set
+ *
+ * Limitation:
+ * This method will NOT work for sets with several columns (i.e. several objects per row)
+ *
+ * @return \DBObjectSearch
+ *
+ * @throws \CoreException
+ */
public function GetFilter()
{
// Make sure that we carry on the parameters of the set with the filter
@@ -567,13 +531,10 @@ class DBObjectSet implements iDBObjectSetIterator
// Note: the arguments found within a set can be object (but not in a filter)
// That's why PrepareQueryArguments must be invoked there
$oFilter->SetInternalParams(array_merge($oFilter->GetInternalParams(), $this->m_aArgs));
-
- if (count($this->m_aAddedIds) == 0)
- {
+
+ if (count($this->m_aAddedIds) == 0) {
return $oFilter;
- }
- else
- {
+ } else {
$oIdListExpr = ListExpression::FromScalars(array_keys($this->m_aAddedIds));
$oIdExpr = new FieldExpression('id', $oFilter->GetClassAlias());
$oIdInList = new BinaryExpression($oIdExpr, 'IN', $oIdListExpr);
@@ -584,7 +545,7 @@ class DBObjectSet implements iDBObjectSetIterator
/**
* The (common ancestor) class of the objects in the first column of this set
- *
+ *
* @return string The class of the objects in the first column
*/
public function GetClass()
@@ -594,7 +555,7 @@ class DBObjectSet implements iDBObjectSetIterator
/**
* The alias for the class of the objects in the first column of this set
- *
+ *
* @return string The alias of the class in the first column
*/
public function GetClassAlias()
@@ -604,7 +565,7 @@ class DBObjectSet implements iDBObjectSetIterator
/**
* The list of all classes (one per column) which are part of this set
- *
+ *
* @return array Format: alias => class
*/
public function GetSelectedClasses()
@@ -612,13 +573,13 @@ class DBObjectSet implements iDBObjectSetIterator
return $this->m_oFilter->GetSelectedClasses();
}
- /**
- * The root class (i.e. highest ancestor in the MeaModel class hierarchy) for the first column on this set
- *
- * @return string The root class for the objects in the first column of the set
- *
- * @throws \CoreException
- */
+ /**
+ * The root class (i.e. highest ancestor in the MeaModel class hierarchy) for the first column on this set
+ *
+ * @return string The root class for the objects in the first column of the set
+ *
+ * @throws \CoreException
+ */
public function GetRootClass()
{
return MetaModel::GetRootClass($this->GetClass());
@@ -626,7 +587,7 @@ class DBObjectSet implements iDBObjectSetIterator
/**
* The arguments used for building this set
- *
+ *
* @return array Format: parameter_name => value
*/
public function GetArgs()
@@ -645,50 +606,44 @@ class DBObjectSet implements iDBObjectSetIterator
$this->m_iLimitStart = $iLimitStart;
}
- /**
- * Sets the sort order for loading the rows from the DB. Changing the order by causes a Reload.
- *
- * @param array $aOrderBy Format: [alias.]attcode => boolean (true = ascending, false = descending)
- *
- * @throws \MySQLException
- */
+ /**
+ * Sets the sort order for loading the rows from the DB. Changing the order by causes a Reload.
+ *
+ * @param array $aOrderBy Format: [alias.]attcode => boolean (true = ascending, false = descending)
+ *
+ * @throws \MySQLException
+ */
public function SetOrderBy($aOrderBy)
{
- if ($this->m_aOrderBy != $aOrderBy)
- {
+ if ($this->m_aOrderBy != $aOrderBy) {
$this->m_aOrderBy = $aOrderBy;
- if ($this->m_bLoaded)
- {
+ if ($this->m_bLoaded) {
$this->m_bLoaded = false;
$this->Load();
}
}
}
- /**
- * Sets the sort order for loading the rows from the DB. Changing the order by causes a Reload.
- *
- * @param array $aAliases Format: alias => boolean (true = ascending, false = descending). If omitted, then it defaults to all the selected classes
- *
- * @throws \CoreException
- * @throws \MySQLException
- */
+ /**
+ * Sets the sort order for loading the rows from the DB. Changing the order by causes a Reload.
+ *
+ * @param array $aAliases Format: alias => boolean (true = ascending, false = descending). If omitted, then it defaults to all the selected classes
+ *
+ * @throws \CoreException
+ * @throws \MySQLException
+ */
public function SetOrderByClasses($aAliases = null)
{
- if ($aAliases === null)
- {
- $aAliases = array();
- foreach ($this->GetSelectedClasses() as $sAlias => $sClass)
- {
+ if ($aAliases === null) {
+ $aAliases = [];
+ foreach ($this->GetSelectedClasses() as $sAlias => $sClass) {
$aAliases[$sAlias] = true;
}
}
- $aAttributes = array();
- foreach ($aAliases as $sAlias => $bClassDirection)
- {
- foreach (MetaModel::GetOrderByDefault($this->m_oFilter->GetClassName($sAlias)) as $sAttCode => $bAttributeDirection)
- {
+ $aAttributes = [];
+ foreach ($aAliases as $sAlias => $bClassDirection) {
+ foreach (MetaModel::GetOrderByDefault($this->m_oFilter->GetClassName($sAlias)) as $sAttCode => $bAttributeDirection) {
$bDirection = $bClassDirection ? $bAttributeDirection : !$bAttributeDirection;
$aAttributes[$sAlias.'.'.$sAttCode] = $bDirection;
}
@@ -698,7 +653,7 @@ class DBObjectSet implements iDBObjectSetIterator
/**
* Returns the 'count' limit for loading the rows from the DB
- *
+ *
* @return int
*/
public function GetLimitCount()
@@ -708,7 +663,7 @@ class DBObjectSet implements iDBObjectSetIterator
/**
* Returns the 'start' limit for loading the rows from the DB
- *
+ *
* @return int
*/
public function GetLimitStart()
@@ -716,79 +671,71 @@ class DBObjectSet implements iDBObjectSetIterator
return $this->m_iLimitStart;
}
- /**
- * Get the sort order used for loading this set from the database
- *
- * Limitation: the sort order has no effect on objects added in-memory
- *
- * @return array Format: field_code => boolean (true = ascending, false = descending)
- *
- * @throws \CoreException
- */
+ /**
+ * Get the sort order used for loading this set from the database
+ *
+ * Limitation: the sort order has no effect on objects added in-memory
+ *
+ * @return array Format: field_code => boolean (true = ascending, false = descending)
+ *
+ * @throws \CoreException
+ */
public function GetRealSortOrder()
{
- if (!$this->m_bSort)
- {
+ if (!$this->m_bSort) {
// No order by
- return array();
+ return [];
}
// Get the class default sort order if not specified with the API
//
- if (empty($this->m_aOrderBy))
- {
+ if (empty($this->m_aOrderBy)) {
return MetaModel::GetOrderByDefault($this->m_oFilter->GetClass());
- }
- else
- {
+ } else {
return $this->m_aOrderBy;
}
}
- /**
- * Loads the set from the database. Actually performs the SQL query to retrieve the records from the DB.
- *
- * @throws \Exception
- * @throws \MySQLException
- */
+ /**
+ * Loads the set from the database. Actually performs the SQL query to retrieve the records from the DB.
+ *
+ * @throws \Exception
+ * @throws \MySQLException
+ */
public function Load()
{
- if ($this->m_bLoaded) return;
+ if ($this->m_bLoaded) {
+ return;
+ }
// Note: it is mandatory to set this value now, to protect against reentrance
$this->m_bLoaded = true;
$sSQL = $this->_makeSelectQuery($this->m_aAttToLoad);
-
- if (is_object($this->m_oSQLResult))
- {
+
+ if (is_object($this->m_oSQLResult)) {
// Free previous resultset if any
$this->m_oSQLResult->free();
$this->m_oSQLResult = null;
}
- try
- {
- $oKPI = new ExecutionKPI();
+ try {
+ $oKPI = new ExecutionKPI();
$this->m_oSQLResult = CMDBSource::Query($sSQL);
- $sOQL = $this->GetPseudoOQL($this->m_oFilter, $this->GetRealSortOrder(), $this->m_iLimitCount, $this->m_iLimitStart, false);
- $oKPI->ComputeStats('OQL Query Exec', $sOQL);
- } catch (MySQLException $e)
- {
+ $sOQL = $this->GetPseudoOQL($this->m_oFilter, $this->GetRealSortOrder(), $this->m_iLimitCount, $this->m_iLimitStart, false);
+ $oKPI->ComputeStats('OQL Query Exec', $sOQL);
+ } catch (MySQLException $e) {
// 1116 = ER_TOO_MANY_TABLES
// https://dev.mysql.com/doc/refman/5.7/en/error-messages-server.html#error_er_too_many_tables
- if ($e->getCode() != 1116)
- {
+ if ($e->getCode() != 1116) {
throw $e;
}
// N.689 Workaround for the 61 max joins in MySQL : full lazy load !
- $aAttToLoad = array();
- foreach($this->m_oFilter->GetSelectedClasses() as $sClassAlias => $sClass)
- {
- $aAttToLoad[$sClassAlias] = array();
+ $aAttToLoad = [];
+ foreach ($this->m_oFilter->GetSelectedClasses() as $sClassAlias => $sClass) {
+ $aAttToLoad[$sClassAlias] = [];
$bIsAbstractClass = MetaModel::IsAbstract($sClass);
$bIsClassWithChildren = MetaModel::HasChildrenClasses($sClass);
- if ($bIsAbstractClass || $bIsClassWithChildren)
- {
+ if ($bIsAbstractClass || $bIsClassWithChildren) {
// we need finalClass field at least to be able to instantiate the real corresponding object !
$aAttToLoad[$sClassAlias]['finalclass'] = MetaModel::GetAttributeDef($sClass, 'finalclass');
}
@@ -797,65 +744,74 @@ class DBObjectSet implements iDBObjectSetIterator
$this->m_oSQLResult = CMDBSource::Query($sSQL); // may fail again
}
- if ($this->m_oSQLResult === false) return;
+ if ($this->m_oSQLResult === false) {
+ return;
+ }
- if ((($this->m_iLimitCount == 0) || ($this->m_iLimitCount > $this->m_oSQLResult->num_rows)) && ($this->m_iLimitStart == 0))
- {
+ if ((($this->m_iLimitCount == 0) || ($this->m_iLimitCount > $this->m_oSQLResult->num_rows)) && ($this->m_iLimitStart == 0)) {
$this->m_iNumTotalDBRows = $this->m_oSQLResult->num_rows;
}
$this->m_iNumLoadedDBRows = $this->m_oSQLResult->num_rows;
}
- /**
- * @param string[] $aAttToLoad
- *
- * @return string SQL query
- *
- * @throws \CoreException
- * @throws \MissingQueryArgument
- */
+ /**
+ * @param string[] $aAttToLoad
+ *
+ * @return string SQL query
+ *
+ * @throws \CoreException
+ * @throws \MissingQueryArgument
+ */
private function _makeSelectQuery($aAttToLoad)
{
- if ($this->m_iLimitCount > 0)
- {
- $sSQL = $this->m_oFilter->MakeSelectQuery($this->GetRealSortOrder(), $this->m_aArgs, $aAttToLoad,
- $this->m_aExtendedDataSpec, $this->m_iLimitCount, $this->m_iLimitStart);
- }
- else
- {
- $sSQL = $this->m_oFilter->MakeSelectQuery($this->GetRealSortOrder(), $this->m_aArgs, $aAttToLoad,
- $this->m_aExtendedDataSpec);
+ if ($this->m_iLimitCount > 0) {
+ $sSQL = $this->m_oFilter->MakeSelectQuery(
+ $this->GetRealSortOrder(),
+ $this->m_aArgs,
+ $aAttToLoad,
+ $this->m_aExtendedDataSpec,
+ $this->m_iLimitCount,
+ $this->m_iLimitStart
+ );
+ } else {
+ $sSQL = $this->m_oFilter->MakeSelectQuery(
+ $this->GetRealSortOrder(),
+ $this->m_aArgs,
+ $aAttToLoad,
+ $this->m_aExtendedDataSpec
+ );
}
return $sSQL;
}
- /**
- * The total number of rows in this set. Independently of the SetLimit used for loading the set and taking into
- * account the rows added in-memory.
- *
- * May actually perform the SQL query SELECT COUNT... if the set was not previously loaded, or loaded with a
- * SetLimit
- *
- * @api
- * @return int The total number of rows for this set.
- *
- * @throws \CoreException
- * @throws \MissingQueryArgument
- * @throws \MySQLException
- * @throws \MySQLHasGoneAwayException
- */
+ /**
+ * The total number of rows in this set. Independently of the SetLimit used for loading the set and taking into
+ * account the rows added in-memory.
+ *
+ * May actually perform the SQL query SELECT COUNT... if the set was not previously loaded, or loaded with a
+ * SetLimit
+ *
+ * @api
+ * @return int The total number of rows for this set.
+ *
+ * @throws \CoreException
+ * @throws \MissingQueryArgument
+ * @throws \MySQLException
+ * @throws \MySQLHasGoneAwayException
+ */
public function Count(): int
{
- if (is_null($this->m_iNumTotalDBRows))
- {
- $oKPI = new ExecutionKPI();
- $sSQL = $this->m_oFilter->MakeSelectQuery(array(), $this->m_aArgs, null, null, 0, 0, true);
+ if (is_null($this->m_iNumTotalDBRows)) {
+ $oKPI = new ExecutionKPI();
+ $sSQL = $this->m_oFilter->MakeSelectQuery([], $this->m_aArgs, null, null, 0, 0, true);
$resQuery = CMDBSource::Query($sSQL);
- $sOQL = $this->GetPseudoOQL($this->m_oFilter, array(), 0, 0, true);
- $oKPI->ComputeStats('OQL Query Exec', $sOQL);
- if (!$resQuery) return 0;
+ $sOQL = $this->GetPseudoOQL($this->m_oFilter, [], 0, 0, true);
+ $oKPI->ComputeStats('OQL Query Exec', $sOQL);
+ if (!$resQuery) {
+ return 0;
+ }
$aRow = CMDBSource::FetchArray($resQuery);
CMDBSource::FreeResult($resQuery);
@@ -865,41 +821,41 @@ class DBObjectSet implements iDBObjectSetIterator
return $this->m_iNumTotalDBRows + count($this->m_aAddedObjects); // Does it fix Trac #887 ??
}
- /**
- * @param \DBSearch $oFilter
- * @param array $aOrder
- * @param int $iLimitCount
- * @param int $iLimitStart
- * @param bool $bCount
- *
- * @return string
- */
- private function GetPseudoOQL($oFilter, $aOrder, $iLimitCount, $iLimitStart, $bCount)
- {
- $sOQL = '';
- if ($bCount) {
- $sOQL .= 'COUNT ';
- }
- $sOQL .= $oFilter->ToOQL();
+ /**
+ * @param \DBSearch $oFilter
+ * @param array $aOrder
+ * @param int $iLimitCount
+ * @param int $iLimitStart
+ * @param bool $bCount
+ *
+ * @return string
+ */
+ private function GetPseudoOQL($oFilter, $aOrder, $iLimitCount, $iLimitStart, $bCount)
+ {
+ $sOQL = '';
+ if ($bCount) {
+ $sOQL .= 'COUNT ';
+ }
+ $sOQL .= $oFilter->ToOQL();
- if ($iLimitCount > 0) {
- $sOQL .= ' LIMIT ';
- if ($iLimitStart > 0) {
- $sOQL .= "$iLimitStart, ";
- }
- $sOQL .= "$iLimitCount";
- }
+ if ($iLimitCount > 0) {
+ $sOQL .= ' LIMIT ';
+ if ($iLimitStart > 0) {
+ $sOQL .= "$iLimitStart, ";
+ }
+ $sOQL .= "$iLimitCount";
+ }
- if (count($aOrder) > 0) {
- $sOQL .= ' ORDER BY ';
- $aOrderBy = [];
- foreach ($aOrder as $sAttCode => $bAsc) {
- $aOrderBy[] = $sAttCode.' '.($bAsc ? 'ASC' : 'DESC');
- }
- $sOQL .= implode(', ', $aOrderBy);
- }
- return $sOQL;
- }
+ if (count($aOrder) > 0) {
+ $sOQL .= ' ORDER BY ';
+ $aOrderBy = [];
+ foreach ($aOrder as $sAttCode => $bAsc) {
+ $aOrderBy[] = $sAttCode.' '.($bAsc ? 'ASC' : 'DESC');
+ }
+ $sOQL .= implode(', ', $aOrderBy);
+ }
+ return $sOQL;
+ }
/**
* Check if the count exceeds a given limit
@@ -915,26 +871,20 @@ class DBObjectSet implements iDBObjectSetIterator
*/
public function CountExceeds($iLimit)
{
- if (is_null($this->m_iNumTotalDBRows))
- {
- $oKPI = new ExecutionKPI();
- $sSQL = $this->m_oFilter->MakeSelectQuery(array(), $this->m_aArgs, null, null, $iLimit + 2, 0, true);
+ if (is_null($this->m_iNumTotalDBRows)) {
+ $oKPI = new ExecutionKPI();
+ $sSQL = $this->m_oFilter->MakeSelectQuery([], $this->m_aArgs, null, null, $iLimit + 2, 0, true);
$resQuery = CMDBSource::Query($sSQL);
- $sOQL = $this->GetPseudoOQL($this->m_oFilter, array(), $iLimit + 2, 0, true);
- $oKPI->ComputeStats('OQL Query Exec', $sOQL);
- if ($resQuery)
- {
+ $sOQL = $this->GetPseudoOQL($this->m_oFilter, [], $iLimit + 2, 0, true);
+ $oKPI->ComputeStats('OQL Query Exec', $sOQL);
+ if ($resQuery) {
$aRow = CMDBSource::FetchArray($resQuery);
$iCount = intval($aRow['COUNT']);
CMDBSource::FreeResult($resQuery);
- }
- else
- {
+ } else {
$iCount = 0;
}
- }
- else
- {
+ } else {
$iCount = $this->m_iNumTotalDBRows;
}
@@ -955,26 +905,20 @@ class DBObjectSet implements iDBObjectSetIterator
*/
public function CountWithLimit($iLimit)
{
- if (is_null($this->m_iNumTotalDBRows))
- {
- $oKPI = new ExecutionKPI();
- $sSQL = $this->m_oFilter->MakeSelectQuery(array(), $this->m_aArgs, null, null, $iLimit + 2, 0, true);
+ if (is_null($this->m_iNumTotalDBRows)) {
+ $oKPI = new ExecutionKPI();
+ $sSQL = $this->m_oFilter->MakeSelectQuery([], $this->m_aArgs, null, null, $iLimit + 2, 0, true);
$resQuery = CMDBSource::Query($sSQL);
- $sOQL = $this->GetPseudoOQL($this->m_oFilter, array(), $iLimit + 2, 0, true);
- $oKPI->ComputeStats('OQL Query Exec', $sOQL);
- if ($resQuery)
- {
+ $sOQL = $this->GetPseudoOQL($this->m_oFilter, [], $iLimit + 2, 0, true);
+ $oKPI->ComputeStats('OQL Query Exec', $sOQL);
+ if ($resQuery) {
$aRow = CMDBSource::FetchArray($resQuery);
CMDBSource::FreeResult($resQuery);
$iCount = intval($aRow['COUNT']);
- }
- else
- {
+ } else {
$iCount = 0;
}
- }
- else
- {
+ } else {
$iCount = $this->m_iNumTotalDBRows;
}
@@ -983,7 +927,7 @@ class DBObjectSet implements iDBObjectSetIterator
/**
* Number of rows available in memory (loaded from DB + added in memory)
- *
+ *
* @return number The number of rows available for Fetch'ing
*/
protected function CountLoaded()
@@ -991,53 +935,44 @@ class DBObjectSet implements iDBObjectSetIterator
return $this->m_iNumLoadedDBRows + count($this->m_aAddedObjects);
}
- /**
- * Fetch an object (with the given class alias) at the current position in the set and move the cursor to the next position.
- *
- * @api
- *
- * @param string $sRequestedClassAlias The class alias to fetch (defaults to the first selected class)
- *
- * @return \DBObject The fetched object or null when at the end
- *
- * @throws \CoreException
- * @throws \CoreUnexpectedValue
- * @throws \MySQLException
- */
+ /**
+ * Fetch an object (with the given class alias) at the current position in the set and move the cursor to the next position.
+ *
+ * @api
+ *
+ * @param string $sRequestedClassAlias The class alias to fetch (defaults to the first selected class)
+ *
+ * @return \DBObject The fetched object or null when at the end
+ *
+ * @throws \CoreException
+ * @throws \CoreUnexpectedValue
+ * @throws \MySQLException
+ */
public function Fetch($sRequestedClassAlias = '')
{
- if (!$this->m_bLoaded) $this->Load();
+ if (!$this->m_bLoaded) {
+ $this->Load();
+ }
- if ($this->m_iCurrRow >= $this->CountLoaded())
- {
+ if ($this->m_iCurrRow >= $this->CountLoaded()) {
return null;
}
-
- if (strlen($sRequestedClassAlias) == 0)
- {
+
+ if (strlen($sRequestedClassAlias) == 0) {
$sRequestedClassAlias = $this->m_oFilter->GetClassAlias();
}
- if ($this->m_iCurrRow < $this->m_iNumLoadedDBRows)
- {
+ if ($this->m_iCurrRow < $this->m_iNumLoadedDBRows) {
// Pick the row from the database
$aRow = CMDBSource::FetchArray($this->m_oSQLResult);
- foreach ($this->m_oFilter->GetSelectedClasses() as $sClassAlias => $sClass)
- {
- if ($sRequestedClassAlias == $sClassAlias)
- {
- if (is_null($aRow[$sClassAlias.'id']))
- {
+ foreach ($this->m_oFilter->GetSelectedClasses() as $sClassAlias => $sClass) {
+ if ($sRequestedClassAlias == $sClassAlias) {
+ if (is_null($aRow[$sClassAlias.'id'])) {
$oRetObj = null;
- }
- else
- {
- try
- {
+ } else {
+ try {
$oRetObj = MetaModel::GetObjectByRow($sClass, $aRow, $sClassAlias, $this->m_aAttToLoad, $this->m_aExtendedDataSpec);
- }
- catch (CoreException $e)
- {
+ } catch (CoreException $e) {
$this->m_iCurrRow++;
$oRetObj = $this->Fetch($sRequestedClassAlias);
}
@@ -1045,9 +980,7 @@ class DBObjectSet implements iDBObjectSetIterator
break;
}
}
- }
- else
- {
+ } else {
// Pick the row from the objects added *in memory*
$oRetObj = $this->m_aAddedObjects[$this->m_iCurrRow - $this->m_iNumLoadedDBRows][$sRequestedClassAlias];
}
@@ -1055,50 +988,43 @@ class DBObjectSet implements iDBObjectSetIterator
return $oRetObj;
}
- /**
- * Fetch the whole row of objects (if several classes have been specified in the query) and move the cursor to the next position
- *
- * @api
- *
- * @return array An associative with the format 'classAlias' => $oObj representing the current row of the set. Returns null when at the end.
- *
- * @throws \CoreException
- * @throws \CoreUnexpectedValue
- * @throws \MySQLException
- */
+ /**
+ * Fetch the whole row of objects (if several classes have been specified in the query) and move the cursor to the next position
+ *
+ * @api
+ *
+ * @return array An associative with the format 'classAlias' => $oObj representing the current row of the set. Returns null when at the end.
+ *
+ * @throws \CoreException
+ * @throws \CoreUnexpectedValue
+ * @throws \MySQLException
+ */
public function FetchAssoc()
{
- if (!$this->m_bLoaded) $this->Load();
+ if (!$this->m_bLoaded) {
+ $this->Load();
+ }
- if ($this->m_iCurrRow >= $this->CountLoaded())
- {
+ if ($this->m_iCurrRow >= $this->CountLoaded()) {
return null;
}
-
- if ($this->m_iCurrRow < $this->m_iNumLoadedDBRows)
- {
+
+ if ($this->m_iCurrRow < $this->m_iNumLoadedDBRows) {
// Pick the row from the database
$aRow = CMDBSource::FetchArray($this->m_oSQLResult);
- $aRetObjects = array();
- foreach ($this->m_oFilter->GetSelectedClasses() as $sClassAlias => $sClass)
- {
- if (is_null($aRow[$sClassAlias.'id']))
- {
+ $aRetObjects = [];
+ foreach ($this->m_oFilter->GetSelectedClasses() as $sClassAlias => $sClass) {
+ if (is_null($aRow[$sClassAlias.'id'])) {
$oObj = null;
- }
- else
- {
+ } else {
$oObj = MetaModel::GetObjectByRow($sClass, $aRow, $sClassAlias, $this->m_aAttToLoad, $this->m_aExtendedDataSpec);
}
$aRetObjects[$sClassAlias] = $oObj;
}
- }
- else
- {
+ } else {
// Pick the row from the objects added *in memory*
- $aRetObjects = array();
- foreach ($this->m_oFilter->GetSelectedClasses() as $sClassAlias => $sClass)
- {
+ $aRetObjects = [];
+ foreach ($this->m_oFilter->GetSelectedClasses() as $sClassAlias => $sClass) {
$aRetObjects[$sClassAlias] = $this->m_aAddedObjects[$this->m_iCurrRow - $this->m_iNumLoadedDBRows][$sClassAlias];
}
}
@@ -1115,182 +1041,181 @@ class DBObjectSet implements iDBObjectSetIterator
*/
public function Rewind()
{
- if ($this->m_bLoaded)
- {
+ if ($this->m_bLoaded) {
$this->Seek(0);
}
}
- /**
- * Position the cursor (for iterating in the set) to the given position
- *
- * @param int $iRow
- *
- * @throws \CoreException
- * @throws \MissingQueryArgument
- * @throws \MySQLException
- * @throws \MySQLHasGoneAwayException
- * @since 3.1.0 N°4517 Now returns void for return type to match parent class and be compatible with PHP 8.1
- */
+ /**
+ * Position the cursor (for iterating in the set) to the given position
+ *
+ * @param int $iRow
+ *
+ * @throws \CoreException
+ * @throws \MissingQueryArgument
+ * @throws \MySQLException
+ * @throws \MySQLHasGoneAwayException
+ * @since 3.1.0 N°4517 Now returns void for return type to match parent class and be compatible with PHP 8.1
+ */
public function Seek($iRow): void
{
- if (!$this->m_bLoaded) $this->Load();
+ if (!$this->m_bLoaded) {
+ $this->Load();
+ }
$this->m_iCurrRow = min($iRow, $this->Count());
- if ($this->m_iCurrRow < $this->m_iNumLoadedDBRows)
- {
+ if ($this->m_iCurrRow < $this->m_iNumLoadedDBRows) {
$this->m_oSQLResult->data_seek($this->m_iCurrRow);
}
}
- /**
- * Add an object to the current set (in-memory only, nothing is written to the database)
- *
- * Limitation:
- * Sets with several objects per row are NOT supported
- *
- * @param \DBObject $oObject The object to add
- * @param string $sClassAlias The alias for the class of the object
- *
- * @throws \MySQLException
- */
+ /**
+ * Add an object to the current set (in-memory only, nothing is written to the database)
+ *
+ * Limitation:
+ * Sets with several objects per row are NOT supported
+ *
+ * @param \DBObject $oObject The object to add
+ * @param string $sClassAlias The alias for the class of the object
+ *
+ * @throws \MySQLException
+ */
public function AddObject($oObject, $sClassAlias = '')
{
- if (!$this->m_bLoaded) $this->Load();
+ if (!$this->m_bLoaded) {
+ $this->Load();
+ }
- if (strlen($sClassAlias) == 0)
- {
+ if (strlen($sClassAlias) == 0) {
$sClassAlias = $this->m_oFilter->GetClassAlias();
}
$iNextPos = count($this->m_aAddedObjects);
$this->m_aAddedObjects[$iNextPos][$sClassAlias] = $oObject;
- if (!is_null($oObject))
- {
+ if (!is_null($oObject)) {
$this->m_aAddedIds[$oObject->GetKey()] = true;
}
}
- /**
- * Add a hash containig objects into the current set.
- *
- * The expected format for the hash is: $aObjectArray[$idx][$sClassAlias] => $oObject
- * Limitation:
- * The aliases MUST match the ones used in the current set
- * Only the ID of the objects associated to the first alias (column) is remembered.. in case we have to rebuild a filter
- *
- * @param array $aObjectArray
- *
- * @throws \MySQLException
- */
+ /**
+ * Add a hash containig objects into the current set.
+ *
+ * The expected format for the hash is: $aObjectArray[$idx][$sClassAlias] => $oObject
+ * Limitation:
+ * The aliases MUST match the ones used in the current set
+ * Only the ID of the objects associated to the first alias (column) is remembered.. in case we have to rebuild a filter
+ *
+ * @param array $aObjectArray
+ *
+ * @throws \MySQLException
+ */
protected function AddObjectExtended($aObjectArray)
{
- if (!$this->m_bLoaded) $this->Load();
+ if (!$this->m_bLoaded) {
+ $this->Load();
+ }
$iNextPos = count($this->m_aAddedObjects);
-
+
$sFirstAlias = $this->m_oFilter->GetClassAlias();
- foreach ($aObjectArray as $sClassAlias => $oObject)
- {
+ foreach ($aObjectArray as $sClassAlias => $oObject) {
$this->m_aAddedObjects[$iNextPos][$sClassAlias] = $oObject;
-
- if (!is_null($oObject) && ($sFirstAlias == $sClassAlias))
- {
+
+ if (!is_null($oObject) && ($sFirstAlias == $sClassAlias)) {
$this->m_aAddedIds[$oObject->GetKey()] = true;
}
}
}
- /**
- * Add an array of objects into the current set
- *
- * Limitation:
- * Sets with several classes per row are not supported (use AddObjectExtended instead)
- *
- * @param array $aObjects The array of objects to add
- * @param string $sClassAlias The Alias of the class for the added objects
- *
- * @throws \MySQLException
- */
+ /**
+ * Add an array of objects into the current set
+ *
+ * Limitation:
+ * Sets with several classes per row are not supported (use AddObjectExtended instead)
+ *
+ * @param array $aObjects The array of objects to add
+ * @param string $sClassAlias The Alias of the class for the added objects
+ *
+ * @throws \MySQLException
+ */
public function AddObjectArray($aObjects, $sClassAlias = '')
{
- if (!$this->m_bLoaded) $this->Load();
+ if (!$this->m_bLoaded) {
+ $this->Load();
+ }
// #@# todo - add a check on the object class ?
- foreach ($aObjects as $oObj)
- {
+ foreach ($aObjects as $oObj) {
$this->AddObject($oObj, $sClassAlias);
}
}
/**
* Append a given set to the current object. (This method used to be named Merge)
- *
+ *
* Limitation:
* The added objects are not checked for duplicates (i.e. one cann add several times the same object, or add an object already present in the set).
- *
+ *
* @param \DBObjectSet $oObjectSet The set to append
- *
+ *
* @throws \CoreException
*/
public function Append(DBObjectSet $oObjectSet)
{
- if ($this->GetRootClass() != $oObjectSet->GetRootClass())
- {
+ if ($this->GetRootClass() != $oObjectSet->GetRootClass()) {
throw new CoreException("Could not merge two objects sets if they don't have the same root class");
}
- if (!$this->m_bLoaded) $this->Load();
+ if (!$this->m_bLoaded) {
+ $this->Load();
+ }
$oObjectSet->Seek(0);
- while ($oObject = $oObjectSet->Fetch())
- {
+ while ($oObject = $oObjectSet->Fetch()) {
$this->AddObject($oObject);
}
}
- /**
- * Create a set containing the objects present in both the current set and another specified set
- *
- * Limitations:
- * Will NOT work if only a subset of the sets was loaded with SetLimit.
- * Works only with sets made of objects loaded from the database since the comparison is based on the objects identifiers
- *
- * @param \DBObjectSet $oObjectSet The set to intersect with. The current position inside the set will be lost (= at the end)
- *
- * @return \DBObjectSet A new set of objects, containing the objects present in both sets (based on their identifier)
- *
- * @throws \Exception
- * @throws \CoreException
- * @throws \CoreUnexpectedValue
- * @throws \MissingQueryArgument
- * @throws \MySQLException
- * @throws \MySQLHasGoneAwayException
- */
+ /**
+ * Create a set containing the objects present in both the current set and another specified set
+ *
+ * Limitations:
+ * Will NOT work if only a subset of the sets was loaded with SetLimit.
+ * Works only with sets made of objects loaded from the database since the comparison is based on the objects identifiers
+ *
+ * @param \DBObjectSet $oObjectSet The set to intersect with. The current position inside the set will be lost (= at the end)
+ *
+ * @return \DBObjectSet A new set of objects, containing the objects present in both sets (based on their identifier)
+ *
+ * @throws \Exception
+ * @throws \CoreException
+ * @throws \CoreUnexpectedValue
+ * @throws \MissingQueryArgument
+ * @throws \MySQLException
+ * @throws \MySQLHasGoneAwayException
+ */
public function CreateIntersect(DBObjectSet $oObjectSet)
{
- if ($this->GetRootClass() != $oObjectSet->GetRootClass())
- {
+ if ($this->GetRootClass() != $oObjectSet->GetRootClass()) {
throw new CoreException("Could not 'intersect' two objects sets if they don't have the same root class");
}
- if (!$this->m_bLoaded) $this->Load();
+ if (!$this->m_bLoaded) {
+ $this->Load();
+ }
- $aId2Row = array();
+ $aId2Row = [];
$iCurrPos = $this->m_iCurrRow; // Save the cursor
$idx = 0;
- while($oObj = $this->Fetch())
- {
+ while ($oObj = $this->Fetch()) {
$aId2Row[$oObj->GetKey()] = $idx;
$idx++;
}
-
+
$oNewSet = DBObjectSet::FromScratch($this->GetClass());
$oObjectSet->Seek(0);
- while ($oObject = $oObjectSet->Fetch())
- {
- if (array_key_exists($oObject->GetKey(), $aId2Row))
- {
+ while ($oObject = $oObjectSet->Fetch()) {
+ if (array_key_exists($oObject->GetKey(), $aId2Row)) {
$oNewSet->AddObject($oObject);
}
}
@@ -1298,34 +1223,34 @@ class DBObjectSet implements iDBObjectSetIterator
return $oNewSet;
}
- /**
- * Compare two sets of objects to determine if their content is identical or not.
- *
- * Limitation:
- * Works only for sets of 1 column (i.e. one class of object selected)
- *
- * @param \DBObjectSet $oObjectSet
- * @param array $aExcludeColumns The list of columns to exclude frop the comparison
- *
- * @return boolean True if the sets are identical, false otherwise
- *
- * @throws \CoreException
- */
- public function HasSameContents(DBObjectSet $oObjectSet, $aExcludeColumns = array())
- {
+ /**
+ * Compare two sets of objects to determine if their content is identical or not.
+ *
+ * Limitation:
+ * Works only for sets of 1 column (i.e. one class of object selected)
+ *
+ * @param \DBObjectSet $oObjectSet
+ * @param array $aExcludeColumns The list of columns to exclude frop the comparison
+ *
+ * @return boolean True if the sets are identical, false otherwise
+ *
+ * @throws \CoreException
+ */
+ public function HasSameContents(DBObjectSet $oObjectSet, $aExcludeColumns = [])
+ {
$oComparator = new DBObjectSetComparator($this, $oObjectSet, $aExcludeColumns);
return $oComparator->SetsAreEquivalent();
}
/**
* Build a new set (in memory) made of objects of the given set which are NOT present in the current set
- *
+ *
* Limitations:
* The objects inside the set must be written in the database since the comparison is based on their identifiers
* Sets with several objects per row are NOT supported
- *
+ *
* @param \DBObjectSet $oObjectSet
- *
+ *
* @return \DBObjectSet The "delta" set.
*
* @throws \Exception
@@ -1333,17 +1258,17 @@ class DBObjectSet implements iDBObjectSetIterator
*/
public function CreateDelta(DBObjectSet $oObjectSet)
{
- if ($this->GetRootClass() != $oObjectSet->GetRootClass())
- {
+ if ($this->GetRootClass() != $oObjectSet->GetRootClass()) {
throw new CoreException("Could not 'delta' two objects sets if they don't have the same root class");
}
- if (!$this->m_bLoaded) $this->Load();
+ if (!$this->m_bLoaded) {
+ $this->Load();
+ }
- $aId2Row = array();
+ $aId2Row = [];
$iCurrPos = $this->m_iCurrRow; // Save the cursor
$idx = 0;
- while($oObj = $this->Fetch())
- {
+ while ($oObj = $this->Fetch()) {
$aId2Row[$oObj->GetKey()] = $idx;
$idx++;
}
@@ -1351,10 +1276,8 @@ class DBObjectSet implements iDBObjectSetIterator
$oNewSet = DBObjectSet::FromScratch($this->GetClass());
$oObjectSet->Seek(0);
- while ($oObject = $oObjectSet->Fetch())
- {
- if (!array_key_exists($oObject->GetKey(), $aId2Row))
- {
+ while ($oObject = $oObjectSet->Fetch()) {
+ if (!array_key_exists($oObject->GetKey(), $aId2Row)) {
$oNewSet->AddObject($oObject);
}
}
@@ -1362,145 +1285,126 @@ class DBObjectSet implements iDBObjectSetIterator
return $oNewSet;
}
- /**
- * Compute the "RelatedObjects" (forward or "down" direction) for the set
- * for the specified relation
- *
- * @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 \Exception
- * @throws \CoreException
- * @throws \CoreUnexpectedValue
- * @throws \MySQLException
- */
+ /**
+ * Compute the "RelatedObjects" (forward or "down" direction) for the set
+ * for the specified relation
+ *
+ * @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 \Exception
+ * @throws \CoreException
+ * @throws \CoreUnexpectedValue
+ * @throws \MySQLException
+ */
public function GetRelatedObjectsDown($sRelCode, $iMaxDepth = 99, $bEnableRedundancy = true)
{
$oGraph = new RelationGraph();
$this->Rewind();
- while($oObj = $this->Fetch())
- {
+ while ($oObj = $this->Fetch()) {
$oGraph->AddSourceObject($oObj);
}
$oGraph->ComputeRelatedObjectsDown($sRelCode, $iMaxDepth, $bEnableRedundancy);
return $oGraph;
}
- /**
- * Compute the "RelatedObjects" (reverse or "up" direction) for the set
- * for the specified relation
- *
- * @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 \Exception
- * @throws \CoreException
- * @throws \CoreUnexpectedValue
- * @throws \MySQLException
- */
+ /**
+ * Compute the "RelatedObjects" (reverse or "up" direction) for the set
+ * for the specified relation
+ *
+ * @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 \Exception
+ * @throws \CoreException
+ * @throws \CoreUnexpectedValue
+ * @throws \MySQLException
+ */
public function GetRelatedObjectsUp($sRelCode, $iMaxDepth = 99, $bEnableRedundancy = true)
{
$oGraph = new RelationGraph();
$this->Rewind();
- while($oObj = $this->Fetch())
- {
+ while ($oObj = $this->Fetch()) {
$oGraph->AddSinkObject($oObj);
}
$oGraph->ComputeRelatedObjectsUp($sRelCode, $iMaxDepth, $bEnableRedundancy);
return $oGraph;
}
- /**
- * Builds an object that contains the values that are common to all the objects
- * in the set. If for a given attribute, objects in the set have various values
- * then the resulting object will contain null for this value.
- *
- * @param array $aValues Hash Output: the distribution of the values, in the set, for each attribute
- *
- * @return \DBObject The object with the common values
- *
- * @throws \Exception
- * @throws \CoreException
- * @throws \CoreUnexpectedValue
- * @throws \MySQLException
- */
+ /**
+ * Builds an object that contains the values that are common to all the objects
+ * in the set. If for a given attribute, objects in the set have various values
+ * then the resulting object will contain null for this value.
+ *
+ * @param array $aValues Hash Output: the distribution of the values, in the set, for each attribute
+ *
+ * @return \DBObject The object with the common values
+ *
+ * @throws \Exception
+ * @throws \CoreException
+ * @throws \CoreUnexpectedValue
+ * @throws \MySQLException
+ */
public function ComputeCommonObject(&$aValues)
{
$sClass = $this->GetClass();
$aList = MetaModel::ListAttributeDefs($sClass);
- $aValues = array();
- foreach($aList as $sAttCode => $oAttDef)
- {
- if ($oAttDef->IsScalar())
- {
- $aValues[$sAttCode] = array();
+ $aValues = [];
+ foreach ($aList as $sAttCode => $oAttDef) {
+ if ($oAttDef->IsScalar()) {
+ $aValues[$sAttCode] = [];
}
}
$this->Rewind();
- while($oObj = $this->Fetch())
- {
- foreach($aList as $sAttCode => $oAttDef)
- {
- if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
- {
+ while ($oObj = $this->Fetch()) {
+ foreach ($aList as $sAttCode => $oAttDef) {
+ if ($oAttDef->IsScalar() && $oAttDef->IsWritable()) {
$currValue = $oObj->Get($sAttCode);
- if (is_object($currValue)) continue; // Skip non scalar values...
- if(!array_key_exists($currValue, $aValues[$sAttCode]))
- {
- $aValues[$sAttCode][$currValue] = array('count' => 1, 'display' => $oObj->GetAsHTML($sAttCode));
- }
- else
- {
- $aValues[$sAttCode][$currValue]['count']++;
+ if (is_object($currValue)) {
+ continue;
+ } // Skip non scalar values...
+ if (!array_key_exists($currValue, $aValues[$sAttCode])) {
+ $aValues[$sAttCode][$currValue] = ['count' => 1, 'display' => $oObj->GetAsHTML($sAttCode)];
+ } else {
+ $aValues[$sAttCode][$currValue]['count']++;
}
}
}
}
-
- foreach($aValues as $sAttCode => $aMultiValues)
- {
- if (count($aMultiValues) > 1)
- {
+
+ foreach ($aValues as $sAttCode => $aMultiValues) {
+ if (count($aMultiValues) > 1) {
uasort($aValues[$sAttCode], 'HashCountComparison');
}
}
-
-
- // Now create an object that has values for the homogenous values only
+
+ // Now create an object that has values for the homogenous values only
$oCommonObj = new $sClass(); // @@ What if the class is abstract ?
- $aComments = array();
+ $aComments = [];
$iFormId = cmdbAbstractObject::GetNextFormId(); // Identifier that prefixes all the form fields
$sReadyScript = '';
- $aDependsOn = array();
+ $aDependsOn = [];
$sFormPrefix = '2_';
- foreach($aList as $sAttCode => $oAttDef)
- {
- if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
- {
- if ($oAttDef->GetEditClass() == 'One Way Password')
- {
+ foreach ($aList as $sAttCode => $oAttDef) {
+ if ($oAttDef->IsScalar() && $oAttDef->IsWritable()) {
+ if ($oAttDef->GetEditClass() == 'One Way Password') {
$oCommonObj->Set($sAttCode, null);
- }
- else
- {
+ } else {
$iCount = count($aValues[$sAttCode]);
- if ($iCount == 1)
- {
+ if ($iCount == 1) {
// Homogenous value
reset($aValues[$sAttCode]);
$aKeys = array_keys($aValues[$sAttCode]);
$currValue = $aKeys[0]; // The only value is the first key
$oCommonObj->Set($sAttCode, $currValue);
- }
- else
- {
+ } else {
// Non-homogenous value
$oCommonObj->Set($sAttCode, null);
}
@@ -1520,21 +1424,18 @@ class DBObjectSet implements iDBObjectSetIterator
// The complete list of arguments will include magic arguments (e.g. current_user->attcode)
$aScalarArgs = MetaModel::PrepareQueryArguments($this->m_oFilter->GetInternalParams(), $this->m_aArgs, $this->m_oFilter->GetExpectedArguments());
$aConst = $this->m_oFilter->ListConstantFields();
-
- foreach($aConst as $sClassAlias => $aVals)
- {
- foreach($aVals as $sCode => $oExpr)
- {
- if (is_object($oExpr)) // Array_merge_recursive creates an array when the same key is present multiple times... ignore them
- {
+
+ foreach ($aConst as $sClassAlias => $aVals) {
+ foreach ($aVals as $sCode => $oExpr) {
+ if (is_object($oExpr)) { // Array_merge_recursive creates an array when the same key is present multiple times... ignore them
$oScalarExpr = $oExpr->GetAsScalar($aScalarArgs);
$aConst[$sClassAlias][$sCode] = $oScalarExpr->GetValue();
}
}
}
- return $aConst;
+ return $aConst;
}
-
+
public function ApplyParameters()
{
$aAllArgs = MetaModel::PrepareQueryArguments($this->m_oFilter->GetInternalParams(), $this->m_aArgs, $this->m_oFilter->GetExpectedArguments());
@@ -1549,11 +1450,10 @@ class DBObjectSet implements iDBObjectSetIterator
*/
function HashCountComparison($a, $b) // Sort descending on 'count'
{
- if ($a['count'] == $b['count'])
- {
- return 0;
- }
- return ($a['count'] > $b['count']) ? -1 : 1;
+ if ($a['count'] == $b['count']) {
+ return 0;
+ }
+ return ($a['count'] > $b['count']) ? -1 : 1;
}
/**
@@ -1561,7 +1461,7 @@ function HashCountComparison($a, $b) // Sort descending on 'count'
* The FIRST SET MUST BE LOADED FROM THE DATABASE, the second one can be a set of objects in memory
* When computing the actual differences, the algorithm tries to preserve as much as possible the EXISTING
* objects (i.e. prefers 'modified' to 'removed' + 'added')
- *
+ *
* LIMITATIONS:
* - only DBObjectSets with one column (i.e. one class of object selected) are supported
* - the first set must be the one loaded from the database
@@ -1590,7 +1490,7 @@ class DBObjectSetComparator
protected $sAdditionalKeyColumn;
protected $aAdditionalKeys;
-
+
/**
* Initializes the comparator
* @param iDBObjectSetIterator $oSet1 The first set of objects to compare, or null
@@ -1598,63 +1498,55 @@ class DBObjectSetComparator
* @param array $aExcludedColumns The list of columns (= attribute codes) to exclude from the comparison
* @param string $sAdditionalKeyColumn The attribute code of an additional column to be considered as a key indentifying the object (useful for n:n links)
*/
- public function __construct(iDBObjectSetIterator $oSet1, iDBObjectSetIterator $oSet2, $aExcludedColumns = array(), $sAdditionalKeyColumn = null)
+ public function __construct(iDBObjectSetIterator $oSet1, iDBObjectSetIterator $oSet2, $aExcludedColumns = [], $sAdditionalKeyColumn = null)
{
$this->aFingerprints1 = null;
$this->aFingerprints2 = null;
- $this->aIDs1 = array();
- $this->aIDs2 = array();
+ $this->aIDs1 = [];
+ $this->aIDs2 = [];
$this->aExcludedColumns = $aExcludedColumns;
$this->sAdditionalKeyColumn = $sAdditionalKeyColumn;
$this->aAdditionalKeys = null;
$this->oSet1 = $oSet1;
- $this->oSet2 = $oSet2;
+ $this->oSet2 = $oSet2;
}
- /**
- * Builds the lists of fingerprints and initializes internal structures, if it was not already done
- *
- * @internal
- *
- * @throws \CoreException
- */
+ /**
+ * Builds the lists of fingerprints and initializes internal structures, if it was not already done
+ *
+ * @internal
+ *
+ * @throws \CoreException
+ */
protected function ComputeFingerprints()
{
- if ($this->aFingerprints1 === null)
- {
- $this->aFingerprints1 = array();
- $this->aFingerprints2 = array();
- $this->aAdditionalKeys = array();
-
- if ($this->oSet1 !== null)
- {
+ if ($this->aFingerprints1 === null) {
+ $this->aFingerprints1 = [];
+ $this->aFingerprints2 = [];
+ $this->aAdditionalKeys = [];
+
+ if ($this->oSet1 !== null) {
$this->oSet1->Rewind();
- while($oObj = $this->oSet1->Fetch())
- {
+ while ($oObj = $this->oSet1->Fetch()) {
$sFingerprint = $oObj->Fingerprint($this->aExcludedColumns);
$this->aFingerprints1[$sFingerprint] = $oObj;
- if (!$oObj->IsNew())
- {
+ if (!$oObj->IsNew()) {
$this->aIDs1[$oObj->GetKey()] = $oObj;
}
}
$this->oSet1->Rewind();
}
-
- if ($this->oSet2 !== null)
- {
+
+ if ($this->oSet2 !== null) {
$this->oSet2->Rewind();
- while($oObj = $this->oSet2->Fetch())
- {
+ while ($oObj = $this->oSet2->Fetch()) {
$sFingerprint = $oObj->Fingerprint($this->aExcludedColumns);
$this->aFingerprints2[$sFingerprint] = $oObj;
- if (!$oObj->IsNew())
- {
+ if (!$oObj->IsNew()) {
$this->aIDs2[$oObj->GetKey()] = $oObj;
}
-
- if ($this->sAdditionalKeyColumn !== null)
- {
+
+ if ($this->sAdditionalKeyColumn !== null) {
$this->aAdditionalKeys[$oObj->Get($this->sAdditionalKeyColumn)] = $oObj;
}
}
@@ -1663,82 +1555,75 @@ class DBObjectSetComparator
}
}
- /**
- * Tells if the sets are equivalent or not. Returns as soon as the first difference is found.
- *
- * @internal
- *
- * @return boolean true if the set have an equivalent content, false otherwise
- *
- * @throws \CoreException
- */
+ /**
+ * Tells if the sets are equivalent or not. Returns as soon as the first difference is found.
+ *
+ * @internal
+ *
+ * @return boolean true if the set have an equivalent content, false otherwise
+ *
+ * @throws \CoreException
+ */
public function SetsAreEquivalent()
{
- if (($this->oSet1 === null) && ($this->oSet2 === null))
- {
+ if (($this->oSet1 === null) && ($this->oSet2 === null)) {
// Both sets are empty, they are equal
return true;
- }
- else if (($this->oSet1 === null) || ($this->oSet2 === null))
- {
+ } elseif (($this->oSet1 === null) || ($this->oSet2 === null)) {
// one of them is empty, they are different
return false;
}
-
- if (($this->oSet1->GetRootClass() != $this->oSet2->GetRootClass()) || ($this->oSet1->Count() != $this->oSet2->Count())) return false;
-
+
+ if (($this->oSet1->GetRootClass() != $this->oSet2->GetRootClass()) || ($this->oSet1->Count() != $this->oSet2->Count())) {
+ return false;
+ }
+
$this->ComputeFingerprints();
-
+
// Check that all objects in Set1 are also in Set2
- foreach($this->aFingerprints1 as $sFingerprint => $oObj)
- {
- if (!array_key_exists($sFingerprint, $this->aFingerprints2))
- {
+ foreach ($this->aFingerprints1 as $sFingerprint => $oObj) {
+ if (!array_key_exists($sFingerprint, $this->aFingerprints2)) {
return false;
}
}
-
+
// Vice versa
// Check that all objects in Set2 are also in Set1
- foreach($this->aFingerprints2 as $sFingerprint => $oObj)
- {
- if (!array_key_exists($sFingerprint, $this->aFingerprints1))
- {
+ foreach ($this->aFingerprints2 as $sFingerprint => $oObj) {
+ if (!array_key_exists($sFingerprint, $this->aFingerprints1)) {
return false;
}
}
-
+
return true;
}
- /**
- * Get the list of differences between the two sets. In ordeer to write back into the database only the minimum changes
- * THE FIRST SET MUST BE THE ONE LOADED FROM THE DATABASE
- *
- * @internal
- *
- * @return array 'added' => DBObject(s), 'removed' => DBObject(s), 'modified' => DBObjects(s)
- *
- * @throws \Exception
- * @throws \CoreException
- */
+ /**
+ * Get the list of differences between the two sets. In ordeer to write back into the database only the minimum changes
+ * THE FIRST SET MUST BE THE ONE LOADED FROM THE DATABASE
+ *
+ * @internal
+ *
+ * @return array 'added' => DBObject(s), 'removed' => DBObject(s), 'modified' => DBObjects(s)
+ *
+ * @throws \Exception
+ * @throws \CoreException
+ */
public function GetDifferences()
{
- $aResult = array('added' => array(), 'removed' => array(), 'modified' => array());
+ $aResult = ['added' => [], 'removed' => [], 'modified' => []];
$this->ComputeFingerprints();
-
+
// Check that all objects in Set1 are also in Set2
- foreach($this->aFingerprints1 as $sFingerprint => $oObj)
- {
+ foreach ($this->aFingerprints1 as $sFingerprint => $oObj) {
// Beware: the elements from the first set MUST come from the database, otherwise the result will be irrelevant
- if ($oObj->IsNew()) throw new Exception('Cannot compute differences when elements from the first set are NOT in the database');
- if (array_key_exists($oObj->GetKey(), $this->aIDs2) && ($this->aIDs2[$oObj->GetKey()]->IsModified()))
- {
+ if ($oObj->IsNew()) {
+ throw new Exception('Cannot compute differences when elements from the first set are NOT in the database');
+ }
+ if (array_key_exists($oObj->GetKey(), $this->aIDs2) && ($this->aIDs2[$oObj->GetKey()]->IsModified())) {
// The very same object exists in both set, but was modified since its load
$aResult['modified'][$oObj->GetKey()] = $this->aIDs2[$oObj->GetKey()];
- }
- else if (($this->sAdditionalKeyColumn !== null) && array_key_exists($oObj->Get($this->sAdditionalKeyColumn), $this->aAdditionalKeys))
- {
+ } elseif (($this->sAdditionalKeyColumn !== null) && array_key_exists($oObj->Get($this->sAdditionalKeyColumn), $this->aAdditionalKeys)) {
// Special case for n:n links where the link is recreated between the very same 2 objects, but some of its attributes are modified
// Let's consider this as a "modification" instead of "deletion" + "creation" in order to have a "clean" history for the objects
$oDestObj = $this->aAdditionalKeys[$oObj->Get($this->sAdditionalKeyColumn)];
@@ -1747,51 +1632,43 @@ class DBObjectSetComparator
// Mark this as processed, so that the pass on aFingerprints2 below ignores this object
$sNewFingerprint = $oDestObj->Fingerprint($this->aExcludedColumns);
$this->aFingerprints2[$sNewFingerprint] = $oCloneObj;
- }
- else if (!array_key_exists($sFingerprint, $this->aFingerprints2))
- {
+ } elseif (!array_key_exists($sFingerprint, $this->aFingerprints2)) {
$aResult['removed'][] = $oObj;
}
}
-
+
// Vice versa
// Check that all objects in Set2 are also in Set1
- foreach($this->aFingerprints2 as $sFingerprint => $oObj)
- {
- if (array_key_exists($oObj->GetKey(), $this->aIDs1) && ($oObj->IsModified()))
- {
+ foreach ($this->aFingerprints2 as $sFingerprint => $oObj) {
+ if (array_key_exists($oObj->GetKey(), $this->aIDs1) && ($oObj->IsModified())) {
// Already marked as modified above
//$aResult['modified'][$oObj->GetKey()] = $oObj;
- }
- else if (!array_key_exists($sFingerprint, $this->aFingerprints1))
- {
+ } elseif (!array_key_exists($sFingerprint, $this->aFingerprints1)) {
$aResult['added'][] = $oObj;
}
}
return $aResult;
}
- /**
- * Helper to clone (in memory) an object and to apply to it the values taken from a second object
- *
- * @internal
- *
- * @param \DBObject $oObjToClone
- * @param \DBObject $oObjWithValues
- *
- * @return \DBObject The modified clone
- *
- * @throws \ArchivedObjectException
- * @throws \CoreException
- * @throws \CoreUnexpectedValue
- */
+ /**
+ * Helper to clone (in memory) an object and to apply to it the values taken from a second object
+ *
+ * @internal
+ *
+ * @param \DBObject $oObjToClone
+ * @param \DBObject $oObjWithValues
+ *
+ * @return \DBObject The modified clone
+ *
+ * @throws \ArchivedObjectException
+ * @throws \CoreException
+ * @throws \CoreUnexpectedValue
+ */
protected function CopyFrom($oObjToClone, $oObjWithValues)
{
$oObj = MetaModel::GetObject(get_class($oObjToClone), $oObjToClone->GetKey());
- foreach(MetaModel::ListAttributeDefs(get_class($oObj)) as $sAttCode => $oAttDef)
- {
- if (!in_array($sAttCode, $this->aExcludedColumns) && $oAttDef->IsWritable())
- {
+ foreach (MetaModel::ListAttributeDefs(get_class($oObj)) as $sAttCode => $oAttDef) {
+ if (!in_array($sAttCode, $this->aExcludedColumns) && $oAttDef->IsWritable()) {
$oObj->Set($sAttCode, $oObjWithValues->Get($sAttCode));
}
}
diff --git a/core/dbproperty.class.inc.php b/core/dbproperty.class.inc.php
index b03aae2fe..c7ddcc542 100644
--- a/core/dbproperty.class.inc.php
+++ b/core/dbproperty.class.inc.php
@@ -1,9 +1,10 @@
-
/**
* Database properties - manage database instances in a complex installation
*
@@ -24,9 +24,8 @@
* @license http://opensource.org/licenses/AGPL-3.0
*/
-
/**
- * A database property
+ * A database property
*
* @package iTopORM
*/
@@ -34,40 +33,37 @@ class DBProperty extends DBObject
{
public static function Init()
{
- $aParams = array
- (
+ $aParams =
+ [
"category" => "cloud",
"key_type" => "autoincrement",
"name_attcode" => "name",
"state_attcode" => "",
- "reconc_keys" => array(),
+ "reconc_keys" => [],
"db_table" => "priv_db_properties",
"db_key_field" => "id",
"db_finalclass_field" => "",
- );
+ ];
MetaModel::Init_Params($aParams);
//MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeString("name", array("allowed_values"=>null, "sql"=>"name", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeString("description", array("allowed_values"=>null, "sql"=>"description", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeString("value", array("allowed_values"=>null, "sql"=>"value", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeString("name", ["allowed_values" => null, "sql" => "name", "default_value" => null, "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeString("description", ["allowed_values" => null, "sql" => "description", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeString("value", ["allowed_values" => null, "sql" => "value", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
- MetaModel::Init_AddAttribute(new AttributeDateTime("change_date", array("allowed_values"=>null, "sql"=>"change_date", "default_value"=>"NOW()", "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeString("change_comment", array("allowed_values"=>null, "sql"=>"change_comment", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeDateTime("change_date", ["allowed_values" => null, "sql" => "change_date", "default_value" => "NOW()", "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeString("change_comment", ["allowed_values" => null, "sql" => "change_comment", "default_value" => null, "is_null_allowed" => true, "depends_on" => []]));
}
/**
- * Helper to check wether the table has been created into the DB
+ * Helper to check wether the table has been created into the DB
* (this table did not exist in 1.0.1 and older versions)
*/
public static function IsInstalled()
{
$sTable = MetaModel::DBGetTable(__CLASS__);
- if (CMDBSource::IsTable($sTable))
- {
+ if (CMDBSource::IsTable($sTable)) {
return true;
- }
- else
- {
+ } else {
return false;
}
return false;
@@ -75,12 +71,10 @@ class DBProperty extends DBObject
public static function SetProperty($sName, $sValue, $sComment = '', $sDescription = null)
{
- try
- {
+ try {
$oSearch = DBObjectSearch::FromOQL('SELECT DBProperty WHERE name = :name');
- $oSet = new DBObjectSet($oSearch, array(), array('name' => $sName));
- if ($oSet->Count() == 0)
- {
+ $oSet = new DBObjectSet($oSearch, [], ['name' => $sName]);
+ if ($oSet->Count() == 0) {
$oProp = new DBProperty();
$oProp->Set('name', $sName);
$oProp->Set('description', $sDescription);
@@ -88,31 +82,23 @@ class DBProperty extends DBObject
$oProp->Set('change_date', time());
$oProp->Set('change_comment', $sComment);
$oProp->DBInsert();
- }
- elseif ($oSet->Count() == 1)
- {
+ } elseif ($oSet->Count() == 1) {
$oProp = $oSet->fetch();
- if (!is_null($sDescription))
- {
+ if (!is_null($sDescription)) {
$oProp->Set('description', $sDescription);
}
$oProp->Set('value', $sValue);
$oProp->Set('change_date', time());
$oProp->Set('change_comment', $sComment);
$oProp->DBUpdate();
- }
- else
- {
+ } else {
// Houston...
throw new CoreException('duplicate db property');
}
- }
- catch (MySQLException $e)
- {
+ } catch (MySQLException $e) {
// This might be because the table could not be found,
// let's check it and discard silently if this is really the case
- if (self::IsInstalled())
- {
+ if (self::IsInstalled()) {
throw $e;
}
IssueLog::Error('Attempting to write a DBProperty while the module has not been installed');
@@ -121,34 +107,25 @@ class DBProperty extends DBObject
public static function GetProperty($sName, $default = null)
{
- try
- {
+ try {
$oSearch = DBObjectSearch::FromOQL('SELECT DBProperty WHERE name = :name');
- $oSet = new DBObjectSet($oSearch, array(), array('name' => $sName));
+ $oSet = new DBObjectSet($oSearch, [], ['name' => $sName]);
$iCount = $oSet->Count();
- if ($iCount == 0)
- {
+ if ($iCount == 0) {
//throw new CoreException('unknown db property', array('name' => $sName));
$sValue = $default;
- }
- elseif ($iCount == 1)
- {
+ } elseif ($iCount == 1) {
$oProp = $oSet->fetch();
$sValue = $oProp->Get('value');
- }
- else
- {
+ } else {
// $iCount > 1
// Houston...
- throw new CoreException('duplicate db property', array('name' => $sName, 'count' => $iCount));
+ throw new CoreException('duplicate db property', ['name' => $sName, 'count' => $iCount]);
}
- }
- catch (MySQLException $e)
- {
+ } catch (MySQLException $e) {
// This might be because the table could not be found,
// let's check it and discard silently if this is really the case
- if (self::IsInstalled())
- {
+ if (self::IsInstalled()) {
throw $e;
}
$sValue = $default;
@@ -156,5 +133,3 @@ class DBProperty extends DBObject
return $sValue;
}
}
-
-?>
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/deletionplan.class.inc.php b/core/deletionplan.class.inc.php
index 493e0a1c8..fa12655e3 100644
--- a/core/deletionplan.class.inc.php
+++ b/core/deletionplan.class.inc.php
@@ -1,4 +1,5 @@
array(
+ protected static $m_aModeUpdate = [
+ DEL_SILENT => [
DEL_SILENT => DEL_SILENT,
DEL_AUTO => DEL_AUTO,
- DEL_MANUAL => DEL_MANUAL
- ),
- DEL_MANUAL => array(
+ DEL_MANUAL => DEL_MANUAL,
+ ],
+ DEL_MANUAL => [
DEL_SILENT => DEL_MANUAL,
DEL_AUTO => DEL_AUTO,
- DEL_MANUAL => DEL_MANUAL
- ),
- DEL_AUTO => array(
+ DEL_MANUAL => DEL_MANUAL,
+ ],
+ DEL_AUTO => [
DEL_SILENT => DEL_AUTO,
DEL_AUTO => DEL_AUTO,
- DEL_MANUAL => DEL_AUTO
- )
- );
+ DEL_MANUAL => DEL_AUTO,
+ ],
+ ];
public function __construct()
{
$this->m_iToDelete = 0;
$this->m_iToUpdate = 0;
- $this->m_aToDelete = array();
- $this->m_aToUpdate = array();
+ $this->m_aToDelete = [];
+ $this->m_aToUpdate = [];
$this->m_bFoundStopper = false;
$this->m_bFoundSecurityIssue = false;
@@ -65,22 +66,17 @@ class DeletionPlan
$this->m_iToDelete = 0;
$this->m_iToUpdate = 0;
- foreach($this->m_aToDelete as $sClass => $aToDelete)
- {
- foreach($aToDelete as $iId => $aData)
- {
+ foreach ($this->m_aToDelete as $sClass => $aToDelete) {
+ foreach ($aToDelete as $iId => $aData) {
$this->m_iToDelete++;
- if (isset($aData['issue']))
- {
+ if (isset($aData['issue'])) {
$this->m_bFoundStopper = true;
$this->m_bFoundManualOperation = true;
- if (isset($aData['issue_security']))
- {
+ if (isset($aData['issue_security'])) {
$this->m_bFoundSecurityIssue = true;
}
}
- if ($aData['mode'] == DEL_MANUAL)
- {
+ if ($aData['mode'] == DEL_MANUAL) {
$this->m_aToDelete[$sClass][$iId]['issue'] = $sClass.'::'.$iId.' '.Dict::S('UI:Delete:MustBeDeletedManually');
$this->m_bFoundStopper = true;
$this->m_bFoundManualDelete = true;
@@ -92,30 +88,25 @@ class DeletionPlan
// www.php.net/manual/fr/function.set-time-limit.php#72305
$iPreviousTimeLimit = ini_get('max_execution_time');
$iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
- foreach($this->m_aToUpdate as $sClass => $aToUpdate)
- {
- foreach($aToUpdate as $iId => $aData)
- {
+ foreach ($this->m_aToUpdate as $sClass => $aToUpdate) {
+ foreach ($aToUpdate as $iId => $aData) {
set_time_limit(intval($iLoopTimeLimit));
$this->m_iToUpdate++;
$oObject = $aData['to_reset'];
- $aExtKeyLabels = array();
- foreach ($aData['attributes'] as $sRemoteExtKey => $aRemoteAttDef)
- {
+ $aExtKeyLabels = [];
+ foreach ($aData['attributes'] as $sRemoteExtKey => $aRemoteAttDef) {
$oObject->Set($sRemoteExtKey, $aData['values'][$sRemoteExtKey]);
$aExtKeyLabels[] = $aRemoteAttDef->GetLabel();
}
- $this->m_aToUpdate[$sClass][$iId]['attributes_list'] = implode(', ', $aExtKeyLabels);
+ $this->m_aToUpdate[$sClass][$iId]['attributes_list'] = implode(', ', $aExtKeyLabels);
list($bRes, $aIssues, $bSecurityIssues) = $oObject->CheckToWrite();
- if (!$bRes)
- {
+ if (!$bRes) {
$this->m_aToUpdate[$sClass][$iId]['issue'] = implode(', ', $aIssues);
$this->m_bFoundStopper = true;
- if ($bSecurityIssues)
- {
+ if ($bSecurityIssues) {
$this->m_aToUpdate[$sClass][$iId]['issue_security'] = true;
$this->m_bFoundSecurityIssue = true;
}
@@ -127,23 +118,17 @@ class DeletionPlan
public function GetIssues()
{
- $aIssues = array();
- foreach ($this->m_aToDelete as $sClass => $aToDelete)
- {
- foreach ($aToDelete as $iId => $aData)
- {
- if (isset($aData['issue']))
- {
+ $aIssues = [];
+ foreach ($this->m_aToDelete as $sClass => $aToDelete) {
+ foreach ($aToDelete as $iId => $aData) {
+ if (isset($aData['issue'])) {
$aIssues[] = $aData['issue'];
}
}
}
- foreach ($this->m_aToUpdate as $sClass => $aToUpdate)
- {
- foreach ($aToUpdate as $iId => $aData)
- {
- if (isset($aData['issue']))
- {
+ foreach ($this->m_aToUpdate as $sClass => $aToUpdate) {
+ foreach ($aToUpdate as $iId => $aData) {
+ if (isset($aData['issue'])) {
$aIssues[] = $aData['issue'];
}
}
@@ -192,63 +177,50 @@ class DeletionPlan
public function AddToDelete($oObject, $iDeletionMode = null)
{
- if (is_null($iDeletionMode))
- {
+ if (is_null($iDeletionMode)) {
$bRequestedExplicitely = true;
$iDeletionMode = DEL_AUTO;
- }
- else
- {
+ } else {
$bRequestedExplicitely = false;
}
$sClass = get_class($oObject);
$iId = $oObject->GetKey();
- if (isset($this->m_aToUpdate[$sClass][$iId]))
- {
+ if (isset($this->m_aToUpdate[$sClass][$iId])) {
unset($this->m_aToUpdate[$sClass][$iId]);
}
- if (isset($this->m_aToDelete[$sClass][$iId]))
- {
- if ($this->m_aToDelete[$sClass][$iId]['requested_explicitely'])
- {
+ if (isset($this->m_aToDelete[$sClass][$iId])) {
+ if ($this->m_aToDelete[$sClass][$iId]['requested_explicitely']) {
// No change: let it in mode DEL_AUTO
- }
- else
- {
+ } else {
$iPrevDeletionMode = $this->m_aToDelete[$sClass][$iId]['mode'];
$iNewDeletionMode = self::$m_aModeUpdate[$iPrevDeletionMode][$iDeletionMode];
$this->m_aToDelete[$sClass][$iId]['mode'] = $iNewDeletionMode;
-
- if ($bRequestedExplicitely)
- {
+
+ if ($bRequestedExplicitely) {
// This object was in the root list
$this->m_aToDelete[$sClass][$iId]['requested_explicitely'] = true;
$this->m_aToDelete[$sClass][$iId]['mode'] = DEL_AUTO;
}
}
- }
- else
- {
- $this->m_aToDelete[$sClass][$iId] = array(
+ } else {
+ $this->m_aToDelete[$sClass][$iId] = [
'to_delete' => $oObject,
'mode' => $iDeletionMode,
'requested_explicitely' => $bRequestedExplicitely,
- );
+ ];
}
}
public function SetDeletionIssues($oObject, $aIssues, $bSecurityIssue)
{
- if (count($aIssues ?? []) > 0)
- {
+ if (count($aIssues ?? []) > 0) {
$sClass = get_class($oObject);
$iId = $oObject->GetKey();
$this->m_aToDelete[$sClass][$iId]['issue'] = implode(', ', $aIssues);
- if ($bSecurityIssue)
- {
+ if ($bSecurityIssue) {
$this->m_aToDelete[$sClass][$iId]['issue_security'] = true;
}
}
@@ -258,21 +230,16 @@ class DeletionPlan
{
$sClass = get_class($oObject);
$iId = $oObject->GetKey();
- if (isset($this->m_aToDelete[$sClass][$iId]))
- {
+ if (isset($this->m_aToDelete[$sClass][$iId])) {
// skip... it should be deleted anyhow !
- }
- else
- {
- if (!isset($this->m_aToUpdate[$sClass][$iId]))
- {
- $this->m_aToUpdate[$sClass][$iId] = array(
+ } else {
+ if (!isset($this->m_aToUpdate[$sClass][$iId])) {
+ $this->m_aToUpdate[$sClass][$iId] = [
'to_reset' => $oObject,
- );
+ ];
}
$this->m_aToUpdate[$sClass][$iId]['attributes'][$oAttDef->GetCode()] = $oAttDef;
$this->m_aToUpdate[$sClass][$iId]['values'][$oAttDef->GetCode()] = $value;
}
}
}
-?>
diff --git a/core/designdocument.class.inc.php b/core/designdocument.class.inc.php
index ceb3fdbf0..2befa6b8f 100644
--- a/core/designdocument.class.inc.php
+++ b/core/designdocument.class.inc.php
@@ -1,4 +1,5 @@
preserveWhiteSpace = true; // otherwise the formatOutput option would have no effect
}
+ /**
+ * @param string $source
+ * @param int $options
+ *
+ * @return bool|\DOMDocument
+ */
+ public function loadXML(string $source, int $options = 0): bool|DOMDocument
+ {
+ return parent::loadXML($source, $options | LIBXML_BIGLINES);
+ }
+
/**
* Overload of the standard API
*
@@ -135,13 +145,10 @@ class DesignDocument extends DOMDocument
*/
public static function XPathQuote($sValue)
{
- if (strpos($sValue, '"') !== false)
- {
+ if (strpos($sValue, '"') !== false) {
$aParts = explode('"', $sValue);
$sRet = 'concat("'.implode('", \'"\', "', $aParts).'")';
- }
- else
- {
+ } else {
$sRet = '"'.$sValue.'"';
}
return $sRet;
@@ -156,12 +163,9 @@ class DesignDocument extends DOMDocument
public function GetNodes($sXPath, $oContextNode = null)
{
$oXPath = new \DOMXPath($this);
- if (is_null($oContextNode))
- {
+ if (is_null($oContextNode)) {
$oResult = $oXPath->query($sXPath);
- }
- else
- {
+ } else {
$oResult = $oXPath->query($sXPath, $oContextNode);
}
return $oResult;
@@ -174,8 +178,12 @@ class DesignDocument extends DOMDocument
*/
public static function GetItopNodePath($oNode)
{
- if ($oNode instanceof \DOMDocument) return '';
- if (is_null($oNode)) return '';
+ if ($oNode instanceof \DOMDocument) {
+ return '';
+ }
+ if (is_null($oNode)) {
+ return '';
+ }
$sId = $oNode->getAttribute('id');
$sNodeDesc = ($sId != '') ? $oNode->nodeName.'['.$sId.']' : $oNode->nodeName;
@@ -303,16 +311,13 @@ class DesignElement extends \DOMElement
public function GetUniqueElement($sTagName, $bMustExist = true)
{
$oNode = null;
- foreach($this->childNodes as $oChildNode)
- {
- if ($oChildNode->nodeName == $sTagName)
- {
+ foreach ($this->childNodes as $oChildNode) {
+ if ($oChildNode->nodeName == $sTagName) {
$oNode = $oChildNode;
break;
}
}
- if ($bMustExist && is_null($oNode))
- {
+ if ($bMustExist && is_null($oNode)) {
throw new DOMFormatException('Missing unique tag: '.$sTagName);
}
return $oNode;
@@ -337,20 +342,17 @@ class DesignElement extends \DOMElement
public function GetText($sDefault = null)
{
$sText = null;
- foreach($this->childNodes as $oChildNode)
- {
- if ($oChildNode instanceof \DOMText)
- {
- if (is_null($sText)) $sText = '';
+ foreach ($this->childNodes as $oChildNode) {
+ if ($oChildNode instanceof \DOMText) {
+ if (is_null($sText)) {
+ $sText = '';
+ }
$sText .= $oChildNode->wholeText;
}
}
- if (is_null($sText))
- {
+ if (is_null($sText)) {
return $sDefault;
- }
- else
- {
+ } else {
return $sText;
}
}
@@ -367,8 +369,7 @@ class DesignElement extends \DOMElement
public function GetChildText($sTagName, $sDefault = null)
{
$sRet = $sDefault;
- if ($oChild = $this->GetOptionalElement($sTagName))
- {
+ if ($oChild = $this->GetOptionalElement($sTagName)) {
$sRet = $oChild->GetText($sDefault);
}
return $sRet;
@@ -427,7 +428,6 @@ class DesignElement extends \DOMElement
return self::_FindNode($this, $oRefNode, $sSearchId);
}
-
/**
* Find the child node matching the given node.
* UNSAFE: may return nodes marked as _alteration="removed"
@@ -482,32 +482,25 @@ class DesignElement extends \DOMElement
*/
public static function _FindNodes(DOMNode $oParent, DesignElement $oRefNode, string $sSearchId = null)
{
- if ($oParent instanceof DOMDocument)
- {
+ if ($oParent instanceof DOMDocument) {
$oDoc = $oParent->firstChild->ownerDocument;
$oRoot = $oParent;
- }
- else
- {
+ } else {
$oDoc = $oParent->ownerDocument;
$oRoot = $oParent;
}
$oXPath = new DOMXPath($oDoc);
- if ($oRefNode->hasAttribute('id'))
- {
+ if ($oRefNode->hasAttribute('id')) {
// Find the elements having the same tag name and id
- if (!$sSearchId)
- {
+ if (!$sSearchId) {
$sSearchId = $oRefNode->getAttribute('id');
}
$sQuotedId = DesignDocument::XPathQuote($sSearchId);
$sXPath = './'.$oRefNode->tagName."[@id=$sQuotedId]";
$oRes = $oXPath->query($sXPath, $oRoot);
- }
- else
- {
+ } else {
// Get the elements having the same tag name
$sXPath = './'.$oRefNode->tagName;
diff --git a/core/dict.class.inc.php b/core/dict.class.inc.php
index 002ca3c4b..ae87c76c5 100644
--- a/core/dict.class.inc.php
+++ b/core/dict.class.inc.php
@@ -1,4 +1,5 @@
-
define('DICT_ERR_STRING', 1); // when a string is missing, return the identifier
define('DICT_ERR_EXCEPTION', 2); // when a string is missing, throw an exception
//define('DICT_ERR_LOG', 3); // when a string is missing, log an error
-
/**
* Class Dict
* Management of localizable strings
@@ -32,8 +31,8 @@ class Dict
protected static $m_sDefaultLanguage = 'EN US';
protected static $m_sCurrentLanguage = null; // No language selected by default
- protected static $m_aLanguages = array(); // array( code => array( 'description' => '...', 'localized_description' => '...') ...)
- protected static $m_aData = array();
+ protected static $m_aLanguages = []; // array( code => array( 'description' => '...', 'localized_description' => '...') ...)
+ protected static $m_aData = [];
protected static $m_sApplicationPrefix = null;
/** @var \ApcService $m_oApcService */
protected static $m_oApcService = null;
@@ -45,8 +44,7 @@ class Dict
*/
public static function SetDefaultLanguage($sLanguageCode)
{
- if (!array_key_exists($sLanguageCode, self::$m_aLanguages))
- {
+ if (!array_key_exists($sLanguageCode, self::$m_aLanguages)) {
throw new DictExceptionUnknownLanguage($sLanguageCode);
}
self::$m_sDefaultLanguage = $sLanguageCode;
@@ -60,18 +58,15 @@ class Dict
*/
public static function SetUserLanguage($sLanguageCode = null)
{
- if (!is_null($sLanguageCode) && !array_key_exists($sLanguageCode, self::$m_aLanguages))
- {
+ if (!is_null($sLanguageCode) && !array_key_exists($sLanguageCode, self::$m_aLanguages)) {
throw new DictExceptionUnknownLanguage($sLanguageCode);
}
self::$m_sCurrentLanguage = $sLanguageCode;
}
-
public static function GetUserLanguage()
{
- if (self::$m_sCurrentLanguage == null) // May happen when no user is logged in (i.e. login screen, non-authenticated page)
- {
+ if (self::$m_sCurrentLanguage == null) { // May happen when no user is logged in (i.e. login screen, non-authenticated page)
// In which case let's use the default language
return self::$m_sDefaultLanguage;
}
@@ -99,8 +94,7 @@ class Dict
public static function Exists($sStringCode)
{
$sImpossibleString = 'aVlHYKEI3TZuDV5o0pghv7fvhYNYuzYkTk7WL0Zoqw8rggE7aq';
- if (static::S($sStringCode, $sImpossibleString) === $sImpossibleString)
- {
+ if (static::S($sStringCode, $sImpossibleString) === $sImpossibleString) {
return false;
}
return true;
@@ -139,26 +133,22 @@ class Dict
$sLangCode = self::GetUserLanguage();
self::InitLangIfNeeded($sLangCode);
- if (! array_key_exists($sLangCode, self::$m_aData))
- {
+ if (! array_key_exists($sLangCode, self::$m_aData)) {
IssueLog::Warning("Cannot find $sLangCode in all registered dictionaries.");
// It may happen, when something happens before the dictionaries get loaded
return [ 'label' => $sStringCode, 'lang' => $sLangCode ];
}
$aCurrentDictionary = self::$m_aData[$sLangCode];
- if (is_array($aCurrentDictionary) && array_key_exists($sStringCode, $aCurrentDictionary))
- {
+ if (is_array($aCurrentDictionary) && array_key_exists($sStringCode, $aCurrentDictionary)) {
return [ 'label' => $aCurrentDictionary[$sStringCode], 'lang' => $sLangCode ];
}
- if (!$bUserLanguageOnly)
- {
+ if (!$bUserLanguageOnly) {
// Attempt to find the string in the default language
//
self::InitLangIfNeeded(self::$m_sDefaultLanguage);
$aDefaultDictionary = self::$m_aData[self::$m_sDefaultLanguage];
- if (is_array($aDefaultDictionary) && array_key_exists($sStringCode, $aDefaultDictionary))
- {
+ if (is_array($aDefaultDictionary) && array_key_exists($sStringCode, $aDefaultDictionary)) {
return [ 'label' => $aDefaultDictionary[$sStringCode], 'lang' => self::$m_sDefaultLanguage ];
}
// Attempt to find the string in english
@@ -166,22 +156,19 @@ class Dict
self::InitLangIfNeeded('EN US');
$aDefaultDictionary = self::$m_aData['EN US'];
- if (is_array($aDefaultDictionary) && array_key_exists($sStringCode, $aDefaultDictionary))
- {
+ if (is_array($aDefaultDictionary) && array_key_exists($sStringCode, $aDefaultDictionary)) {
return [ 'label' => $aDefaultDictionary[$sStringCode], 'lang' => 'EN US' ];
}
}
// Could not find the string...
//
- if (is_null($sDefault))
- {
+ if (is_null($sDefault)) {
return [ 'label' => $sStringCode, 'lang' => null ];
}
return [ 'label' => $sDefault, 'lang' => null ];
}
-
/**
* Formats a localized string with numbered placeholders (%1$s...) for the additional arguments
* See vsprintf for more information about the syntax of the placeholders
@@ -199,15 +186,14 @@ class Dict
$aArguments = func_get_args();
array_shift($aArguments);
- if ($sLocalizedFormat == $sFormatCode)
- {
+ if ($sLocalizedFormat == $sFormatCode) {
// Make sure the information will be displayed (ex: an error occurring before the dictionary gets loaded)
return $sFormatCode.' - '.implode(', ', $aArguments);
}
- try{
+ try {
return utils::VSprintf($sLocalizedFormat, $aArguments);
- } catch(\Throwable $e){
+ } catch (\Throwable $e) {
\IssueLog::Error("Cannot format dict key", null, ["sFormatCode" => $sFormatCode, "sLangCode" => $sLangCode, 'exception_msg' => $e->getMessage() ]);
return $sFormatCode.' - '.implode(', ', $aArguments);
}
@@ -236,8 +222,9 @@ class Dict
* @since 2.7.6 N°4125
* @return \ApcService
*/
- public static function GetApcService() {
- if (self::$m_oApcService === null){
+ public static function GetApcService()
+ {
+ if (self::$m_oApcService === null) {
self::$m_oApcService = new ApcService();
}
return self::$m_oApcService;
@@ -247,7 +234,8 @@ class Dict
* @since 2.7.6 N°4125
* @param \ApcService $m_oApcService
*/
- public static function SetApcService($oApcService) {
+ public static function SetApcService($oApcService)
+ {
self::$m_oApcService = $oApcService;
}
@@ -258,19 +246,20 @@ class Dict
*/
public static function InitLangIfNeeded($sLangCode)
{
- if (array_key_exists($sLangCode, self::$m_aData)) return true;
+ if (array_key_exists($sLangCode, self::$m_aData)) {
+ return true;
+ }
$bResult = false;
if (self::GetApcService()->function_exists('apc_fetch')
- && (self::$m_sApplicationPrefix !== null))
- {
+ && (self::$m_sApplicationPrefix !== null)) {
// Note: For versions of APC older than 3.0.17, fetch() accepts only one parameter
//
self::$m_aData[$sLangCode] = self::GetApcService()->apc_fetch(self::$m_sApplicationPrefix.'-dict-'.$sLangCode);
if (self::$m_aData[$sLangCode] === false) {
unset(self::$m_aData[$sLangCode]);
- } else if (! is_array(self::$m_aData[$sLangCode])) {
+ } elseif (! is_array(self::$m_aData[$sLangCode])) {
// N°4125: we don't fix dictionary corrupted cache (on iTop side).
// but we log an error in a dedicated channel to let itop administrator be aware of a potential APCu issue to fix.
IssueLog::Error("APCu corrupted data (with $sLangCode dictionary). APCu configuration and running version should be troubleshooted...", LogChannels::APC);
@@ -279,14 +268,12 @@ class Dict
$bResult = true;
}
}
- if (!$bResult)
- {
+ if (!$bResult) {
$sDictFile = APPROOT.'env-'.utils::GetCurrentEnvironment().'/dictionaries/'.str_replace(' ', '-', strtolower($sLangCode)).'.dict.php';
require_once($sDictFile);
if (self::GetApcService()->function_exists('apc_store')
- && (self::$m_sApplicationPrefix !== null))
- {
+ && (self::$m_sApplicationPrefix !== null)) {
self::GetApcService()->apc_store(self::$m_sApplicationPrefix.'-dict-'.$sLangCode, self::$m_aData[$sLangCode]);
}
$bResult = true;
@@ -309,10 +296,8 @@ class Dict
*/
public static function ResetCache($sApplicationPrefix)
{
- if (function_exists('apc_delete'))
- {
- foreach(self::$m_aLanguages as $sLang => $void)
- {
+ if (function_exists('apc_delete')) {
+ foreach (self::$m_aLanguages as $sLang => $void) {
apc_delete($sApplicationPrefix.'-dict-'.$sLang);
}
}
@@ -320,7 +305,6 @@ class Dict
/////////////////////////////////////////////////////////////////////////
-
/**
* Clone a string in every language (if it exists in that language)
*
@@ -330,8 +314,8 @@ class Dict
*/
public static function CloneString($sSourceCode, $sDestCode)
{
- foreach(self::$m_aLanguages as $sLanguageCode => $foo) {
- if (isset(self::$m_aData[$sLanguageCode][$sSourceCode]) && !isset(self::$m_aData[$sLanguageCode][$sDestCode] )) {
+ foreach (self::$m_aLanguages as $sLanguageCode => $foo) {
+ if (isset(self::$m_aData[$sLanguageCode][$sSourceCode]) && !isset(self::$m_aData[$sLanguageCode][$sDestCode])) {
self::$m_aData[$sLanguageCode][$sDestCode] = self::$m_aData[$sLanguageCode][$sSourceCode];
}
}
@@ -339,40 +323,31 @@ class Dict
public static function MakeStats($sLanguageCode, $sLanguageRef = 'EN US')
{
- $aMissing = array(); // Strings missing for the target language
- $aUnexpected = array(); // Strings defined for the target language, but not found in the reference dictionary
- $aNotTranslated = array(); // Strings having the same value in both dictionaries
- $aOK = array(); // Strings having different values in both dictionaries
+ $aMissing = []; // Strings missing for the target language
+ $aUnexpected = []; // Strings defined for the target language, but not found in the reference dictionary
+ $aNotTranslated = []; // Strings having the same value in both dictionaries
+ $aOK = []; // Strings having different values in both dictionaries
- foreach (self::$m_aData[$sLanguageRef] as $sStringCode => $sValue)
- {
- if (!array_key_exists($sStringCode, self::$m_aData[$sLanguageCode]))
- {
+ foreach (self::$m_aData[$sLanguageRef] as $sStringCode => $sValue) {
+ if (!array_key_exists($sStringCode, self::$m_aData[$sLanguageCode])) {
$aMissing[$sStringCode] = $sValue;
}
}
- foreach (self::$m_aData[$sLanguageCode] as $sStringCode => $sValue)
- {
- if (!array_key_exists($sStringCode, self::$m_aData[$sLanguageRef]))
- {
+ foreach (self::$m_aData[$sLanguageCode] as $sStringCode => $sValue) {
+ if (!array_key_exists($sStringCode, self::$m_aData[$sLanguageRef])) {
$aUnexpected[$sStringCode] = $sValue;
- }
- else
- {
+ } else {
// The value exists in the reference
$sRefValue = self::$m_aData[$sLanguageRef][$sStringCode];
- if ($sValue == $sRefValue)
- {
+ if ($sValue == $sRefValue) {
$aNotTranslated[$sStringCode] = $sValue;
- }
- else
- {
+ } else {
$aOK[$sStringCode] = $sValue;
}
}
}
- return array($aMissing, $aUnexpected, $aNotTranslated, $aOK);
+ return [$aMissing, $aUnexpected, $aNotTranslated, $aOK];
}
public static function Dump()
@@ -389,10 +364,9 @@ class Dict
// ~~ or ~* can be used to indicate entries still to be translated.
public static function Add($sLanguageCode, $sEnglishLanguageDesc, $sLocalizedLanguageDesc, $aEntries)
{
- if (!array_key_exists($sLanguageCode, self::$m_aLanguages))
- {
- self::$m_aLanguages[$sLanguageCode] = array('description' => $sEnglishLanguageDesc, 'localized_description' => $sLocalizedLanguageDesc);
- self::$m_aData[$sLanguageCode] = array();
+ if (!array_key_exists($sLanguageCode, self::$m_aLanguages)) {
+ self::$m_aLanguages[$sLanguageCode] = ['description' => $sEnglishLanguageDesc, 'localized_description' => $sLocalizedLanguageDesc];
+ self::$m_aData[$sLanguageCode] = [];
}
// No need to actually load the strings since it's only used to know the list of languages
// at setup time !!
@@ -408,27 +382,22 @@ class Dict
{
self::InitLangIfNeeded(self::GetUserLanguage());
self::InitLangIfNeeded(self::$m_sDefaultLanguage);
- $aEntries = array();
+ $aEntries = [];
$iLength = strlen($sStartingWith);
// First prefill the array with entries from the default language
- foreach(self::$m_aData[self::$m_sDefaultLanguage] as $sCode => $sEntry)
- {
- if (substr($sCode, 0, $iLength) == $sStartingWith)
- {
+ foreach (self::$m_aData[self::$m_sDefaultLanguage] as $sCode => $sEntry) {
+ if (substr($sCode, 0, $iLength) == $sStartingWith) {
$aEntries[$sCode] = $sEntry;
}
}
// Now put (overwrite) the entries for the user language
- foreach(self::$m_aData[self::GetUserLanguage()] as $sCode => $sEntry)
- {
- if (substr($sCode, 0, $iLength) == $sStartingWith)
- {
+ foreach (self::$m_aData[self::GetUserLanguage()] as $sCode => $sEntry) {
+ if (substr($sCode, 0, $iLength) == $sStartingWith) {
$aEntries[$sCode] = $sEntry;
}
}
return $aEntries;
}
}
-?>
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/email.class.inc.php b/core/email.class.inc.php
index ca26d9223..5e559861c 100644
--- a/core/email.class.inc.php
+++ b/core/email.class.inc.php
@@ -1,9 +1,10 @@
-
/**
* Send an email (abstraction for synchronous/asynchronous modes)
*
@@ -27,9 +27,9 @@
use Combodo\iTop\Core\Email\EmailFactory;
use Combodo\iTop\Core\Email\iEMail;
-define ('EMAIL_SEND_OK', 0);
-define ('EMAIL_SEND_PENDING', 1);
-define ('EMAIL_SEND_ERROR', 2);
+define('EMAIL_SEND_OK', 0);
+define('EMAIL_SEND_PENDING', 1);
+define('EMAIL_SEND_ERROR', 2);
class EMail implements iEMail
{
@@ -43,18 +43,18 @@ class EMail implements iEMail
protected $oMailer;
// Serialization formats
- const ORIGINAL_FORMAT = 1; // Original format, consisting in serializing the whole object, inculding the Swift Mailer's object.
+ public const ORIGINAL_FORMAT = 1; // Original format, consisting in serializing the whole object, inculding the Swift Mailer's object.
// Did not work with attachements since their binary representation cannot be stored as a valid UTF-8 string
- const FORMAT_V2 = 2; // New format, only the raw data are serialized (base64 encoded if needed)
-
+ public const FORMAT_V2 = 2; // New format, only the raw data are serialized (base64 encoded if needed)
+
/** @var int ENUM_SEND_DEFAULT This option can be used when sending an e-mail to respect the default configuration parameter. */
- const ENUM_SEND_DEFAULT = 0;
-
+ public const ENUM_SEND_DEFAULT = 0;
+
/** @var int ENUM_SEND_FORCE_SYNCHRONOUS This option can be used when sending an e-mail to ignore the default and force synchronous sending instead. Example of a use case: instant e-mail test. */
- const ENUM_SEND_FORCE_SYNCHRONOUS = 1;
-
+ public const ENUM_SEND_FORCE_SYNCHRONOUS = 1;
+
/** @var int ENUM_SEND_FORCE_ASYNCHRONOUS This option can be used when sending an e-mail to ignore the default and force synchronous sending instead. Example of a use case: Bulk mails. */
- const ENUM_SEND_FORCE_ASYNCHRONOUS = 2;
+ public const ENUM_SEND_FORCE_ASYNCHRONOUS = 2;
public function __construct()
{
@@ -157,7 +157,7 @@ class EMail implements iEMail
public function SetBody($sBody, $sMimeType = 'text/html', $sCustomStyles = null)
{
$this->oMailer->SetBody($sBody, $sMimeType, $sCustomStyles);
- }
+ }
public function AddPart($sText, $sMimeType = 'text/html')
{
@@ -208,4 +208,4 @@ class EMail implements iEMail
{
$this->oMailer->SetRecipientReplyTo($sAddress);
}
-}
\ No newline at end of file
+}
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/excelbulkexport.class.inc.php b/core/excelbulkexport.class.inc.php
index 57eb40f96..6f4632962 100644
--- a/core/excelbulkexport.class.inc.php
+++ b/core/excelbulkexport.class.inc.php
@@ -1,4 +1,5 @@
aStatusInfo['formatted_text'] = (bool)utils::ReadParam('formatted_text', 0, true);
-
+
$sDateFormatRadio = utils::ReadParam('excel_date_format_radio', '');
- switch($sDateFormatRadio)
- {
+ switch ($sDateFormatRadio) {
case 'default':
- // Export from the UI => format = same as is the UI
- $this->aStatusInfo['date_format'] = (string)AttributeDateTime::GetFormat();
- break;
-
+ // Export from the UI => format = same as is the UI
+ $this->aStatusInfo['date_format'] = (string)AttributeDateTime::GetFormat();
+ break;
+
case 'custom':
- // Custom format specified from the UI
- $this->aStatusInfo['date_format'] = utils::ReadParam('date_format', (string)AttributeDateTime::GetFormat(), true, 'raw_data');
- break;
+ // Custom format specified from the UI
+ $this->aStatusInfo['date_format'] = utils::ReadParam('date_format', (string)AttributeDateTime::GetFormat(), true, 'raw_data');
+ break;
default:
// Export from the command line (or scripted) => default format is SQL, as in previous versions of iTop, unless specified otherwise
@@ -67,7 +67,7 @@ class ExcelBulkExport extends TabularBulkExport
public function EnumFormParts()
{
- return array_merge(parent::EnumFormParts(), array('xlsx_options' => array('formatted_text'), 'interactive_fields_xlsx' => array('interactive_fields_xlsx')));
+ return array_merge(parent::EnumFormParts(), ['xlsx_options' => ['formatted_text'], 'interactive_fields_xlsx' => ['interactive_fields_xlsx']]);
}
/**
@@ -121,7 +121,6 @@ class ExcelBulkExport extends TabularBulkExport
$oRadioCustom->GetInput()->AddCSSClass('ibo-input-checkbox');
$oFieldSetDate->AddSubBlock($oRadioCustom);
-
$oP->add_ready_script(
<<'.utils::EscapeHtml($oAttDef->GetEditValue($oObj->Get($sAttCode), $oObj)).'';
@@ -175,74 +171,50 @@ EOF
protected function GetValue($oObj, $sAttCode)
{
- switch($sAttCode)
- {
+ switch ($sAttCode) {
case 'id':
$sRet = $oObj->GetKey();
break;
-
+
default:
- $value = $oObj->Get($sAttCode);
- if ($value instanceOf ormCaseLog)
- {
- if (array_key_exists('formatted_text', $this->aStatusInfo) && $this->aStatusInfo['formatted_text'])
- {
- $sText = $value->GetText();
- }
- else
- {
- $sText = $value->GetAsPlainText();
- }
- // Extract the case log as text and remove the "===" which make Excel think that the cell contains a formula the next time you edit it!
- $sRet = trim(preg_replace('/========== ([^=]+) ============/', '********** $1 ************', $sText));
- }
- else if ($value instanceOf DBObjectSet)
- {
- $oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
- $sRet = $oAttDef->GetAsCSV($value, '', '', $oObj);
- }
- else if ($value instanceOf ormDocument)
- {
- $oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
- $sRet = $oAttDef->GetAsCSV($value, '', '', $oObj);
- }
- else if ($value instanceOf ormSet)
- {
- $oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
- $sRet = $oAttDef->GetAsCSV($value, '', '', $oObj);
- }
- else
- {
- $oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
- if ($oAttDef instanceof AttributeDateTime)
- {
- // Date and times are formatted using the ISO encoding, not the localized format
- if ($oAttDef->IsNull($value))
- {
- // NOt a valid date
- $sRet = '';
+ $value = $oObj->Get($sAttCode);
+ if ($value instanceof ormCaseLog) {
+ if (array_key_exists('formatted_text', $this->aStatusInfo) && $this->aStatusInfo['formatted_text']) {
+ $sText = $value->GetText();
+ } else {
+ $sText = $value->GetAsPlainText();
}
- else
- {
- $sRet = $value;
+ // Extract the case log as text and remove the "===" which make Excel think that the cell contains a formula the next time you edit it!
+ $sRet = trim(preg_replace('/========== ([^=]+) ============/', '********** $1 ************', $sText));
+ } elseif ($value instanceof DBObjectSet) {
+ $oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
+ $sRet = $oAttDef->GetAsCSV($value, '', '', $oObj);
+ } elseif ($value instanceof ormDocument) {
+ $oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
+ $sRet = $oAttDef->GetAsCSV($value, '', '', $oObj);
+ } elseif ($value instanceof ormSet) {
+ $oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
+ $sRet = $oAttDef->GetAsCSV($value, '', '', $oObj);
+ } else {
+ $oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
+ if ($oAttDef instanceof AttributeDateTime) {
+ // Date and times are formatted using the ISO encoding, not the localized format
+ if ($oAttDef->IsNull($value)) {
+ // NOt a valid date
+ $sRet = '';
+ } else {
+ $sRet = $value;
+ }
+ } elseif (array_key_exists('formatted_text', $this->aStatusInfo) && $this->aStatusInfo['formatted_text']) {
+ if ($oAttDef instanceof AttributeText && $oAttDef->GetFormat() == 'html') {
+ $sRet = str_replace(">", ">", $value);
+ } else {
+ $sRet = $oAttDef->GetEditValue($value, $oObj);
+ }
+ } else {
+ $sRet = $oAttDef->GetAsPlainText($value, $oObj);
}
}
- else if (array_key_exists('formatted_text', $this->aStatusInfo) && $this->aStatusInfo['formatted_text'])
- {
- if ($oAttDef instanceof AttributeText && $oAttDef->GetFormat()=='html')
- {
- $sRet = str_replace(">", ">", $value);
- }
- else
- {
- $sRet = $oAttDef->GetEditValue($value, $oObj);
- }
- }
- else
- {
- $sRet = $oAttDef->GetAsPlainText($value, $oObj);
- }
- }
}
return $sRet;
}
@@ -255,14 +227,12 @@ EOF
$this->aStatusInfo['position'] = 0;
$this->aStatusInfo['total'] = $oSet->Count();
- foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
- {
+ foreach ($this->aStatusInfo['fields'] as $iCol => $aFieldSpec) {
$sExtendedAttCode = $aFieldSpec['sFieldSpec'];
$sAttCode = $aFieldSpec['sAttCode'];
$sColLabel = $aFieldSpec['sColLabel'];
-
- switch($sAttCode)
- {
+
+ switch ($sAttCode) {
case 'id':
$sType = '0';
break;
@@ -270,22 +240,18 @@ EOF
default:
$oAttDef = MetaModel::GetAttributeDef($aFieldSpec['sClass'], $aFieldSpec['sAttCode']);
$sType = 'string';
- if($oAttDef instanceof AttributeDate)
- {
+ if ($oAttDef instanceof AttributeDate) {
$sType = 'date';
- }
- else if($oAttDef instanceof AttributeDateTime)
- {
+ } elseif ($oAttDef instanceof AttributeDateTime) {
$sType = 'datetime';
}
}
- $aTableHeaders[] = array('label' => $sColLabel, 'type' => $sType);
+ $aTableHeaders[] = ['label' => $sColLabel, 'type' => $sType];
}
$sRow = json_encode($aTableHeaders);
$hFile = @fopen($this->aStatusInfo['tmp_file'], 'ab');
- if ($hFile === false)
- {
+ if ($hFile === false) {
throw new Exception('ExcelBulkExport: Failed to open temporary data file: "'.$this->aStatusInfo['tmp_file'].'" for writing.');
}
fwrite($hFile, $sRow."\n");
@@ -307,19 +273,16 @@ EOF
$iCount = 0;
$iPreviousTimeLimit = ini_get('max_execution_time');
$iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
- while($aRow = $oSet->FetchAssoc())
- {
+ while ($aRow = $oSet->FetchAssoc()) {
set_time_limit(intval($iLoopTimeLimit));
- $aData = array();
- foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
- {
+ $aData = [];
+ foreach ($this->aStatusInfo['fields'] as $iCol => $aFieldSpec) {
$sAlias = $aFieldSpec['sAlias'];
$sAttCode = $aFieldSpec['sAttCode'];
$oObj = $aRow[$sAlias];
$sField = '';
- if ($oObj)
- {
+ if ($oObj) {
$sField = $this->GetValue($oObj, $sAttCode);
}
$aData[] = $sField;
@@ -329,41 +292,35 @@ EOF
}
set_time_limit(intval($iPreviousTimeLimit));
$this->aStatusInfo['position'] += $this->iChunkSize;
- if ($this->aStatusInfo['total'] == 0)
- {
+ if ($this->aStatusInfo['total'] == 0) {
$iPercentage = 100;
$sRetCode = 'done'; // Next phase (GetFooter) will be to build the xlsx file
+ } else {
+ $iPercentage = floor(min(100.0, 100.0 * $this->aStatusInfo['position'] / $this->aStatusInfo['total']));
}
- else
- {
- $iPercentage = floor(min(100.0, 100.0*$this->aStatusInfo['position']/$this->aStatusInfo['total']));
- }
- if ($iCount < $this->iChunkSize)
- {
+ if ($iCount < $this->iChunkSize) {
$sRetCode = 'done';
}
- $aStatus = array('code' => $sRetCode, 'message' => Dict::S('Core:BulkExport:RetrievingData'), 'percentage' => $iPercentage);
+ $aStatus = ['code' => $sRetCode, 'message' => Dict::S('Core:BulkExport:RetrievingData'), 'percentage' => $iPercentage];
return ''; // The actual XLSX file is built in GetFooter();
}
public function GetFooter()
{
$hFile = @fopen($this->aStatusInfo['tmp_file'], 'rb');
- if ($hFile === false)
- {
+ if ($hFile === false) {
throw new Exception('ExcelBulkExport: Failed to open temporary data file: "'.$this->aStatusInfo['tmp_file'].'" for reading.');
}
$sHeaders = fgets($hFile);
$aHeaders = json_decode($sHeaders, true);
- $aData = array();
- while($sLine = fgets($hFile))
- {
+ $aData = [];
+ while ($sLine = fgets($hFile)) {
$aRow = json_decode($sLine);
$aData[] = $aRow;
}
fclose($hFile);
-
+
$fStartExcel = microtime(true);
$writer = new XLSXWriter();
$sDateFormat = isset($this->aStatusInfo['date_format']) ? $this->aStatusInfo['date_format'] : (string)AttributeDateTime::GetFormat();
@@ -372,14 +329,13 @@ EOF
$oDateFormat = new DateTimeFormat($oDateTimeFormat->ToDateFormat());
$writer->setDateFormat($oDateFormat->ToExcel());
$writer->setAuthor(UserRights::GetUserFriendlyName());
- $aHeaderTypes = array();
- $aHeaderNames = array();
- foreach($aHeaders as $Header)
- {
+ $aHeaderTypes = [];
+ $aHeaderNames = [];
+ foreach ($aHeaders as $Header) {
$aHeaderNames[] = $Header['label'];
$aHeaderTypes[] = $Header['type'];
}
- $writer->writeSheet($aData,'Sheet1', $aHeaderTypes, $aHeaderNames);
+ $writer->writeSheet($aData, 'Sheet1', $aHeaderTypes, $aHeaderNames);
$fExcelTime = microtime(true) - $fStartExcel;
//$this->aStatistics['excel_build_duration'] = $fExcelTime;
@@ -405,6 +361,6 @@ EOF
public function GetSupportedFormats()
{
- return array('xlsx' => Dict::S('Core:BulkExport:XLSXFormat'));
+ return ['xlsx' => Dict::S('Core:BulkExport:XLSXFormat')];
}
}
diff --git a/core/htmlbulkexport.class.inc.php b/core/htmlbulkexport.class.inc.php
index 7a78ab0b8..b0d4a9348 100644
--- a/core/htmlbulkexport.class.inc.php
+++ b/core/htmlbulkexport.class.inc.php
@@ -1,4 +1,5 @@
array('interactive_fields_html')));
+ return array_merge(parent::EnumFormParts(), ['interactive_fields_html' => ['interactive_fields_html']]);
}
/**
@@ -52,17 +53,15 @@ class HTMLBulkExport extends TabularBulkExport
break;
default:
- return parent:: GetFormPart($oP, $sPartId);
+ return parent::GetFormPart($oP, $sPartId);
}
}
protected function GetSampleData($oObj, $sAttCode)
{
- if ($sAttCode != 'id')
- {
+ if ($sAttCode != 'id') {
$oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
- if ($oAttDef instanceof AttributeDateTime) // AttributeDate is derived from AttributeDateTime
- {
+ if ($oAttDef instanceof AttributeDateTime) { // AttributeDate is derived from AttributeDateTime
$sClass = (get_class($oAttDef) == 'AttributeDateTime') ? 'user-formatted-date-time' : 'user-formatted-date';
return ''.utils::EscapeHtml($oAttDef->GetEditValue($oObj->Get($sAttCode), $oObj)).'
';
@@ -73,24 +72,18 @@ class HTMLBulkExport extends TabularBulkExport
protected function GetValue($oObj, $sAttCode)
{
- switch($sAttCode)
- {
+ switch ($sAttCode) {
case 'id':
$sRet = $oObj->GetHyperlink();
break;
-
+
default:
$value = $oObj->Get($sAttCode);
- if ($value instanceof ormCaseLog)
- {
+ if ($value instanceof ormCaseLog) {
$sRet = $value->GetAsSimpleHtml();
- }
- elseif ($value instanceof ormStopWatch)
- {
+ } elseif ($value instanceof ormStopWatch) {
$sRet = $value->GetTimeSpent();
- }
- else
- {
+ } else {
$sRet = $oObj->GetAsHtml($sAttCode);
}
}
@@ -100,7 +93,7 @@ class HTMLBulkExport extends TabularBulkExport
public function GetHeader()
{
$sData = '';
-
+
$oSet = new DBObjectSet($this->oSearch);
$this->aStatusInfo['status'] = 'running';
$this->aStatusInfo['position'] = 0;
@@ -109,8 +102,7 @@ class HTMLBulkExport extends TabularBulkExport
$sData .= "\n";
$sData .= "\n";
$sData .= "\n";
- foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
- {
+ foreach ($this->aStatusInfo['fields'] as $iCol => $aFieldSpec) {
$sData .= "".$aFieldSpec['sColLabel']." \n";
}
$sData .= " \n";
@@ -135,32 +127,25 @@ class HTMLBulkExport extends TabularBulkExport
$sData = '';
$iPreviousTimeLimit = ini_get('max_execution_time');
$iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
- while($aRow = $oSet->FetchAssoc())
- {
+ while ($aRow = $oSet->FetchAssoc()) {
set_time_limit(intval($iLoopTimeLimit));
$oMainObj = $aRow[$sFirstAlias];
$sHilightClass = '';
- if ($oMainObj)
- {
+ if ($oMainObj) {
$sHilightClass = MetaModel::GetHilightClass($sClass, $aRow[$sFirstAlias]);
}
- if ($sHilightClass != '')
- {
+ if ($sHilightClass != '') {
$sData .= "";
- }
- else
- {
+ } else {
$sData .= " ";
}
- foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
- {
+ foreach ($this->aStatusInfo['fields'] as $iCol => $aFieldSpec) {
$sAlias = $aFieldSpec['sAlias'];
$sAttCode = $aFieldSpec['sAttCode'];
$oObj = $aRow[$sAlias];
$sField = '';
- if ($oObj)
- {
+ if ($oObj) {
$sField = $this->GetValue($oObj, $sAttCode);
}
$sValue = ($sField === '') ? ' ' : $sField;
@@ -171,21 +156,17 @@ class HTMLBulkExport extends TabularBulkExport
}
set_time_limit(intval($iPreviousTimeLimit));
$this->aStatusInfo['position'] += $this->iChunkSize;
- if ($this->aStatusInfo['total'] == 0)
- {
+ if ($this->aStatusInfo['total'] == 0) {
$iPercentage = 100;
- }
- else
- {
- $iPercentage = floor(min(100.0, 100.0*$this->aStatusInfo['position']/$this->aStatusInfo['total']));
+ } else {
+ $iPercentage = floor(min(100.0, 100.0 * $this->aStatusInfo['position'] / $this->aStatusInfo['total']));
}
- if ($iCount < $this->iChunkSize)
- {
+ if ($iCount < $this->iChunkSize) {
$sRetCode = 'done';
}
- $aStatus = array('code' => $sRetCode, 'message' => Dict::S('Core:BulkExport:RetrievingData'), 'percentage' => $iPercentage);
+ $aStatus = ['code' => $sRetCode, 'message' => Dict::S('Core:BulkExport:RetrievingData'), 'percentage' => $iPercentage];
return $sData;
}
@@ -198,7 +179,7 @@ class HTMLBulkExport extends TabularBulkExport
public function GetSupportedFormats()
{
- return array('html' => Dict::S('Core:BulkExport:HTMLFormat'));
+ return ['html' => Dict::S('Core:BulkExport:HTMLFormat')];
}
public function GetMimeType()
diff --git a/core/htmlsanitizer.class.inc.php b/core/htmlsanitizer.class.inc.php
index 7fa1e9690..d6f43eb65 100644
--- a/core/htmlsanitizer.class.inc.php
+++ b/core/htmlsanitizer.class.inc.php
@@ -1,4 +1,5 @@
DoSanitize($sHTML);
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
if ($sSanitizerClass != 'HTMLDOMSanitizer') {
IssueLog::Warning('Failed to sanitize an HTML string with "'.$sSanitizerClass.'". The following exception occured: '.$e->getMessage());
IssueLog::Warning('Will try to sanitize with HTMLDOMSanitizer.');
// try again with the HTMLDOMSanitizer
$oSanitizer = new HTMLDOMSanitizer();
$sCleanHTML = $oSanitizer->DoSanitize($sHTML);
- }
- else
- {
+ } else {
IssueLog::Error('Failed to sanitize an HTML string with "HTMLDOMSanitizer". The following exception occured: '.$e->getMessage());
IssueLog::Error('The HTML will NOT be sanitized.');
$sCleanHTML = $sHTML;
@@ -104,8 +102,6 @@ class HTMLNullSanitizer extends HTMLSanitizer
}
}
-
-
/**
* Common implementation for sanitizer using DOM parsing
*/
@@ -166,7 +162,7 @@ abstract class DOMSanitizer extends HTMLSanitizer
protected function CleanNode(DOMNode $oElement)
{
- $aAttrToRemove = array();
+ $aAttrToRemove = [];
// Gather the attributes to remove
if ($oElement->hasAttributes()) {
foreach ($oElement->attributes as $oAttr) {
@@ -174,13 +170,13 @@ abstract class DOMSanitizer extends HTMLSanitizer
if ((false === empty($this->GetAttrsBlackList()))
&& (in_array($sAttr, $this->GetAttrsBlackList(), true))) {
$aAttrToRemove[] = $oAttr->name;
- } else if ((false === empty($this->GetTagsWhiteList()))
+ } elseif ((false === empty($this->GetTagsWhiteList()))
&& (false === in_array($sAttr, $this->GetTagsWhiteList()[strtolower($oElement->tagName)]))) {
$aAttrToRemove[] = $oAttr->name;
- } else if (!$this->IsValidAttributeContent($sAttr, $oAttr->value)) {
+ } elseif (!$this->IsValidAttributeContent($sAttr, $oAttr->value)) {
// Invalid content
$aAttrToRemove[] = $oAttr->name;
- } else if ($sAttr == 'style') {
+ } elseif ($sAttr == 'style') {
// Special processing for style tags
$sCleanStyle = $this->CleanStyle($oAttr->value);
if ($sCleanStyle == '') {
@@ -192,17 +188,15 @@ abstract class DOMSanitizer extends HTMLSanitizer
}
}
// Now remove them
- foreach($aAttrToRemove as $sName)
- {
+ foreach ($aAttrToRemove as $sName) {
$oElement->removeAttribute($sName);
}
}
- if ($oElement->hasChildNodes())
- {
- $aChildElementsToRemove = array();
+ if ($oElement->hasChildNodes()) {
+ $aChildElementsToRemove = [];
// Gather the child noes to remove
- foreach($oElement->childNodes as $oNode) {
+ foreach ($oElement->childNodes as $oNode) {
if ($oNode instanceof DOMElement) {
$sNodeTagName = strtolower($oNode->tagName);
}
@@ -210,11 +204,11 @@ abstract class DOMSanitizer extends HTMLSanitizer
&& (false === empty($this->GetTagsBlackList()))
&& (in_array($sNodeTagName, $this->GetTagsBlackList(), true))) {
$aChildElementsToRemove[] = $oNode;
- } else if (($oNode instanceof DOMElement)
+ } elseif (($oNode instanceof DOMElement)
&& (false === empty($this->GetTagsWhiteList()))
&& (false === array_key_exists($sNodeTagName, $this->GetTagsWhiteList()))) {
$aChildElementsToRemove[] = $oNode;
- } else if ($oNode instanceof DOMComment) {
+ } elseif ($oNode instanceof DOMComment) {
$aChildElementsToRemove[] = $oNode;
} else {
// Recurse
@@ -225,8 +219,7 @@ abstract class DOMSanitizer extends HTMLSanitizer
}
}
// Now remove them
- foreach($aChildElementsToRemove as $oDomElement)
- {
+ foreach ($aChildElementsToRemove as $oDomElement) {
$oElement->removeChild($oDomElement);
}
}
@@ -252,7 +245,7 @@ abstract class DOMSanitizer extends HTMLSanitizer
return $sStyle;
}
- $aAllowedStyles = array();
+ $aAllowedStyles = [];
$aItems = explode(';', $sStyle);
{
foreach ($aItems as $sItem) {
@@ -267,78 +260,76 @@ abstract class DOMSanitizer extends HTMLSanitizer
}
}
-
-
class HTMLDOMSanitizer extends DOMSanitizer
{
/**
* @var array
* @see https://www.itophub.io/wiki/page?id=2_6_0%3Aadmin%3Arich_text_limitations
*/
- protected static $aTagsWhiteList = array(
- 'html' => array(),
- 'body' => array(),
- 'a' => array('href', 'name', 'style', 'class', 'target', 'title', 'data-role', 'data-object-class', 'data-object-id', 'data-object-key'),
- 'p' => array('style', 'class'),
- 'blockquote' => array('style', 'class'),
- 'br' => array(),
- 'span' => array('style', 'class'),
- 'div' => array('style', 'class'),
- 'b' => array('class'),
- 'i' => array('class'),
- 'u' => array('class'),
- 'em' => array('class'),
- 'strong' => array('class'),
- 'img' => array('src', 'style', 'class', 'alt', 'title', 'width', 'height'),
- 'ul' => array('style', 'class'),
- 'ol' => array('reversed', 'start', 'style', 'class', 'type'),
- 'li' => array('style', 'class', 'value'),
- 'h1' => array('style', 'class'),
- 'h2' => array('style', 'class'),
- 'h3' => array('style', 'class'),
- 'h4' => array('style', 'class'),
- 'nav' => array('style', 'class'),
- 'section' => array('style', 'class'),
- 'code' => array('style', 'class'),
- 'table' => array('style', 'class', 'width', 'summary', 'align', 'border', 'cellpadding', 'cellspacing'),
- 'colgroup' => array(),
- 'col' => array('style'),
- 'thead' => array('style', 'class'),
- 'tbody' => array('style', 'class'),
- 'tr' => array('style', 'class', 'colspan', 'rowspan'),
- 'td' => array('style', 'class', 'colspan', 'rowspan'),
- 'th' => array('style', 'class', 'colspan', 'rowspan'),
- 'fieldset' => array('style', 'class'),
- 'legend' => array('style', 'class'),
- 'font' => array('face', 'color', 'style', 'class', 'size'),
- 'big' => array(),
- 'small' => array(),
- 'tt' => array(),
- 'kbd' => array(),
- 'samp' => array(),
- 'var' => array(),
- 'del' => array(),
- 's' => array(), // strikethrough
- 'ins' => array(),
- 'cite' => array(),
- 'q' => array(),
- 'hr' => array('style', 'class'),
- 'pre' => array('class'),
- 'center' => array(),
- 'figure' => array('style', 'class'), // Ckeditor 5 puts images in figures
- 'figcaption' => array('class'),
- 'mark' => array('class')
- );
+ protected static $aTagsWhiteList = [
+ 'html' => [],
+ 'body' => [],
+ 'a' => ['href', 'name', 'style', 'class', 'target', 'title', 'data-role', 'data-object-class', 'data-object-id', 'data-object-key'],
+ 'p' => ['style', 'class'],
+ 'blockquote' => ['style', 'class'],
+ 'br' => [],
+ 'span' => ['style', 'class'],
+ 'div' => ['style', 'class'],
+ 'b' => ['class'],
+ 'i' => ['class'],
+ 'u' => ['class'],
+ 'em' => ['class'],
+ 'strong' => ['class'],
+ 'img' => ['src', 'style', 'class', 'alt', 'title', 'width', 'height'],
+ 'ul' => ['style', 'class'],
+ 'ol' => ['reversed', 'start', 'style', 'class', 'type'],
+ 'li' => ['style', 'class', 'value'],
+ 'h1' => ['style', 'class'],
+ 'h2' => ['style', 'class'],
+ 'h3' => ['style', 'class'],
+ 'h4' => ['style', 'class'],
+ 'nav' => ['style', 'class'],
+ 'section' => ['style', 'class'],
+ 'code' => ['style', 'class'],
+ 'table' => ['style', 'class', 'width', 'summary', 'align', 'border', 'cellpadding', 'cellspacing'],
+ 'colgroup' => [],
+ 'col' => ['style'],
+ 'thead' => ['style', 'class'],
+ 'tbody' => ['style', 'class'],
+ 'tr' => ['style', 'class', 'colspan', 'rowspan'],
+ 'td' => ['style', 'class', 'colspan', 'rowspan'],
+ 'th' => ['style', 'class', 'colspan', 'rowspan'],
+ 'fieldset' => ['style', 'class'],
+ 'legend' => ['style', 'class'],
+ 'font' => ['face', 'color', 'style', 'class', 'size'],
+ 'big' => [],
+ 'small' => [],
+ 'tt' => [],
+ 'kbd' => [],
+ 'samp' => [],
+ 'var' => [],
+ 'del' => [],
+ 's' => [], // strikethrough
+ 'ins' => [],
+ 'cite' => [],
+ 'q' => [],
+ 'hr' => ['style', 'class'],
+ 'pre' => ['class'],
+ 'center' => [],
+ 'figure' => ['style', 'class'], // Ckeditor 5 puts images in figures
+ 'figcaption' => ['class'],
+ 'mark' => ['class'],
+ ];
- protected static $aAttrsWhiteList = array(
+ protected static $aAttrsWhiteList = [
'src' => '/^(http:|https:|data:)/i',
- );
+ ];
/**
* @var array
* @see https://www.itophub.io/wiki/page?id=2_6_0%3Aadmin%3Arich_text_limitations
*/
- protected static $aStylesWhiteList = array(
+ protected static $aStylesWhiteList = [
'aspect-ratio',
'background-color',
'border',
@@ -361,7 +352,7 @@ class HTMLDOMSanitizer extends DOMSanitizer
'vertical-align',
'width',
'white-space',
- );
+ ];
public function __construct($sInlineImageClassName = InlineImage::class)
{
@@ -431,15 +422,13 @@ class HTMLDOMSanitizer extends DOMSanitizer
// Export only the content of the body tag
$sCleanHtml = $this->oDoc->saveHTML($oNodesList->item(0));
// remove the body tag itself
- $sCleanHtml = str_replace(array('', ''), '', $sCleanHtml);
+ $sCleanHtml = str_replace(['', ''], '', $sCleanHtml);
}
return $sCleanHtml;
}
}
-
-
/**
* @since 2.6.5 2.7.6 3.0.0 N°4360
*/
diff --git a/core/iTopConfigParser.php b/core/iTopConfigParser.php
index 723bffe01..a077a8a96 100644
--- a/core/iTopConfigParser.php
+++ b/core/iTopConfigParser.php
@@ -1,4 +1,5 @@
createForNewestSupportedVersion();
- $this->aVarsMap = array(
- 'MySettings' => array(),
- 'MyModuleSettings' => array(),
- 'MyModules' => array(),
- );
+ $this->aVarsMap = [
+ 'MySettings' => [],
+ 'MyModuleSettings' => [],
+ 'MyModules' => [],
+ ];
- if ($sConfig !== null)
- {
+ if ($sConfig !== null) {
$this->BrowseFile($oParser, $sConfig);
}
}
@@ -67,15 +66,15 @@ class iTopConfigParser
*/
public function GetVarValue($arrayName, $key)
{
- if (!array_key_exists($arrayName, $this->aVarsMap)){
- return array('found' => false);
+ if (!array_key_exists($arrayName, $this->aVarsMap)) {
+ return ['found' => false];
}
$arrayValue = $this->aVarsMap[$arrayName];
- if (!array_key_exists($key, $arrayValue)){
- return array('found' => false);
+ if (!array_key_exists($key, $arrayValue)) {
+ return ['found' => false];
}
- return array('found' => true,
- 'value' => $arrayValue[$key]);
+ return ['found' => true,
+ 'value' => $arrayValue[$key]];
}
/**
@@ -90,8 +89,7 @@ class iTopConfigParser
try {
$aNodes = $oParser->parse($sConfig);
- }
- catch (\Error $e) {
+ } catch (\Error $e) {
$sMessage = Dict::Format('config-parse-error', $e->getMessage(), $e->getLine());
$this->oException = new \Exception($sMessage, 0, $e);
}
@@ -122,7 +120,7 @@ class iTopConfigParser
if (!array_key_exists($sCurrentRootVar, $this->aVarsMap)) {
continue;
}
- $aCurrentRootVarMap =& $this->aVarsMap[$sCurrentRootVar];
+ $aCurrentRootVarMap = & $this->aVarsMap[$sCurrentRootVar];
foreach ($oAssignation->expr->items as $oItem) {
$sValue = $prettyPrinter->prettyPrintExpr($oItem->value);
@@ -130,4 +128,4 @@ class iTopConfigParser
}
}
}
-}
\ No newline at end of file
+}
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/introspection.class.inc.php b/core/introspection.class.inc.php
index cee5f9087..9e59be2a7 100644
--- a/core/introspection.class.inc.php
+++ b/core/introspection.class.inc.php
@@ -1,9 +1,10 @@
child classes
- protected $aAttributes = array();
+ protected $aAttributeHierarchy = []; // class => child classes
+ protected $aAttributes = [];
public function __construct()
{
@@ -35,25 +36,19 @@ class Introspection
protected function InitAttributes()
{
- foreach(get_declared_classes() as $sPHPClass)
- {
+ foreach (get_declared_classes() as $sPHPClass) {
$oRefClass = new ReflectionClass($sPHPClass);
- if ($sPHPClass == 'AttributeDefinition' || $oRefClass->isSubclassOf('AttributeDefinition'))
- {
- if ($oParentClass = $oRefClass->getParentClass())
- {
+ if ($sPHPClass == 'AttributeDefinition' || $oRefClass->isSubclassOf('AttributeDefinition')) {
+ if ($oParentClass = $oRefClass->getParentClass()) {
$sParentClass = $oParentClass->getName();
- if (!array_key_exists($sParentClass, $this->aAttributeHierarchy))
- {
- $this->aAttributeHierarchy[$sParentClass] = array();
+ if (!array_key_exists($sParentClass, $this->aAttributeHierarchy)) {
+ $this->aAttributeHierarchy[$sParentClass] = [];
}
$this->aAttributeHierarchy[$sParentClass][] = $sPHPClass;
- }
- else
- {
+ } else {
$sParentClass = null;
}
- $this->aAttributes[$sPHPClass] = array(
+ $this->aAttributes[$sPHPClass] = [
'parent' => $sParentClass,
'LoadInObject' => $sPHPClass::LoadInObject(),
'LoadFromDB' => $sPHPClass::LoadFromDB(),
@@ -63,7 +58,7 @@ class Introspection
'IsScalar' => $sPHPClass::IsScalar(),
'IsLinkset' => $sPHPClass::IsLinkset(),
'IsHierarchicalKey' => $sPHPClass::IsHierarchicalKey(),
- );
+ ];
}
}
}
@@ -77,7 +72,7 @@ class Introspection
}
public function EnumAttributeCharacteristics()
{
- return array(
+ return [
'LoadInObject' => 'Is the value stored in the object itself?',
'LoadFromDB' => 'Is the value read from the DB?',
'IsBasedOnDBColumns' => 'Is this a value stored within one or several columns?',
@@ -86,8 +81,6 @@ class Introspection
'IsScalar' => 'Is this a value that makes sense in a SQL/OQL expression?',
'IsLinkset' => 'Is this a collection (1-N or N-N)?',
'IsHierarchicalKey' => 'Is this attribute an external key pointing to the host class?',
- );
+ ];
}
}
-
-
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/log.class.inc.php b/core/log.class.inc.php
index de8364c5f..4fa837842 100644
--- a/core/log.class.inc.php
+++ b/core/log.class.inc.php
@@ -1,4 +1,5 @@
-
/**
* @since 2.7.0 N°2518 N°2793
*/
@@ -66,7 +66,7 @@ abstract class RotatingLogFileNameBuilder implements iLogFileNameBuilder
* We are caching the file mtime though
* @var array with full file path as key and DateTime (file last modification time) as value
*/
- protected static $aLogFileLastModified = array();
+ protected static $aLogFileLastModified = [];
/** @var string */
protected $sLogFileFullPath;
/** @var string */
@@ -86,8 +86,7 @@ abstract class RotatingLogFileNameBuilder implements iLogFileNameBuilder
protected function GetLastModifiedDateForFile()
{
- if (isset(static::$aLogFileLastModified[$this->sLogFileFullPath]))
- {
+ if (isset(static::$aLogFileLastModified[$this->sLogFileFullPath])) {
return static::$aLogFileLastModified[$this->sLogFileFullPath];
}
@@ -131,16 +130,13 @@ abstract class RotatingLogFileNameBuilder implements iLogFileNameBuilder
$oConfig = utils::GetConfig();
utils::InitTimeZone($oConfig);
- if ($this->GetLastModifiedDateForFile() === null)
- {
- if (!$this->IsLogFileExists())
- {
+ if ($this->GetLastModifiedDateForFile() === null) {
+ if (!$this->IsLogFileExists()) {
return;
}
$iLogDateLastModifiedTimeStamp = filemtime($this->sLogFileFullPath);
- if ($iLogDateLastModifiedTimeStamp === false)
- {
+ if ($iLogDateLastModifiedTimeStamp === false) {
return;
}
$oDateTime = DateTime::createFromFormat('U', $iLogDateLastModifiedTimeStamp);
@@ -152,8 +148,7 @@ abstract class RotatingLogFileNameBuilder implements iLogFileNameBuilder
$oNow = new DateTime();
$bShouldRotate = $this->ShouldRotate($this->GetLastModifiedDateForFile(), $oNow);
- if (!$bShouldRotate)
- {
+ if (!$bShouldRotate) {
return;
}
@@ -170,33 +165,28 @@ abstract class RotatingLogFileNameBuilder implements iLogFileNameBuilder
*/
protected function RotateLogFile($oLogFileLastModified)
{
- if (!$this->IsLogFileExists()) // extra check, but useful for cron also !
- {
+ if (!$this->IsLogFileExists()) { // extra check, but useful for cron also !
return;
}
$oLock = null;
- try
- {
+ try {
$oLock = new iTopMutex('log_rotation_'.$this->sLogFileFullPath);
$oLock->Lock();
- if (!$this->IsLogFileExists()) // extra extra check if we were blocked and another process moved the file in the meantime
- {
+ if (!$this->IsLogFileExists()) { // extra extra check if we were blocked and another process moved the file in the meantime
$oLock->Unlock();
return;
}
$this->ResetLastModifiedDateForFile();
$sNewLogFileName = $this->GetRotatedFileName($oLogFileLastModified);
rename($this->sLogFileFullPath, $sNewLogFileName);
- }
- catch (Exception $e)
- {
+ } catch (Exception $e) {
// nothing to do, cannot log... file will be renamed on the next call O:)
return;
- }
- finally
- {
- if (!is_null($oLock)) { $oLock->Unlock();}
+ } finally {
+ if (!is_null($oLock)) {
+ $oLock->Unlock();
+ }
}
}
@@ -227,13 +217,11 @@ abstract class RotatingLogFileNameBuilder implements iLogFileNameBuilder
*/
public function IsLogFileExists()
{
- if (!file_exists($this->sLogFileFullPath))
- {
+ if (!file_exists($this->sLogFileFullPath)) {
return false;
}
- if (!is_readable($this->sLogFileFullPath))
- {
+ if (!is_readable($this->sLogFileFullPath)) {
return false;
}
@@ -290,13 +278,11 @@ class DailyRotatingLogFileNameBuilder extends RotatingLogFileNameBuilder
$iNowYear = $oNow->format('Y');
$iNowDay = $oNow->format('z');
- if ($iLogYear !== $iNowYear)
- {
+ if ($iLogYear !== $iNowYear) {
return true;
}
- if ($iLogDay !== $iNowDay)
- {
+ if ($iLogDay !== $iNowDay) {
return true;
}
@@ -341,13 +327,11 @@ class WeeklyRotatingLogFileNameBuilder extends RotatingLogFileNameBuilder
$iNowYear = $oNow->format('Y');
$iNowWeek = $oNow->format('W');
- if ($iLogYear !== $iNowYear)
- {
+ if ($iLogYear !== $iNowYear) {
return true;
}
- if ($iLogWeek !== $iNowWeek)
- {
+ if ($iLogWeek !== $iNowWeek) {
return true;
}
@@ -381,13 +365,11 @@ class MonthlyRotatingLogFileNameBuilder extends RotatingLogFileNameBuilder
$iNowYear = $oNow->format('Y');
$iNowMonth = $oNow->format('n');
- if ($iLogYear !== $iNowYear)
- {
+ if ($iLogYear !== $iNowYear) {
return true;
}
- if ($iLogMonth !== $iNowMonth)
- {
+ if ($iLogMonth !== $iNowMonth) {
return true;
}
@@ -435,8 +417,7 @@ class LogFileNameBuilderFactory
{
$oConfig = utils::GetConfig();
$sFileNameBuilderImpl = $oConfig->Get('log_filename_builder_impl');
- if (!is_a($sFileNameBuilderImpl, iLogFileNameBuilder::class, true))
- {
+ if (!is_a($sFileNameBuilderImpl, iLogFileNameBuilder::class, true)) {
$sFileNameBuilderImpl = 'DefaultLogFileNameBuilder';
}
@@ -444,7 +425,6 @@ class LogFileNameBuilderFactory
}
}
-
/**
* File logging
*
@@ -469,38 +449,37 @@ class FileLog
$this->oFileNameBuilder = LogFileNameBuilderFactory::GetInstance($sFileName);
}
- public function Error($sText, $sChannel = '', $aContext = array())
+ public function Error($sText, $sChannel = '', $aContext = [])
{
$this->Write($sText, __FUNCTION__, $sChannel, $aContext);
}
- public function Warning($sText, $sChannel = '', $aContext = array())
+ public function Warning($sText, $sChannel = '', $aContext = [])
{
$this->Write($sText, __FUNCTION__, $sChannel, $aContext);
}
- public function Info($sText, $sChannel = '', $aContext = array())
+ public function Info($sText, $sChannel = '', $aContext = [])
{
$this->Write($sText, __FUNCTION__, $sChannel, $aContext);
}
- public function Ok($sText, $sChannel = '', $aContext = array())
+ public function Ok($sText, $sChannel = '', $aContext = [])
{
$this->Write($sText, __FUNCTION__, $sChannel, $aContext);
}
- public function Debug($sText, $sChannel = '', $aContext = array())
+ public function Debug($sText, $sChannel = '', $aContext = [])
{
$this->Write($sText, __FUNCTION__, $sChannel, $aContext);
}
- public function Trace($sText, $sChannel = '', $aContext = array())
+ public function Trace($sText, $sChannel = '', $aContext = [])
{
$this->Write($sText, __FUNCTION__, $sChannel, $aContext);
}
-
- protected function Write($sText, $sLevel = '', $sChannel = '', $aContext = array())
+ protected function Write($sText, $sLevel = '', $sChannel = '', $aContext = [])
{
$sTextPrefix = empty($sLevel) ? '' : (str_pad($sLevel, 7));
$sTextPrefix .= ' | ';
@@ -533,7 +512,6 @@ class FileLog
}
}
-
/**
* Simple enum like class to factorize channels values as constants
* Channels are used especially as parameters in {@see \LogAPI} methods
@@ -638,7 +616,6 @@ class LogChannels
public const SECURITY = 'Security';
}
-
abstract class LogAPI
{
public const CHANNEL_DEFAULT = '';
@@ -666,19 +643,18 @@ abstract class LogAPI
*/
public const LEVEL_DEFAULT_DB = false;
- protected static $aLevelsPriority = array(
+ protected static $aLevelsPriority = [
self::LEVEL_ERROR => 400,
self::LEVEL_WARNING => 300,
self::LEVEL_INFO => 200,
self::LEVEL_OK => 200,
self::LEVEL_DEBUG => 100,
self::LEVEL_TRACE => 50,
- );
+ ];
public const ENUM_CONFIG_PARAM_FILE = 'log_level_min';
public const ENUM_CONFIG_PARAM_DB = 'log_level_min.write_in_db';
-
/**
* Parameter to enable log purge.
*
@@ -727,27 +703,27 @@ abstract class LogAPI
static::Log(self::LEVEL_ERROR, $sMessage, $sChannel, $aContext);
}
- public static function Warning($sMessage, $sChannel = null, $aContext = array())
+ public static function Warning($sMessage, $sChannel = null, $aContext = [])
{
static::Log(self::LEVEL_WARNING, $sMessage, $sChannel, $aContext);
}
- public static function Info($sMessage, $sChannel = null, $aContext = array())
+ public static function Info($sMessage, $sChannel = null, $aContext = [])
{
static::Log(self::LEVEL_INFO, $sMessage, $sChannel, $aContext);
}
- public static function Ok($sMessage, $sChannel = null, $aContext = array())
+ public static function Ok($sMessage, $sChannel = null, $aContext = [])
{
static::Log(self::LEVEL_OK, $sMessage, $sChannel, $aContext);
}
- public static function Debug($sMessage, $sChannel = null, $aContext = array())
+ public static function Debug($sMessage, $sChannel = null, $aContext = [])
{
static::Log(self::LEVEL_DEBUG, $sMessage, $sChannel, $aContext);
}
- public static function Trace($sMessage, $sChannel = null, $aContext = array())
+ public static function Trace($sMessage, $sChannel = null, $aContext = [])
{
static::Log(self::LEVEL_TRACE, $sMessage, $sChannel, $aContext);
}
@@ -755,7 +731,7 @@ abstract class LogAPI
/**
* @throws \ConfigException if log wrongly configured
*/
- public static function Log($sLevel, $sMessage, $sChannel = null, $aContext = array())
+ public static function Log($sLevel, $sMessage, $sChannel = null, $aContext = [])
{
if (!isset(self::$aLevelsPriority[$sLevel])) {
IssueLog::Error("invalid log level '{$sLevel}'");
@@ -773,7 +749,7 @@ abstract class LogAPI
/**
* @throws \ConfigException
*/
- protected static function WriteLog(string $sLevel, string $sMessage, ?string $sChannel = null, ?array $aContext = array()): void
+ protected static function WriteLog(string $sLevel, string $sMessage, ?string $sChannel = null, ?array $aContext = []): void
{
if (
(null !== static::$m_oFileLog)
@@ -925,15 +901,13 @@ abstract class LogAPI
try {
self::$oLastEventIssue = static::GetEventIssue($sMessage, $sChannel, $aContext);
self::$oLastEventIssue->DBInsertNoReload();
- }
- catch (Exception $e) {
+ } catch (Exception $e) {
// calling low level methods : if we would call Error() for example we would try to write to DB again...
static::$m_oFileLog->Error('Failed to log issue into the DB', LogChannels::CORE, [
'exception message' => $e->getMessage(),
'exception stack' => $e->getTraceAsString(),
]);
- }
- finally {
+ } finally {
$bWriteToDbReentrance = false;
}
}
@@ -1001,13 +975,13 @@ abstract class LogAPI
class SetupLog extends LogAPI
{
- const CHANNEL_DEFAULT = 'SetupLog';
+ public const CHANNEL_DEFAULT = 'SetupLog';
/**
* @inheritDoc
*
* As this object is used during setup, without any conf file available, customizing the level can be done by changing this constant !
*/
- const LEVEL_DEFAULT = self::LEVEL_INFO;
+ public const LEVEL_DEFAULT = self::LEVEL_INFO;
protected static $m_oFileLog = null;
@@ -1024,14 +998,14 @@ class SetupLog extends LogAPI
class IssueLog extends LogAPI
{
- const CHANNEL_DEFAULT = 'IssueLog';
+ public const CHANNEL_DEFAULT = 'IssueLog';
protected static $m_oFileLog = null;
}
class ToolsLog extends LogAPI
{
- const CHANNEL_DEFAULT = 'ToolsLog';
+ public const CHANNEL_DEFAULT = 'ToolsLog';
protected static $m_oFileLog = null;
}
@@ -1044,17 +1018,16 @@ class ToolsLog extends LogAPI
*/
class DeadLockLog extends LogAPI
{
- const CHANNEL_WAIT_TIMEOUT = 'Deadlock-WaitTimeout';
- const CHANNEL_DEADLOCK_FOUND = 'Deadlock-Found';
- const CHANNEL_DEFAULT = self::CHANNEL_WAIT_TIMEOUT;
+ public const CHANNEL_WAIT_TIMEOUT = 'Deadlock-WaitTimeout';
+ public const CHANNEL_DEADLOCK_FOUND = 'Deadlock-Found';
+ public const CHANNEL_DEFAULT = self::CHANNEL_WAIT_TIMEOUT;
/** @var \FileLog we want our own instance ! */
protected static $m_oFileLog = null;
public static function Enable($sTargetFile = null)
{
- if (empty($sTargetFile))
- {
+ if (empty($sTargetFile)) {
$sTargetFile = APPROOT.'log/deadlocks.log';
}
parent::Enable($sTargetFile);
@@ -1063,8 +1036,7 @@ class DeadLockLog extends LogAPI
/** @noinspection PhpUnreachableStatementInspection we want to keep the break statements to keep clarity and avoid errors */
private static function GetChannelFromMysqlErrorNo($iMysqlErrorNo)
{
- switch ($iMysqlErrorNo)
- {
+ switch ($iMysqlErrorNo) {
case CMDBSource::MYSQL_ERRNO_WAIT_TIMEOUT:
return self::CHANNEL_WAIT_TIMEOUT;
break;
@@ -1089,14 +1061,13 @@ class DeadLockLog extends LogAPI
* @since 2.7.1 method creation
* @since 2.7.5 3.0.0 rename param names and fix phpdoc (thanks Hipska !)
*/
- public static function Log($sLevel, $sMessage, $iMysqlErrorNumber = null, $aContext = array())
+ public static function Log($sLevel, $sMessage, $iMysqlErrorNumber = null, $aContext = [])
{
$sChannel = self::GetChannelFromMysqlErrorNo($iMysqlErrorNumber);
parent::Log($sLevel, $sMessage, $sChannel, $aContext);
}
}
-
/**
* Starting with the WARNING level we will log in a dedicated file (/log/deprecated-calls.log) :
* - iTop deprecated files or code
@@ -1144,8 +1115,7 @@ class DeprecatedCallsLog extends LogAPI
{
try {
$bIsLogLevelEnabled = static::IsLogLevelEnabled(self::LEVEL_WARNING, self::ENUM_CHANNEL_PHP_LIBMETHOD);
- }
- catch (ConfigException $e) {
+ } catch (ConfigException $e) {
$bIsLogLevelEnabled = false;
}
@@ -1160,7 +1130,8 @@ class DeprecatedCallsLog extends LogAPI
* @since 3.0.0 N°3002 logs deprecated notices in called code
* @since 3.0.4 N°6274 do not set handler when in PHPUnit context (otherwise PHP notices won't be caught)
*/
- public static function Enable($sTargetFile = null): void {
+ public static function Enable($sTargetFile = null): void
+ {
if (empty($sTargetFile)) {
$sTargetFile = APPROOT.'log/deprecated-calls.log';
}
@@ -1255,8 +1226,7 @@ class DeprecatedCallsLog extends LogAPI
if (!static::IsLogLevelEnabled(self::LEVEL_WARNING, self::ENUM_CHANNEL_FILE)) {
return;
}
- }
- catch (ConfigException $e) {
+ } catch (ConfigException $e) {
return;
}
@@ -1297,8 +1267,7 @@ class DeprecatedCallsLog extends LogAPI
if (!static::IsLogLevelEnabled(self::LEVEL_WARNING, self::ENUM_CHANNEL_PHP_API)) {
return;
}
- }
- catch (ConfigException $oException) {
+ } catch (ConfigException $oException) {
return;
}
@@ -1326,8 +1295,7 @@ class DeprecatedCallsLog extends LogAPI
if (!static::IsLogLevelEnabled(self::LEVEL_WARNING, self::ENUM_CHANNEL_PHP_METHOD)) {
return;
}
- }
- catch (ConfigException $e) {
+ } catch (ConfigException $e) {
return;
}
@@ -1335,8 +1303,7 @@ class DeprecatedCallsLog extends LogAPI
if (isset($aStack[1]['class'])) {
$sFunctionDesc = $aStack[1]['class'].$aStack[1]['type'].$aStack[1]['function'];
- }
- else {
+ } else {
$sFunctionDesc = $aStack[1]['function'];
}
@@ -1347,7 +1314,6 @@ class DeprecatedCallsLog extends LogAPI
$sMessage .= '. Caller: '.self::SummarizeCallStack(array_slice($aStack, 1));
-
static::Warning($sMessage, self::ENUM_CHANNEL_PHP_METHOD);
static::ForwardToTriggerError($sMessage);
}
@@ -1362,8 +1328,7 @@ class DeprecatedCallsLog extends LogAPI
if (!static::IsLogLevelEnabled(self::LEVEL_WARNING, self::ENUM_CHANNEL_PHP_ENDPOINT)) {
return;
}
- }
- catch (ConfigException $e) {
+ } catch (ConfigException $e) {
return;
}
@@ -1382,12 +1347,11 @@ class DeprecatedCallsLog extends LogAPI
static::ForwardToTriggerError($sMessage);
}
- public static function Log($sLevel, $sMessage, $sChannel = null, $aContext = array()): void
+ public static function Log($sLevel, $sMessage, $sChannel = null, $aContext = []): void
{
try {
parent::Log($sLevel, $sMessage, $sChannel, $aContext);
- }
- catch (ConfigException $e) {
+ } catch (ConfigException $e) {
// nothing much we can do... and we don't want to crash the caller !
}
}
@@ -1419,13 +1383,11 @@ class DeprecatedCallsLog extends LogAPI
// If possible and meaningful, add the class and method
if (isset($aCallStack[1]['class'])) {
$sSummary = $aCallStack[1]['class'].$aCallStack[1]['type'].$aCallStack[1]['function']." ($sFileLine)";
- }
- elseif (isset($aCallStack[1]['function'])) {
+ } elseif (isset($aCallStack[1]['function'])) {
if (in_array($aCallStack[1]['function'], ['include', 'require', 'include_once', 'require_once'])) {
// No need to show the generic mechanism of inclusion
$bRecurse = false;
- }
- else {
+ } else {
$sSummary = $aCallStack[1]['function']." ($sFileLine)";
}
}
@@ -1448,7 +1410,6 @@ class DeprecatedCallsLog extends LogAPI
}
}
-
class LogFileRotationProcess implements iScheduledProcess
{
/**
@@ -1456,12 +1417,12 @@ class LogFileRotationProcess implements iScheduledProcess
*
* @var string[]
*/
- const LOGFILES_TO_ROTATE = array(
+ public const LOGFILES_TO_ROTATE = [
'setup.log',
'error.log',
'tools.log',
'itop-fence.log',
- );
+ ];
/**
* @inheritDoc
@@ -1499,7 +1460,7 @@ class LogFileRotationProcess implements iScheduledProcess
public function PurgeLogs(): array
{
// result
- $aFilesResult = array();
+ $aFilesResult = [];
// Max keep days
$iMaxDays = MetaModel::GetConfig()->Get(LogAPI::ENUM_CONFIG_PARAM_PURGE_MAX_KEEP_DAYS);
@@ -1518,9 +1479,9 @@ class LogFileRotationProcess implements iScheduledProcess
$sFileRealPath = $oLogFile->getRealPath();
// Check file extension
- if(!in_array($oLogFile->getExtension(), ['log','sql','xml'])){
+ if (!in_array($oLogFile->getExtension(), ['log','sql','xml'])) {
continue;
- }
+ }
// Compute number of days since last modification
$oDateFileLastModification = new DateTime();
@@ -1542,7 +1503,7 @@ class LogFileRotationProcess implements iScheduledProcess
if (!is_writable($sFileRealPath)) {
$aFileResult['error'] = Dict::S('itop-log-mgmt:UI:Error:file_read_only');
} // unlink OK
- else if (unlink($sFileRealPath)) {
+ elseif (unlink($sFileRealPath)) {
$aFileResult['deleted'] = true;
} // unlink KO
else {
@@ -1565,8 +1526,7 @@ class LogFileRotationProcess implements iScheduledProcess
{
try {
$sLogFileNameBuilder = $this->GetLogFileNameBuilderClassName();
- }
- catch (ProcessException $e) {
+ } catch (ProcessException $e) {
return new DateTime('3000-01-01');
}
@@ -1582,8 +1542,7 @@ class LogFileRotationProcess implements iScheduledProcess
private function GetLogFileNameBuilderClassName()
{
$sLogFileNameBuilder = MetaModel::GetConfig()->Get('log_filename_builder_impl');
- if (is_a($sLogFileNameBuilder, RotatingLogFileNameBuilder::class, true))
- {
+ if (is_a($sLogFileNameBuilder, RotatingLogFileNameBuilder::class, true)) {
return $sLogFileNameBuilder;
}
@@ -1611,7 +1570,7 @@ class ExceptionLog extends LogAPI
* As it encapsulate the operations performed using the Exception, you should prefer it to the standard API inherited from LogApi `ExceptionLog::Error($oException->getMessage(), get_class($oException), ['__exception' => $oException]);`
* The parameter order is not standard, but in our use case, the resulting API is way more convenient this way !
*/
- public static function LogException(Throwable $oException, $aContext = array(), $sLevel = self::LEVEL_ERROR): void
+ public static function LogException(Throwable $oException, $aContext = [], $sLevel = self::LEVEL_ERROR): void
{
if (!isset(self::$aLevelsPriority[$sLevel])) {
IssueLog::Error("invalid log level '{$sLevel}'");
@@ -1633,13 +1592,13 @@ class ExceptionLog extends LogAPI
}
/** @noinspection PhpUnhandledExceptionInspection */
- public static function Log($sLevel, $sMessage, $sChannel = null, $aContext = array())
+ public static function Log($sLevel, $sMessage, $sChannel = null, $aContext = [])
{
throw new ApplicationException('Do not call this directly, prefer using ExceptionLog::LogException() instead');
}
/** @noinspection PhpParameterNameChangedDuringInheritanceInspection */
- protected static function WriteLog(string $sLevel, string $sMessage, ?string $sExceptionClass = null, ?array $aContext = array()): void
+ protected static function WriteLog(string $sLevel, string $sMessage, ?string $sExceptionClass = null, ?array $aContext = []): void
{
if (
(null !== static::$m_oFileLog)
diff --git a/core/metamodel.class.php b/core/metamodel.class.php
index 3375e991d..318fe3775 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,15 +6117,16 @@ 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, [
+ $e = new CoreException($sNotFoundErrorMessage);
+ IssueLog::Error($sNotFoundErrorMessage, LogChannels::CMDB_SOURCE, [
'class' => $sClass,
'key' => $iKey,
'sql_query' => $sSQL,
+ 'stack' => $e->getTraceAsString(),
]);
- throw new CoreException($sNotFoundErrorMessage);
+ throw $e;
}
return $aRow;
@@ -6752,40 +6149,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 +6290,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 +6322,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 +6333,7 @@ abstract class MetaModel
}
/** @var array */
- static protected $m_aCacheObjectByColumn = array();
+ protected static $m_aCacheObjectByColumn = [];
/**
* @param string $sClass
@@ -6982,15 +6362,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 +6386,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 +6410,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 +6446,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 +6497,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 +6541,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 +6563,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 +6617,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 +6672,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 +6685,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 +6698,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 +6719,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 +6737,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 +6791,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 +6864,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 +6896,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 +7013,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 +7028,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/metamodelmodifier.inc.php b/core/metamodelmodifier.inc.php
index 5da53d262..1dcff60d8 100644
--- a/core/metamodelmodifier.inc.php
+++ b/core/metamodelmodifier.inc.php
@@ -1,9 +1,10 @@
-
/**
- * Any extension to hook the initialization of the metamodel
+ * Any extension to hook the initialization of the metamodel
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -28,5 +28,3 @@ interface iOnClassInitialization
{
public function OnAfterClassInitialization($sClass);
}
-
-?>
diff --git a/core/modelreflection.class.inc.php b/core/modelreflection.class.inc.php
index 7b3b7be09..220a08045 100644
--- a/core/modelreflection.class.inc.php
+++ b/core/modelreflection.class.inc.php
@@ -1,9 +1,10 @@
-
/**
- * Reflection API for the MetaModel (partial)
+ * Reflection API for the MetaModel (partial)
*
* @copyright Copyright (C) 2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -37,10 +37,9 @@ define('ENUM_CHILD_CLASSES_EXCLUDETOP', 1);
*/
define('ENUM_CHILD_CLASSES_ALL', 2);
-
abstract class ModelReflection
{
- abstract public function GetClassIcon($sClass, $bImgTag = true);
+ abstract public function GetClassIcon($sClass, $bImgTag = true);
abstract public function IsValidAttCode($sClass, $sAttCode);
abstract public function GetName($sClass);
abstract public function GetLabel($sClass, $sAttCodeEx);
@@ -70,9 +69,8 @@ abstract class ModelReflection
$sLocalizedFormat = $this->DictString($sFormatCode);
$aArguments = func_get_args();
array_shift($aArguments);
-
- if ($sLocalizedFormat == $sFormatCode)
- {
+
+ if ($sLocalizedFormat == $sFormatCode) {
// Make sure the information will be displayed (ex: an error occuring before the dictionary gets loaded)
return $sFormatCode.' - '.implode(', ', $aArguments);
}
@@ -88,7 +86,7 @@ abstract class ModelReflection
* @return \RunTimeIconSelectionField
*/
abstract public function GetIconSelectionField($sCode, $sLabel = '', $defaultValue = '');
-
+
abstract public function GetRootClass($sClass);
abstract public function EnumChildClasses($sClass, $iOption = ENUM_CHILD_CLASSES_EXCLUDETOP);
}
@@ -104,7 +102,6 @@ abstract class QueryReflection
abstract public function GetClassAlias();
}
-
class ModelReflectionRuntime extends ModelReflection
{
public function __construct()
@@ -115,22 +112,22 @@ class ModelReflectionRuntime extends ModelReflection
{
return MetaModel::GetClassIcon($sClass, $bImgTag);
}
-
+
public function IsValidAttCode($sClass, $sAttCode)
{
return MetaModel::IsValidAttCode($sClass, $sAttCode);
}
-
+
public function GetName($sClass)
{
return MetaModel::GetName($sClass);
}
-
+
public function GetLabel($sClass, $sAttCodeEx)
{
return MetaModel::GetLabel($sClass, $sAttCodeEx);
}
-
+
public function GetValueLabel($sClass, $sAttCode, $sValue)
{
$oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
@@ -140,11 +137,9 @@ class ModelReflectionRuntime extends ModelReflection
public function ListAttributes($sClass, $sScope = null)
{
$aScope = null;
- if ($sScope != null)
- {
- $aScope = array();
- foreach (explode(',', $sScope) as $sScopeClass)
- {
+ if ($sScope != null) {
+ $aScope = [];
+ foreach (explode(',', $sScope) as $sScopeClass) {
$aScope[] = trim($sScopeClass);
}
}
@@ -163,30 +158,25 @@ class ModelReflectionRuntime extends ModelReflection
break;
}
}
- }
- else
- {
+ } else {
$aAttributes[$sAttCode] = $sAttributeClass;
}
}
return $aAttributes;
}
-
+
public function GetAttributeProperty($sClass, $sAttCode, $sPropName, $default = null)
{
$ret = $default;
$oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
$aParams = $oAttDef->GetParams();
- if (array_key_exists($sPropName, $aParams))
- {
+ if (array_key_exists($sPropName, $aParams)) {
$ret = $aParams[$sPropName];
}
- if ($oAttDef instanceof AttributeHierarchicalKey)
- {
- if ($sPropName == 'targetclass')
- {
+ if ($oAttDef instanceof AttributeHierarchicalKey) {
+ if ($sPropName == 'targetclass') {
$ret = $sClass;
}
}
@@ -197,29 +187,24 @@ class ModelReflectionRuntime extends ModelReflection
{
return MetaModel::GetAllowedValues_att($sClass, $sAttCode);
}
-
+
public function HasChildrenClasses($sClass)
{
return MetaModel::HasChildrenClasses($sClass);
}
-
+
public function GetClasses($sCategories = '', $bExcludeLinks = false)
{
$aClasses = MetaModel::GetClasses($sCategories);
- if ($bExcludeLinks)
- {
+ if ($bExcludeLinks) {
$aExcluded = MetaModel::GetLinkClasses();
- $aRes = array();
- foreach ($aClasses as $sClass)
- {
- if (!array_key_exists($sClass, $aExcluded))
- {
+ $aRes = [];
+ foreach ($aClasses as $sClass) {
+ if (!array_key_exists($sClass, $aExcluded)) {
$aRes[] = $sClass;
}
}
- }
- else
- {
+ } else {
$aRes = $aClasses;
}
return $aRes;
@@ -264,19 +249,18 @@ class ModelReflectionRuntime extends ModelReflection
{
return new RunTimeIconSelectionField($sCode, $sLabel, $defaultValue);
}
-
+
public function GetRootClass($sClass)
{
return MetaModel::GetRootClass($sClass);
}
-
+
public function EnumChildClasses($sClass, $iOption = ENUM_CHILD_CLASSES_EXCLUDETOP)
{
return MetaModel::EnumChildClasses($sClass, $iOption);
}
}
-
class QueryReflectionRuntime extends QueryReflection
{
protected $oFilter;
diff --git a/core/moduledesign.class.inc.php b/core/moduledesign.class.inc.php
index 8b76e8a56..16b5d57a2 100644
--- a/core/moduledesign.class.inc.php
+++ b/core/moduledesign.class.inc.php
@@ -1,4 +1,5 @@
LoadFromCompiledDesigns($sDesignSourceId);
}
}
@@ -80,18 +79,13 @@ class ModuleDesign extends \Combodo\iTop\DesignDocument
{
$sDesignDir = APPROOT.'env-'.utils::GetCurrentEnvironment().'/core/module_designs/';
$sFile = $sDesignDir.$sDesignSourceId.'.xml';
- if (!file_exists($sFile))
- {
+ if (!file_exists($sFile)) {
$aFiles = glob($sDesignDir.'/*.xml');
- if (count($aFiles) == 0)
- {
+ if (count($aFiles) == 0) {
$sAvailable = 'none!';
- }
- else
- {
- $aAvailable = array();
- foreach ($aFiles as $sFile)
- {
+ } else {
+ $aAvailable = [];
+ foreach ($aFiles as $sFile) {
$aAvailable[] = "'".basename($sFile, '.xml')."'";
}
$sAvailable = implode(', ', $aAvailable);
@@ -105,11 +99,9 @@ class ModuleDesign extends \Combodo\iTop\DesignDocument
$this->load($sFile);
//$bValidated = $oDocument->schemaValidate(APPROOT.'setup/itop_design.xsd');
$aErrors = libxml_get_errors();
- if (count($aErrors) > 0)
- {
- $aDisplayErrors = array();
- foreach($aErrors as $oXmlError)
- {
+ if (count($aErrors) > 0) {
+ $aDisplayErrors = [];
+ foreach ($aErrors as $oXmlError) {
$aDisplayErrors[] = 'Line '.$oXmlError->line.': '.$oXmlError->message;
}
diff --git a/core/modulehandler.class.inc.php b/core/modulehandler.class.inc.php
index 21d9b7204..60249aa4c 100644
--- a/core/modulehandler.class.inc.php
+++ b/core/modulehandler.class.inc.php
@@ -1,9 +1,10 @@
-
/**
* Class ModuleHandler
- * Defines the API to implement module specific actions during page execution
+ * Defines the API to implement module specific actions during page execution
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -36,17 +36,16 @@ abstract class ModuleHandlerAPI implements ModuleHandlerApiInterface
}
public function __construct()
- {
- }
+ {
+ }
}
-
interface ModuleHandlerApiInterface
{
- public static function OnMetaModelStarted();
+ public static function OnMetaModelStarted();
- public static function OnMenuCreation();
+ public static function OnMenuCreation();
- public function __construct(); //empty params is required in order to be instantiable by MetaModel::InitClasses()
-}
\ No newline at end of file
+ public function __construct(); //empty params is required in order to be instantiable by MetaModel::InitClasses()
+}
diff --git a/core/mutex.class.inc.php b/core/mutex.class.inc.php
index 94db80198..4e7c096c1 100644
--- a/core/mutex.class.inc.php
+++ b/core/mutex.class.inc.php
@@ -1,9 +1,10 @@
-
/**
* Class iTopMutex
* A class to serialize the execution of some code sections
@@ -44,17 +44,20 @@ class iTopMutex
protected $sDBSubname;
protected $bDBTlsEnabled;
protected $sDBTlsCA;
- static protected $aAcquiredLocks = array(); // Number of instances of the Mutex, having the lock, in this page
+ protected static $aAcquiredLocks = []; // Number of instances of the Mutex, having the lock, in this page
public function __construct(
- $sName, $sDBHost = null, $sDBUser = null, $sDBPwd = null, $bDBTlsEnabled = null, $sDBTlsCA = null
- )
- {
+ $sName,
+ $sDBHost = null,
+ $sDBUser = null,
+ $sDBPwd = null,
+ $bDBTlsEnabled = null,
+ $sDBTlsCA = null
+ ) {
// Compute the name of a lock for mysql
// Note: names are server-wide!!! So let's make the name specific to this iTop instance
$oConfig = MetaModel::GetConfig();
- if ($oConfig === null)
- {
+ if ($oConfig === null) {
$oConfig = utils::GetConfig(); // Will return an empty config when called during the setup
}
$this->sDBHost = is_null($sDBHost) ? $oConfig->Get('db_host') : $sDBHost;
@@ -67,8 +70,7 @@ class iTopMutex
$this->sDBTlsCA = is_null($sDBTlsCA) ? $oConfig->Get('db_tls.ca') : $sDBTlsCA;
$this->sName = $sName;
- if (substr($sName, -strlen($this->sDBName.$sDBSubname)) != $this->sDBName.$sDBSubname)
- {
+ if (substr($sName, -strlen($this->sDBName.$sDBSubname)) != $this->sDBName.$sDBSubname) {
// If the name supplied already ends with the expected suffix
// don't add it twice, since the setup may try to detect an already
// running cron job by its mutex, without knowing if the config already exists or not
@@ -80,8 +82,7 @@ class iTopMutex
$this->bLocked = false; // Not yet locked
- if (!array_key_exists($this->sName, self::$aAcquiredLocks))
- {
+ if (!array_key_exists($this->sName, self::$aAcquiredLocks)) {
self::$aAcquiredLocks[$this->sName] = 0;
}
@@ -108,11 +109,9 @@ class iTopMutex
return new iTopMutex(...$aArgs);
}
-
public function __destruct()
{
- if ($this->bLocked)
- {
+ if ($this->bLocked) {
$this->Unlock();
}
mysqli_close($this->hDBLink);
@@ -122,27 +121,22 @@ class iTopMutex
* Acquire the mutex. Uses a MySQL lock. Warn : can have an abnormal behavior on MySQL clusters (see R-016204)
*
* @see https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
- */
+ */
public function Lock()
{
- if ($this->bLocked)
- {
+ if ($this->bLocked) {
// Lock already acquired
return;
}
- if (self::$aAcquiredLocks[$this->sName] == 0)
- {
- do
- {
+ if (self::$aAcquiredLocks[$this->sName] == 0) {
+ do {
$res = $this->QueryToScalar("SELECT GET_LOCK('".$this->sName."', 3600)");
- if (is_null($res))
- {
+ if (is_null($res)) {
throw new Exception("Failed to acquire the lock '".$this->sName."'");
}
// $res === '1' means I hold the lock
// $res === '0' means it timed out
- }
- while ($res !== '1');
+ } while ($res !== '1');
}
$this->bLocked = true;
self::$aAcquiredLocks[$this->sName]++;
@@ -150,66 +144,56 @@ class iTopMutex
/**
* Attempt to acquire the mutex
- * @returns bool True if the mutex is acquired, false if already locked elsewhere
- */
+ * @returns bool True if the mutex is acquired, false if already locked elsewhere
+ */
public function TryLock()
{
- if ($this->bLocked)
- {
+ if ($this->bLocked) {
return true; // Already acquired
}
- if (self::$aAcquiredLocks[$this->sName] > 0)
- {
+ if (self::$aAcquiredLocks[$this->sName] > 0) {
self::$aAcquiredLocks[$this->sName]++;
$this->bLocked = true;
return true;
}
-
+
$res = $this->QueryToScalar("SELECT GET_LOCK('".$this->sName."', 0)");
- if (is_null($res))
- {
+ if (is_null($res)) {
throw new Exception("Failed to acquire the lock '".$this->sName."'");
}
// $res === '1' means I hold the lock
// $res === '0' means it timed out
- if ($res === '1')
- {
+ if ($res === '1') {
$this->bLocked = true;
self::$aAcquiredLocks[$this->sName]++;
}
- if (($res !== '1') && ($res !== '0'))
- {
+ if (($res !== '1') && ($res !== '0')) {
$sMsg = 'GET_LOCK('.$this->sName.', 0) returned: '.var_export($res, true).'. Expected values are: 0, 1 or null';
IssueLog::Error($sMsg);
throw new Exception($sMsg);
}
return ($res !== '0');
}
-
+
/**
* Check if the mutex is locked WITHOUT TRYING TO ACQUIRE IT
* @returns bool True if the mutex is in use, false otherwise
*/
public function IsLocked()
{
- if ($this->bLocked)
- {
+ if ($this->bLocked) {
return true; // Already acquired
}
- if (self::$aAcquiredLocks[$this->sName] > 0)
- {
+ if (self::$aAcquiredLocks[$this->sName] > 0) {
return true;
}
-
+
$res = $this->QueryToScalar("SELECT IS_FREE_LOCK('".$this->sName."')"); // IS_FREE_LOCK detects some error cases that IS_USED_LOCK do not detect
- if (is_null($res))
- {
+ if (is_null($res)) {
$sMsg = "MySQL Error, IS_FREE_LOCK('".$this->sName."') returned null. Error (".mysqli_errno($this->hDBLink).") = '".mysqli_error($this->hDBLink)."'";
IssueLog::Error($sMsg);
throw new Exception($sMsg);
- }
- else if ($res == '1')
- {
+ } elseif ($res == '1') {
// Lock is free
return false;
}
@@ -218,21 +202,18 @@ class iTopMutex
/**
* Release the mutex
- */
+ */
public function Unlock()
{
- if (!$this->bLocked)
- {
+ if (!$this->bLocked) {
// ??? the lock is not acquired, exit
- return;
+ return;
}
- if (self::$aAcquiredLocks[$this->sName] == 0)
- {
+ if (self::$aAcquiredLocks[$this->sName] == 0) {
return; // Safety net
}
-
- if (self::$aAcquiredLocks[$this->sName] == 1)
- {
+
+ if (self::$aAcquiredLocks[$this->sName] == 1) {
$res = $this->QueryToScalar("SELECT RELEASE_LOCK('".$this->sName."')");
}
$this->bLocked = false;
@@ -259,7 +240,7 @@ class iTopMutex
$this->hDBLink = CMDBSource::GetMysqliInstance($sServer, $sUser, $sPwd, $sSource, $bTlsEnabled, $sTlsCA, false);
if (!$this->hDBLink) {
- throw new MySQLException('Could not connect to the DB server '.mysqli_connect_error().' (mysql errno: '.mysqli_connect_errno(), array('host' => $sDBHost, 'user' => $sDBUser));
+ throw new MySQLException('Could not connect to the DB server '.mysqli_connect_error().' (mysql errno: '.mysqli_connect_errno(), ['host' => $sDBHost, 'user' => $sDBUser]);
}
// Make sure that the server variable `wait_timeout` is at least 86400 seconds for this connection,
@@ -290,20 +271,15 @@ class iTopMutex
}
}
-
protected function QueryToScalar($sSql)
{
$result = mysqli_query($this->hDBLink, $sSql);
- if (!$result)
- {
+ if (!$result) {
throw new Exception("Failed to issue MySQL query '".$sSql."': ".mysqli_error($this->hDBLink).' (mysql errno: '.mysqli_errno($this->hDBLink).')');
}
- if ($aRow = mysqli_fetch_array($result, MYSQLI_BOTH))
- {
+ if ($aRow = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$res = $aRow[0];
- }
- else
- {
+ } else {
mysqli_free_result($result);
throw new Exception("No result for query '".$sSql."'");
}
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/oqlclassnode.class.inc.php b/core/oqlclassnode.class.inc.php
index 5abeb17e5..a77e42675 100644
--- a/core/oqlclassnode.class.inc.php
+++ b/core/oqlclassnode.class.inc.php
@@ -1,10 +1,10 @@
sNodeClass = $sNodeClass;
- if (empty($sNodeClassAlias))
- {
+ if (empty($sNodeClassAlias)) {
$this->sNodeClassAlias = $oBuild->GetEmptyClassAlias();
- }
- else
- {
+ } else {
$this->sNodeClassAlias = $sNodeClassAlias;
}
- $this->aJoins = array();
- $this->aExtKeys = array();
- if (is_null($sOQLClassAlias))
- {
+ $this->aJoins = [];
+ $this->aExtKeys = [];
+ if (is_null($sOQLClassAlias)) {
$this->sOQLClassAlias = $this->sNodeClassAlias;
- }
- else
- {
+ } else {
$this->sOQLClassAlias = $sOQLClassAlias;
}
$this->oBuild = $oBuild;
@@ -60,9 +54,8 @@ class OQLClassNode
public function AddExternalKey($sKeyAttCode)
{
- if (!isset($this->aExtKeys[$sKeyAttCode]))
- {
- $this->aExtKeys[$sKeyAttCode] = array();
+ if (!isset($this->aExtKeys[$sKeyAttCode])) {
+ $this->aExtKeys[$sKeyAttCode] = [];
}
}
@@ -72,7 +65,6 @@ class OQLClassNode
$this->aExtKeys[$sKeyAttCode][$sFieldAttCode] = $oAttDef;
}
-
public function AddInnerJoin($oOQLClassNode, $sLeftField, $sRightField, $bOutbound = true)
{
$this->AddJoin(OQLJoin::JOIN_INNER, $oOQLClassNode, $sLeftField, $sRightField, $bOutbound);
@@ -82,7 +74,7 @@ class OQLClassNode
{
$this->AddJoin(OQLJoin::JOIN_LEFT, $oOQLClassNode, $sLeftField, $sRightField, $bOutbound);
}
-
+
public function AddInnerJoinTree($oOQLClassNode, $sLeftField, $sRightField, $bOutbound = true, $iOperatorCode = TREE_OPERATOR_BELOW, $bInvertOnClause = false)
{
$this->AddJoin(OQLJoin::JOIN_INNER_TREE, $oOQLClassNode, $sLeftField, $sRightField, $bOutbound, $iOperatorCode, $bInvertOnClause);
@@ -90,8 +82,16 @@ class OQLClassNode
private function AddJoin($sJoinType, $oOQLClassNode, $sLeftField, $sRightField, $bOutbound = true, $sTreeOperator = null, $bInvertOnClause = false)
{
- $oOQLJoin = new OQLJoin($this->oBuild, $sJoinType, $oOQLClassNode, $sLeftField, $sRightField, $bOutbound, $sTreeOperator,
- $bInvertOnClause);
+ $oOQLJoin = new OQLJoin(
+ $this->oBuild,
+ $sJoinType,
+ $oOQLClassNode,
+ $sLeftField,
+ $sRightField,
+ $bOutbound,
+ $sTreeOperator,
+ $bInvertOnClause
+ );
$this->AddOQLJoin($sLeftField, $oOQLJoin);
}
@@ -116,26 +116,21 @@ class OQLClassNode
public function RenderDebug()
{
$sOQL = "SELECT `{$this->sNodeClassAlias}` FROM `{$this->sNodeClass}` AS `{$this->sNodeClassAlias}`";
- foreach ($this->aJoins as $aJoins)
- {
- foreach ($aJoins as $oJoin)
- {
+ foreach ($this->aJoins as $aJoins) {
+ foreach ($aJoins as $oJoin) {
$sOQL .= "{$oJoin->RenderDebug($this->sNodeClassAlias)}";
}
}
-
return $sOQL;
}
public function Browse(Closure $callback)
{
$callback($this);
- foreach ($this->GetJoins() as $aJoins)
- {
+ foreach ($this->GetJoins() as $aJoins) {
/** @var \OQLJoin $oJoin */
- foreach ($aJoins as $oJoin)
- {
+ foreach ($aJoins as $oJoin) {
$oJoin->GetOOQLClassNode()->Browse($callback);
}
}
@@ -182,8 +177,7 @@ class OQLClassNode
public function RemoveJoin($sLeftKey, $index)
{
unset($this->aJoins[$sLeftKey][$index]);
- if (empty($this->aJoins[$sLeftKey]))
- {
+ if (empty($this->aJoins[$sLeftKey])) {
unset($this->aJoins[$sLeftKey]);
}
}
@@ -192,10 +186,10 @@ class OQLClassNode
class OQLJoin
{
- const JOIN_INNER = 'inner';
- const JOIN_LEFT = 'left';
- const JOIN_INNER_TREE = 'inner_tree';
-
+ public const JOIN_INNER = 'inner';
+ public const JOIN_LEFT = 'left';
+ public const JOIN_INNER_TREE = 'inner_tree';
+
private $sJoinType;
/** @var \OQLClassNode */
private $oOQLClassNode;
@@ -238,8 +232,16 @@ class OQLJoin
public function NewOQLJoinWithClassNode($oOQLClassNode)
{
- return new self($this->oBuild, $this->sJoinType, $oOQLClassNode, $this->sLeftField, $this->sRightField, $this->bOutbound,
- $this->sTreeOperator, $this->bInvertOnClause);
+ return new self(
+ $this->oBuild,
+ $this->sJoinType,
+ $oOQLClassNode,
+ $this->sLeftField,
+ $this->sRightField,
+ $this->bOutbound,
+ $this->sTreeOperator,
+ $this->bInvertOnClause
+ );
}
/**
@@ -252,27 +254,20 @@ class OQLJoin
// Translate the fields before copy to SQL
$sLeft = $oBaseSQLQuery->GetTableAlias().'.'.$this->sLeftField;
$oLeftField = $oBuild->m_oQBExpressions->GetJoinField($sLeft);
- if ($oLeftField)
- {
+ if ($oLeftField) {
$sSQLLeft = $oLeftField->GetName();
- }
- else
- {
+ } else {
$sSQLLeft = "no_field_found_for_$sLeft";
}
$sRight = $oJoinedSQLQuery->GetTableAlias().'.'.$this->sRightField;
$oRightField = $oBuild->m_oQBExpressions->GetJoinField($sRight);
- if ($oRightField)
- {
+ if ($oRightField) {
$sSQLRight = $oRightField->GetName();
- }
- else
- {
+ } else {
$sSQLRight = "no_field_found_for_$sRight";
}
- switch ($this->sJoinType)
- {
+ switch ($this->sJoinType) {
case self::JOIN_INNER:
$oBaseSQLQuery->AddInnerJoin($oJoinedSQLQuery, $sSQLLeft, $sSQLRight);
break;
@@ -296,10 +291,8 @@ class OQLJoin
$sOQL = "\n{$sPrefix}{$sType} JOIN `{$this->oOQLClassNode->GetNodeClass()}` AS `{$this->oOQLClassNode->GetNodeClassAlias()}`";
$sOQL .= "\n{$sPrefix} ON `{$sClassAlias}`.`{$this->sLeftField}` = `{$this->oOQLClassNode->GetNodeClassAlias()}`.`{$this->sRightField}`";
$sPrefix .= " ";
- foreach ($this->oOQLClassNode->GetJoins() as $aJoins)
- {
- foreach ($aJoins as $oJoin)
- {
+ foreach ($this->oOQLClassNode->GetJoins() as $aJoins) {
+ foreach ($aJoins as $oJoin) {
$sOQL .= " {$oJoin->RenderDebug($this->oOQLClassNode->GetNodeClassAlias(), $sPrefix)}";
}
}
diff --git a/core/oqlclasstreebuilder.class.inc.php b/core/oqlclasstreebuilder.class.inc.php
index f984dbae8..bbb80cb40 100644
--- a/core/oqlclasstreebuilder.class.inc.php
+++ b/core/oqlclasstreebuilder.class.inc.php
@@ -1,10 +1,10 @@
oDBObjectSearch = $oDBObjetSearch;
$this->sClass = $oDBObjetSearch->GetFirstJoinedClass();
$this->sClassAlias = $oDBObjetSearch->GetFirstJoinedClassAlias();
- if (empty($this->sClassAlias))
- {
+ if (empty($this->sClassAlias)) {
$this->sClassAlias = $oBuild->GetEmptyClassAlias();
}
$this->oOQLClassNode = new OQLClassNode($oBuild, $this->sClass, $this->sClassAlias);
@@ -89,10 +88,8 @@ class OQLClassTreeBuilder
*/
private function AddExternalKeysFromSearch()
{
- foreach ($this->oDBObjectSearch->GetCriteria_PointingTo() as $sKeyAttCode => $aPointingTo)
- {
- if (array_key_exists(TREE_OPERATOR_EQUALS, $aPointingTo))
- {
+ foreach ($this->oDBObjectSearch->GetCriteria_PointingTo() as $sKeyAttCode => $aPointingTo) {
+ if (array_key_exists(TREE_OPERATOR_EQUALS, $aPointingTo)) {
$this->oOQLClassNode->AddExternalKey($sKeyAttCode);
}
}
@@ -109,69 +106,53 @@ class OQLClassTreeBuilder
// array of (attcode => fieldexpression)
$aExpectedAttributes = $this->oBuild->m_oQBExpressions->GetUnresolvedFields($this->sClassAlias);
- $aPolymorphicJoinAlias = array(); // array of (subclass => alias)
- foreach ($aExpectedAttributes as $sExpectedAttCode => $oExpression)
- {
- if (!MetaModel::IsValidAttCode($this->sClass, $sExpectedAttCode))
- {
+ $aPolymorphicJoinAlias = []; // array of (subclass => alias)
+ foreach ($aExpectedAttributes as $sExpectedAttCode => $oExpression) {
+ if (!MetaModel::IsValidAttCode($this->sClass, $sExpectedAttCode)) {
continue;
}
$oAttDef = MetaModel::GetAttributeDef($this->sClass, $sExpectedAttCode);
- if ($oAttDef->IsBasedOnOQLExpression())
- {
+ if ($oAttDef->IsBasedOnOQLExpression()) {
// To optimize: detect a restriction on child classes in the condition expression
// e.g. SELECT FunctionalCI WHERE finalclass IN ('Server', 'VirtualMachine')
$oExpression = DBObjectSearch::GetPolymorphicExpression($this->sClass, $sExpectedAttCode);
- $aRequiredFields = array();
+ $aRequiredFields = [];
$oExpression->GetUnresolvedFields('', $aRequiredFields);
- $aTranslateFields = array();
- foreach ($aRequiredFields as $sSubClass => $aFields)
- {
- foreach ($aFields as $sAttCode => $oField)
- {
+ $aTranslateFields = [];
+ foreach ($aRequiredFields as $sSubClass => $aFields) {
+ foreach ($aFields as $sAttCode => $oField) {
$oAttDef = MetaModel::GetAttributeDef($sSubClass, $sAttCode);
- if ($oAttDef->IsExternalKey())
- {
+ if ($oAttDef->IsExternalKey()) {
$sClassOfAttribute = MetaModel::GetAttributeOrigin($sSubClass, $sAttCode);
- if (MetaModel::IsParentClass($sClassOfAttribute, $this->sClass))
- {
+ if (MetaModel::IsParentClass($sClassOfAttribute, $this->sClass)) {
$this->oOQLClassNode->AddExternalKey($sAttCode);
}
- }
- elseif ($oAttDef->IsExternalField())
- {
+ } elseif ($oAttDef->IsExternalField()) {
$sKeyAttCode = $oAttDef->GetKeyAttCode();
$sClassOfAttribute = MetaModel::GetAttributeOrigin($sSubClass, $sKeyAttCode);
- if (MetaModel::IsParentClass($sClassOfAttribute, $this->sClass))
- {
+ if (MetaModel::IsParentClass($sClassOfAttribute, $this->sClass)) {
$this->oOQLClassNode->AddExternalField($sKeyAttCode, $sAttCode, $oAttDef);
}
- }
- else
- {
+ } else {
$sClassOfAttribute = MetaModel::GetAttributeOrigin($sSubClass, $sAttCode);
}
- if (MetaModel::IsParentClass($sClassOfAttribute, $this->sClass))
- {
+ if (MetaModel::IsParentClass($sClassOfAttribute, $this->sClass)) {
// The attribute is part of the standard query
//
$sAliasForAttribute = $this->sClassAlias;
- }
- else
- {
+ } else {
// The attribute will be available from an additional outer join
// For each subclass (table) one single join is enough
//
- if (!array_key_exists($sClassOfAttribute, $aPolymorphicJoinAlias))
- {
- $sAliasForAttribute = $this->oBuild->GenerateClassAlias($this->sClassAlias.'_poly_'.$sClassOfAttribute,
- $sClassOfAttribute);
+ if (!array_key_exists($sClassOfAttribute, $aPolymorphicJoinAlias)) {
+ $sAliasForAttribute = $this->oBuild->GenerateClassAlias(
+ $this->sClassAlias.'_poly_'.$sClassOfAttribute,
+ $sClassOfAttribute
+ );
$aPolymorphicJoinAlias[$sClassOfAttribute] = $sAliasForAttribute;
- }
- else
- {
+ } else {
$sAliasForAttribute = $aPolymorphicJoinAlias[$sClassOfAttribute];
}
}
@@ -181,7 +162,7 @@ class OQLClassTreeBuilder
}
$oExpression = $oExpression->Translate($aTranslateFields, false);
- $aTranslateNow = array();
+ $aTranslateNow = [];
$aTranslateNow[$this->sClassAlias][$sExpectedAttCode] = $oExpression;
$this->oBuild->m_oQBExpressions->Translate($aTranslateNow, false);
}
@@ -200,12 +181,9 @@ class OQLClassTreeBuilder
// array of (attcode => fieldexpression)
$aExpectedAttributes = $this->oBuild->m_oQBExpressions->GetUnresolvedFields($this->sClassAlias);
- foreach (MetaModel::ListAttributeDefs($this->sClass) as $sAttCode => $oAttDef)
- {
- if ($oAttDef->IsExternalField())
- {
- if (array_key_exists($sAttCode, $aExpectedAttributes))
- {
+ foreach (MetaModel::ListAttributeDefs($this->sClass) as $sAttCode => $oAttDef) {
+ if ($oAttDef->IsExternalField()) {
+ if (array_key_exists($sAttCode, $aExpectedAttributes)) {
// Add the external attribute
$sKeyAttCode = $oAttDef->GetKeyAttCode();
$this->oOQLClassNode->AddExternalField($sKeyAttCode, $sAttCode, $oAttDef);
@@ -225,16 +203,13 @@ class OQLClassTreeBuilder
$aAllPointingTo = $this->oDBObjectSearch->GetCriteria_PointingTo();
// Add filters from external keys
- foreach (array_keys($this->oOQLClassNode->GetExternalKeys()) as $sKeyAttCode)
- {
- if (!MetaModel::IsValidAttCode($this->sClass, $sKeyAttCode))
- {
+ foreach (array_keys($this->oOQLClassNode->GetExternalKeys()) as $sKeyAttCode) {
+ if (!MetaModel::IsValidAttCode($this->sClass, $sKeyAttCode)) {
continue;
} // Not defined in the class, skip it
$oKeyAttDef = MetaModel::GetAttributeDef($this->sClass, $sKeyAttCode);
- $aPointingTo = isset($aAllPointingTo[$sKeyAttCode]) ? $aAllPointingTo[$sKeyAttCode] : array();
- if (!array_key_exists(TREE_OPERATOR_EQUALS, $aPointingTo))
- {
+ $aPointingTo = isset($aAllPointingTo[$sKeyAttCode]) ? $aAllPointingTo[$sKeyAttCode] : [];
+ if (!array_key_exists(TREE_OPERATOR_EQUALS, $aPointingTo)) {
// The join was not explicitly defined in the filter,
// we need to do it now
$sKeyClass = $oKeyAttDef->GetTargetClass();
@@ -246,14 +221,10 @@ class OQLClassTreeBuilder
}
$oQBContextExpressions = $this->oBuild->m_oQBExpressions;
- foreach ($aAllPointingTo as $sKeyAttCode => $aPointingTo)
- {
- foreach ($aPointingTo as $iOperatorCode => $aFilter)
- {
- foreach ($aFilter as $oExtFilter)
- {
- if (!MetaModel::IsValidAttCode($this->sClass, $sKeyAttCode))
- {
+ foreach ($aAllPointingTo as $sKeyAttCode => $aPointingTo) {
+ foreach ($aPointingTo as $iOperatorCode => $aFilter) {
+ foreach ($aFilter as $oExtFilter) {
+ if (!MetaModel::IsValidAttCode($this->sClass, $sKeyAttCode)) {
continue;
} // Not defined in the class, skip it
// The aliases should not conflict because normalization occurred while building the filter
@@ -263,34 +234,29 @@ class OQLClassTreeBuilder
// Note: there is no search condition in $oExtFilter, because normalization did merge the condition onto the top of the filter tree
- if ($iOperatorCode == TREE_OPERATOR_EQUALS)
- {
- if ($this->oOQLClassNode->HasExternalKey($sKeyAttCode))
- {
+ if ($iOperatorCode == TREE_OPERATOR_EQUALS) {
+ if ($this->oOQLClassNode->HasExternalKey($sKeyAttCode)) {
// Specify expected attributes for the target class query
// ... and use the current alias !
- $aTranslateNow = array(); // Translation for external fields - must be performed before the join is done (recursion...)
- foreach ($this->oOQLClassNode->GetExternalKey($sKeyAttCode) as $sAttCode => $oAtt)
- {
+ $aTranslateNow = []; // Translation for external fields - must be performed before the join is done (recursion...)
+ foreach ($this->oOQLClassNode->GetExternalKey($sKeyAttCode) as $sAttCode => $oAtt) {
$oExtAttDef = $oAtt->GetExtAttDef();
- if ($oExtAttDef->IsBasedOnOQLExpression())
- {
+ if ($oExtAttDef->IsBasedOnOQLExpression()) {
$sExtAttCode = $oExtAttDef->GetCode();
- }
- else
- {
+ } else {
$sExtAttCode = $oAtt->GetExtAttCode();
}
// Translate mainclass.extfield => remoteclassalias.remotefieldcode
$aTranslateNow[$this->sClassAlias][$sAttCode] = new FieldExpression($sExtAttCode, $sKeyClassAlias);
}
- if ($oKeyAttDef instanceof AttributeObjectKey)
- {
+ if ($oKeyAttDef instanceof AttributeObjectKey) {
// Add the condition: `$sTargetAlias`.$sClassAttCode IN (subclasses of $sKeyClass')
$sClassAttCode = $oKeyAttDef->Get('class_attcode');
- $oClassListExpr = ListExpression::FromScalars(MetaModel::EnumChildClasses($sKeyClass,
- ENUM_CHILD_CLASSES_ALL));
+ $oClassListExpr = ListExpression::FromScalars(MetaModel::EnumChildClasses(
+ $sKeyClass,
+ ENUM_CHILD_CLASSES_ALL
+ ));
$oClassExpr = new FieldExpression($sClassAttCode, $this->sClassAlias);
$oClassRestriction = new BinaryExpression($oClassExpr, 'IN', $oClassListExpr);
$oQBContextExpressions->AddCondition($oClassRestriction);
@@ -304,24 +270,18 @@ class OQLClassTreeBuilder
$oOQLClassTreeBuilder = new OQLClassTreeBuilder($oExtFilter, $this->oBuild);
$oSelectExtKey = $oOQLClassTreeBuilder->DevelopOQLClassNode();
- if ($oKeyAttDef->IsNullAllowed())
- {
+ if ($oKeyAttDef->IsNullAllowed()) {
$this->oOQLClassNode->AddLeftJoin($oSelectExtKey, $sKeyAttCode, $sExternalKeyField, true);
- }
- else
- {
+ } else {
$this->oOQLClassNode->AddInnerJoin($oSelectExtKey, $sKeyAttCode, $sExternalKeyField, true);
}
}
- }
- elseif (MetaModel::GetAttributeOrigin($sKeyClass, $sKeyAttCode) == $this->sClass)
- {
+ } elseif (MetaModel::GetAttributeOrigin($sKeyClass, $sKeyAttCode) == $this->sClass) {
$sExternalKeyField = $sKeyAttCode;
$oOQLClassTreeBuilder = new OQLClassTreeBuilder($oExtFilter, $this->oBuild);
$oSelectExtKey = $oOQLClassTreeBuilder->DevelopOQLClassNode();
-
$this->oOQLClassNode->AddInnerJoinTree($oSelectExtKey, $sKeyAttCode, $sExternalKeyField, true, $iOperatorCode);
}
}
@@ -336,25 +296,22 @@ class OQLClassTreeBuilder
*/
private function JoinClassesReferencedBy()
{
- foreach ($this->oDBObjectSearch->GetCriteria_ReferencedBy() as $sForeignClass => $aReferences)
- {
- foreach ($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator)
- {
- foreach ($aFiltersByOperator as $iOperatorCode => $aFilters)
- {
- foreach ($aFilters as $oForeignFilter)
- {
+ foreach ($this->oDBObjectSearch->GetCriteria_ReferencedBy() as $sForeignClass => $aReferences) {
+ foreach ($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) {
+ foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) {
+ foreach ($aFilters as $oForeignFilter) {
$oForeignKeyAttDef = MetaModel::GetAttributeDef($sForeignClass, $sForeignExtKeyAttCode);
$sForeignClassAlias = $oForeignFilter->GetFirstJoinedClassAlias();
- if ($oForeignKeyAttDef instanceof AttributeObjectKey)
- {
+ if ($oForeignKeyAttDef instanceof AttributeObjectKey) {
$sClassAttCode = $oForeignKeyAttDef->Get('class_attcode');
// Add the condition: `$sForeignClassAlias`.$sClassAttCode IN (subclasses of $sClass')
- $oClassListExpr = ListExpression::FromScalars(MetaModel::EnumChildClasses($this->sClass,
- ENUM_CHILD_CLASSES_ALL));
+ $oClassListExpr = ListExpression::FromScalars(MetaModel::EnumChildClasses(
+ $this->sClass,
+ ENUM_CHILD_CLASSES_ALL
+ ));
$oClassExpr = new FieldExpression($sClassAttCode, $sForeignClassAlias);
$oClassRestriction = new BinaryExpression($oClassExpr, 'IN', $oClassListExpr);
$this->oBuild->m_oQBExpressions->AddCondition($oClassRestriction);
@@ -363,12 +320,9 @@ class OQLClassTreeBuilder
$oOQLClassTreeBuilder = new OQLClassTreeBuilder($oForeignFilter, $this->oBuild);
$oSelectForeign = $oOQLClassTreeBuilder->DevelopOQLClassNode();
- if ($iOperatorCode == TREE_OPERATOR_EQUALS)
- {
+ if ($iOperatorCode == TREE_OPERATOR_EQUALS) {
$this->oOQLClassNode->AddInnerJoin($oSelectForeign, 'id', $sForeignExtKeyAttCode, false);
- }
- else
- {
+ } else {
// Hierarchical key
$this->oOQLClassNode->AddInnerJoinTree($oSelectForeign, $sForeignExtKeyAttCode, $sForeignExtKeyAttCode, false, $iOperatorCode, true);
}
@@ -387,8 +341,7 @@ class OQLClassTreeBuilder
*/
private function JoinClassesForPolymorphicExpressions($aPolymorphicJoinAlias)
{
- foreach ($aPolymorphicJoinAlias as $sSubClass => $sSubClassAlias)
- {
+ foreach ($aPolymorphicJoinAlias as $sSubClass => $sSubClassAlias) {
$oSubClassFilter = new DBObjectSearch($sSubClass, $sSubClassAlias);
$oOQLClassTreeBuilder = new OQLClassTreeBuilder($oSubClassFilter, $this->oBuild);
$oSelectPoly = $oOQLClassTreeBuilder->DevelopOQLClassNode();
diff --git a/core/oqlclasstreeoptimizer.class.inc.php b/core/oqlclasstreeoptimizer.class.inc.php
index 48931835c..55538647a 100644
--- a/core/oqlclasstreeoptimizer.class.inc.php
+++ b/core/oqlclasstreeoptimizer.class.inc.php
@@ -1,13 +1,13 @@
oBuild->m_oQBExpressions->GetExpectedFields($oCurrentClassNode->GetNodeClassAlias());
$bCanBeRemoved = empty($aExpectedAttributes);
- foreach ($oCurrentClassNode->GetJoins() as $sLeftKey => $aJoins)
- {
- foreach ($aJoins as $index => $oJoin)
- {
- if ($this->PruneJoins($oJoin->GetOOQLClassNode()))
- {
- if ($oJoin->IsOutbound())
- {
+ foreach ($oCurrentClassNode->GetJoins() as $sLeftKey => $aJoins) {
+ foreach ($aJoins as $index => $oJoin) {
+ if ($this->PruneJoins($oJoin->GetOOQLClassNode())) {
+ if ($oJoin->IsOutbound()) {
// If joined class in not the same class than the external key target class
// then the join cannot be removed because it is used to filter the request
$sJoinedClass = $oJoin->GetOOQLClassNode()->GetNodeClass();
@@ -59,15 +55,11 @@ class OQLClassTreeOptimizer
// The join is not used, remove from tree
$oCurrentClassNode->RemoveJoin($sLeftKey, $index);
}
- }
- else
- {
+ } else {
// Inbound joins cannot be removed
$bCanBeRemoved = false;
}
- }
- else
- {
+ } else {
// This join is used, so the current node cannot be removed
$bCanBeRemoved = false;
}
@@ -75,4 +67,4 @@ class OQLClassTreeOptimizer
}
return $bCanBeRemoved;
}
-}
\ No newline at end of file
+}
diff --git a/core/ormStyle.class.inc.php b/core/ormStyle.class.inc.php
index 43f8a0c14..614526a5e 100644
--- a/core/ormStyle.class.inc.php
+++ b/core/ormStyle.class.inc.php
@@ -1,4 +1,5 @@
sIcon;
}
-}
\ No newline at end of file
+}
diff --git a/core/ormcaselog.class.inc.php b/core/ormcaselog.class.inc.php
index fe089bf0e..f820f1d2f 100644
--- a/core/ormcaselog.class.inc.php
+++ b/core/ormcaselog.class.inc.php
@@ -1,9 +1,10 @@
m_sLog = $sLog;
$this->m_aIndex = $aIndex;
$this->m_bModified = false;
}
-
+
public function GetText($bConvertToPlainText = false)
{
- if ($bConvertToPlainText)
- {
+ if ($bConvertToPlainText) {
// Rebuild the log, but filtering any HTML markup for the all {@see static::ENUM_FORMAT_HTML} entries in the log
return $this->GetAsPlainText();
- }
- else
- {
+ } else {
return $this->m_sLog;
}
}
-
+
public static function FromJSON($oJson)
{
- if (!isset($oJson->items))
- {
+ if (!isset($oJson->items)) {
throw new Exception("Missing 'items' elements");
}
$oCaseLog = new ormCaseLog();
- foreach($oJson->items as $oItem)
- {
+ foreach ($oJson->items as $oItem) {
$oCaseLog->AddLogEntryFromJSON($oItem);
}
return $oCaseLog;
}
/**
- * Return a value that will be further JSON encoded
- */
+ * Return a value that will be further JSON encoded
+ */
public function GetForJSON()
{
// Order by ascending date
- $aRet = array('entries' => array_reverse($this->GetAsArray()));
+ $aRet = ['entries' => array_reverse($this->GetAsArray())];
return $aRet;
}
@@ -118,10 +114,9 @@ class ormCaseLog {
*/
public function GetAsArray()
{
- $aEntries = array();
+ $aEntries = [];
$iPos = 0;
- for($index=count($this->m_aIndex)-1 ; $index >= 0 ; $index--)
- {
+ for ($index = count($this->m_aIndex) - 1 ; $index >= 0 ; $index--) {
$iPos += $this->m_aIndex[$index]['separator_length'];
$sTextEntry = substr($this->m_sLog, $iPos, $this->m_aIndex[$index]['text_length']);
$iPos += $this->m_aIndex[$index]['text_length'];
@@ -130,27 +125,20 @@ class ormCaseLog {
// therefore we have changed the format. To preserve the compatibility with existing
// installations of iTop, both format are allowed:
// the 'date' item is either a DateTime object, or a unix timestamp
- if (is_int($this->m_aIndex[$index]['date']))
- {
+ if (is_int($this->m_aIndex[$index]['date'])) {
// Unix timestamp
- $sDate = date(AttributeDateTime::GetInternalFormat(),$this->m_aIndex[$index]['date']);
- }
- elseif (is_object($this->m_aIndex[$index]['date']))
- {
- if (version_compare(phpversion(), '5.3.0', '>='))
- {
+ $sDate = date(AttributeDateTime::GetInternalFormat(), $this->m_aIndex[$index]['date']);
+ } elseif (is_object($this->m_aIndex[$index]['date'])) {
+ if (version_compare(phpversion(), '5.3.0', '>=')) {
// DateTime
$sDate = $this->m_aIndex[$index]['date']->format(AttributeDateTime::GetInternalFormat());
- }
- else
- {
+ } else {
// No Warning... but the date is unknown
$sDate = '';
}
}
- $sFormat = array_key_exists('format', $this->m_aIndex[$index]) ? $this->m_aIndex[$index]['format'] : static::ENUM_FORMAT_TEXT;
- switch($sFormat)
- {
+ $sFormat = array_key_exists('format', $this->m_aIndex[$index]) ? $this->m_aIndex[$index]['format'] : static::ENUM_FORMAT_TEXT;
+ switch ($sFormat) {
case static::ENUM_FORMAT_TEXT:
$sHtmlEntry = utils::TextToHtml($sTextEntry);
break;
@@ -160,27 +148,26 @@ class ormCaseLog {
$sTextEntry = utils::HtmlToText($sHtmlEntry);
break;
}
- $aEntries[] = array(
+ $aEntries[] = [
'date' => $sDate,
'user_login' => $this->m_aIndex[$index]['user_name'],
'user_id' => $this->m_aIndex[$index]['user_id'],
'message' => $sTextEntry,
'message_html' => $sHtmlEntry,
- );
+ ];
}
// Process the case of an eventual remainder (quick migration of AttributeText fields)
- if ($iPos < (utils::StrLen($this->m_sLog) - 1))
- {
+ if ($iPos < (utils::StrLen($this->m_sLog) - 1)) {
$sTextEntry = substr($this->m_sLog, $iPos);
- $aEntries[] = array(
+ $aEntries[] = [
'date' => '',
'user_login' => '',
'user_id' => 0,
'message' => $sTextEntry,
'message_html' => utils::TextToHtml($sTextEntry),
- );
+ ];
}
return $aEntries;
@@ -195,14 +182,13 @@ class ormCaseLog {
{
$sPlainText = '';
$aJSON = $this->GetForJSON();
- foreach($aJSON['entries'] as $aData)
- {
+ foreach ($aJSON['entries'] as $aData) {
$sSeparator = sprintf(CASELOG_SEPARATOR, $aData['date'], $aData['user_login'], $aData['user_id']);
$sPlainText .= $sSeparator.$aData['message'];
}
- return $sPlainText;
+ return $sPlainText;
}
-
+
public function GetIndex()
{
return $this->m_aIndex;
@@ -210,25 +196,27 @@ class ormCaseLog {
public function __toString()
{
- if($this->IsEmpty()) return '';
+ if ($this->IsEmpty()) {
+ return '';
+ }
- return $this->m_sLog;
+ return $this->m_sLog;
}
public function IsEmpty()
- {
- return ($this->m_sLog === null);
- }
+ {
+ return ($this->m_sLog === null);
+ }
/**
* @return int The number of entries in this log
* @since 3.0.0
*/
- public function GetEntryCount(): int
- {
- return count($this->m_aIndex);
- }
-
+ public function GetEntryCount(): int
+ {
+ return count($this->m_aIndex);
+ }
+
public function ClearModifiedFlag()
{
$this->m_bModified = false;
@@ -236,7 +224,7 @@ class ormCaseLog {
/**
* Produces an HTML representation, aimed at being used within an email
- */
+ */
public function GetAsEmailHtml()
{
$sStyleCaseLogHeader = '';
@@ -245,18 +233,14 @@ class ormCaseLog {
$sHtml = ''; // Use table-layout:fixed to force the with to be independent from the actual content
$iPos = 0;
$aIndex = $this->m_aIndex;
- for($index=count($aIndex)-1 ; $index >= 0 ; $index--)
- {
+ for ($index = count($aIndex) - 1 ; $index >= 0 ; $index--) {
$iPos += $aIndex[$index]['separator_length'];
$sTextEntry = substr($this->m_sLog, $iPos, $aIndex[$index]['text_length']);
$sCSSClass = 'caselog_entry_html';
- if (!array_key_exists('format', $aIndex[$index]) || ($aIndex[$index]['format'] == static::ENUM_FORMAT_TEXT))
- {
+ if (!array_key_exists('format', $aIndex[$index]) || ($aIndex[$index]['format'] == static::ENUM_FORMAT_TEXT)) {
$sCSSClass = 'caselog_entry';
- $sTextEntry = str_replace(array("\r\n", "\n", "\r"), " ", utils::EscapeHtml($sTextEntry));
- }
- else
- {
+ $sTextEntry = str_replace(["\r\n", "\n", "\r"], " ", utils::EscapeHtml($sTextEntry));
+ } else {
$sTextEntry = InlineImage::FixUrls($sTextEntry);
}
$iPos += $aIndex[$index]['text_length'];
@@ -266,20 +250,14 @@ class ormCaseLog {
// therefore we have changed the format. To preserve the compatibility with existing
// installations of iTop, both format are allowed:
// the 'date' item is either a DateTime object, or a unix timestamp
- if (is_int($aIndex[$index]['date']))
- {
+ if (is_int($aIndex[$index]['date'])) {
// Unix timestamp
$sDate = date((string)AttributeDateTime::GetFormat(), $aIndex[$index]['date']);
- }
- elseif (is_object($aIndex[$index]['date']))
- {
- if (version_compare(phpversion(), '5.3.0', '>='))
- {
+ } elseif (is_object($aIndex[$index]['date'])) {
+ if (version_compare(phpversion(), '5.3.0', '>=')) {
// DateTime
$sDate = $aIndex[$index]['date']->format((string)AttributeDateTime::GetFormat());
- }
- else
- {
+ } else {
// No Warning... but the date is unknown
$sDate = '';
}
@@ -295,7 +273,7 @@ class ormCaseLog {
// Process the case of an eventual remainder (quick migration of AttributeText fields)
if ($iPos < (utils::StrLen($this->m_sLog) - 1)) {
$sTextEntry = substr($this->m_sLog, $iPos);
- $sTextEntry = str_replace(array("\r\n", "\n", "\r"), " ", utils::EscapeHtml($sTextEntry));
+ $sTextEntry = str_replace(["\r\n", "\n", "\r"], " ", utils::EscapeHtml($sTextEntry));
if (count($this->m_aIndex) == 0) {
$sHtml .= '';
@@ -313,10 +291,10 @@ class ormCaseLog {
$sHtml .= '
';
return $sHtml;
}
-
+
/**
* Produces an HTML representation, aimed at being used to produce a PDF with TCPDF (no table)
- */
+ */
public function GetAsSimpleHtml($aTransfoHandler = null)
{
$sStyleCaseLogEntry = '';
@@ -324,13 +302,13 @@ class ormCaseLog {
$sHtml = '';
$iPos = 0;
$aIndex = $this->m_aIndex;
- for($index=count($aIndex)-1 ; $index >= 0 ; $index--) {
+ for ($index = count($aIndex) - 1 ; $index >= 0 ; $index--) {
$iPos += $aIndex[$index]['separator_length'];
$sTextEntry = substr($this->m_sLog, $iPos, $aIndex[$index]['text_length']);
$sCSSClass = 'case_log_simple_html_entry_html';
if (!array_key_exists('format', $aIndex[$index]) || ($aIndex[$index]['format'] == static::ENUM_FORMAT_TEXT)) {
$sCSSClass = 'case_log_simple_html_entry';
- $sTextEntry = str_replace(array("\r\n", "\n", "\r"), " ", utils::EscapeHtml($sTextEntry));
+ $sTextEntry = str_replace(["\r\n", "\n", "\r"], " ", utils::EscapeHtml($sTextEntry));
if (!is_null($aTransfoHandler)) {
$sTextEntry = call_user_func($aTransfoHandler, $sTextEntry);
}
@@ -339,7 +317,7 @@ class ormCaseLog {
$sTextEntry = call_user_func($aTransfoHandler, $sTextEntry, true /* wiki "links" only */);
}
$sTextEntry = InlineImage::FixUrls($sTextEntry);
- }
+ }
$iPos += $aIndex[$index]['text_length'];
$sEntry = '';
@@ -347,20 +325,14 @@ class ormCaseLog {
// therefore we have changed the format. To preserve the compatibility with existing
// installations of iTop, both format are allowed:
// the 'date' item is either a DateTime object, or a unix timestamp
- if (is_int($aIndex[$index]['date']))
- {
+ if (is_int($aIndex[$index]['date'])) {
// Unix timestamp
- $sDate = date((string)AttributeDateTime::GetFormat(),$aIndex[$index]['date']);
- }
- elseif (is_object($aIndex[$index]['date']))
- {
- if (version_compare(phpversion(), '5.3.0', '>='))
- {
+ $sDate = date((string)AttributeDateTime::GetFormat(), $aIndex[$index]['date']);
+ } elseif (is_object($aIndex[$index]['date'])) {
+ if (version_compare(phpversion(), '5.3.0', '>=')) {
// DateTime
$sDate = $aIndex[$index]['date']->format((string)AttributeDateTime::GetFormat());
- }
- else
- {
+ } else {
// No Warning... but the date is unknown
$sDate = '';
}
@@ -376,7 +348,7 @@ class ormCaseLog {
// Process the case of an eventual remainder (quick migration of AttributeText fields)
if ($iPos < (utils::StrLen($this->m_sLog) - 1)) {
$sTextEntry = substr($this->m_sLog, $iPos);
- $sTextEntry = str_replace(array("\r\n", "\n", "\r"), " ", utils::EscapeHtml($sTextEntry));
+ $sTextEntry = str_replace(["\r\n", "\n", "\r"], " ", utils::EscapeHtml($sTextEntry));
if (count($this->m_aIndex) == 0) {
$sHtml .= ' ';
@@ -397,7 +369,7 @@ class ormCaseLog {
/**
* Produces an HTML representation, aimed at being used within the iTop framework
- */
+ */
public function GetAsHTML(WebPage $oP = null, $bEditMode = false, $aTransfoHandler = null)
{
$bPrintableVersion = (utils::ReadParam('printable', '0') == '1');
@@ -405,35 +377,27 @@ class ormCaseLog {
$oBlock = UIContentBlockUIBlockFactory::MakeStandard(null, ['ibo-caselog-list']);
$iPos = 0;
$aIndex = $this->m_aIndex;
- if (($bEditMode) && (count($aIndex) > 0) && $this->m_bModified)
- {
+ if (($bEditMode) && (count($aIndex) > 0) && $this->m_bModified) {
// Don't display the first element, that is still considered as editable
$aLastEntry = end($aIndex);
$iPos = $aLastEntry['separator_length'] + $aLastEntry['text_length'];
array_pop($aIndex);
}
- for($index=count($aIndex)-1 ; $index >= 0 ; $index--)
- {
- if (!$bPrintableVersion && ($index < count($aIndex) - CASELOG_VISIBLE_ITEMS))
- {
+ for ($index = count($aIndex) - 1 ; $index >= 0 ; $index--) {
+ if (!$bPrintableVersion && ($index < count($aIndex) - CASELOG_VISIBLE_ITEMS)) {
$bIsOpen = false;
- }
- else
- {
+ } else {
$bIsOpen = true;
}
$iPos += $aIndex[$index]['separator_length'];
$sTextEntry = substr($this->m_sLog, $iPos, $aIndex[$index]['text_length']);
if (!array_key_exists('format', $aIndex[$index]) || ($aIndex[$index]['format'] == static::ENUM_FORMAT_TEXT)) {
- $sTextEntry = str_replace(array("\r\n", "\n", "\r"), " ", utils::EscapeHtml($sTextEntry));
+ $sTextEntry = str_replace(["\r\n", "\n", "\r"], " ", utils::EscapeHtml($sTextEntry));
if (!is_null($aTransfoHandler)) {
$sTextEntry = call_user_func($aTransfoHandler, $sTextEntry);
}
- }
- else
- {
- if (!is_null($aTransfoHandler))
- {
+ } else {
+ if (!is_null($aTransfoHandler)) {
$sTextEntry = call_user_func($aTransfoHandler, $sTextEntry, true /* wiki "links" only */);
}
$sTextEntry = InlineImage::FixUrls($sTextEntry);
@@ -444,25 +408,19 @@ class ormCaseLog {
// therefore we have changed the format. To preserve the compatibility with existing
// installations of iTop, both format are allowed:
// the 'date' item is either a DateTime object, or a unix timestamp
- if (is_int($aIndex[$index]['date']))
- {
+ if (is_int($aIndex[$index]['date'])) {
// Unix timestamp
- $sDate = date((string)AttributeDateTime::GetFormat(),$aIndex[$index]['date']);
- }
- elseif (is_object($aIndex[$index]['date']))
- {
- if (version_compare(phpversion(), '5.3.0', '>='))
- {
+ $sDate = date((string)AttributeDateTime::GetFormat(), $aIndex[$index]['date']);
+ } elseif (is_object($aIndex[$index]['date'])) {
+ if (version_compare(phpversion(), '5.3.0', '>=')) {
// DateTime
$sDate = $aIndex[$index]['date']->format((string)AttributeDateTime::GetFormat());
- }
- else
- {
+ } else {
// No Warning... but the date is unknown
$sDate = '';
}
}
- $oCollapsibleBlock = CollapsibleSectionUIBlockFactory::MakeStandard( sprintf(Dict::S('UI:CaseLog:Header_Date_UserName'), $sDate, $aIndex[$index]['user_name']));
+ $oCollapsibleBlock = CollapsibleSectionUIBlockFactory::MakeStandard(sprintf(Dict::S('UI:CaseLog:Header_Date_UserName'), $sDate, $aIndex[$index]['user_name']));
$oCollapsibleBlock->AddSubBlock(new Html($sTextEntry));
$oCollapsibleBlock->SetOpenedByDefault($bIsOpen);
$oBlock->AddSubBlock($oCollapsibleBlock);
@@ -471,7 +429,7 @@ class ormCaseLog {
if ($iPos < (utils::StrLen($this->m_sLog) - 1)) {
// In this case the format is always "text"
$sTextEntry = substr($this->m_sLog, $iPos);
- $sTextEntry = str_replace(array("\r\n", "\n", "\r"), " ", utils::EscapeHtml($sTextEntry));
+ $sTextEntry = str_replace(["\r\n", "\n", "\r"], " ", utils::EscapeHtml($sTextEntry));
if (!is_null($aTransfoHandler)) {
$sTextEntry = call_user_func($aTransfoHandler, $sTextEntry);
}
@@ -481,27 +439,22 @@ class ormCaseLog {
$oCollapsibleBlock->AddSubBlock(new Html($sTextEntry));
$oCollapsibleBlock->SetOpenedByDefault(true);
$oBlock->AddSubBlock($oCollapsibleBlock);
- }
- else
- {
- if (!$bPrintableVersion && (count($this->m_aIndex) - CASELOG_VISIBLE_ITEMS > 0))
- {
+ } else {
+ if (!$bPrintableVersion && (count($this->m_aIndex) - CASELOG_VISIBLE_ITEMS > 0)) {
$bIsOpen = false;
- }
- else
- {
+ } else {
$bIsOpen = true;
}
- $oCollapsibleBlock = CollapsibleSectionUIBlockFactory::MakeStandard( Dict::S('UI:CaseLog:InitialValue'));
+ $oCollapsibleBlock = CollapsibleSectionUIBlockFactory::MakeStandard(Dict::S('UI:CaseLog:InitialValue'));
$oCollapsibleBlock->AddSubBlock(new Html($sTextEntry));
$oCollapsibleBlock->SetOpenedByDefault($bIsOpen);
}
}
$oBlockRenderer = new BlockRenderer($oBlock);
$sHtml = $oBlockRenderer->RenderHtml();
- $sScript = $oBlockRenderer->RenderJsInlineRecursively($oBlock,iUIBlock::ENUM_JS_TYPE_ON_READY);
+ $sScript = $oBlockRenderer->RenderJsInlineRecursively($oBlock, iUIBlock::ENUM_JS_TYPE_ON_READY);
$aJsFiles = $oBlockRenderer->GetJsFiles();
- if ($sScript!=''){
+ if ($sScript != '') {
if ($oP == null) {
$sScript = '';
$sHtml .= $sScript;
@@ -510,7 +463,7 @@ class ormCaseLog {
}
}
// Ugly hack as we use a block and strip its content above, we'll also need JS files it depends on
- if(count($aJsFiles) > 0){
+ if (count($aJsFiles) > 0) {
foreach ($aJsFiles as $sFileAbsUrl) {
if ($oP === null) {
$sScript = '';
@@ -520,7 +473,7 @@ class ormCaseLog {
}
}
}
-
+
return $sHtml;
}
@@ -535,7 +488,7 @@ class ormCaseLog {
* @throws \ArchivedObjectException
* @throws \CoreException
* @throws \OQLException
- *
+ *
* @since 3.0.0 New $iOnBehalfOfId parameter
* @since 3.0.0 May throw \ArchivedObjectException exception
*/
@@ -546,24 +499,19 @@ class ormCaseLog {
if ($sOnBehalfOf == '' && $iOnBehalfOfId === null) {
$sOnBehalfOf = UserRights::GetUserFriendlyName();
$iUserId = UserRights::GetUserId();
- }
- elseif ($iOnBehalfOfId !== null) {
+ } elseif ($iOnBehalfOfId !== null) {
$iUserId = $iOnBehalfOfId;
/* @var User $oUser */
$oUser = MetaModel::GetObject('User', $iUserId, false, true);
if ($oUser !== null && $sOnBehalfOf === '') {
$sOnBehalfOf = $oUser->GetFriendlyName();
}
- }
- else
- {
+ } else {
$iUserId = null;
}
- if ($this->m_bModified)
- {
+ if ($this->m_bModified) {
$aLatestEntry = end($this->m_aIndex);
- if ($aLatestEntry['user_name'] == $sOnBehalfOf)
- {
+ if ($aLatestEntry['user_name'] == $sOnBehalfOf) {
// Append the new text to the previous one
$sPreviousText = substr($this->m_sLog, $aLatestEntry['separator_length'], $aLatestEntry['text_length']);
$sText = $sPreviousText."\n".$sText;
@@ -578,72 +526,55 @@ class ormCaseLog {
$iSepLength = strlen($sSeparator);
$iTextlength = strlen($sText);
$this->m_sLog = $sSeparator.$sText.$this->m_sLog; // Latest entry printed first
- $this->m_aIndex[] = array(
+ $this->m_aIndex[] = [
'user_name' => $sOnBehalfOf,
'user_id' => $iUserId,
'date' => time(),
'text_length' => $iTextlength,
'separator_length' => $iSepLength,
'format' => static::ENUM_FORMAT_HTML,
- );
+ ];
$this->m_bModified = true;
}
public function AddLogEntryFromJSON($oJson, $bCheckUserId = true)
{
- if (isset($oJson->user_id))
- {
- if (!UserRights::IsAdministrator())
- {
+ if (isset($oJson->user_id)) {
+ if (!UserRights::IsAdministrator()) {
throw new Exception("Only administrators can set the user id", RestResult::UNAUTHORIZED);
}
- if ($bCheckUserId && ($oJson->user_id != 0))
- {
- try
- {
+ if ($bCheckUserId && ($oJson->user_id != 0)) {
+ try {
$oUser = RestUtils::FindObjectFromKey('User', $oJson->user_id);
- }
- catch(Exception $e)
- {
+ } catch (Exception $e) {
throw new Exception('user_id: '.$e->getMessage(), $e->getCode());
}
$iUserId = $oUser->GetKey();
$sOnBehalfOf = $oUser->GetFriendlyName();
- }
- else
- {
+ } else {
$iUserId = $oJson->user_id;
$sOnBehalfOf = $oJson->user_login;
}
- }
- else
- {
+ } else {
$iUserId = UserRights::GetUserId();
$sOnBehalfOf = UserRights::GetUserFriendlyName();
}
-
- if (isset($oJson->date))
- {
+
+ if (isset($oJson->date)) {
$oDate = new DateTime($oJson->date);
$iDate = (int) $oDate->format('U');
- }
- else
- {
+ } else {
$iDate = time();
}
- if (isset($oJson->format))
- {
+ if (isset($oJson->format)) {
$sFormat = $oJson->format;
- }
- else
- {
+ } else {
// The default is HTML
$sFormat = static::ENUM_FORMAT_HTML;
}
$sText = isset($oJson->message) ? $oJson->message : '';
- if ($sFormat == static::ENUM_FORMAT_HTML)
- {
+ if ($sFormat == static::ENUM_FORMAT_HTML) {
$sText = HTMLSanitizer::Sanitize($sText);
}
@@ -653,14 +584,14 @@ class ormCaseLog {
$iSepLength = strlen($sSeparator);
$iTextlength = strlen($sText);
$this->m_sLog = $sSeparator.$sText.$this->m_sLog; // Latest entry printed first
- $this->m_aIndex[] = array(
- 'user_name' => $sOnBehalfOf,
- 'user_id' => $iUserId,
- 'date' => $iDate,
- 'text_length' => $iTextlength,
+ $this->m_aIndex[] = [
+ 'user_name' => $sOnBehalfOf,
+ 'user_id' => $iUserId,
+ 'date' => $iDate,
+ 'text_length' => $iTextlength,
'separator_length' => $iSepLength,
'format' => $sFormat,
- );
+ ];
$this->m_bModified = true;
}
@@ -668,8 +599,7 @@ class ormCaseLog {
public function GetModifiedEntry($sFormat = self::ENUM_FORMAT_TEXT)
{
$sModifiedEntry = '';
- if ($this->m_bModified)
- {
+ if ($this->m_bModified) {
$sModifiedEntry = $this->GetLatestEntry($sFormat);
}
return $sModifiedEntry;
@@ -717,7 +647,7 @@ class ormCaseLog {
$iLast = end($aKeys); // Strict standards: the parameter passed to 'end' must be a variable since it is passed by reference
return $iLast;
}
-
+
/**
* Get the text string corresponding to the given entry in the log (zero based index, older entries first)
* @param integer $iIndex
@@ -727,8 +657,7 @@ class ormCaseLog {
{
$iPos = 0;
$index = count($this->m_aIndex) - 1;
- while($index > $iIndex)
- {
+ while ($index > $iIndex) {
$iPos += $this->m_aIndex[$index]['separator_length'];
$iPos += $this->m_aIndex[$index]['text_length'];
$index--;
diff --git a/core/ormcustomfieldsvalue.class.inc.php b/core/ormcustomfieldsvalue.class.inc.php
index ef8149fa0..d280a4179 100644
--- a/core/ormcustomfieldsvalue.class.inc.php
+++ b/core/ormcustomfieldsvalue.class.inc.php
@@ -1,4 +1,5 @@
-
/**
* Base class to hold the value managed by {@see CustomFieldsHandler} and {@see AttributeCustomFields}
*
diff --git a/core/ormdocument.class.inc.php b/core/ormdocument.class.inc.php
index 45a573096..56618dcaf 100644
--- a/core/ormdocument.class.inc.php
+++ b/core/ormdocument.class.inc.php
@@ -1,4 +1,5 @@
file($sPath);
}
@@ -144,7 +144,9 @@ class ormDocument
public function __toString()
{
- if($this->IsEmpty()) return '';
+ if ($this->IsEmpty()) {
+ return '';
+ }
return MyHelpers::beautifulstr($this->m_data, 100, true);
}
@@ -180,7 +182,7 @@ class ormDocument
return true;
}
}
-
+
public function GetMimeType()
{
return $this->m_sMimeType;
@@ -188,8 +190,7 @@ class ormDocument
public function GetMainMimeType()
{
$iSeparatorPos = strpos($this->m_sMimeType, '/');
- if ($iSeparatorPos > 0)
- {
+ if ($iSeparatorPos > 0) {
return substr($this->m_sMimeType, 0, $iSeparatorPos);
}
return $this->m_sMimeType;
@@ -267,22 +268,22 @@ class ormDocument
}
return $sResult;
}
-
+
/**
* Returns an hyperlink to display the document *inline*
* @return string
- */
+ */
public function GetDisplayLink($sClass, $Id, $sAttCode)
{
$sUrl = $this->GetDisplayURL($sClass, $Id, $sAttCode);
return "".utils::EscapeHtml($this->GetFileName())." \n";
}
-
+
/**
* Returns an hyperlink to download the document (content-disposition: attachment)
* @return string
- */
+ */
public function GetDownloadLink($sClass, $Id, $sAttCode)
{
$sUrl = $this->GetDownloadURL($sClass, $Id, $sAttCode);
@@ -298,7 +299,7 @@ class ormDocument
{
$sSignature = $this->GetSignature();
// TODO: When refactoring this with the URLMaker system, mind to also change calls in the portal (look for the "p_object_document_display" route)
- return utils::GetAbsoluteUrlAppRoot() . "pages/ajax.render.php?operation=display_document&class=$sClass&id=$Id&field=$sAttCode&s=$sSignature&cache=86400";
+ return utils::GetAbsoluteUrlAppRoot()."pages/ajax.render.php?operation=display_document&class=$sClass&id=$Id&field=$sAttCode&s=$sSignature&cache=86400";
}
/**
@@ -310,22 +311,21 @@ class ormDocument
// Compute a signature to reset the cache anytime the data changes (this is acceptable if used only with icon files)
$sSignature = $this->GetSignature();
// TODO: When refactoring this with the URLMaker system, mind to also change calls in the portal (look for the "p_object_document_display" route)
- return utils::GetAbsoluteUrlAppRoot() . "pages/ajax.document.php?operation=download_document&class=$sClass&id=$Id&field=$sAttCode&s=$sSignature&cache=86400";
+ return utils::GetAbsoluteUrlAppRoot()."pages/ajax.document.php?operation=download_document&class=$sClass&id=$Id&field=$sAttCode&s=$sSignature&cache=86400";
}
public function IsPreviewAvailable()
{
$bRet = false;
- switch($this->GetMimeType())
- {
+ switch ($this->GetMimeType()) {
case 'image/png':
case 'image/jpg':
case 'image/jpeg':
case 'image/gif':
case 'image/bmp':
case 'image/svg+xml':
- $bRet = true;
- break;
+ $bRet = true;
+ break;
}
return $bRet;
}
@@ -345,11 +345,9 @@ class ormDocument
*/
public static function DownloadDocument(WebPage $oPage, $sClass, $id, $sAttCode, $sContentDisposition = 'attachment', $sSecretField = null, $sSecretValue = null)
{
- try
- {
+ try {
$oObj = MetaModel::GetObject($sClass, $id, false, false);
- if (!is_object($oObj))
- {
+ if (!is_object($oObj)) {
// If access to the document is not granted, check if the access to the host object is allowed
$oObj = MetaModel::GetObject($sClass, $id, false, true);
if ($oObj instanceof Attachment) {
@@ -364,30 +362,28 @@ class ormDocument
throw new Exception("Invalid id ($id) for class '$sClass' - the object does not exist or you are not allowed to view it");
}
}
- if (($sSecretField != null) && ($oObj->Get($sSecretField) != $sSecretValue))
- {
+ if (($sSecretField != null) && ($oObj->Get($sSecretField) != $sSecretValue)) {
usleep(200);
throw new Exception("Invalid secret for class '$sClass' - the object does not exist or you are not allowed to view it");
}
/** @var \ormDocument $oDocument */
$oDocument = $oObj->Get($sAttCode);
- if (is_object($oDocument))
- {
- $aEventData = array(
+ if (is_object($oDocument)) {
+ $aEventData = [
'debug_info' => $oDocument->GetFileName(),
'object' => $oObj,
'att_code' => $sAttCode,
'document' => $oDocument,
'content_disposition' => $sContentDisposition,
- );
+ ];
EventService::FireEvent(new EventData(\EVENT_DOWNLOAD_DOCUMENT, $sClass, $aEventData));
$oPage->TrashUnexpectedOutput();
$oPage->SetContentType($oDocument->GetMimeType());
- $oPage->SetContentDisposition($sContentDisposition,$oDocument->GetFileName());
+ $oPage->SetContentDisposition($sContentDisposition, $oDocument->GetFileName());
$oPage->add($oDocument->GetData());
// Update downloads count only when content disposition is set to "attachment" as other disposition are to display the document within the page
- if($sContentDisposition === static::ENUM_CONTENT_DISPOSITION_ATTACHMENT) {
+ if ($sContentDisposition === static::ENUM_CONTENT_DISPOSITION_ATTACHMENT) {
$oDocument->IncreaseDownloadsCount();
$oObj->Set($sAttCode, $oDocument);
// $oObj can be a \DBObject or \cmdbAbstractObject so we ahve to protect it
@@ -398,9 +394,7 @@ class ormDocument
$oObj->DBUpdate();
}
}
- }
- catch(Exception $e)
- {
+ } catch (Exception $e) {
$oPage->p($e->getMessage());
}
}
@@ -413,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':
@@ -434,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;
}
@@ -462,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);
@@ -479,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();
@@ -508,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/ormpassword.class.inc.php b/core/ormpassword.class.inc.php
index a90780bdd..f8b4d2122 100644
--- a/core/ormpassword.class.inc.php
+++ b/core/ormpassword.class.inc.php
@@ -1,9 +1,10 @@
-
require_once(APPROOT.'/core/simplecrypt.class.inc.php');
/**
@@ -45,7 +45,7 @@ class ormPassword
//only used for <= 2.5 hashed password
$this->m_sSalt = $sSalt;
}
-
+
/**
* Encrypts the clear text password, with a unique salt
*/
@@ -68,17 +68,17 @@ class ormPassword
{
return utils::IsNullOrEmptyString($this->m_sHashed);
}
-
+
public function GetHash()
{
return $this->m_sHashed;
}
-
+
public function GetSalt()
{
return $this->m_sSalt;
}
-
+
/**
* Displays the password: displays some stars
* @return string
@@ -97,19 +97,16 @@ class ormPassword
{
$bResult = false;
$aInfo = password_get_info($this->m_sHashed);
- if (is_null($aInfo["algo"]) || $aInfo["algo"] === 0)
- {
+ if (is_null($aInfo["algo"]) || $aInfo["algo"] === 0) {
//unknown, assume it's a legacy password
$sHashedPwd = $this->ComputeHash($sClearTextPassword);
$bResult = ($this->m_sHashed == $sHashedPwd);
- }
- else
- {
+ } else {
$bResult = password_verify($sClearTextPassword, $this->m_sHashed);
}
return $bResult;
}
-
+
/**
* Computes the hashed version of a password using a unique salt
* for this password. A unique salt is generated if needed
@@ -117,11 +114,9 @@ class ormPassword
*/
protected function ComputeHash($sClearTextPwd)
{
- if ($this->m_sSalt == null)
- {
+ if ($this->m_sSalt == null) {
$this->m_sSalt = SimpleCrypt::GetNewSalt();
}
return hash('sha256', $this->m_sSalt.$sClearTextPwd);
}
}
-?>
diff --git a/core/ormset.class.inc.php b/core/ormset.class.inc.php
index 139207c78..4667f51c2 100644
--- a/core/ormset.class.inc.php
+++ b/core/ormset.class.inc.php
@@ -1,4 +1,5 @@
GetValues();
- if (!empty($aValue))
- {
+ if (!empty($aValue)) {
return implode(', ', $aValue);
- }
- else
- {
+ } else {
return ' ';
}
}
@@ -86,8 +84,7 @@ class ormSet
$this->sAttCode = $sAttCode;
$oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
- if (!$oAttDef instanceof AttributeSet)
- {
+ if (!$oAttDef instanceof AttributeSet) {
throw new Exception("ormSet: field {$sClass}:{$sAttCode} is not a set");
}
$this->sClass = $sClass;
@@ -119,19 +116,16 @@ class ormSet
*/
public function SetValues($aItems)
{
- if (!is_array($aItems))
- {
+ if (!is_array($aItems)) {
throw new CoreUnexpectedValue("Wrong value {$aItems} for {$this->sClass}:{$this->sAttCode}");
}
- $aValues = array();
+ $aValues = [];
$iCount = 0;
$bError = false;
- foreach($aItems as $sItem)
- {
+ foreach ($aItems as $sItem) {
$iCount++;
- if (($this->iLimit != 0) && ($iCount > $this->iLimit))
- {
+ if (($this->iLimit != 0) && ($iCount > $this->iLimit)) {
$bError = true;
continue;
}
@@ -139,13 +133,12 @@ class ormSet
}
$this->aPreserved = &$aValues;
- $this->aRemoved = array();
- $this->aAdded = array();
- $this->aModified = array();
+ $this->aRemoved = [];
+ $this->aAdded = [];
+ $this->aModified = [];
$this->aOriginalObjects = $aValues;
- if ($bError)
- {
+ if ($bError) {
throw new CoreException("Maximum number of items ({$this->iLimit}) reached for {$this->sClass}:{$this->sAttCode}");
}
}
@@ -167,10 +160,9 @@ class ormSet
public function GetLabels()
{
- $aLabels = array();
+ $aLabels = [];
$aValues = $this->GetValues();
- foreach ($aValues as $sValue)
- {
+ foreach ($aValues as $sValue) {
$aLabels[$sValue] = $sValue;
}
return $aLabels;
@@ -213,18 +205,16 @@ class ormSet
$oSet->SetValues($aOrigItems);
// now remove everything
- foreach($aOrigItems as $oItem)
- {
+ foreach ($aOrigItems as $oItem) {
$oSet->Remove($oItem);
}
// now add the tags of the other ItemSet
- foreach($oOtherSet->GetValues() as $oItem)
- {
+ foreach ($oOtherSet->GetValues() as $oItem) {
$oSet->Add($oItem);
}
- $aDelta = array();
+ $aDelta = [];
$aDelta['added'] = $oSet->GetAdded();
$aDelta['removed'] = $oSet->GetRemoved();
@@ -250,17 +240,13 @@ class ormSet
*/
public function ApplyDelta($aDelta)
{
- if (isset($aDelta['removed']))
- {
- foreach($aDelta['removed'] as $oItem)
- {
+ if (isset($aDelta['removed'])) {
+ foreach ($aDelta['removed'] as $oItem) {
$this->Remove($oItem);
}
}
- if (isset($aDelta['added']))
- {
- foreach($aDelta['added'] as $oItem)
- {
+ if (isset($aDelta['added'])) {
+ foreach ($aDelta['added'] as $oItem) {
$this->Add($oItem);
}
}
@@ -276,24 +262,19 @@ class ormSet
*/
public function Add($oItem)
{
- if (($this->iLimit != 0) && ($this->Count() > $this->iLimit))
- {
+ if (($this->iLimit != 0) && ($this->Count() > $this->iLimit)) {
throw new CoreException("Maximum number of items ({$this->iLimit}) reached for {$this->sClass}:{$this->sAttCode}");
}
- if ($this->IsItemInList($this->aPreserved, $oItem) || $this->IsItemInList($this->aAdded, $oItem))
- {
+ if ($this->IsItemInList($this->aPreserved, $oItem) || $this->IsItemInList($this->aAdded, $oItem)) {
// nothing to do, already existing tag
return;
}
// if removed and added again
- if (($this->RemoveItemFromList($this->aRemoved, $oItem)) !== false)
- {
+ if (($this->RemoveItemFromList($this->aRemoved, $oItem)) !== false) {
// put it back into preserved
$this->aPreserved[] = $oItem;
// no need to add it to aModified : was already done when calling RemoveItem method
- }
- else
- {
+ } else {
$this->aAdded[] = $oItem;
$this->aModified[] = $oItem;
}
@@ -304,21 +285,18 @@ class ormSet
*/
public function Remove($oItem)
{
- if ($this->IsItemInList($this->aRemoved, $oItem))
- {
+ if ($this->IsItemInList($this->aRemoved, $oItem)) {
// nothing to do, already removed tag
return;
}
- if ($this->RemoveItemFromList($this->aAdded, $oItem) !== false)
- {
+ if ($this->RemoveItemFromList($this->aAdded, $oItem) !== false) {
$this->aModified[] = $oItem;
return; // if present in added, can't be in preserved !
}
- if ($this->RemoveItemFromList($this->aPreserved, $oItem) !== false)
- {
+ if ($this->RemoveItemFromList($this->aPreserved, $oItem) !== false) {
$this->aModified[] = $oItem;
$this->aRemoved[] = $oItem;
}
@@ -337,14 +315,11 @@ class ormSet
*/
private function RemoveItemFromList(&$aItemList, $oItem)
{
- if (!($this->IsItemInList($aItemList, $oItem)))
- {
+ if (!($this->IsItemInList($aItemList, $oItem))) {
return false;
}
- foreach ($aItemList as $index => $value)
- {
- if ($value === $oItem)
- {
+ foreach ($aItemList as $index => $value) {
+ if ($value === $oItem) {
unset($aItemList[$index]);
return $oItem;
}
@@ -362,16 +337,13 @@ class ormSet
*/
public function GenerateDiffFromArray($aItems)
{
- foreach($this->GetValues() as $oCurrentItem)
- {
- if (!in_array($oCurrentItem, $aItems))
- {
+ foreach ($this->GetValues() as $oCurrentItem) {
+ if (!in_array($oCurrentItem, $aItems)) {
$this->Remove($oCurrentItem);
}
}
- foreach($aItems as $oNewItem)
- {
+ foreach ($aItems as $oNewItem) {
$this->Add($oNewItem);
}
}
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/ormtagset.class.inc.php b/core/ormtagset.class.inc.php
index 2f11a9fef..1af654905 100644
--- a/core/ormtagset.class.inc.php
+++ b/core/ormtagset.class.inc.php
@@ -1,4 +1,5 @@
sClass}:{$this->sAttCode}");
}
- $oTags = array();
+ $oTags = [];
$iCount = 0;
$bError = false;
- foreach($aTagCodes as $sTagCode)
- {
+ foreach ($aTagCodes as $sTagCode) {
$iCount++;
- if (($this->iLimit != 0) && ($iCount > $this->iLimit))
- {
+ if (($this->iLimit != 0) && ($iCount > $this->iLimit)) {
$bError = true;
continue;
}
@@ -74,13 +71,12 @@ final class ormTagSet extends ormSet
}
$this->aPreserved = &$oTags;
- $this->aRemoved = array();
- $this->aAdded = array();
- $this->aModified = array();
+ $this->aRemoved = [];
+ $this->aAdded = [];
+ $this->aModified = [];
$this->aOriginalObjects = $oTags;
- if ($bError)
- {
+ if ($bError) {
throw new CoreException("Maximum number of tags ({$this->iLimit}) reached for {$this->sClass}:{$this->sAttCode}");
}
}
@@ -90,13 +86,11 @@ final class ormTagSet extends ormSet
*/
public function GetValues()
{
- $aValues = array();
- foreach($this->aPreserved as $sTagCode => $oTag)
- {
+ $aValues = [];
+ foreach ($this->aPreserved as $sTagCode => $oTag) {
$aValues[] = $sTagCode;
}
- foreach($this->aAdded as $sTagCode => $oTag)
- {
+ foreach ($this->aAdded as $sTagCode => $oTag) {
$aValues[] = $sTagCode;
}
@@ -110,25 +104,19 @@ final class ormTagSet extends ormSet
*/
public function GetLabels()
{
- $aTags = array();
+ $aTags = [];
/** @var \TagSetFieldData $oTag */
- foreach($this->aPreserved as $sTagCode => $oTag)
- {
- try
- {
+ foreach ($this->aPreserved as $sTagCode => $oTag) {
+ try {
$aTags[$sTagCode] = $oTag->Get('label');
- } catch (CoreException $e)
- {
+ } catch (CoreException $e) {
IssueLog::Error($e->getMessage());
}
}
- foreach($this->aAdded as $sTagCode => $oTag)
- {
- try
- {
+ foreach ($this->aAdded as $sTagCode => $oTag) {
+ try {
$aTags[$sTagCode] = $oTag->Get('label');
- } catch (CoreException $e)
- {
+ } catch (CoreException $e) {
IssueLog::Error($e->getMessage());
}
}
@@ -142,13 +130,11 @@ final class ormTagSet extends ormSet
*/
public function GetTags()
{
- $aTags = array();
- foreach($this->aPreserved as $sTagCode => $oTag)
- {
+ $aTags = [];
+ foreach ($this->aPreserved as $sTagCode => $oTag) {
$aTags[$sTagCode] = $oTag;
}
- foreach($this->aAdded as $sTagCode => $oTag)
- {
+ foreach ($this->aAdded as $sTagCode => $oTag) {
$aTags[$sTagCode] = $oTag;
}
ksort($aTags);
@@ -161,9 +147,8 @@ final class ormTagSet extends ormSet
*/
private function GetAddedCodes()
{
- $aTags = array();
- foreach($this->aAdded as $sTagCode => $oTag)
- {
+ $aTags = [];
+ foreach ($this->aAdded as $sTagCode => $oTag) {
$aTags[] = $sTagCode;
}
ksort($aTags);
@@ -176,9 +161,8 @@ final class ormTagSet extends ormSet
*/
private function GetRemovedCodes()
{
- $aTags = array();
- foreach($this->aRemoved as $sTagCode => $oTag)
- {
+ $aTags = [];
+ foreach ($this->aRemoved as $sTagCode => $oTag) {
$aTags[] = $sTagCode;
}
ksort($aTags);
@@ -191,9 +175,8 @@ final class ormTagSet extends ormSet
*/
private function GetAddedTags()
{
- $aTags = array();
- foreach($this->aAdded as $sTagCode => $oTag)
- {
+ $aTags = [];
+ foreach ($this->aAdded as $sTagCode => $oTag) {
$aTags[$sTagCode] = $oTag;
}
ksort($aTags);
@@ -206,9 +189,8 @@ final class ormTagSet extends ormSet
*/
private function GetRemovedTags()
{
- $aTags = array();
- foreach($this->aRemoved as $sTagCode => $oTag)
- {
+ $aTags = [];
+ foreach ($this->aRemoved as $sTagCode => $oTag) {
$aTags[$sTagCode] = $oTag;
}
ksort($aTags);
@@ -236,16 +218,14 @@ final class ormTagSet extends ormSet
$aOrigTagCodes = $this->GetValues();
$oTag->SetValues($aOrigTagCodes);
// now remove everything
- foreach($aOrigTagCodes as $sTagCode)
- {
+ foreach ($aOrigTagCodes as $sTagCode) {
$oTag->Remove($sTagCode);
}
// now add the tags of the other TagSet
- foreach($oOtherTagSet->GetValues() as $sTagCode)
- {
+ foreach ($oOtherTagSet->GetValues() as $sTagCode) {
$oTag->Add($sTagCode);
}
- $aDelta = array();
+ $aDelta = [];
$aDelta['added'] = $oTag->GetAddedCodes();
$aDelta['removed'] = $oTag->GetRemovedCodes();
@@ -272,16 +252,14 @@ final class ormTagSet extends ormSet
$aOrigTagCodes = $this->GetValues();
$oTag->SetValues($aOrigTagCodes);
// now remove everything
- foreach($aOrigTagCodes as $sTagCode)
- {
+ foreach ($aOrigTagCodes as $sTagCode) {
$oTag->Remove($sTagCode);
}
// now add the tags of the other TagSet
- foreach($oOtherTagSet->GetValues() as $sTagCode)
- {
+ foreach ($oOtherTagSet->GetValues() as $sTagCode) {
$oTag->Add($sTagCode);
}
- $aDelta = array();
+ $aDelta = [];
$aDelta['added'] = $oTag->GetAddedTags();
$aDelta['removed'] = $oTag->GetRemovedTags();
@@ -332,17 +310,13 @@ final class ormTagSet extends ormSet
*/
public function ApplyDelta($aDelta)
{
- if (isset($aDelta['removed']))
- {
- foreach($aDelta['removed'] as $oItem)
- {
+ if (isset($aDelta['removed'])) {
+ foreach ($aDelta['removed'] as $oItem) {
$this->Remove($oItem);
}
}
- if (isset($aDelta['added']))
- {
- foreach($aDelta['added'] as $oItem)
- {
+ if (isset($aDelta['added'])) {
+ foreach ($aDelta['added'] as $oItem) {
$this->Add($oItem);
}
}
@@ -357,22 +331,19 @@ final class ormTagSet extends ormSet
*/
public function GenerateDiffFromArray($aItems)
{
- foreach($this->GetValues() as $oCurrentItem)
- {
- if (!in_array($oCurrentItem, $aItems))
- {
+ foreach ($this->GetValues() as $oCurrentItem) {
+ if (!in_array($oCurrentItem, $aItems)) {
$this->Remove($oCurrentItem);
}
}
- foreach($aItems as $oNewItem)
- {
+ foreach ($aItems as $oNewItem) {
$this->Add($oNewItem);
}
// Keep only the aModified list
- $this->aRemoved = array();
- $this->aAdded = array();
+ $this->aRemoved = [];
+ $this->aAdded = [];
}
/**
@@ -384,13 +355,11 @@ final class ormTagSet extends ormSet
*/
public function IsValidTag($sTagCode)
{
- try
- {
+ try {
$this->GetTagFromCode($sTagCode);
return true;
- } catch (Exception $e)
- {
+ } catch (Exception $e) {
return false;
}
}
@@ -403,24 +372,19 @@ final class ormTagSet extends ormSet
*/
public function Add($sTagCode)
{
- if (($this->iLimit != 0) && ($this->Count() == $this->iLimit))
- {
+ if (($this->iLimit != 0) && ($this->Count() == $this->iLimit)) {
throw new CoreException("Maximum number of tags ({$this->iLimit}) reached for {$this->sClass}:{$this->sAttCode}");
}
- if ($this->IsTagInList($this->aPreserved, $sTagCode) || $this->IsTagInList($this->aAdded, $sTagCode))
- {
+ if ($this->IsTagInList($this->aPreserved, $sTagCode) || $this->IsTagInList($this->aAdded, $sTagCode)) {
// nothing to do, already existing tag
return;
}
// if removed then added again
- if (($oTag = $this->RemoveTagFromList($this->aRemoved, $sTagCode)) !== false)
- {
+ if (($oTag = $this->RemoveTagFromList($this->aRemoved, $sTagCode)) !== false) {
// put it back into preserved
$this->aPreserved[$sTagCode] = $oTag;
// no need to add it to aModified : was already done when calling Remove method
- }
- else
- {
+ } else {
$oTag = $this->GetTagFromCode($sTagCode);
$this->aAdded[$sTagCode] = $oTag;
$this->aModified[$sTagCode] = $oTag;
@@ -432,23 +396,20 @@ final class ormTagSet extends ormSet
*/
public function Remove($sTagCode)
{
- if ($this->IsTagInList($this->aRemoved, $sTagCode))
- {
+ if ($this->IsTagInList($this->aRemoved, $sTagCode)) {
// nothing to do, already removed tag
return;
}
$oTag = $this->RemoveTagFromList($this->aAdded, $sTagCode);
- if ($oTag !== false)
- {
+ if ($oTag !== false) {
$this->aModified[$sTagCode] = $oTag;
return; // if present in added, can't be in preserved !
}
$oTag = $this->RemoveTagFromList($this->aPreserved, $sTagCode);
- if ($oTag !== false)
- {
+ if ($oTag !== false) {
$this->aModified[$sTagCode] = $oTag;
$this->aRemoved[$sTagCode] = $oTag;
}
@@ -467,8 +428,7 @@ final class ormTagSet extends ormSet
*/
private function RemoveTagFromList(&$aTagList, $sTagCode)
{
- if (!($this->IsTagInList($aTagList, $sTagCode)))
- {
+ if (!($this->IsTagInList($aTagList, $sTagCode))) {
return false;
}
@@ -488,10 +448,8 @@ final class ormTagSet extends ormSet
private function GetTagFromCode($sTagCode)
{
$aAllowedTags = $this->GetAllowedTags();
- foreach($aAllowedTags as $oAllowedTag)
- {
- if ($oAllowedTag->Get('code') === $sTagCode)
- {
+ foreach ($aAllowedTags as $oAllowedTag) {
+ if ($oAllowedTag->Get('code') === $sTagCode) {
return $oAllowedTag;
}
}
@@ -508,10 +466,8 @@ final class ormTagSet extends ormSet
public function GetTagFromLabel($sTagLabel)
{
$aAllowedTags = $this->GetAllowedTags();
- foreach($aAllowedTags as $oAllowedTag)
- {
- if ($oAllowedTag->Get('label') === $sTagLabel)
- {
+ foreach ($aAllowedTags as $oAllowedTag) {
+ if ($oAllowedTag->Get('label') === $sTagLabel) {
return $oAllowedTag->Get('code');
}
}
@@ -538,12 +494,10 @@ final class ormTagSet extends ormSet
*/
public function Equals(ormSet $other)
{
- if (!($other instanceof ormTagSet))
- {
+ if (!($other instanceof ormTagSet)) {
return false;
}
- if ($this->GetTagDataClass() !== $other->GetTagDataClass())
- {
+ if ($this->GetTagDataClass() !== $other->GetTagDataClass()) {
return false;
}
diff --git a/core/ownershiplock.class.inc.php b/core/ownershiplock.class.inc.php
index b9d4c751b..a72131adc 100644
--- a/core/ownershiplock.class.inc.php
+++ b/core/ownershiplock.class.inc.php
@@ -1,4 +1,5 @@
'',
'key_type' => 'autoincrement',
- 'name_attcode' => array('obj_class', 'obj_key'),
+ 'name_attcode' => ['obj_class', 'obj_key'],
'state_attcode' => '',
- 'reconc_keys' => array(''),
+ 'reconc_keys' => [''],
'db_table' => 'priv_ownership_token',
'db_key_field' => 'id',
'db_finalclass_field' => '',
- );
+ ];
MetaModel::Init_Params($aParams);
MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeDateTime("acquired", array("allowed_values"=>null, "sql"=>'acquired', "default_value"=>'NOW()', "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeDateTime("last_seen", array("allowed_values"=>null, "sql"=>'last_seen', "default_value"=>'NOW()', "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeString("obj_class", array("allowed_values"=>null, "sql"=>'obj_class', "default_value"=>'', "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeInteger("obj_key", array("allowed_values"=>null, "sql"=>'obj_key', "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeString("token", array("allowed_values"=>null, "sql"=>'token', "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeExternalKey("user_id", array("targetclass"=>"User", "jointype"=> '', "allowed_values"=>null, "sql"=>"user_id", "is_null_allowed"=>true, "on_target_delete"=>DEL_SILENT, "depends_on"=>array())));
+ MetaModel::Init_AddAttribute(new AttributeDateTime("acquired", ["allowed_values" => null, "sql" => 'acquired', "default_value" => 'NOW()', "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeDateTime("last_seen", ["allowed_values" => null, "sql" => 'last_seen', "default_value" => 'NOW()', "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeString("obj_class", ["allowed_values" => null, "sql" => 'obj_class', "default_value" => '', "is_null_allowed" => false, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeInteger("obj_key", ["allowed_values" => null, "sql" => 'obj_key', "default_value" => '', "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeString("token", ["allowed_values" => null, "sql" => 'token', "default_value" => '', "is_null_allowed" => true, "depends_on" => []]));
+ MetaModel::Init_AddAttribute(new AttributeExternalKey("user_id", ["targetclass" => "User", "jointype" => '', "allowed_values" => null, "sql" => "user_id", "is_null_allowed" => true, "on_target_delete" => DEL_SILENT, "depends_on" => []]));
- MetaModel::Init_SetZListItems('details', array ('obj_class', 'obj_key', 'last_seen', 'token'));
- MetaModel::Init_SetZListItems('standard_search', array ('obj_class', 'obj_key', 'last_seen', 'token'));
- MetaModel::Init_SetZListItems('list', array ('obj_class', 'obj_key', 'last_seen', 'token'));
+ MetaModel::Init_SetZListItems('details', ['obj_class', 'obj_key', 'last_seen', 'token']);
+ MetaModel::Init_SetZListItems('standard_search', ['obj_class', 'obj_key', 'last_seen', 'token']);
+ MetaModel::Init_SetZListItems('list', ['obj_class', 'obj_key', 'last_seen', 'token']);
}
}
@@ -67,7 +68,7 @@ class iTopOwnershipLock
protected $sObjClass;
protected $iObjKey;
protected $oToken;
-
+
/**
* Acquires an exclusive lock on the specified DBObject. Once acquired, the lock is identified
* by a unique "token" string.
@@ -78,15 +79,15 @@ class iTopOwnershipLock
public static function AcquireLock($sObjClass, $iObjKey)
{
$oMutex = new iTopMutex('lock_'.$sObjClass.'::'.$iObjKey);
-
+
$oMutex->Lock();
$oOwnershipLock = new iTopOwnershipLock($sObjClass, $iObjKey);
$token = $oOwnershipLock->Acquire();
$oMutex->Unlock();
-
- return array('success' => $token !== false, 'token' => $token, 'lock' => $oOwnershipLock, 'acquired' => $oOwnershipLock->oToken->Get('acquired'));
+
+ return ['success' => $token !== false, 'token' => $token, 'lock' => $oOwnershipLock, 'acquired' => $oOwnershipLock->oToken->Get('acquired')];
}
-
+
/**
* Extends the ownership lock or acquires it if none exists
* Returns a hash array with 3 elements:
@@ -99,18 +100,18 @@ class iTopOwnershipLock
public static function ExtendLock($sObjClass, $iObjKey, $sToken)
{
$oMutex = new iTopMutex('lock_'.$sObjClass.'::'.$iObjKey);
-
+
$oMutex->Lock();
$oOwnershipLock = new iTopOwnershipLock($sObjClass, $iObjKey);
$aResult = $oOwnershipLock->Extend($sToken);
$oMutex->Unlock();
-
+
return $aResult;
}
/**
* Releases the given lock for the specified object
- *
+ *
* @param string $sObjClass The class of the object
* @param int $iObjKey The identifier of the object
* @param string $sToken The string identifying the lock
@@ -119,13 +120,13 @@ class iTopOwnershipLock
public static function ReleaseLock($sObjClass, $iObjKey, $sToken)
{
$oMutex = new iTopMutex('lock_'.$sObjClass.'::'.$iObjKey);
-
+
$oMutex->Lock();
$oOwnershipLock = new iTopOwnershipLock($sObjClass, $iObjKey);
$bResult = $oOwnershipLock->Release($sToken);
self::DeleteExpiredLocks(); // Cleanup orphan locks
$oMutex->Unlock();
-
+
return $bResult;
}
@@ -139,17 +140,16 @@ class iTopOwnershipLock
public static function KillLock($sObjClass, $iObjKey)
{
$oMutex = new iTopMutex('lock_'.$sObjClass.'::'.$iObjKey);
-
+
$oMutex->Lock();
$sOQL = "SELECT iTopOwnershipToken WHERE obj_class = :obj_class AND obj_key = :obj_key";
- $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL, array('obj_class' => $sObjClass, 'obj_key' => $iObjKey)));
- while($oLock = $oSet->Fetch())
- {
+ $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL, ['obj_class' => $sObjClass, 'obj_key' => $iObjKey]));
+ while ($oLock = $oSet->Fetch()) {
$oLock->DBDelete();
}
$oMutex->Unlock();
}
-
+
/**
* Checks if an exclusive lock exists on the specified DBObject.
* @param string $sObjClass The class of the object for which to acquire the lock
@@ -160,26 +160,24 @@ class iTopOwnershipLock
{
$bLocked = false;
$oMutex = new iTopMutex('lock_'.$sObjClass.'::'.$iObjKey);
-
+
$oMutex->Lock();
$oOwnershipLock = new iTopOwnershipLock($sObjClass, $iObjKey);
- if ($oOwnershipLock->IsOwned())
- {
+ if ($oOwnershipLock->IsOwned()) {
$bLocked = true;
}
$oMutex->Unlock();
-
- return array('locked' =>$bLocked, 'owner' => $oOwnershipLock->GetOwner());
+
+ return ['locked' => $bLocked, 'owner' => $oOwnershipLock->GetOwner()];
}
-
+
/**
* Get the current owner of the lock
* @return User
*/
public function GetOwner()
{
- if ($this->IsTokenValid())
- {
+ if ($this->IsTokenValid()) {
return MetaModel::GetObject('User', $this->oToken->Get('user_id'), false, true);
}
return null;
@@ -194,33 +192,30 @@ class iTopOwnershipLock
protected function __construct($sObjClass, $iObjKey)
{
$sOQL = "SELECT iTopOwnershipToken WHERE obj_class = :obj_class AND obj_key = :obj_key";
- $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL, array('obj_class' => $sObjClass, 'obj_key' => $iObjKey)));
+ $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL, ['obj_class' => $sObjClass, 'obj_key' => $iObjKey]));
$this->oToken = $oSet->Fetch();
$this->sObjClass = $sObjClass;
$this->iObjKey = $iObjKey;
// IssueLog::Info("iTopOwnershipLock::__construct($sObjClass, $iObjKey) oToken::".($this->oToken ? $this->oToken->GetKey() : 'null'));
}
-
+
protected function IsOwned()
{
return $this->IsTokenValid();
}
-
+
protected function Acquire($sToken = null)
{
- if ($this->IsTokenValid())
- {
+ if ($this->IsTokenValid()) {
// IssueLog::Info("Acquire($sToken) returns false");
return false;
- }
- else
- {
+ } else {
$sToken = $this->TakeOwnership($sToken);
// IssueLog::Info("Acquire($sToken) returns $sToken");
return $sToken;
}
}
-
+
/**
* Extends the ownership lock or acquires it if none exists
* Returns a hash array with 3 elements:
@@ -233,96 +228,79 @@ class iTopOwnershipLock
*/
protected function Extend($sToken)
{
- $aResult = array('status' => true, 'owner' => '', 'operation' => 'renewed');
-
- if ($this->IsTokenValid())
- {
- if ($sToken === $this->oToken->Get('token'))
- {
+ $aResult = ['status' => true, 'owner' => '', 'operation' => 'renewed'];
+
+ if ($this->IsTokenValid()) {
+ if ($sToken === $this->oToken->Get('token')) {
$this->oToken->Set('last_seen', date(AttributeDateTime::GetSQLFormat()));
$this->oToken->DBUpdate();
$aResult['acquired'] = $this->oToken->Get('acquired');
- }
- else
- {
+ } else {
// IssueLog::Info("Extend($sToken) returns false");
$aResult['status'] = false;
$aResult['operation'] = 'lost';
$aResult['owner'] = $this->GetOwner();
$aResult['acquired'] = $this->oToken->Get('acquired');
}
- }
- else
- {
+ } else {
$aResult['status'] = false;
$aResult['operation'] = 'expired';
}
// IssueLog::Info("Extend($sToken) returns true");
return $aResult;
}
-
+
protected function HasOwnership($sToken)
{
$bRet = false;
- if ($this->IsTokenValid())
- {
- if ($sToken === $this->oToken->Get('token'))
- {
+ if ($this->IsTokenValid()) {
+ if ($sToken === $this->oToken->Get('token')) {
$bRet = true;
}
}
// IssueLog::Info("HasOwnership($sToken) return $bRet");
return $bRet;
}
-
+
protected function Release($sToken)
{
$bRet = false;
// IssueLog::Info("Release... begin [$sToken]");
- if (($this->oToken) && ($sToken === $this->oToken->Get('token')))
- {
+ if (($this->oToken) && ($sToken === $this->oToken->Get('token'))) {
// IssueLog::Info("oToken::".$this->oToken->GetKey().' ('.$sToken.') to be deleted');
$this->oToken->DBDelete();
// IssueLog::Info("oToken deleted");
$this->oToken = null;
$bRet = true;
- }
- else if ($this->oToken == null)
- {
- // IssueLog::Info("Release FAILED oToken == null !!!");
- }
- else
- {
- // IssueLog::Info("Release FAILED inconsistent tokens: sToken=\"".$sToken.'", oToken->Get(\'token\')="'.$this->oToken->Get('token').'"');
+ } elseif ($this->oToken == null) {
+ // IssueLog::Info("Release FAILED oToken == null !!!");
+ } else {
+ // IssueLog::Info("Release FAILED inconsistent tokens: sToken=\"".$sToken.'", oToken->Get(\'token\')="'.$this->oToken->Get('token').'"');
}
// IssueLog::Info("Release... end");
return $bRet;
}
-
+
protected function IsTokenValid()
{
$bRet = false;
- if ($this->oToken != null)
- {
+ if ($this->oToken != null) {
$sToken = $this->oToken->Get('token');
$sDate = $this->oToken->Get('last_seen');
- if (($sDate != '') && ($sToken != ''))
- {
+ if (($sDate != '') && ($sToken != '')) {
$oLastSeenTime = new DateTime($sDate);
$iNow = date('U');
- if (($iNow - $oLastSeenTime->format('U')) < MetaModel::GetConfig()->Get('concurrent_lock_expiration_delay'))
- {
+ if (($iNow - $oLastSeenTime->format('U')) < MetaModel::GetConfig()->Get('concurrent_lock_expiration_delay')) {
$bRet = true;
}
}
}
- return $bRet;
+ return $bRet;
}
-
+
protected function TakeOwnership($sToken = null)
{
- if ($this->oToken == null)
- {
+ if ($this->oToken == null) {
$this->oToken = new iTopOwnershipToken();
$this->oToken->Set('obj_class', $this->sObjClass);
$this->oToken->Set('obj_key', $this->iObjKey);
@@ -330,23 +308,21 @@ class iTopOwnershipLock
$this->oToken->Set('acquired', date(AttributeDateTime::GetSQLFormat()));
$this->oToken->Set('user_id', UserRights::GetUserId());
$this->oToken->Set('last_seen', date(AttributeDateTime::GetSQLFormat()));
- if ($sToken === null)
- {
+ if ($sToken === null) {
$sToken = sprintf('%X', microtime(true));
}
$this->oToken->Set('token', $sToken);
$this->oToken->DBWrite();
return $this->oToken->Get('token');
}
-
+
protected static function DeleteExpiredLocks()
{
$sOQL = "SELECT iTopOwnershipToken WHERE last_seen < :last_seen_limit";
- $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL, array('last_seen_limit' => date(AttributeDateTime::GetSQLFormat(), time() - MetaModel::GetConfig()->Get('concurrent_lock_expiration_delay')))));
- while($oToken = $oSet->Fetch())
- {
+ $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL, ['last_seen_limit' => date(AttributeDateTime::GetSQLFormat(), time() - MetaModel::GetConfig()->Get('concurrent_lock_expiration_delay'))]));
+ while ($oToken = $oSet->Fetch()) {
$oToken->DBDelete();
}
-
+
}
}
diff --git a/core/pdfbulkexport.class.inc.php b/core/pdfbulkexport.class.inc.php
index 64c2daed5..ed21d58c7 100644
--- a/core/pdfbulkexport.class.inc.php
+++ b/core/pdfbulkexport.class.inc.php
@@ -1,4 +1,5 @@
array('pdf_options')), parent::EnumFormParts());
+ return array_merge(['pdf_options' => ['pdf_options']], parent::EnumFormParts());
}
/**
@@ -125,33 +126,31 @@ EOF
break;
default:
- return parent:: GetFormPart($oP, $sPartId);
+ return parent::GetFormPart($oP, $sPartId);
}
}
-
public function ReadParameters()
{
parent::ReadParameters();
$this->aStatusInfo['page_size'] = utils::ReadParam('page_size', 'A4', true, 'raw_data');
$this->aStatusInfo['page_orientation'] = utils::ReadParam('page_orientation', 'L', true);
-
+
$sDateFormatRadio = utils::ReadParam('pdf_date_format_radio', '');
- switch($sDateFormatRadio)
- {
+ switch ($sDateFormatRadio) {
case 'default':
- // Export from the UI => format = same as is the UI
- $this->aStatusInfo['date_format'] = (string)AttributeDateTime::GetFormat();
- break;
-
+ // Export from the UI => format = same as is the UI
+ $this->aStatusInfo['date_format'] = (string)AttributeDateTime::GetFormat();
+ break;
+
case 'custom':
- // Custom format specified from the UI
- $this->aStatusInfo['date_format'] = utils::ReadParam('date_format', (string)AttributeDateTime::GetFormat(), true, 'raw_data');
- break;
-
+ // Custom format specified from the UI
+ $this->aStatusInfo['date_format'] = utils::ReadParam('date_format', (string)AttributeDateTime::GetFormat(), true, 'raw_data');
+ break;
+
default:
- // Export from the command line (or scripted) => default format is SQL, as in previous versions of iTop, unless specified otherwise
- $this->aStatusInfo['date_format'] = utils::ReadParam('date_format', (string)AttributeDateTime::GetSQLFormat(), true, 'raw_data');
+ // Export from the command line (or scripted) => default format is SQL, as in previous versions of iTop, unless specified otherwise
+ $this->aStatusInfo['date_format'] = utils::ReadParam('date_format', (string)AttributeDateTime::GetSQLFormat(), true, 'raw_data');
}
}
@@ -160,8 +159,7 @@ EOF
$this->aStatusInfo['tmp_file'] = $this->MakeTmpFile('data');
$sData = parent::GetHeader();
$hFile = @fopen($this->aStatusInfo['tmp_file'], 'ab');
- if ($hFile === false)
- {
+ if ($hFile === false) {
throw new Exception('PDFBulkExport: Failed to open temporary data file: "'.$this->aStatusInfo['tmp_file'].'" for writing.');
}
fwrite($hFile, $sData."\n");
@@ -180,8 +178,7 @@ EOF
AttributeDateTime::SetFormat($oPrevFormat);
AttributeDate::SetFormat($oPrevDateFormat);
$hFile = @fopen($this->aStatusInfo['tmp_file'], 'ab');
- if ($hFile === false)
- {
+ if ($hFile === false) {
throw new Exception('PDFBulkExport: Failed to open temporary data file: "'.$this->aStatusInfo['tmp_file'].'" for writing.');
}
fwrite($hFile, $sData."\n");
@@ -214,8 +211,7 @@ EOF
*/
protected function GetSampleData($oObj, $sAttCode)
{
- if ($sAttCode !== 'id')
- {
+ if ($sAttCode !== 'id') {
$oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
// As sample data will be displayed in the web browser, AttributeImage needs to be rendered with a regular HTML format, meaning its "src" looking like "data:image/png;base64,iVBORw0KGgoAAAANSUh..."
@@ -245,17 +241,12 @@ EOF
$value = $oObj->Get($sAttCode);
if ($value instanceof ormDocument) {
$oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
- if ($oAttDef instanceof AttributeImage)
- {
+ if ($oAttDef instanceof AttributeImage) {
$sRet = $this->GetAttributeImageValue($oObj, $sAttCode, static::ENUM_OUTPUT_TYPE_REAL);
- }
- else
- {
+ } else {
$sRet = parent::GetValue($oObj, $sAttCode);
}
- }
- else
- {
+ } else {
$sRet = parent::GetValue($oObj, $sAttCode);
}
}
@@ -334,7 +325,7 @@ EOF
public function GetSupportedFormats()
{
- return array('pdf' => Dict::S('Core:BulkExport:PDFFormat'));
+ return ['pdf' => Dict::S('Core:BulkExport:PDFFormat')];
}
public function GetMimeType()
diff --git a/core/plugininstanciationmanager.class.inc.php b/core/plugininstanciationmanager.class.inc.php
index b5d0ec87c..595c2804d 100644
--- a/core/plugininstanciationmanager.class.inc.php
+++ b/core/plugininstanciationmanager.class.inc.php
@@ -1,25 +1,21 @@
isInstantiable())
- {
+ if ($class->isInstantiable()) {
$newPerInstanceClasses[$sClassName] = new $sClassName();
}
}
diff --git a/core/pluginmanager.class.inc.php b/core/pluginmanager.class.inc.php
index ef41a4d8d..54c51c694 100644
--- a/core/pluginmanager.class.inc.php
+++ b/core/pluginmanager.class.inc.php
@@ -1,13 +1,12 @@
m_aExtensionClassNames = $m_aExtensionClassNames;
- if ($m_pluginInstanciationManager == null)
- {
+ if ($m_pluginInstanciationManager == null) {
$this->m_pluginInstantiationManager = new PluginInstanciationManager();
- }
- else
- {
+ } else {
$this->m_pluginInstantiationManager = $m_pluginInstanciationManager;
}
}
@@ -38,7 +34,7 @@ class PluginManager
*/
public function EnumPlugins($sInterface, $sFilterInstanceOf = null, $bCanInstantiatePlugins = true)
{
- $aPlugins = array();
+ $aPlugins = [];
if (array_key_exists($sInterface, self::$m_aExtensionClasses)) {
$aAllPlugins = self::$m_aExtensionClasses[$sInterface];
@@ -46,17 +42,14 @@ class PluginManager
return $aAllPlugins;
};
- $aPlugins = array();
+ $aPlugins = [];
foreach ($aAllPlugins as $sPluginClass => $instance) {
if ($instance instanceof $sFilterInstanceOf) {
$aPlugins[$sPluginClass] = $instance;
}
}
- }
- else
- {
- if ($bCanInstantiatePlugins && array_key_exists($sInterface, $this->m_aExtensionClassNames))
- {
+ } else {
+ if ($bCanInstantiatePlugins && array_key_exists($sInterface, $this->m_aExtensionClassNames)) {
$this->InstantiatePlugins($sInterface);
return $this->EnumPlugins($sInterface, $sFilterInstanceOf, false);
@@ -80,17 +73,12 @@ class PluginManager
public function GetPlugins($sInterface, $sClassName, $bCanInstantiatePlugins = true)
{
$oInstance = null;
- if (array_key_exists($sInterface, self::$m_aExtensionClasses))
- {
- if (array_key_exists($sClassName, self::$m_aExtensionClasses[$sInterface]))
- {
+ if (array_key_exists($sInterface, self::$m_aExtensionClasses)) {
+ if (array_key_exists($sClassName, self::$m_aExtensionClasses[$sInterface])) {
return self::$m_aExtensionClasses[$sInterface][$sClassName];
}
- }
- else
- {
- if ($bCanInstantiatePlugins && array_key_exists($sInterface, $this->m_aExtensionClassNames))
- {
+ } else {
+ if ($bCanInstantiatePlugins && array_key_exists($sInterface, $this->m_aExtensionClassNames)) {
$this->InstantiatePlugins($sInterface);
return $this->GetPlugins($sInterface, $sClassName, false);
}
diff --git a/core/querybuildercontext.class.inc.php b/core/querybuildercontext.class.inc.php
index a3c679508..d17dd0949 100644
--- a/core/querybuildercontext.class.inc.php
+++ b/core/querybuildercontext.class.inc.php
@@ -1,9 +1,10 @@
m_oQBExpressions = new QueryBuilderExpressions($oFilter, $aGroupByExpr, $aSelectExpr);
$this->m_aClassAliases = $oFilter->GetJoinedClasses();
- $this->m_aTableAliases = array();
- $this->m_aFilteredTables = array();
+ $this->m_aTableAliases = [];
+ $this->m_aFilteredTables = [];
$this->m_aModifierProperties = $aModifierProperties;
- if (is_null($aSelectedClasses))
- {
+ if (is_null($aSelectedClasses)) {
$this->m_aSelectedClasses = $oFilter->GetSelectedClasses();
- }
- else
- {
+ } else {
// For the unions, the selected classes can be upper in the hierarchy (lowest common ancestor)
$this->m_aSelectedClasses = $aSelectedClasses;
}
// Add all the attribute of interest
- foreach ($this->m_aSelectedClasses as $sClassAlias => $sClass)
- {
+ foreach ($this->m_aSelectedClasses as $sClassAlias => $sClass) {
$sTableAlias = $sClassAlias;
- if (empty($sTableAlias))
- {
+ if (empty($sTableAlias)) {
$sTableAlias = $this->GenerateClassAlias("$sClass", $sClass);
$this->m_sEmptyClassAlias = $sTableAlias;
}
// default to the whole list of attributes + the very std id/finalclass
$this->m_oQBExpressions->AddSelect($sClassAlias.'id', new FieldExpression('id', $sTableAlias));
- if (is_null($aAttToLoad) || !array_key_exists($sClassAlias, $aAttToLoad))
- {
+ if (is_null($aAttToLoad) || !array_key_exists($sClassAlias, $aAttToLoad)) {
$sSelectedClass = $this->GetSelectedClass($sClassAlias);
$aAttList = MetaModel::ListAttributeDefs($sSelectedClass);
- }
- else
- {
+ } else {
$aAttList = $aAttToLoad[$sClassAlias];
}
- foreach ($aAttList as $sAttCode => $oAttDef)
- {
- if (!$oAttDef->IsScalar())
- {
+ foreach ($aAttList as $sAttCode => $oAttDef) {
+ if (!$oAttDef->IsScalar()) {
continue;
}
$oExpression = new FieldExpression($sAttCode, $sTableAlias);
@@ -117,13 +108,10 @@ class QueryBuilderContext
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 [];
}
}
@@ -134,13 +122,10 @@ class QueryBuilderContext
public function AddFilteredTable($sTableAlias, $oCondition)
{
- if (array_key_exists($sTableAlias, $this->m_aFilteredTables))
- {
+ if (array_key_exists($sTableAlias, $this->m_aFilteredTables)) {
$this->m_aFilteredTables[$sTableAlias][] = $oCondition;
- }
- else
- {
- $this->m_aFilteredTables[$sTableAlias] = array($oCondition);
+ } else {
+ $this->m_aFilteredTables[$sTableAlias] = [$oCondition];
}
}
@@ -157,5 +142,4 @@ class QueryBuilderContext
return $this->m_sEmptyClassAlias;
}
-
}
diff --git a/core/querybuilderexpressions.class.inc.php b/core/querybuilderexpressions.class.inc.php
index c713610a8..a6e229cef 100644
--- a/core/querybuilderexpressions.class.inc.php
+++ b/core/querybuilderexpressions.class.inc.php
@@ -26,25 +26,21 @@ class QueryBuilderExpressions
public function __construct(DBObjectSearch $oSearch, $aGroupByExpr = null, $aSelectExpr = null)
{
$this->m_oConditionExpr = $oSearch->GetCriteria();
- if (!$oSearch->GetShowObsoleteData())
- {
- foreach ($oSearch->GetSelectedClasses() as $sAlias => $sClass)
- {
- if (MetaModel::IsObsoletable($sClass))
- {
+ if (!$oSearch->GetShowObsoleteData()) {
+ foreach ($oSearch->GetSelectedClasses() as $sAlias => $sClass) {
+ if (MetaModel::IsObsoletable($sClass)) {
$oNotObsolete = new BinaryExpression(new FieldExpression('obsolescence_flag', $sAlias), '=', new ScalarExpression(0));
$this->m_oConditionExpr = $this->m_oConditionExpr->LogAnd($oNotObsolete);
}
}
}
- $this->m_aSelectExpr = is_null($aSelectExpr) ? array() : $aSelectExpr;
+ $this->m_aSelectExpr = is_null($aSelectExpr) ? [] : $aSelectExpr;
$this->m_aGroupByExpr = $aGroupByExpr;
- $this->m_aJoinFields = array();
- $this->m_aJoinFields = array();
+ $this->m_aJoinFields = [];
+ $this->m_aJoinFields = [];
- $this->m_aClassIds = array();
- foreach ($oSearch->GetJoinedClasses() as $sClassAlias => $sClass)
- {
+ $this->m_aClassIds = [];
+ foreach ($oSearch->GetJoinedClasses() as $sClassAlias => $sClass) {
$this->m_aClassIds[$sClassAlias] = new FieldExpression('id', $sClassAlias);
}
}
@@ -117,13 +113,11 @@ class QueryBuilderExpressions
*/
public function GetMandatoryTables(&$aTables = null)
{
- if (is_null($aTables))
- {
- $aTables = array();
+ if (is_null($aTables)) {
+ $aTables = [];
}
- foreach ($this->m_aClassIds as $sClass => $oExpression)
- {
+ foreach ($this->m_aClassIds as $sClass => $oExpression) {
$oExpression->CollectUsedParents($aTables);
}
@@ -138,8 +132,7 @@ class QueryBuilderExpressions
public function GetUnresolvedFields($sAlias)
{
$aUnresolved = $this->GetExpectedFields($sAlias);
- foreach ($this->m_aJoinFields as $oExpression)
- {
+ foreach ($this->m_aJoinFields as $oExpression) {
$oExpression->GetUnresolvedFields($sAlias, $aUnresolved);
}
return $aUnresolved;
@@ -155,17 +148,14 @@ class QueryBuilderExpressions
*/
public function GetExpectedFields($sAlias)
{
- $aUnresolved = array();
+ $aUnresolved = [];
$this->m_oConditionExpr->GetUnresolvedFields($sAlias, $aUnresolved);
- foreach ($this->m_aSelectExpr as $sColAlias => $oExpr)
- {
+ foreach ($this->m_aSelectExpr as $sColAlias => $oExpr) {
$oExpr->GetUnresolvedFields($sAlias, $aUnresolved);
}
- if (!empty($this->m_aGroupByExpr))
- {
- foreach ($this->m_aGroupByExpr as $sColAlias => $oExpr)
- {
+ if (!empty($this->m_aGroupByExpr)) {
+ foreach ($this->m_aGroupByExpr as $sColAlias => $oExpr) {
$oExpr->GetUnresolvedFields($sAlias, $aUnresolved);
}
}
@@ -175,31 +165,24 @@ class QueryBuilderExpressions
public function Translate($aTranslationData, $bMatchAll = true, $bMarkFieldsAsResolved = true)
{
$this->m_oConditionExpr = $this->m_oConditionExpr->Translate($aTranslationData, $bMatchAll, $bMarkFieldsAsResolved);
- foreach ($this->m_aSelectExpr as $sColAlias => $oExpr)
- {
+ foreach ($this->m_aSelectExpr as $sColAlias => $oExpr) {
$this->m_aSelectExpr[$sColAlias] = $oExpr->Translate($aTranslationData, $bMatchAll, $bMarkFieldsAsResolved);
- if ($this->m_aSelectExpr[$sColAlias] instanceof FieldExpressionResolved)
- {
+ if ($this->m_aSelectExpr[$sColAlias] instanceof FieldExpressionResolved) {
// Split the field with the relevant alias
- foreach ($this->m_aSelectExpr[$sColAlias]->AdditionalExpressions() as $sSuffix => $oAdditionalExpr)
- {
+ foreach ($this->m_aSelectExpr[$sColAlias]->AdditionalExpressions() as $sSuffix => $oAdditionalExpr) {
$this->m_aSelectExpr[$sColAlias.$sSuffix] = $oAdditionalExpr->Translate($aTranslationData, $bMatchAll, $bMarkFieldsAsResolved);
}
}
}
- if ($this->m_aGroupByExpr)
- {
- foreach ($this->m_aGroupByExpr as $sColAlias => $oExpr)
- {
+ if ($this->m_aGroupByExpr) {
+ foreach ($this->m_aGroupByExpr as $sColAlias => $oExpr) {
$this->m_aGroupByExpr[$sColAlias] = $oExpr->Translate($aTranslationData, $bMatchAll, $bMarkFieldsAsResolved);
}
}
- foreach ($this->m_aJoinFields as $index => $oExpression)
- {
+ foreach ($this->m_aJoinFields as $index => $oExpression) {
$this->m_aJoinFields[$index] = $oExpression->Translate($aTranslationData, $bMatchAll, $bMarkFieldsAsResolved);
}
- foreach ($this->m_aClassIds as $sClass => $oExpression)
- {
+ foreach ($this->m_aClassIds as $sClass => $oExpression) {
$this->m_aClassIds[$sClass] = $oExpression->Translate($aTranslationData, $bMatchAll, $bMarkFieldsAsResolved);
}
}
@@ -207,20 +190,16 @@ class QueryBuilderExpressions
public function RenameParam($sOldName, $sNewName)
{
$this->m_oConditionExpr->RenameParam($sOldName, $sNewName);
- foreach ($this->m_aSelectExpr as $sColAlias => $oExpr)
- {
+ foreach ($this->m_aSelectExpr as $sColAlias => $oExpr) {
$this->m_aSelectExpr[$sColAlias] = $oExpr->RenameParam($sOldName, $sNewName);
}
- if ($this->m_aGroupByExpr)
- {
- foreach ($this->m_aGroupByExpr as $sColAlias => $oExpr)
- {
+ if ($this->m_aGroupByExpr) {
+ foreach ($this->m_aGroupByExpr as $sColAlias => $oExpr) {
$this->m_aGroupByExpr[$sColAlias] = $oExpr->RenameParam($sOldName, $sNewName);
}
}
- foreach ($this->m_aJoinFields as $index => $oExpression)
- {
+ foreach ($this->m_aJoinFields as $index => $oExpression) {
$this->m_aJoinFields[$index] = $oExpression->RenameParam($sOldName, $sNewName);
}
}
-}
\ No newline at end of file
+}
diff --git a/core/querymodifier.class.inc.php b/core/querymodifier.class.inc.php
index ab7df0f35..57fe4e79b 100644
--- a/core/querymodifier.class.inc.php
+++ b/core/querymodifier.class.inc.php
@@ -1,9 +1,10 @@
-
/**
* Interface iQueryModifier
- * Defines the API to tweak queries (e.g. translate data on the fly)
+ * Defines the API to tweak queries (e.g. translate data on the fly)
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -31,4 +31,3 @@ interface iQueryModifier
public function GetFieldExpression(QueryBuilderContext &$oBuild, $sClass, $sAttCode, $sColId, Expression $oFieldSQLExp, SQLQuery &$oSelect);
}
-?>
diff --git a/core/relationgraph.class.inc.php b/core/relationgraph.class.inc.php
index 43b82f703..246b8f360 100644
--- a/core/relationgraph.class.inc.php
+++ b/core/relationgraph.class.inc.php
@@ -1,4 +1,5 @@
-
/**
* Data structures (i.e. PHP classes) to build and use relation graphs
*
* @copyright Copyright (C) 2015-2024 Combodo SARL
* @license http://opensource.org/licenses/AGPL-3.0
- *
+ *
*/
require_once(APPROOT.'core/simplegraph.class.inc.php');
@@ -61,24 +61,17 @@ class RelationObjectNode extends GraphNode
public function GetDotAttributes($bNoLabel = false)
{
$sDot = parent::GetDotAttributes();
- if ($this->GetProperty('developped', false))
- {
+ if ($this->GetProperty('developped', false)) {
$sDot .= ',fontcolor=black';
- }
- else
- {
+ } else {
$sDot .= ',fontcolor=lightgrey';
}
- if ($this->GetProperty('source', false) || $this->GetProperty('sink', false))
- {
+ if ($this->GetProperty('source', false) || $this->GetProperty('sink', false)) {
$sDot .= ',shape=rectangle';
}
- if ($this->GetProperty('is_reached', false))
- {
+ if ($this->GetProperty('is_reached', false)) {
$sDot .= ',fillcolor="#ffdddd"';
- }
- else
- {
+ } else {
$sDot .= ',fillcolor=white';
}
return $sDot;
@@ -92,11 +85,9 @@ class RelationObjectNode extends GraphNode
*/
public function ReachDown($sProperty, $value)
{
- if (is_null($this->GetProperty($sProperty)) && ($this->GetProperty($sProperty.'_allowed') !== false))
- {
+ if (is_null($this->GetProperty($sProperty)) && ($this->GetProperty($sProperty.'_allowed') !== false)) {
$this->SetProperty($sProperty, $value);
- foreach ($this->GetOutgoingEdges() as $oOutgoingEdge)
- {
+ foreach ($this->GetOutgoingEdges() as $oOutgoingEdge) {
// Recurse
$oOutgoingEdge->GetSinkNode()->ReachDown($sProperty, $value);
}
@@ -154,11 +145,9 @@ class RelationRedundancyNode extends GraphNode
public function ReachDown($sProperty, $value)
{
$this->SetProperty($sProperty.'_count', $this->GetProperty($sProperty.'_count', 0) + 1);
- if ($this->GetProperty($sProperty.'_count') > $this->GetProperty('threshold'))
- {
+ if ($this->GetProperty($sProperty.'_count') > $this->GetProperty('threshold')) {
// Looping... though there should be only ONE SINGLE outgoing edge
- foreach ($this->GetOutgoingEdges() as $oOutgoingEdge)
- {
+ foreach ($this->GetOutgoingEdges() as $oOutgoingEdge) {
// Recurse
$oOutgoingEdge->GetSinkNode()->ReachDown($sProperty, $value);
}
@@ -166,10 +155,9 @@ class RelationRedundancyNode extends GraphNode
}
}
-
/**
* Helper to name the edges in a unique way
- */
+ */
class RelationEdge extends GraphEdge
{
/**
@@ -196,11 +184,11 @@ class RelationEdge extends GraphEdge
* source: boolean, that node was added as a source node
* sink: boolean, that node was added as a sink node
* reached: boolean, that node has been marked as reached (impacted by the source nodes)
- * developped: boolean, that node has been visited to search for related objects
+ * developped: boolean, that node has been visited to search for related objects
* 1) RelationRedundancyNode
* reached_count: int, the number of source nodes having reached=true
- * threshold: float, if reached_count > threshold, the sink nodes become reachable
- */
+ * threshold: float, if reached_count > threshold, the sink nodes become reachable
+ */
class RelationGraph extends SimpleGraph
{
protected $aSourceNodes; // Index of source nodes (for a quicker access)
@@ -211,10 +199,10 @@ class RelationGraph extends SimpleGraph
public function __construct()
{
parent::__construct();
- $this->aSourceNodes = array();
- $this->aSinkNodes = array();
- $this->aRedundancySettings = array();
- $this->aContextSearches = array();
+ $this->aSourceNodes = [];
+ $this->aSinkNodes = [];
+ $this->aRedundancySettings = [];
+ $this->aContextSearches = [];
}
/**
@@ -252,25 +240,25 @@ class RelationGraph extends SimpleGraph
*/
public function AddContextQuery($key, $sOQL)
{
- if ($sOQL === '') { return;}
-
+ if ($sOQL === '') {
+ return;
+ }
+
$oSearch = static::MakeSearch($sOQL);
$aAliases = $oSearch->GetSelectedClasses();
- if (count($aAliases) < 2 )
- {
+ if (count($aAliases) < 2) {
IssueLog::Error("Invalid context query '$sOQL'. A context query must contain at least two columns.");
throw new Exception("Invalid context query '$sOQL'. A context query must contain at least two columns. Columns: ".implode(', ', $aAliases).'. ');
}
$aAliasNames = array_keys($aAliases);
$oCondition = new BinaryExpression(new FieldExpression('id', $aAliasNames[0]), '=', new VariableExpression('id'));
$oSearch->AddConditionExpression($oCondition);
-
+
$sClass = $oSearch->GetClass();
- if (!array_key_exists($sClass, $this->aContextSearches))
- {
- $this->aContextSearches[$sClass] = array();
+ if (!array_key_exists($sClass, $this->aContextSearches)) {
+ $this->aContextSearches[$sClass] = [];
}
- $this->aContextSearches[$sClass][] = array('key' => $key, 'search' => $oSearch);
+ $this->aContextSearches[$sClass][] = ['key' => $key, 'search' => $oSearch];
}
/**
@@ -286,25 +274,19 @@ class RelationGraph extends SimpleGraph
$bRet = false;
$sFinalClass = get_class($oObj);
$aParentClasses = MetaModel::EnumParentClasses($sFinalClass, ENUM_PARENT_CLASSES_ALL);
-
- foreach($aParentClasses as $sClass)
- {
- if (array_key_exists($sClass, $this->aContextSearches))
- {
- foreach($this->aContextSearches[$sClass] as $aContextQuery)
- {
+
+ foreach ($aParentClasses as $sClass) {
+ if (array_key_exists($sClass, $this->aContextSearches)) {
+ foreach ($this->aContextSearches[$sClass] as $aContextQuery) {
$aAliases = $aContextQuery['search']->GetSelectedClasses();
$aAliasNames = array_keys($aAliases);
$sRootCauseAlias = $aAliasNames[1]; // 1st column (=0) = object, second column = root cause
- $oSet = new DBObjectSet($aContextQuery['search'], array(), array('id' => $oObj->GetKey()));
- $oSet->OptimizeColumnLoad(array($aAliasNames[0] => array(), $aAliasNames[1] => array())); // Do not load any column... better do a reload than many joins
- while($aRow = $oSet->FetchAssoc())
- {
- if (!is_null($aRow[$sRootCauseAlias]))
- {
- if (!array_key_exists($aContextQuery['key'], $aRootCauses))
- {
- $aRootCauses[$aContextQuery['key']] = array();
+ $oSet = new DBObjectSet($aContextQuery['search'], [], ['id' => $oObj->GetKey()]);
+ $oSet->OptimizeColumnLoad([$aAliasNames[0] => [], $aAliasNames[1] => []]); // Do not load any column... better do a reload than many joins
+ while ($aRow = $oSet->FetchAssoc()) {
+ if (!is_null($aRow[$sRootCauseAlias])) {
+ if (!array_key_exists($aContextQuery['key'], $aRootCauses)) {
+ $aRootCauses[$aContextQuery['key']] = [];
}
$aRootCauses[$aContextQuery['key']][] = $aRow[$sRootCauseAlias];
$bRet = true;
@@ -327,47 +309,41 @@ class RelationGraph extends SimpleGraph
* @throws \CoreException
* @throws \Exception
*/
- public function ComputeRelatedObjectsDown($sRelCode, $iMaxDepth, $bEnableRedundancy, $aUnreachableObjects = array())
+ public function ComputeRelatedObjectsDown($sRelCode, $iMaxDepth, $bEnableRedundancy, $aUnreachableObjects = [])
{
//echo "Sources only... \n".$this->DumpAsHtmlImage()." \n";
// Build the graph out of the sources
- foreach ($this->aSourceNodes as $oSourceNode)
- {
+ foreach ($this->aSourceNodes as $oSourceNode) {
$this->AddRelatedObjects($sRelCode, true, $oSourceNode, $iMaxDepth, $bEnableRedundancy);
//echo "After processing of {$oSourceNode->GetId()} \n".$this->DumpAsHtmlImage()." \n";
}
-
+
// Mark the unreachable nodes
- foreach ($aUnreachableObjects as $oObj)
- {
+ foreach ($aUnreachableObjects as $oObj) {
$sNodeId = RelationObjectNode::MakeId($oObj);
$oNode = $this->GetNode($sNodeId);
- if($oNode)
- {
+ if ($oNode) {
$oNode->SetProperty('is_reached_allowed', false);
}
}
-
+
// Determine the reached nodes
- foreach ($this->aSourceNodes as $oSourceNode)
- {
+ foreach ($this->aSourceNodes as $oSourceNode) {
$oSourceNode->ReachDown('is_reached', true);
//echo "After reaching from {$oSourceNode->GetId()} \n".$this->DumpAsHtmlImage()." \n";
}
-
+
// Mark also the "context" nodes as reached and record the "root causes" for each node
$oIterator = new RelationTypeIterator($this, 'Node');
- foreach($oIterator as $oNode)
- {
+ foreach ($oIterator as $oNode) {
$oObj = $oNode->GetProperty('object');
- $aRootCauses = array();
- if (!is_null($oObj) && $this->IsPartOfContext($oObj, $aRootCauses))
- {
+ $aRootCauses = [];
+ if (!is_null($oObj) && $this->IsPartOfContext($oObj, $aRootCauses)) {
$oNode->SetProperty('context_root_causes', $aRootCauses);
$oNode->ReachDown('is_reached', true);
- }
+ }
}
- if ( MetaModel::GetConfig()->Get('relations.complete_analysis')) {
+ if (MetaModel::GetConfig()->Get('relations.complete_analysis')) {
$this->ApplyUserRightsOnGraph();
}
}
@@ -386,30 +362,26 @@ class RelationGraph extends SimpleGraph
{
//echo "Sinks only... \n".$this->DumpAsHtmlImage()." \n";
// Build the graph out of the sinks
- foreach ($this->aSinkNodes as $oSinkNode)
- {
+ foreach ($this->aSinkNodes as $oSinkNode) {
$this->AddRelatedObjects($sRelCode, false, $oSinkNode, $iMaxDepth, $bEnableRedundancy);
//echo "After processing of {$oSinkNode->GetId()} \n".$this->DumpAsHtmlImage()." \n";
}
// Mark also the "context" nodes as reached and record the "root causes" for each node
$oIterator = new RelationTypeIterator($this, 'Node');
- foreach($oIterator as $oNode)
- {
+ foreach ($oIterator as $oNode) {
$oObj = $oNode->GetProperty('object');
- $aRootCauses = array();
- if (!is_null($oObj) && $this->IsPartOfContext($oObj, $aRootCauses))
- {
+ $aRootCauses = [];
+ if (!is_null($oObj) && $this->IsPartOfContext($oObj, $aRootCauses)) {
$oNode->SetProperty('context_root_causes', $aRootCauses);
$oNode->ReachDown('is_reached', true);
- }
+ }
}
- if ( MetaModel::GetConfig()->Get('relations.complete_analysis')) {
+ if (MetaModel::GetConfig()->Get('relations.complete_analysis')) {
$this->ApplyUserRightsOnGraph();
}
}
-
/**
* Recursively find related objects, and add them into the graph
*
@@ -423,27 +395,22 @@ class RelationGraph extends SimpleGraph
*/
protected function AddRelatedObjects($sRelCode, $bDown, $oObjectNode, $iMaxDepth, $bEnableRedundancy)
{
- if ($iMaxDepth > 0)
- {
- if ($oObjectNode instanceof RelationRedundancyNode)
- {
+ if ($iMaxDepth > 0) {
+ if ($oObjectNode instanceof RelationRedundancyNode) {
// Note: this happens when recursing on an existing part of the graph
// Skip that redundancy node
$aRelatedEdges = $bDown ? $oObjectNode->GetOutgoingEdges() : $oObjectNode->GetIncomingEdges();
- foreach ($aRelatedEdges as $oRelatedEdge)
- {
+ foreach ($aRelatedEdges as $oRelatedEdge) {
$oRelatedNode = $bDown ? $oRelatedEdge->GetSinkNode() : $oRelatedEdge->GetSourceNode();
// Recurse (same depth)
$this->AddRelatedObjects($sRelCode, $bDown, $oRelatedNode, $iMaxDepth, $bEnableRedundancy);
}
- }
- elseif ($oObjectNode->GetProperty('developped', false))
- {
+ } elseif ($oObjectNode->GetProperty('developped', false)) {
// No need to explore the underlying graph at all. We can stop here since the node has already been developped.
// Otherwise in case of "loops" in the graph we would recurse up to the max depth limit
// without producing any difference in the resulting graph... but potentially taking a LOOOONG time.
return;
-
+
// Former code was
//$aRelatedEdges = $bDown ? $oObjectNode->GetOutgoingEdges() : $oObjectNode->GetIncomingEdges();
//foreach ($aRelatedEdges as $oRelatedEdge)
@@ -452,60 +419,50 @@ class RelationGraph extends SimpleGraph
// // Recurse (decrement the depth)
// $this->AddRelatedObjects($sRelCode, $bDown, $oRelatedNode, $iMaxDepth - 1, $bEnableRedundancy);
//}
- }
- else
- {
+ } else {
$oObjectNode->SetProperty('developped', true);
-
+
$oObject = $oObjectNode->GetProperty('object');
$iPreviousTimeLimit = ini_get('max_execution_time');
$iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
- foreach (MetaModel::EnumRelationQueries(get_class($oObject), $sRelCode, $bDown) as $sDummy => $aQueryInfo)
- {
- $sQuery = $bDown ? $aQueryInfo['sQueryDown'] : $aQueryInfo['sQueryUp'];
- try
- {
+ foreach (MetaModel::EnumRelationQueries(get_class($oObject), $sRelCode, $bDown) as $sDummy => $aQueryInfo) {
+ $sQuery = $bDown ? $aQueryInfo['sQueryDown'] : $aQueryInfo['sQueryUp'];
+ try {
$oFlt = static::MakeSearch($sQuery);
- if ( MetaModel::GetConfig()->Get('relations.complete_analysis')) {
+ if (MetaModel::GetConfig()->Get('relations.complete_analysis')) {
//no filter to find all impacts
$oFlt->AllowAllData(true);
}
- $oObjSet = new DBObjectSet($oFlt, array(), $oObject->ToArgsForQuery());
+ $oObjSet = new DBObjectSet($oFlt, [], $oObject->ToArgsForQuery());
$oRelatedObj = $oObjSet->Fetch();
- }
- catch (Exception $e)
- {
+ } catch (Exception $e) {
$sDirection = $bDown ? 'downstream' : 'upstream';
throw new Exception("Wrong query ($sDirection) for the relation $sRelCode/{$aQueryInfo['sDefinedInClass']}/{$aQueryInfo['sNeighbour']}: ".$e->getMessage());
}
- if ($oRelatedObj)
- {
- do
- {
+ if ($oRelatedObj) {
+ do {
set_time_limit(intval($iLoopTimeLimit));
- $sObjectRef = RelationObjectNode::MakeId($oRelatedObj);
- $oRelatedNode = $this->GetNode($sObjectRef);
- if (is_null($oRelatedNode)) {
- $oRelatedNode = new RelationObjectNode($this, $oRelatedObj);
- }
- $oSourceNode = $bDown ? $oObjectNode : $oRelatedNode;
- $oSinkNode = $bDown ? $oRelatedNode : $oObjectNode;
- if ($bEnableRedundancy)
- {
- $oRedundancyNode = $this->ComputeRedundancy($sRelCode, $aQueryInfo, $oSourceNode, $oSinkNode);
- } else {
- $oRedundancyNode = null;
- }
- if (!$oRedundancyNode) {
- // Direct link (otherwise handled by ComputeRedundancy)
- new RelationEdge($this, $oSourceNode, $oSinkNode);
- }
+ $sObjectRef = RelationObjectNode::MakeId($oRelatedObj);
+ $oRelatedNode = $this->GetNode($sObjectRef);
+ if (is_null($oRelatedNode)) {
+ $oRelatedNode = new RelationObjectNode($this, $oRelatedObj);
+ }
+ $oSourceNode = $bDown ? $oObjectNode : $oRelatedNode;
+ $oSinkNode = $bDown ? $oRelatedNode : $oObjectNode;
+ if ($bEnableRedundancy) {
+ $oRedundancyNode = $this->ComputeRedundancy($sRelCode, $aQueryInfo, $oSourceNode, $oSinkNode);
+ } else {
+ $oRedundancyNode = null;
+ }
+ if (!$oRedundancyNode) {
+ // Direct link (otherwise handled by ComputeRedundancy)
+ new RelationEdge($this, $oSourceNode, $oSinkNode);
+ }
// Recurse
$this->AddRelatedObjects($sRelCode, $bDown, $oRelatedNode, $iMaxDepth - 1, $bEnableRedundancy);
- }
- while ($oRelatedObj = $oObjSet->Fetch());
+ } while ($oRelatedObj = $oObjSet->Fetch());
}
}
set_time_limit(intval($iPreviousTimeLimit));
@@ -528,48 +485,41 @@ class RelationGraph extends SimpleGraph
{
$oRedundancyNode = null;
$oObject = $oToNode->GetProperty('object');
- if ($this->IsRedundancyEnabled($sRelCode, $aQueryInfo, $oToNode))
- {
+ if ($this->IsRedundancyEnabled($sRelCode, $aQueryInfo, $oToNode)) {
$sUniqueNeighbourId = $aQueryInfo['sDefinedInClass'].'-'.$aQueryInfo['sNeighbour'];
$sId = RelationRedundancyNode::MakeId($sRelCode, $sUniqueNeighbourId, $oFromNode->GetProperty('object'), $oToNode->GetProperty('object'));
$oRedundancyNode = $this->GetNode($sId);
- if (is_null($oRedundancyNode))
- {
+ if (is_null($oRedundancyNode)) {
// Get the upper neighbours
$sQuery = $aQueryInfo['sQueryUp'];
- if (!$sQuery)
- {
+ if (!$sQuery) {
throw new Exception("Redundancy cannot be enabled on the relation $sRelCode/{$aQueryInfo['sDefinedInClass']}/{$aQueryInfo['sNeighbour']}: its direction is \"{$aQueryInfo['sDirection']}\"");
}
- try
- {
+ try {
$oFlt = static::MakeSearch($sQuery);
- if ( MetaModel::GetConfig()->Get('relations.complete_analysis')) {
+ if (MetaModel::GetConfig()->Get('relations.complete_analysis')) {
//no filter to find all impacts
$oFlt->AllowAllData(true);
}
- $oObjSet = new DBObjectSet($oFlt, array(), $oObject->ToArgsForQuery());
+ $oObjSet = new DBObjectSet($oFlt, [], $oObject->ToArgsForQuery());
$iCount = $oObjSet->Count();
- }
- catch (Exception $e)
- {
+ } catch (Exception $e) {
throw new Exception("Wrong query (upstream) for the relation $sRelCode/{$aQueryInfo['sDefinedInClass']}/{$aQueryInfo['sNeighbour']}: ".$e->getMessage());
}
-
+
$iMinUp = $this->GetRedundancyMinUp($sRelCode, $aQueryInfo, $oToNode, $iCount);
$fThreshold = max(0, $iCount - $iMinUp);
$oRedundancyNode = new RelationRedundancyNode($this, $sId, $iMinUp, $fThreshold);
new RelationEdge($this, $oRedundancyNode, $oToNode);
-
- while ($oUpperObj = $oObjSet->Fetch())
- {
- $sObjectRef = RelationObjectNode::MakeId($oUpperObj);
- $oUpperNode = $this->GetNode($sObjectRef);
- if (is_null($oUpperNode)) {
- $oUpperNode = new RelationObjectNode($this, $oUpperObj);
- }
- new RelationEdge($this, $oUpperNode, $oRedundancyNode);
+
+ while ($oUpperObj = $oObjSet->Fetch()) {
+ $sObjectRef = RelationObjectNode::MakeId($oUpperObj);
+ $oUpperNode = $this->GetNode($sObjectRef);
+ if (is_null($oUpperNode)) {
+ $oUpperNode = new RelationObjectNode($this, $oUpperObj);
+ }
+ new RelationEdge($this, $oUpperNode, $oRedundancyNode);
}
}
}
@@ -590,8 +540,7 @@ class RelationGraph extends SimpleGraph
$bRet = false;
$oToObject = $oToNode->GetProperty('object');
$oRedundancyAttDef = $this->FindRedundancyAttribute($sRelCode, $aQueryInfo, get_class($oToObject));
- if ($oRedundancyAttDef)
- {
+ if ($oRedundancyAttDef) {
$sValue = $oToObject->Get($oRedundancyAttDef->GetCode());
$bRet = $oRedundancyAttDef->IsEnabled($sValue);
}
@@ -614,15 +563,11 @@ class RelationGraph extends SimpleGraph
$oToObject = $oToNode->GetProperty('object');
$oRedundancyAttDef = $this->FindRedundancyAttribute($sRelCode, $aQueryInfo, get_class($oToObject));
- if ($oRedundancyAttDef)
- {
+ if ($oRedundancyAttDef) {
$sValue = $oToObject->Get($oRedundancyAttDef->GetCode());
- if ($oRedundancyAttDef->GetMinUpType($sValue) == 'count')
- {
+ if ($oRedundancyAttDef->GetMinUpType($sValue) == 'count') {
$iMinUp = $oRedundancyAttDef->GetMinUpValue($sValue);
- }
- else
- {
+ } else {
$iMinUp = $iUpstreamObjects * $oRedundancyAttDef->GetMinUpValue($sValue) / 100;
}
}
@@ -641,16 +586,11 @@ class RelationGraph extends SimpleGraph
protected function FindRedundancyAttribute($sRelCode, $aQueryInfo, $sClass)
{
$oRet = null;
- foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
- {
- if ($oAttDef instanceof AttributeRedundancySettings)
- {
- if ($oAttDef->Get('relation_code') == $sRelCode)
- {
- if ($oAttDef->Get('from_class') == $aQueryInfo['sFromClass'])
- {
- if ($oAttDef->Get('neighbour_id') == $aQueryInfo['sNeighbour'])
- {
+ foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) {
+ if ($oAttDef instanceof AttributeRedundancySettings) {
+ if ($oAttDef->Get('relation_code') == $sRelCode) {
+ if ($oAttDef->Get('from_class') == $aQueryInfo['sFromClass']) {
+ if ($oAttDef->Get('neighbour_id') == $aQueryInfo['sNeighbour']) {
$oRet = $oAttDef;
break;
}
@@ -660,29 +600,26 @@ class RelationGraph extends SimpleGraph
}
return $oRet;
}
-
+
/**
* Get the objects referenced by the graph as a hash array: 'class' => array of objects
* @return array Ambigous
*/
public function GetObjectsByClass()
{
- $aResults = array();
+ $aResults = [];
$oIterator = new RelationTypeIterator($this, 'Node');
- foreach($oIterator as $oNode)
- {
+ foreach ($oIterator as $oNode) {
$oObj = $oNode->GetProperty('object'); // Some nodes (Redundancy Nodes and Group) do not contain an object
- if ($oObj)
- {
+ if ($oObj) {
$sObjClass = get_class($oObj);
- if (!array_key_exists($sObjClass, $aResults))
- {
- $aResults[$sObjClass] = array();
+ if (!array_key_exists($sObjClass, $aResults)) {
+ $aResults[$sObjClass] = [];
}
$aResults[$sObjClass][] = $oObj;
}
}
- return $aResults;
+ return $aResults;
}
/**
@@ -695,8 +632,7 @@ class RelationGraph extends SimpleGraph
protected static function MakeSearch($sOQL)
{
$oSearch = DBSearch::FromOQL($sOQL);
- if (MetaModel::IsObsoletable($oSearch->GetClass()))
- {
+ if (MetaModel::IsObsoletable($oSearch->GetClass())) {
// Exclude obsolete objects anytime
$oSearch->AddCondition('obsolescence_flag', 0);
}
@@ -705,7 +641,6 @@ class RelationGraph extends SimpleGraph
return $oSearch;
}
-
/**
* @return void
* @throws \CoreException
@@ -733,7 +668,7 @@ class RelationGraph extends SimpleGraph
$sOQL = "SELECT ".$sClass.' WHERE id IN ('.implode(',', $aKeys).')';
$oSearch = DBObjectSearch::FromOQL($sOQL);
$aListId = $oSearch->SelectAttributeToArray('id');
- foreach($aListId as$aItem ) {
+ foreach ($aListId as $aItem) {
unset($aArrayTest[$sClass][$aItem['id']]);
}
}
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 170ddbe20..ea6885d07 100644
--- a/core/simplecrypt.class.inc.php
+++ b/core/simplecrypt.class.inc.php
@@ -1,4 +1,5 @@
oEngine = new $sEngineName;
- }
+ $sEngineName = 'SimpleCrypt'.$sEngineName.'Engine';
+ $this->oEngine = new $sEngineName();
+ }
- /**
- * Encrypts the string with the given key
- * @param string $key
- * @param string $sString Plaintext string
- * @return string Ciphered string
- */
- function Encrypt($key, $sString)
- {
- return $this->oEngine->Encrypt($key,$sString);
- }
+ /**
+ * Encrypts the string with the given key
+ * @param string $key
+ * @param string $sString Plaintext string
+ * @return string Ciphered string
+ */
+ public function Encrypt($key, $sString)
+ {
+ return $this->oEngine->Encrypt($key, $sString);
+ }
- /**
- * Decrypts the string by the given key
- * @param string $key
- * @param string $string Ciphered string
- * @return string Plaintext string
- */
- function Decrypt($key, $string)
- {
- if (is_null($string) || strlen($string) == 0) {
- IssueLog::Warning("Cannot decrypt empty/null value");
+ /**
+ * Decrypts the string by the given key
+ * @param string $key
+ * @param string $string Ciphered string
+ * @return string Plaintext string
+ */
+ public function Decrypt($key, $string)
+ {
+ if (is_null($string) || strlen($string) == 0) {
+ IssueLog::Warning("Cannot decrypt empty/null value");
+ return $string;
+ }
+ return $this->oEngine->Decrypt($key, $string);
+ }
- return $string;
- }
-
- return $this->oEngine->Decrypt($key, $string);
- }
-
- /**
- * Returns a random "salt" value, to be used when "hashing" a password
- * using a one-way encryption algorithm, to prevent an attack using a "rainbow table"
- * Tryes to use the best available random number generator
- * @return string The generated random "salt"
- */
- static function GetNewSalt()
- {
+ /**
+ * Returns a random "salt" value, to be used when "hashing" a password
+ * using a one-way encryption algorithm, to prevent an attack using a "rainbow table"
+ * Tryes to use the best available random number generator
+ * @return string The generated random "salt"
+ */
+ public static function GetNewSalt()
+ {
// Copied from http://www.php.net/manual/en/function.mt-rand.php#83655
// get 128 pseudorandom bits in a string of 16 bytes
$sRandomBits = null;
// Unix/Linux platform?
- $fp = @fopen('/dev/urandom','rb');
- if ($fp !== FALSE)
- {
+ $fp = @fopen('/dev/urandom', 'rb');
+ if ($fp !== false) {
//echo "Random bits pulled from /dev/urandom \n";
- $sRandomBits .= @fread($fp,16);
- @fclose($fp);
- }
- else
- {
+ $sRandomBits .= @fread($fp, 16);
+ @fclose($fp);
+ } else {
// MS-Windows platform?
- if (@class_exists('COM'))
- {
+ if (@class_exists('COM')) {
// http://msdn.microsoft.com/en-us/library/aa388176(VS.85).aspx
- try
- {
- $CAPI_Util = new COM('CAPICOM.Utilities.1');
- $sBase64RandomBits = ''.$CAPI_Util->GetRandom(16,0);
+ try {
+ $CAPI_Util = new COM('CAPICOM.Utilities.1');
+ $sBase64RandomBits = ''.$CAPI_Util->GetRandom(16, 0);
- // if we ask for binary data PHP munges it, so we
- // request base64 return value. We squeeze out the
- // redundancy and useless ==CRLF by hashing...
- if ($sBase64RandomBits)
- {
+ // if we ask for binary data PHP munges it, so we
+ // request base64 return value. We squeeze out the
+ // redundancy and useless ==CRLF by hashing...
+ if ($sBase64RandomBits) {
//echo "Random bits got from CAPICOM.Utilities.1 \n";
- $sRandomBits = md5($sBase64RandomBits, TRUE);
- }
- }
- catch (Exception $ex)
- {
- // echo 'Exception: ' . $ex->getMessage();
+ $sRandomBits = md5($sBase64RandomBits, true);
+ }
+ } catch (Exception $ex) {
+ // echo 'Exception: ' . $ex->getMessage();
}
}
}
- if ($sRandomBits == null)
- {
+ if ($sRandomBits == null) {
// No "strong" random generator available, use PHP's built-in mechanism
//echo "Random bits generated from mt_rand \n";
mt_srand(crc32(microtime()));
$sRandomBits = '';
- for($i = 0; $i < 4; $i++)
- {
+ for ($i = 0; $i < 4; $i++) {
$sRandomBits .= sprintf('%04x', mt_rand(0, 65535));
}
-
}
return $sRandomBits;
- }
+ }
}
/**
@@ -209,8 +189,8 @@ class SimpleCrypt
interface CryptEngine
{
public static function GetNewDefaultParams();
- function Encrypt($key, $sString);
- function Decrypt($key, $encrypted_data);
+ public function Encrypt($key, $sString);
+ public function Decrypt($key, $encrypted_data);
}
/**
@@ -222,34 +202,36 @@ class SimpleCryptSimpleEngine implements CryptEngine
{
public static function GetNewDefaultParams()
{
- return array( 'lib' => 'Simple', 'key' => null);
+ return [ 'lib' => 'Simple', 'key' => null];
}
public function Encrypt($key, $sString)
- {
- $result = '';
- for($i=1; $i<=strlen($sString); $i++)
- {
- $char = substr($sString, $i-1, 1);
- $keychar = substr($key, ($i % strlen($key))-1, 1);
- $char = chr(ord($char)+ord($keychar));
- $result.=$char;
- }
- return $result;
- }
+ {
+ $result = '';
+ for ($i = 1; $i <= strlen($sString); $i++) {
+ $char = substr($sString, $i - 1, 1);
+ $keychar = substr($key, ($i % strlen($key)) - 1, 1);
+ $char = chr(ord($char) + ord($keychar));
+ $result .= $char;
+ }
+ return $result;
+ }
- public function Decrypt($key, $encrypted_data)
- {
- $result = '';
- for($i=1; $i<=strlen($encrypted_data); $i++)
- {
- $char = substr($encrypted_data, $i-1, 1);
- $keychar = substr($key, ($i % strlen($key))-1, 1);
- $char = chr(ord($char)-ord($keychar));
- $result.=$char;
- }
- return $result;
- }
+ public function Decrypt($key, $encrypted_data)
+ {
+ if (is_null($encrypted_data) || strlen($encrypted_data) == 0) {
+ IssueLog::Warning("Cannot decrypt empty/null value");
+ return $encrypted_data;
+ }
+ $result = '';
+ for ($i = 1; $i <= strlen($encrypted_data); $i++) {
+ $char = substr($encrypted_data, $i - 1, 1);
+ $keychar = substr($key, ($i % strlen($key)) - 1, 1);
+ $char = chr(ord($char) - ord($keychar));
+ $result .= $char;
+ }
+ return $result;
+ }
}
/**
@@ -259,57 +241,52 @@ class SimpleCryptSimpleEngine implements CryptEngine
*/
class SimpleCryptMcryptEngine implements CryptEngine
{
- var $alg = MCRYPT_BLOWFISH;
- var $td = null;
+ public $alg = MCRYPT_BLOWFISH;
+ public $td = null;
public static function GetNewDefaultParams()
{
- return array('lib' => 'Mcrypt', 'key' => null);
+ return ['lib' => 'Mcrypt', 'key' => null];
}
-
public function __construct()
{
- $this->td = mcrypt_module_open($this->alg,'','cbc','');
+ $this->td = mcrypt_module_open($this->alg, '', 'cbc', '');
}
- public function Encrypt($key, $sString)
- {
- $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($this->td), MCRYPT_DEV_URANDOM); // MCRYPT_DEV_URANDOM is now useable since itop requires php >= 5.6
- if (false === $iv) {
- throw new Exception('IV generation failed');
- }
+ public function Encrypt($key, $sString)
+ {
+ $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($this->td), MCRYPT_DEV_URANDOM); // MCRYPT_DEV_URANDOM is now useable since itop requires php >= 5.6
+ if (false === $iv) {
+ throw new Exception('IV generation failed');
+ }
mcrypt_generic_init($this->td, $key, $iv);
- if (empty($sString))
- {
+ if (empty($sString)) {
$sString = str_repeat("\0", 8);
}
$encrypted_data = mcrypt_generic($this->td, $sString);
mcrypt_generic_deinit($this->td);
- return $iv.$encrypted_data;
- }
+ return $iv.$encrypted_data;
+ }
- public function Decrypt($key, $encrypted_data)
- {
- $iv = substr($encrypted_data, 0, mcrypt_enc_get_iv_size($this->td));
- $string = substr($encrypted_data, mcrypt_enc_get_iv_size($this->td));
+ public function Decrypt($key, $encrypted_data)
+ {
+ $iv = substr($encrypted_data, 0, mcrypt_enc_get_iv_size($this->td));
+ $string = substr($encrypted_data, mcrypt_enc_get_iv_size($this->td));
$r = mcrypt_generic_init($this->td, $key, $iv);
- if (($r < 0) || ($r === false))
- {
+ if (($r < 0) || ($r === false)) {
$decrypted_data = Dict::S("Core:AttributeEncryptFailedToDecrypt");
- }
- else
- {
+ } else {
$decrypted_data = rtrim(mdecrypt_generic($this->td, $string), "\0");
mcrypt_generic_deinit($this->td);
}
- return $decrypted_data;
- }
+ return $decrypted_data;
+ }
- public function __destruct()
- {
- mcrypt_module_close($this->td);
- }
+ public function __destruct()
+ {
+ mcrypt_module_close($this->td);
+ }
}
/**
* SodiumEngine requires Sodium extension
@@ -321,7 +298,7 @@ class SimpleCryptSodiumEngine implements CryptEngine
{
public static function GetNewDefaultParams()
{
- return array('lib' => 'Sodium', 'key' => bin2hex(sodium_crypto_secretbox_keygen()));
+ return ['lib' => 'Sodium', 'key' => bin2hex(sodium_crypto_secretbox_keygen())];
}
public function Encrypt($key, $sString)
@@ -336,13 +313,16 @@ class SimpleCryptSodiumEngine implements CryptEngine
public function Decrypt($key, $encrypted_data)
{
+ if (is_null($encrypted_data) || strlen($encrypted_data) == 0) {
+ IssueLog::Warning("Cannot decrypt empty/null value");
+ return $encrypted_data;
+ }
$key = hex2bin($key);
$encrypted_data = base64_decode($encrypted_data);
$nonce = mb_substr($encrypted_data, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
$encrypted_data = mb_substr($encrypted_data, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');
$plaintext = sodium_crypto_secretbox_open($encrypted_data, $nonce, $key);
- if ($plaintext === false)
- {
+ if ($plaintext === false) {
$plaintext = Dict::S("Core:AttributeEncryptFailedToDecrypt");
}
sodium_memzero($encrypted_data);
@@ -355,25 +335,28 @@ class SimpleCryptOpenSSLEngine implements CryptEngine
{
public static function GetNewDefaultParams()
{
- return array('lib' => 'OpenSSL', 'key' => bin2hex(openssl_random_pseudo_bytes(32)));
+ return ['lib' => 'OpenSSL', 'key' => bin2hex(openssl_random_pseudo_bytes(32))];
}
public function Encrypt($key, $sString)
{
$key = hex2bin($key);
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length("AES-256-CBC"));
- $encrypted_string = openssl_encrypt($sString, "AES-256-CBC", $key, 0 , $iv);
+ $encrypted_string = openssl_encrypt($sString, "AES-256-CBC", $key, 0, $iv);
return $iv.$encrypted_string;
}
public function Decrypt($key, $encrypted_data)
{
+ if (is_null($encrypted_data) || strlen($encrypted_data) == 0) {
+ IssueLog::Warning("Cannot decrypt empty/null value");
+ return $encrypted_data;
+ }
$key = hex2bin($key);
$iv = mb_substr($encrypted_data, 0, openssl_cipher_iv_length("AES-256-CBC"), '8bit');
$encrypted_data = mb_substr($encrypted_data, openssl_cipher_iv_length("AES-256-CBC"), null, '8bit');
- $plaintext = openssl_decrypt($encrypted_data,"AES-256-CBC", $key, 0 , $iv);
- if ($plaintext === false)
- {
+ $plaintext = openssl_decrypt($encrypted_data, "AES-256-CBC", $key, 0, $iv);
+ if ($plaintext === false) {
$plaintext = Dict::S("Core:AttributeEncryptFailedToDecrypt");
}
return trim($plaintext);
@@ -385,18 +368,16 @@ class SimpleCryptOpenSSLMcryptCompatibilityEngine implements CryptEngine
{
public static function GetNewDefaultParams()
{
- return array('lib' => 'OpenSSLMcryptCompatibility', 'key' => null);
+ return ['lib' => 'OpenSSLMcryptCompatibility', 'key' => null];
}
//fix for php < 7.1.8 (keys are Zero padded instead of cycle padded)
- static private function MakeOpenSSLBlowfishKey($key)
+ private static function MakeOpenSSLBlowfishKey($key)
{
- if("$key" === '')
- {
+ if ("$key" === '') {
return $key;
}
- $len = (16+2)*4;
- while(strlen($key) < $len)
- {
+ $len = (16 + 2) * 4;
+ while (strlen($key) < $len) {
$key .= $key;
}
$key = substr($key, 0, $len);
@@ -407,9 +388,9 @@ class SimpleCryptOpenSSLMcryptCompatibilityEngine implements CryptEngine
$key = SimpleCryptOpenSSLMcryptCompatibilityEngine::MakeOpenSSLBlowfishKey($key);
$blockSize = 8;
$len = strlen($sString);
- $paddingLen = intval (($len + $blockSize -1) / $blockSize) * $blockSize - $len;
+ $paddingLen = intval(($len + $blockSize - 1) / $blockSize) * $blockSize - $len;
$padding = str_repeat("\0", $paddingLen);
- $sData = $sString . $padding;
+ $sData = $sString.$padding;
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length("BF-CBC"));
$encrypted_string = openssl_encrypt($sData, "BF-CBC", $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
return $iv.$encrypted_string;
@@ -417,15 +398,18 @@ class SimpleCryptOpenSSLMcryptCompatibilityEngine implements CryptEngine
public function Decrypt($key, $encrypted_data)
{
+ if (is_null($encrypted_data) || strlen($encrypted_data) == 0) {
+ IssueLog::Warning("Cannot decrypt empty/null value");
+ return $encrypted_data;
+ }
$key = SimpleCryptOpenSSLMcryptCompatibilityEngine::MakeOpenSSLBlowfishKey($key);
$iv = mb_substr($encrypted_data, 0, openssl_cipher_iv_length("BF-CBC"), '8bit');
$encrypted_data = mb_substr($encrypted_data, openssl_cipher_iv_length("BF-CBC"), null, '8bit');
- $plaintext = openssl_decrypt($encrypted_data,"BF-CBC", $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
- if ($plaintext === false)
- {
+ $plaintext = openssl_decrypt($encrypted_data, "BF-CBC", $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
+ if ($plaintext === false) {
$plaintext = Dict::S("Core:AttributeEncryptFailedToDecrypt");
}
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/spreadsheetbulkexport.class.inc.php b/core/spreadsheetbulkexport.class.inc.php
index 46f9ea95f..2006729ba 100644
--- a/core/spreadsheetbulkexport.class.inc.php
+++ b/core/spreadsheetbulkexport.class.inc.php
@@ -1,4 +1,5 @@
array('no-localize'), 'interactive_fields_spreadsheet' => array('interactive_fields_spreadsheet')));
+ return array_merge(parent::EnumFormParts(), ['spreadsheet_options' => ['no-localize'], 'interactive_fields_spreadsheet' => ['interactive_fields_spreadsheet']]);
}
/**
@@ -106,7 +107,7 @@ EOF
break;
default:
- return parent:: GetFormPart($oP, $sPartId);
+ return parent::GetFormPart($oP, $sPartId);
}
}
@@ -116,18 +117,17 @@ EOF
$this->aStatusInfo['formatted_text'] = (bool)utils::ReadParam('formatted_text', 1, true);
$sDateFormatRadio = utils::ReadParam('spreadsheet_date_format_radio', '');
- switch($sDateFormatRadio)
- {
+ switch ($sDateFormatRadio) {
case 'default':
// Export from the UI => format = same as is the UI
$this->aStatusInfo['date_format'] = (string)AttributeDateTime::GetFormat();
break;
-
+
case 'custom':
// Custom format specified from the UI
$this->aStatusInfo['date_format'] = utils::ReadParam('date_format', (string)AttributeDateTime::GetFormat(), true, 'raw_data');
break;
-
+
default:
// Export from the command line (or scripted) => default format is SQL, as in previous versions of iTop, unless specified otherwise
$this->aStatusInfo['date_format'] = utils::ReadParam('date_format', (string)AttributeDateTime::GetSQLFormat(), true, 'raw_data');
@@ -136,11 +136,9 @@ EOF
protected function GetSampleData($oObj, $sAttCode)
{
- if ($sAttCode != 'id')
- {
+ if ($sAttCode != 'id') {
$oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
- if ($oAttDef instanceof AttributeDateTime) // AttributeDate is derived from AttributeDateTime
- {
+ if ($oAttDef instanceof AttributeDateTime) { // AttributeDate is derived from AttributeDateTime
$sClass = (get_class($oAttDef) == 'AttributeDateTime') ? 'user-formatted-date-time' : 'user-formatted-date';
return ''.utils::EscapeHtml($oAttDef->GetEditValue($oObj->Get($sAttCode), $oObj)).'
';
@@ -152,12 +150,11 @@ EOF
protected function GetValue($oObj, $sAttCode)
{
$bFormattedText = (array_key_exists('formatted_text', $this->aStatusInfo) ? $this->aStatusInfo['formatted_text'] : false);
- switch($sAttCode)
- {
+ switch ($sAttCode) {
case 'id':
$sRet = $oObj->GetKey();
break;
-
+
default:
$value = $oObj->Get($sAttCode);
$oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
@@ -167,28 +164,19 @@ EOF
$sRet = $value->GetTimeSpent();
} elseif ($value instanceof ormDocument) {
$sRet = '';
- } elseif ($oAttDef instanceof AttributeText)
- {
- if ($bFormattedText)
- {
+ } elseif ($oAttDef instanceof AttributeText) {
+ if ($bFormattedText) {
// Replace paragraphs (..., etc) by line breaks ( ) since Excel (pre-2016) splits the cells when there is a paragraph
$sRet = static::HtmlToSpreadsheet($oObj->GetAsHTML($sAttCode));
- }
- else
- {
+ } else {
$sRet = utils::HtmlToText($oObj->GetAsHTML($sAttCode));
}
- }
- elseif ($oAttDef instanceof AttributeString)
- {
+ } elseif ($oAttDef instanceof AttributeString) {
$sRet = $oObj->GetAsHTML($sAttCode);
- }
- elseif ($oAttDef instanceof AttributeCustomFields)
- {
+ } elseif ($oAttDef instanceof AttributeCustomFields) {
// Stick to the weird implementation made in GetNextChunk
$sRet = utils::TextToHtml($oObj->GetEditValue($sAttCode));
- }
- else {
+ } else {
if ($this->bLocalizeOutput) {
$sRet = utils::EscapeHtml($oObj->GetEditValue());
} else {
@@ -216,34 +204,26 @@ EOF
$this->aStatusInfo['position'] = 0;
$this->aStatusInfo['total'] = $oSet->Count();
- $aData = array();
- foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
- {
+ $aData = [];
+ foreach ($this->aStatusInfo['fields'] as $iCol => $aFieldSpec) {
$sColLabel = $aFieldSpec['sColLabel'];
- if ($aFieldSpec['sAttCode'] != 'id')
- {
+ if ($aFieldSpec['sAttCode'] != 'id') {
$oAttDef = MetaModel::GetAttributeDef($aFieldSpec['sClass'], $aFieldSpec['sAttCode']);
$oFinalAttDef = $oAttDef->GetFinalAttDef();
- if (get_class($oFinalAttDef) == 'AttributeDateTime')
- {
+ if (get_class($oFinalAttDef) == 'AttributeDateTime') {
$aData[] = $sColLabel.' ('.Dict::S('UI:SplitDateTime-Date').')';
$aData[] = $sColLabel.' ('.Dict::S('UI:SplitDateTime-Time').')';
- }
- else
- {
+ } else {
$aData[] = $sColLabel;
}
- }
- else
- {
+ } else {
$aData[] = $sColLabel;
}
}
$sData = '';
$sData .= "\n";
$sData .= "\n";
- foreach($aData as $sLabel)
- {
+ foreach ($aData as $sLabel) {
$sData .= "".$sLabel." \n";
}
$sData .= " \n";
@@ -270,47 +250,41 @@ EOF
$sData = '';
$iPreviousTimeLimit = ini_get('max_execution_time');
$iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
- while($aRow = $oSet->FetchAssoc())
- {
+ while ($aRow = $oSet->FetchAssoc()) {
set_time_limit(intval($iLoopTimeLimit));
$sData .= "";
- foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
- {
+ foreach ($this->aStatusInfo['fields'] as $iCol => $aFieldSpec) {
$sAlias = $aFieldSpec['sAlias'];
$sAttCode = $aFieldSpec['sAttCode'];
$sField = '';
/** @var \DBObject $oObj */
$oObj = $aRow[$sAlias];
- if ($oObj == null)
- {
+ if ($oObj == null) {
$sData .= " ";
continue;
}
- switch($sAttCode)
- {
+ switch ($sAttCode) {
case 'id':
$sField = $oObj->GetKey();
$sData .= "$sField ";
break;
-
+
default:
$oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
$oFinalAttDef = $oAttDef->GetFinalAttDef();
- if (get_class($oFinalAttDef) == 'AttributeDateTime')
- {
+ if (get_class($oFinalAttDef) == 'AttributeDateTime') {
// Split the date and time in two columns
$sDate = $oDateFormat->Format($oObj->Get($sAttCode));
$sTime = $oTimeFormat->Format($oObj->Get($sAttCode));
$sData .= "$sDate ";
$sData .= "$sTime ";
- }
- else if (get_class($oFinalAttDef) == 'AttributeDate') {
+ } elseif (get_class($oFinalAttDef) == 'AttributeDate') {
$sDate = $oDateFormat->Format($oObj->Get($sAttCode));
$sData .= "$sDate ";
- } else if ($oAttDef instanceof AttributeCaseLog) {
+ } elseif ($oAttDef instanceof AttributeCaseLog) {
$rawValue = $oObj->Get($sAttCode);
$sField = str_replace("\n", " ", utils::EscapeHtml($rawValue->__toString()));
// Trick for Excel: treat the content as text even if it begins with an equal sign
@@ -319,31 +293,22 @@ EOF
if ($bFormattedText) {
// Replace paragraphs (..., etc) by line breaks ( ) since Excel (pre-2016) splits the cells when there is a paragraph
$sField = static::HtmlToSpreadsheet($oObj->GetAsHTML($sAttCode));
- }
- else
- {
+ } else {
// Convert to plain text
$sField = utils::HtmlToText($oObj->GetAsHTML($sAttCode));
}
$sData .= "$sField ";
- }
- elseif ($oAttDef instanceof AttributeCustomFields)
- {
+ } elseif ($oAttDef instanceof AttributeCustomFields) {
// GetAsHTML returns a table that would not fit
$sField = utils::TextToHtml($oObj->GetEditValue($sAttCode));
$sData .= "$sField ";
- }
- else if ($oAttDef instanceof AttributeString)
- {
+ } elseif ($oAttDef instanceof AttributeString) {
$sField = $oObj->GetAsHTML($sAttCode, $this->bLocalizeOutput);
$sData .= "$sField ";
- }
- else if ($oAttDef instanceof AttributeTagSet)
- {
+ } elseif ($oAttDef instanceof AttributeTagSet) {
$sField = utils::HtmlEntities($oObj->GetAsCSV($sAttCode, $this->bLocalizeOutput, ''));
$sData .= "$sField ";
- }
- else {
+ } else {
$rawValue = $oObj->Get($sAttCode);
if ($this->bLocalizeOutput) {
$sField = utils::EscapeHtml($oFinalAttDef->GetEditValue($rawValue));
@@ -360,21 +325,17 @@ EOF
}
set_time_limit(intval($iPreviousTimeLimit));
$this->aStatusInfo['position'] += $this->iChunkSize;
- if ($this->aStatusInfo['total'] == 0)
- {
+ if ($this->aStatusInfo['total'] == 0) {
$iPercentage = 100;
- }
- else
- {
- $iPercentage = floor(min(100.0, 100.0*$this->aStatusInfo['position']/$this->aStatusInfo['total']));
+ } else {
+ $iPercentage = floor(min(100.0, 100.0 * $this->aStatusInfo['position'] / $this->aStatusInfo['total']));
}
- if ($iCount < $this->iChunkSize)
- {
+ if ($iCount < $this->iChunkSize) {
$sRetCode = 'done';
}
- $aStatus = array('code' => $sRetCode, 'message' => Dict::S('Core:BulkExport:RetrievingData'), 'percentage' => $iPercentage);
+ $aStatus = ['code' => $sRetCode, 'message' => Dict::S('Core:BulkExport:RetrievingData'), 'percentage' => $iPercentage];
return $sData;
}
@@ -387,7 +348,7 @@ EOF
public function GetSupportedFormats()
{
- return array('spreadsheet' => Dict::S('Core:BulkExport:SpreadsheetFormat'));
+ return ['spreadsheet' => Dict::S('Core:BulkExport:SpreadsheetFormat')];
}
public function GetMimeType()
@@ -410,33 +371,30 @@ EOF
*/
public static function HtmlToSpreadsheet($sHtml)
{
- if (trim(strip_tags($sHtml)) === '')
- {
+ if (trim(strip_tags($sHtml)) === '') {
// Display this value as an empty cell in the table
return ' ';
}
// The tags listed here are a subset of the whitelist defined in HTMLDOMSanitizer
// Tags causing a visual "line break" in the displayed page (i.e. display: block) are to be replaced by a followed by a
// in order to preserve any inline style/attribute of the removed tag
- $aTagsToReplace = array(
+ $aTagsToReplace = [
'pre', 'div', 'p', 'hr', 'center', 'h1', 'h2', 'h3', 'h4', 'li', 'fieldset', 'legend', 'nav', 'section', 'tr', 'caption',
- );
+ ];
// Tags to completely remove from the markup
- $aTagsToRemove = array(
+ $aTagsToRemove = [
'table', 'thead', 'tbody', 'ul', 'ol', 'td', 'th',
- );
+ ];
// Remove the englobing ...
to prevent an extra line break
$sHtml = preg_replace('|^(.*)
$|s', '$1', $sHtml); // Must use the "s" (. matches newline) modifier
-
- foreach($aTagsToReplace as $sTag)
- {
+
+ foreach ($aTagsToReplace as $sTag) {
$sHtml = preg_replace("|<{$sTag} ?([^>]*)>|is", '', $sHtml);
$sHtml = preg_replace("|{$sTag}>|i", ' ', $sHtml);
}
- foreach($aTagsToRemove as $sTag)
- {
+ foreach ($aTagsToRemove as $sTag) {
$sHtml = preg_replace("|<{$sTag} ?([^>]*)>|is", '', $sHtml);
$sHtml = preg_replace("|{$sTag}>|i", '', $sHtml);
}
diff --git a/core/sqlobjectquery.class.inc.php b/core/sqlobjectquery.class.inc.php
index fe29f4d5b..854d6b01b 100644
--- a/core/sqlobjectquery.class.inc.php
+++ b/core/sqlobjectquery.class.inc.php
@@ -1,9 +1,10 @@
-
/**
* SQLObjectQuery
* build a mySQL compatible SQL query
@@ -25,7 +25,6 @@
* @license http://opensource.org/licenses/AGPL-3.0
*/
-
/**
* SQLObjectQuery
* build a mySQL compatible SQL query
@@ -33,20 +32,19 @@
* @package iTopORM
*/
-
class SQLObjectQuery extends SQLQuery
{
public $m_aContextData = null;
public $m_iOriginalTableCount = 0;
private $m_sTable = '';
private $m_sTableAlias = '';
- private $m_aFields = array();
- private $m_aGroupBy = array();
+ private $m_aFields = [];
+ private $m_aGroupBy = [];
private $m_oConditionExpr = null;
private $m_bToDelete = true; // The current table must be listed for deletion ?
- private $m_aValues = array(); // Values to set in case of an update query
+ private $m_aValues = []; // Values to set in case of an update query
private $m_oSelectedIdField = null;
- private $m_aJoinSelects = array();
+ private $m_aJoinSelects = [];
protected $m_bBeautifulQuery = false;
// Data set by PrepareRendering()
@@ -57,8 +55,7 @@ class SQLObjectQuery extends SQLQuery
private $__aSetValues;
private $__aSelectedIdFields;
-
- public function __construct($sTable, $sTableAlias, $aFields, $bToDelete = true, $aValues = array(), $oSelectedIdField = null)
+ public function __construct($sTable, $sTableAlias, $aFields, $bToDelete = true, $aValues = [], $oSelectedIdField = null)
{
parent::__construct();
@@ -89,12 +86,11 @@ class SQLObjectQuery extends SQLQuery
public function DisplayHtml()
{
- if (count($this->m_aFields) == 0) $sFields = "";
- else
- {
- $aFieldDesc = array();
- foreach ($this->m_aFields as $sAlias => $oExpression)
- {
+ if (count($this->m_aFields) == 0) {
+ $sFields = "";
+ } else {
+ $aFieldDesc = [];
+ foreach ($this->m_aFields as $sAlias => $oExpression) {
$aFieldDesc[] = $oExpression->RenderExpression(false)." as $sAlias ";
}
$sFields = " => ".implode(', ', $aFieldDesc);
@@ -102,26 +98,21 @@ class SQLObjectQuery extends SQLQuery
echo "$this->m_sTable $sFields \n";
// #@# todo - display html of an expression tree
//$this->m_oConditionExpr->DisplayHtml()
- if (count($this->m_aJoinSelects) > 0)
- {
+ if (count($this->m_aJoinSelects) > 0) {
echo "Joined to... \n";
echo "