');
$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/xlsxwriter.class.php b/application/xlsxwriter.class.php
index 853adc1a0..528d61d4f 100644
--- a/application/xlsxwriter.class.php
+++ b/application/xlsxwriter.class.php
@@ -1,43 +1,51 @@
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..5931cc909 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,15 +545,11 @@ 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());
@@ -570,49 +560,36 @@ class ActionEmail extends ActionNotification
// 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/autoload.php b/core/autoload.php
index f89eda208..83f4e972c 100644
--- a/core/autoload.php
+++ b/core/autoload.php
@@ -1,9 +1,10 @@
-
/**
* 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/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/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/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/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/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/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/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..1606439dc 100644
--- a/core/designdocument.class.inc.php
+++ b/core/designdocument.class.inc.php
@@ -1,4 +1,5 @@
query($sXPath);
- }
- else
- {
+ } else {
$oResult = $oXPath->query($sXPath, $oContextNode);
}
return $oResult;
@@ -174,8 +167,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 +300,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 +331,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 +358,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 +417,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 +471,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/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/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/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/log.class.inc.php b/core/log.class.inc.php
index a1688afdc..b79703ebf 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.
*
@@ -715,32 +691,32 @@ abstract class LogAPI
static::$m_oMockMetaModelConfig = $oMetaModelConfig;
}
- public static function Error($sMessage, $sChannel = null, $aContext = array())
+ public static function Error($sMessage, $sChannel = null, $aContext = [])
{
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);
}
@@ -748,7 +724,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}'");
@@ -766,7 +742,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)
@@ -918,15 +894,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;
}
}
@@ -994,13 +968,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;
@@ -1017,14 +991,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;
}
@@ -1037,17 +1011,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);
@@ -1056,8 +1029,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;
@@ -1082,14 +1054,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
@@ -1137,8 +1108,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;
}
@@ -1153,7 +1123,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';
}
@@ -1248,8 +1219,7 @@ class DeprecatedCallsLog extends LogAPI
if (!static::IsLogLevelEnabled(self::LEVEL_WARNING, self::ENUM_CHANNEL_FILE)) {
return;
}
- }
- catch (ConfigException $e) {
+ } catch (ConfigException $e) {
return;
}
@@ -1290,8 +1260,7 @@ class DeprecatedCallsLog extends LogAPI
if (!static::IsLogLevelEnabled(self::LEVEL_WARNING, self::ENUM_CHANNEL_PHP_API)) {
return;
}
- }
- catch (ConfigException $oException) {
+ } catch (ConfigException $oException) {
return;
}
@@ -1319,8 +1288,7 @@ class DeprecatedCallsLog extends LogAPI
if (!static::IsLogLevelEnabled(self::LEVEL_WARNING, self::ENUM_CHANNEL_PHP_METHOD)) {
return;
}
- }
- catch (ConfigException $e) {
+ } catch (ConfigException $e) {
return;
}
@@ -1328,8 +1296,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'];
}
@@ -1340,7 +1307,6 @@ class DeprecatedCallsLog extends LogAPI
$sMessage .= '. Caller: '.self::SummarizeCallStack(array_slice($aStack, 1));
-
static::Warning($sMessage, self::ENUM_CHANNEL_PHP_METHOD);
static::ForwardToTriggerError($sMessage);
}
@@ -1355,8 +1321,7 @@ class DeprecatedCallsLog extends LogAPI
if (!static::IsLogLevelEnabled(self::LEVEL_WARNING, self::ENUM_CHANNEL_PHP_ENDPOINT)) {
return;
}
- }
- catch (ConfigException $e) {
+ } catch (ConfigException $e) {
return;
}
@@ -1375,12 +1340,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 !
}
}
@@ -1412,13 +1376,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)";
}
}
@@ -1441,7 +1403,6 @@ class DeprecatedCallsLog extends LogAPI
}
}
-
class LogFileRotationProcess implements iScheduledProcess
{
/**
@@ -1449,12 +1410,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
@@ -1492,7 +1453,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);
@@ -1511,9 +1472,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();
@@ -1535,7 +1496,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 {
@@ -1558,8 +1519,7 @@ class LogFileRotationProcess implements iScheduledProcess
{
try {
$sLogFileNameBuilder = $this->GetLogFileNameBuilderClassName();
- }
- catch (ProcessException $e) {
+ } catch (ProcessException $e) {
return new DateTime('3000-01-01');
}
@@ -1575,8 +1535,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;
}
@@ -1604,7 +1563,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}'");
@@ -1626,13 +1585,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/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 3ab1ed7cf..3e10c0bdd 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,52 +137,41 @@ 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);
}
}
- $aAttributes = array();
- foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
- {
+ $aAttributes = [];
+ foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) {
$sAttributeClass = get_class($oAttDef);
- if ($aScope != null)
- {
- foreach ($aScope as $sScopeClass)
- {
- if (($sAttributeClass == $sScopeClass) || is_subclass_of($sAttributeClass, $sScopeClass))
- {
+ if ($aScope != null) {
+ foreach ($aScope as $sScopeClass) {
+ if (($sAttributeClass == $sScopeClass) || is_subclass_of($sAttributeClass, $sScopeClass)) {
$aAttributes[$sAttCode] = $sAttributeClass;
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;
}
}
@@ -196,29 +182,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;
@@ -263,19 +244,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/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..527465d4f 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());
}
}
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/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/simplecrypt.class.inc.php b/core/simplecrypt.class.inc.php
index 2875cff2e..e9c304f3d 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)
- {
+ /**
+ * 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);
- }
+ 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
+ */
+ 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);
+ }
- /**
- * 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");
- 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;
- }
+ }
}
/**
@@ -208,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);
}
/**
@@ -221,38 +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)
- {
- 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;
- }
+ 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;
+ }
}
/**
@@ -262,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
@@ -324,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)
@@ -339,17 +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;
- }
+ 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);
@@ -362,29 +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;
- }
+ 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);
@@ -396,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);
@@ -418,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;
@@ -428,16 +398,15 @@ 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;
- }
+ 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);
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 "