diff --git a/addons/userrights/userrightsprofile.class.inc.php b/addons/userrights/userrightsprofile.class.inc.php index b9ac16d84..d2560bbe8 100644 --- a/addons/userrights/userrightsprofile.class.inc.php +++ b/addons/userrights/userrightsprofile.class.inc.php @@ -1,4 +1,5 @@ "addon/userrights,grant_by_profile,filter", "key_type" => "autoincrement", "name_attcode" => "name", - "complementary_name_attcode" => array('description'), + "complementary_name_attcode" => ['description'], "state_attcode" => "", - "reconc_keys" => array(), + "reconc_keys" => [], "db_table" => "priv_urp_profiles", "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"=>false, "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" => false, "depends_on" => []])); - MetaModel::Init_AddAttribute(new AttributeLinkedSetIndirect("user_list", array("linked_class"=>"URP_UserProfile", "ext_key_to_me"=>"profileid", "ext_key_to_remote"=>"userid", "allowed_values"=>null, "count_min"=>1, "count_max"=>0, "depends_on"=>array()))); + MetaModel::Init_AddAttribute(new AttributeLinkedSetIndirect("user_list", ["linked_class" => "URP_UserProfile", "ext_key_to_me" => "profileid", "ext_key_to_remote" => "userid", "allowed_values" => null, "count_min" => 1, "count_max" => 0, "depends_on" => []])); // Display lists - MetaModel::Init_SetZListItems('details', array('name', 'description', 'user_list')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('description')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['name', 'description', 'user_list']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['description']); // Attributes to be displayed for a list // Search criteria - MetaModel::Init_SetZListItems('standard_search', array('name','description')); // Criteria of the std search form - MetaModel::Init_SetZListItems('default_search', array ('name','description')); + MetaModel::Init_SetZListItems('standard_search', ['name','description']); // Criteria of the std search form + MetaModel::Init_SetZListItems('default_search', ['name','description']); } protected static $m_aCacheProfiles = null; public static function DoCreateProfile($sName, $sDescription) { - if (is_null(self::$m_aCacheProfiles)) - { - self::$m_aCacheProfiles = array(); + if (is_null(self::$m_aCacheProfiles)) { + self::$m_aCacheProfiles = []; $oFilterAll = new DBObjectSearch('URP_Profiles'); $oSet = new DBObjectSet($oFilterAll); - while ($oProfile = $oSet->Fetch()) - { + while ($oProfile = $oSet->Fetch()) { self::$m_aCacheProfiles[$oProfile->Get('name')] = $oProfile->GetKey(); } } $sCacheKey = $sName; - if (isset(self::$m_aCacheProfiles[$sCacheKey])) - { + if (isset(self::$m_aCacheProfiles[$sCacheKey])) { return self::$m_aCacheProfiles[$sCacheKey]; } $oNewObj = MetaModel::NewObject("URP_Profiles"); @@ -89,27 +86,21 @@ class URP_Profiles extends UserRightsBaseClassGUI return $iId; } - function GetGrantAsHtml($oUserRights, $sClass, $sAction) + public function GetGrantAsHtml($oUserRights, $sClass, $sAction) { $bGrant = $oUserRights->GetProfileActionGrant($this->GetKey(), $sClass, $sAction); - if (is_null($bGrant)) - { + if (is_null($bGrant)) { return ''.Dict::S('UI:UserManagement:ActionAllowed:No').''; - } - elseif ($bGrant) - { + } elseif ($bGrant) { return ''.Dict::S('UI:UserManagement:ActionAllowed:Yes').''; - } - else - { + } else { return ''.Dict::S('UI:UserManagement:ActionAllowed:No').''; } } - function DoShowGrantSumary($oPage) + public function DoShowGrantSumary($oPage) { - if ($this->GetRawName() == "Administrator") - { + if ($this->GetRawName() == "Administrator") { // Looks dirty, but ok that's THE ONE $oPage->p(Dict::S('UI:UserManagement:AdminProfile+')); return; @@ -118,21 +109,18 @@ class URP_Profiles extends UserRightsBaseClassGUI // Note: for sure, we assume that the instance is derived from UserRightsProfile $oUserRights = UserRights::GetModuleInstance(); - $aDisplayData = array(); - foreach (MetaModel::GetClasses('bizmodel,grant_by_profile') as $sClass) - { - $aStimuli = array(); - foreach (MetaModel::EnumStimuli($sClass) as $sStimulusCode => $oStimulus) - { + $aDisplayData = []; + foreach (MetaModel::GetClasses('bizmodel,grant_by_profile') as $sClass) { + $aStimuli = []; + foreach (MetaModel::EnumStimuli($sClass) as $sStimulusCode => $oStimulus) { $bGrant = $oUserRights->GetClassStimulusGrant($this->GetKey(), $sClass, $sStimulusCode); - if ($bGrant === true) - { + if ($bGrant === true) { $aStimuli[] = ''.utils::EscapeHtml($oStimulus->GetLabel()).''; } } $sStimuli = implode(', ', $aStimuli); - $aDisplayData[] = array( + $aDisplayData[] = [ 'class' => MetaModel::GetName($sClass), 'read' => $this->GetGrantAsHtml($oUserRights, $sClass, 'r'), 'bulkread' => $this->GetGrantAsHtml($oUserRights, $sClass, 'br'), @@ -141,22 +129,22 @@ class URP_Profiles extends UserRightsBaseClassGUI 'delete' => $this->GetGrantAsHtml($oUserRights, $sClass, 'd'), 'bulkdelete' => $this->GetGrantAsHtml($oUserRights, $sClass, 'bd'), 'stimuli' => $sStimuli, - ); + ]; } - $aDisplayConfig = array(); - $aDisplayConfig['class'] = array('label' => Dict::S('UI:UserManagement:Class'), 'description' => Dict::S('UI:UserManagement:Class+')); - $aDisplayConfig['read'] = array('label' => Dict::S('UI:UserManagement:Action:Read'), 'description' => Dict::S('UI:UserManagement:Action:Read+')); - $aDisplayConfig['bulkread'] = array('label' => Dict::S('UI:UserManagement:Action:BulkRead'), 'description' => Dict::S('UI:UserManagement:Action:BulkRead+')); - $aDisplayConfig['write'] = array('label' => Dict::S('UI:UserManagement:Action:Modify'), 'description' => Dict::S('UI:UserManagement:Action:Modify+')); - $aDisplayConfig['bulkwrite'] = array('label' => Dict::S('UI:UserManagement:Action:BulkModify'), 'description' => Dict::S('UI:UserManagement:Action:BulkModify+')); - $aDisplayConfig['delete'] = array('label' => Dict::S('UI:UserManagement:Action:Delete'), 'description' => Dict::S('UI:UserManagement:Action:Delete+')); - $aDisplayConfig['bulkdelete'] = array('label' => Dict::S('UI:UserManagement:Action:BulkDelete'), 'description' => Dict::S('UI:UserManagement:Action:BulkDelete+')); - $aDisplayConfig['stimuli'] = array('label' => Dict::S('UI:UserManagement:Action:Stimuli'), 'description' => Dict::S('UI:UserManagement:Action:Stimuli+')); + $aDisplayConfig = []; + $aDisplayConfig['class'] = ['label' => Dict::S('UI:UserManagement:Class'), 'description' => Dict::S('UI:UserManagement:Class+')]; + $aDisplayConfig['read'] = ['label' => Dict::S('UI:UserManagement:Action:Read'), 'description' => Dict::S('UI:UserManagement:Action:Read+')]; + $aDisplayConfig['bulkread'] = ['label' => Dict::S('UI:UserManagement:Action:BulkRead'), 'description' => Dict::S('UI:UserManagement:Action:BulkRead+')]; + $aDisplayConfig['write'] = ['label' => Dict::S('UI:UserManagement:Action:Modify'), 'description' => Dict::S('UI:UserManagement:Action:Modify+')]; + $aDisplayConfig['bulkwrite'] = ['label' => Dict::S('UI:UserManagement:Action:BulkModify'), 'description' => Dict::S('UI:UserManagement:Action:BulkModify+')]; + $aDisplayConfig['delete'] = ['label' => Dict::S('UI:UserManagement:Action:Delete'), 'description' => Dict::S('UI:UserManagement:Action:Delete+')]; + $aDisplayConfig['bulkdelete'] = ['label' => Dict::S('UI:UserManagement:Action:BulkDelete'), 'description' => Dict::S('UI:UserManagement:Action:BulkDelete+')]; + $aDisplayConfig['stimuli'] = ['label' => Dict::S('UI:UserManagement:Action:Stimuli'), 'description' => Dict::S('UI:UserManagement:Action:Stimuli+')]; $oPage->table($aDisplayConfig, $aDisplayData); } - function DisplayBareRelations(WebPage $oPage, $bEditMode = false) + public function DisplayBareRelations(WebPage $oPage, $bEditMode = false) { parent::DisplayBareRelations($oPage, $bEditMode); @@ -166,10 +154,9 @@ class URP_Profiles extends UserRightsBaseClassGUI public static function GetReadOnlyAttributes() { - return array('name', 'description'); + return ['name', 'description']; } - // returns an array of id => array of column => php value(so-called "real value") public static function GetPredefinedObjects() { @@ -181,15 +168,13 @@ class URP_Profiles extends UserRightsBaseClassGUI protected function OnDelete() { // Don't remove admin profile - if ($this->Get('name') === ADMIN_PROFILE_NAME) - { + if ($this->Get('name') === ADMIN_PROFILE_NAME) { throw new SecurityException(Dict::Format('UI:Login:Error:AccessAdmin')); } // Note: this may break the rule that says: "a user must have at least ONE profile" ! $oLnkSet = $this->Get('user_list'); - while($oLnk = $oLnkSet->Fetch()) - { + while ($oLnk = $oLnkSet->Fetch()) { $oLnk->DBDelete(); } } @@ -202,11 +187,10 @@ class URP_Profiles extends UserRightsBaseClassGUI * @param $sTargetState string The target state in which to evalutate the flags, if empty the current state will be used * @return integer Flags: the binary combination of the flags applicable to this attribute */ - public function GetAttributeFlags($sAttCode, &$aReasons = array(), $sTargetState = '') + public function GetAttributeFlags($sAttCode, &$aReasons = [], $sTargetState = '') { $iFlags = parent::GetAttributeFlags($sAttCode, $aReasons, $sTargetState); - if (MetaModel::GetConfig()->Get('demo_mode')) - { + if (MetaModel::GetConfig()->Get('demo_mode')) { $aReasons[] = 'Sorry, profiles are read-only in the demonstration mode!'; $iFlags |= OPT_ATT_READONLY; } @@ -214,52 +198,52 @@ class URP_Profiles extends UserRightsBaseClassGUI } } - - class URP_UserProfile extends UserRightsBaseClassGUI { public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "addon/userrights,grant_by_profile,filter", "key_type" => "autoincrement", - "name_attcode" => array("userlogin", "profile"), + "name_attcode" => ["userlogin", "profile"], "state_attcode" => "", - "reconc_keys" => array(), + "reconc_keys" => [], "db_table" => "priv_urp_userprofile", "db_key_field" => "id", "db_finalclass_field" => "", "is_link" => true, /** @since 3.1.0 N°6482 */ - 'uniqueness_rules' => array( - 'no_duplicate' => array( - 'attributes' => array( + 'uniqueness_rules' => [ + 'no_duplicate' => [ + 'attributes' => [ 0 => 'userid', 1 => 'profileid', - ), + ], 'filter' => '', 'disabled' => false, 'is_blocking' => true, - ), - ), - ); + ], + ], + ]; MetaModel::Init_Params($aParams); //MetaModel::Init_InheritAttributes(); - MetaModel::Init_AddAttribute(new AttributeExternalKey("userid", array("targetclass" => "User", "jointype" => "", "allowed_values" => null, "sql" => "userid", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => array()))); - MetaModel::Init_AddAttribute(new AttributeExternalField("userlogin", array("allowed_values" => null, "extkey_attcode" => 'userid', "target_attcode" => "login"))); + MetaModel::Init_AddAttribute(new AttributeExternalKey("userid", ["targetclass" => "User", "jointype" => "", "allowed_values" => null, "sql" => "userid", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeExternalField("userlogin", ["allowed_values" => null, "extkey_attcode" => 'userid', "target_attcode" => "login"])); - MetaModel::Init_AddAttribute(new AttributeExternalKey("profileid", - array("targetclass" => "URP_Profiles", "jointype" => "", "allowed_values" => null, "sql" => "profileid", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => array(), "allow_target_creation" => false))); - MetaModel::Init_AddAttribute(new AttributeExternalField("profile", array("allowed_values" => null, "extkey_attcode" => 'profileid', "target_attcode" => "name"))); + MetaModel::Init_AddAttribute(new AttributeExternalKey( + "profileid", + ["targetclass" => "URP_Profiles", "jointype" => "", "allowed_values" => null, "sql" => "profileid", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => [], "allow_target_creation" => false] + )); + MetaModel::Init_AddAttribute(new AttributeExternalField("profile", ["allowed_values" => null, "extkey_attcode" => 'profileid', "target_attcode" => "name"])); - MetaModel::Init_AddAttribute(new AttributeString("reason", array("allowed_values" => null, "sql" => "description", "default_value" => null, "is_null_allowed" => true, "depends_on" => array()))); + MetaModel::Init_AddAttribute(new AttributeString("reason", ["allowed_values" => null, "sql" => "description", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); // Display lists - MetaModel::Init_SetZListItems('details', array('userid', 'profileid', 'reason')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('userid', 'profileid', 'reason')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['userid', 'profileid', 'reason']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['userid', 'profileid', 'reason']); // Attributes to be displayed for a list // Search criteria - MetaModel::Init_SetZListItems('standard_search', array('userid', 'profileid')); // Criteria of the std search form - MetaModel::Init_SetZListItems('advanced_search', array('userid', 'profileid')); // Criteria of the advanced search form + MetaModel::Init_SetZListItems('standard_search', ['userid', 'profileid']); // Criteria of the std search form + MetaModel::Init_SetZListItems('advanced_search', ['userid', 'profileid']); // Criteria of the advanced search form } public function CheckToDelete(&$oDeletionPlan) @@ -267,15 +251,14 @@ class URP_UserProfile extends UserRightsBaseClassGUI if (MetaModel::GetConfig()->Get('demo_mode')) { // Users deletion is NOT allowed in demo mode $oDeletionPlan->AddToDelete($this, null); - $oDeletionPlan->SetDeletionIssues($this, array('deletion not allowed in demo mode.'), true); + $oDeletionPlan->SetDeletionIssues($this, ['deletion not allowed in demo mode.'], true); $oDeletionPlan->ComputeResults(); return false; } try { $this->CheckIfProfileIsAllowed(UR_ACTION_DELETE); - } - catch (SecurityException $e) { + } catch (SecurityException $e) { // Users deletion is NOT allowed $oDeletionPlan->AddToDelete($this, null); $oDeletionPlan->SetDeletionIssues($this, [$e->getMessage()], true); @@ -292,15 +275,14 @@ class URP_UserProfile extends UserRightsBaseClassGUI if (MetaModel::GetConfig()->Get('demo_mode')) { // Users deletion is NOT allowed in demo mode $oDeletionPlan->AddToDelete($this, null); - $oDeletionPlan->SetDeletionIssues($this, array('deletion not allowed in demo mode.'), true); + $oDeletionPlan->SetDeletionIssues($this, ['deletion not allowed in demo mode.'], true); $oDeletionPlan->ComputeResults(); return false; } try { $this->CheckIfProfileIsAllowed(UR_ACTION_DELETE); - } - catch (SecurityException $e) { + } catch (SecurityException $e) { // Users deletion is NOT allowed $oDeletionPlan->AddToDelete($this, null); $oDeletionPlan->SetDeletionIssues($this, [$e->getMessage()], true); @@ -336,33 +318,30 @@ class URP_UserProfile extends UserRightsBaseClassGUI protected function CheckIfProfileIsAllowed($iActionCode) { // When initializing or admin, we need to let everything pass trough - if (!UserRights::IsLoggedIn() || UserRights::IsAdministrator()) { return; } + if (!UserRights::IsLoggedIn() || UserRights::IsAdministrator()) { + return; + } // Only administrators can manage administrators $iOrigUserId = $this->GetOriginal('userid'); - if (!empty($iOrigUserId)) - { + if (!empty($iOrigUserId)) { $oUser = MetaModel::GetObject('User', $iOrigUserId, true, true); - if (UserRights::IsAdministrator($oUser) && !UserRights::IsAdministrator()) - { + if (UserRights::IsAdministrator($oUser) && !UserRights::IsAdministrator()) { throw new SecurityException(Dict::Format('UI:Login:Error:AccessRestricted')); } } $oUser = MetaModel::GetObject('User', $this->Get('userid'), true, true); - if (UserRights::IsAdministrator($oUser) && !UserRights::IsAdministrator()) - { + if (UserRights::IsAdministrator($oUser) && !UserRights::IsAdministrator()) { throw new SecurityException(Dict::Format('UI:Login:Error:AccessRestricted')); } $oSet = new \ormLinkSet(get_class($oUser), 'profile_list', \DBObjectSet::FromScratch(\URP_UserProfile::class)); $oSet->AddItem(MetaModel::NewObject('URP_UserProfile', ['profileid' => $this->GetKey(), 'reason' => 'CheckIfProfileIsAllowed'])); - if (!UserRights::IsActionAllowed(get_class($this), $iActionCode, $oSet)) - { + if (!UserRights::IsActionAllowed(get_class($this), $iActionCode, $oSet)) { throw new SecurityException(Dict::Format('UI:Error:ObjectCannotBeUpdated')); } - if (!UserRights::IsAdministrator() && ($this->Get('profile') === ADMIN_PROFILE_NAME)) - { + if (!UserRights::IsAdministrator() && ($this->Get('profile') === ADMIN_PROFILE_NAME)) { throw new SecurityException(Dict::Format('UI:Login:Error:AccessAdmin')); } } @@ -373,33 +352,33 @@ class URP_UserOrg extends UserRightsBaseClassGUI { public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "addon/userrights,grant_by_profile", "key_type" => "autoincrement", - "name_attcode" => array("userlogin", "allowed_org_name"), + "name_attcode" => ["userlogin", "allowed_org_name"], "state_attcode" => "", - "reconc_keys" => array(), + "reconc_keys" => [], "db_table" => "priv_urp_userorg", "db_key_field" => "id", "db_finalclass_field" => "", - ); + ]; MetaModel::Init_Params($aParams); //MetaModel::Init_InheritAttributes(); - MetaModel::Init_AddAttribute(new AttributeExternalKey("userid", array("targetclass"=>"User", "jointype"=> "", "allowed_values"=>null, "sql"=>"userid", "is_null_allowed"=>false, "on_target_delete"=>DEL_AUTO, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeExternalField("userlogin", array("allowed_values"=>null, "extkey_attcode"=> 'userid', "target_attcode"=>"login"))); + MetaModel::Init_AddAttribute(new AttributeExternalKey("userid", ["targetclass" => "User", "jointype" => "", "allowed_values" => null, "sql" => "userid", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeExternalField("userlogin", ["allowed_values" => null, "extkey_attcode" => 'userid', "target_attcode" => "login"])); - MetaModel::Init_AddAttribute(new AttributeExternalKey("allowed_org_id", array("targetclass"=>"Organization", "jointype"=> "", "allowed_values"=>null, "sql"=>"allowed_org_id", "is_null_allowed"=>false, "on_target_delete"=>DEL_AUTO, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeExternalField("allowed_org_name", array("allowed_values"=>null, "extkey_attcode"=> 'allowed_org_id', "target_attcode"=>"name"))); + MetaModel::Init_AddAttribute(new AttributeExternalKey("allowed_org_id", ["targetclass" => "Organization", "jointype" => "", "allowed_values" => null, "sql" => "allowed_org_id", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeExternalField("allowed_org_name", ["allowed_values" => null, "extkey_attcode" => 'allowed_org_id', "target_attcode" => "name"])); - MetaModel::Init_AddAttribute(new AttributeString("reason", array("allowed_values"=>null, "sql"=>"reason", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); + MetaModel::Init_AddAttribute(new AttributeString("reason", ["allowed_values" => null, "sql" => "reason", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); // Display lists - MetaModel::Init_SetZListItems('details', array('userid', 'allowed_org_id', 'reason')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('allowed_org_id', 'reason')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['userid', 'allowed_org_id', 'reason']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['allowed_org_id', 'reason']); // Attributes to be displayed for a list // Search criteria - MetaModel::Init_SetZListItems('standard_search', array('userid', 'allowed_org_id')); // Criteria of the std search form - MetaModel::Init_SetZListItems('advanced_search', array('userid', 'allowed_org_id')); // Criteria of the advanced search form + MetaModel::Init_SetZListItems('standard_search', ['userid', 'allowed_org_id']); // Criteria of the std search form + MetaModel::Init_SetZListItems('advanced_search', ['userid', 'allowed_org_id']); // Criteria of the advanced search form } protected function OnInsert() @@ -422,40 +401,37 @@ class URP_UserOrg extends UserRightsBaseClassGUI */ protected function CheckIfOrgIsAllowed() { - if (!UserRights::IsLoggedIn() || UserRights::IsAdministrator()) { return; } + if (!UserRights::IsLoggedIn() || UserRights::IsAdministrator()) { + return; + } $oUser = UserRights::GetUserObject(); $oAddon = UserRights::GetModuleInstance(); $aOrgs = $oAddon->GetUserOrgs($oUser, ''); - if (count($aOrgs) > 0) - { + if (count($aOrgs) > 0) { $iOrigOrgId = $this->GetOriginal('allowed_org_id'); - if ((!empty($iOrigOrgId) && !in_array($iOrigOrgId, $aOrgs)) || !in_array($this->Get('allowed_org_id'), $aOrgs)) - { + if ((!empty($iOrigOrgId) && !in_array($iOrigOrgId, $aOrgs)) || !in_array($this->Get('allowed_org_id'), $aOrgs)) { throw new SecurityException(Dict::Format('Class:User/Error:OrganizationNotAllowed')); } } } } - - - class UserRightsProfile extends UserRightsAddOnAPI { - static public $m_aActionCodes = array( + public static $m_aActionCodes = [ UR_ACTION_READ => 'r', UR_ACTION_MODIFY => 'w', UR_ACTION_DELETE => 'd', UR_ACTION_BULK_READ => 'br', UR_ACTION_BULK_MODIFY => 'bw', UR_ACTION_BULK_DELETE => 'bd', - ); + ]; - /** - * @var array $aUsersProfilesList Cache of users' profiles. Hash array of user ID => [profile ID => profile friendlyname, profile ID => profile friendlyname, ...] - * @since 2.7.10 3.0.4 3.1.1 3.2.0 N°6887 - */ + /** + * @var array $aUsersProfilesList Cache of users' profiles. Hash array of user ID => [profile ID => profile friendlyname, profile ID => profile friendlyname, ...] + * @since 2.7.10 3.0.4 3.1.1 3.2.0 N°6887 + */ private $aUsersProfilesList = []; // Installation: create the very first user @@ -476,8 +452,7 @@ class UserRightsProfile extends UserRightsAddOnAPI $oContact = MetaModel::NewObject('Person'); $oContact->Set('name', 'My last name'); $oContact->Set('first_name', 'My first name'); - if (MetaModel::IsValidAttCode('Person', 'org_id')) - { + if (MetaModel::IsValidAttCode('Person', 'org_id')) { $oContact->Set('org_id', $iOrgId); } $oContact->Set('email', 'my.email@foo.org'); @@ -485,20 +460,17 @@ class UserRightsProfile extends UserRightsAddOnAPI } } - $oUser = new UserLocal(); $oUser->Set('login', $sAdminUser); $oUser->Set('password', $sAdminPwd); - if (MetaModel::IsValidAttCode('UserLocal', 'contactid') && ($iContactId != 0)) - { + if (MetaModel::IsValidAttCode('UserLocal', 'contactid') && ($iContactId != 0)) { $oUser->Set('contactid', $iContactId); } $oUser->Set('language', $sLanguage); // Language was chosen during the installation // Add this user to the very specific 'admin' profile - $oAdminProfile = MetaModel::GetObjectFromOQL("SELECT URP_Profiles WHERE name = :name", array('name' => ADMIN_PROFILE_NAME), true /*all data*/); - if (is_object($oAdminProfile)) - { + $oAdminProfile = MetaModel::GetObjectFromOQL("SELECT URP_Profiles WHERE name = :name", ['name' => ADMIN_PROFILE_NAME], true /*all data*/); + if (is_object($oAdminProfile)) { $oSet = new \ormLinkSet(UserLocal::class, 'profile_list', \DBObjectSet::FromScratch(\URP_UserProfile::class)); $oSet->AddItem(MetaModel::NewObject('URP_UserProfile', ['profileid' => $oAdminProfile->GetKey(), 'reason' => 'CreateAdministrator'])); $oUser->Set('profile_list', $oSet); @@ -511,11 +483,11 @@ class UserRightsProfile extends UserRightsAddOnAPI { } - protected $m_aUserOrgs = array(); // userid -> array of orgid + protected $m_aUserOrgs = []; // userid -> array of orgid protected $m_aAdministrators = null; // [user id] // Built on demand, could be optimized if necessary (doing a query for each attribute that needs to be read) - protected $m_aObjectActionGrants = array(); + protected $m_aObjectActionGrants = []; /** * Read and cache organizations allowed to the given user @@ -530,31 +502,25 @@ class UserRightsProfile extends UserRightsAddOnAPI public function GetUserOrgs($oUser, $sClass) { $iUser = $oUser->GetKey(); - if (!array_key_exists($iUser, $this->m_aUserOrgs)) - { - $this->m_aUserOrgs[$iUser] = array(); + if (!array_key_exists($iUser, $this->m_aUserOrgs)) { + $this->m_aUserOrgs[$iUser] = []; $sHierarchicalKeyCode = MetaModel::IsHierarchicalClass('Organization'); - if ($sHierarchicalKeyCode !== false) - { + if ($sHierarchicalKeyCode !== false) { $sUserOrgQuery = 'SELECT UserOrg, Org FROM Organization AS Org JOIN Organization AS Root ON Org.'.$sHierarchicalKeyCode.' BELOW Root.id JOIN URP_UserOrg AS UserOrg ON UserOrg.allowed_org_id = Root.id WHERE UserOrg.userid = :userid'; - $oUserOrgSet = new DBObjectSet(DBObjectSearch::FromOQL_AllData($sUserOrgQuery), array(), array('userid' => $iUser)); - while ($aRow = $oUserOrgSet->FetchAssoc()) - { + $oUserOrgSet = new DBObjectSet(DBObjectSearch::FromOQL_AllData($sUserOrgQuery), [], ['userid' => $iUser]); + while ($aRow = $oUserOrgSet->FetchAssoc()) { $oOrg = $aRow['Org']; $this->m_aUserOrgs[$iUser][] = $oOrg->GetKey(); } - } - else - { + } else { $oSearch = new DBObjectSearch('URP_UserOrg'); $oSearch->AllowAllData(); $oCondition = new BinaryExpression(new FieldExpression('userid'), '=', new VariableExpression('userid')); $oSearch->AddConditionExpression($oCondition); - $oUserOrgSet = new DBObjectSet($oSearch, array(), array('userid' => $iUser)); - while ($oUserOrg = $oUserOrgSet->Fetch()) - { + $oUserOrgSet = new DBObjectSet($oSearch, [], ['userid' => $iUser]); + while ($oUserOrg = $oUserOrgSet->Fetch()) { $this->m_aUserOrgs[$iUser][] = $oUserOrg->Get('allowed_org_id'); } } @@ -565,21 +531,19 @@ class UserRightsProfile extends UserRightsAddOnAPI public function ResetCache() { // Loaded by Load cache - $this->m_aUserOrgs = array(); + $this->m_aUserOrgs = []; // Cache - $this->m_aObjectActionGrants = array(); + $this->m_aObjectActionGrants = []; $this->m_aAdministrators = null; } public function LoadCache() { static $bSharedObjectInitialized = false; - if (!$bSharedObjectInitialized) - { + if (!$bSharedObjectInitialized) { $bSharedObjectInitialized = true; - if (self::HasSharing()) - { + if (self::HasSharing()) { SharedObject::InitSharedClassProperties(); } } @@ -617,45 +581,40 @@ class UserRightsProfile extends UserRightsAddOnAPI */ public function ListProfiles($oUser) { - $aRet = array(); + $aRet = []; $oSearch = new DBObjectSearch('URP_UserProfile'); $oSearch->AllowAllData(); $oSearch->NoContextParameters(); $oSearch->Addcondition('userid', $oUser->GetKey(), '='); $oProfiles = new DBObjectSet($oSearch); - while ($oUserProfile = $oProfiles->Fetch()) - { + while ($oUserProfile = $oProfiles->Fetch()) { $aRet[$oUserProfile->Get('profileid')] = $oUserProfile->Get('profileid_friendlyname'); } return $aRet; } - public function GetSelectFilter($oUser, $sClass, $aSettings = array()) + public function GetSelectFilter($oUser, $sClass, $aSettings = []) { $this->LoadCache(); // Let us pass an administrator for bypassing the grant matrix check in order to test this method without the need to set up a complex profile // In the nominal case Administrators never end up here (since they completely bypass GetSelectFilter) - if (!static::IsAdministrator($oUser) && (MetaModel::HasCategory($sClass, 'silo') || MetaModel::HasCategory($sClass, 'bizmodel'))) - { + if (!static::IsAdministrator($oUser) && (MetaModel::HasCategory($sClass, 'silo') || MetaModel::HasCategory($sClass, 'bizmodel'))) { // N°4354 - Categories 'silo' and 'bizmodel' do check the grant matrix. Whereas 'filter' always allows to read (but the result can be filtered) $aObjectPermissions = $this->GetUserActionGrant($oUser, $sClass, UR_ACTION_READ); - if ($aObjectPermissions['permission'] == UR_ALLOWED_NO) - { + if ($aObjectPermissions['permission'] == UR_ALLOWED_NO) { return false; } } $oFilter = true; - $aConditions = array(); + $aConditions = []; // Determine if this class is part of a silo and build the filter for it $sAttCode = self::GetOwnerOrganizationAttCode($sClass); - if (!is_null($sAttCode)) - { + if (!is_null($sAttCode)) { $aUserOrgs = $this->GetUserOrgs($oUser, $sClass); - if (count($aUserOrgs) > 0) - { + if (count($aUserOrgs) > 0) { $oFilter = $this->MakeSelectFilter($sClass, $aUserOrgs, $aSettings, $sAttCode); } // else: No org means 'any org' @@ -664,20 +623,15 @@ class UserRightsProfile extends UserRightsAddOnAPI // Specific conditions to hide, for non-administrators, the Administrator Users, the Administrator Profile and related links // Note: when logged as an administrator, GetSelectFilter is completely bypassed. - if ($this->AdministratorsAreHidden()) - { - if ($sClass == 'URP_Profiles') - { + if ($this->AdministratorsAreHidden()) { + if ($sClass == 'URP_Profiles') { $oExpression = new FieldExpression('id', $sClass); $oScalarExpr = new ScalarExpression(1); $aConditions[] = new BinaryExpression($oExpression, '!=', $oScalarExpr); - } - else if (($sClass == 'URP_UserProfile') || ($sClass == 'User') || (is_subclass_of($sClass, 'User'))) - { + } elseif (($sClass == 'URP_UserProfile') || ($sClass == 'User') || (is_subclass_of($sClass, 'User'))) { $aAdministrators = $this->GetAdministrators(); - if (count($aAdministrators) > 0) - { + if (count($aAdministrators) > 0) { $sAttCode = ($sClass == 'URP_UserProfile') ? 'userid' : 'id'; $oExpression = new FieldExpression($sAttCode, $sClass); $oListExpr = ListExpression::FromScalars($aAdministrators); @@ -687,17 +641,14 @@ class UserRightsProfile extends UserRightsAddOnAPI } // Handling of the added conditions - if (count($aConditions) > 0) - { - if($oFilter === true) - { + if (count($aConditions) > 0) { + if ($oFilter === true) { // No 'silo' filter, let's build a clean one $oFilter = new DBObjectSearch($sClass); } // Add the conditions to the filter - foreach($aConditions as $oCondition) - { + foreach ($aConditions as $oCondition) { $oFilter->AddConditionExpression($oCondition); } } @@ -712,10 +663,9 @@ class UserRightsProfile extends UserRightsAddOnAPI */ private function GetAdministrators() { - if ($this->m_aAdministrators === null) - { + if ($this->m_aAdministrators === null) { // Find all administrators - $this->m_aAdministrators = array(); + $this->m_aAdministrators = []; $oAdministratorsFilter = new DBObjectSearch('User'); $oLnkFilter = new DBObjectSearch('URP_UserProfile'); $oExpression = new FieldExpression('profileid', 'URP_UserProfile'); @@ -725,9 +675,8 @@ class UserRightsProfile extends UserRightsAddOnAPI $oAdministratorsFilter->AddCondition_ReferencedBy($oLnkFilter, 'userid'); $oAdministratorsFilter->AllowAllData(true); // Mandatory to prevent infinite recursion !! $oSet = new DBObjectSet($oAdministratorsFilter); - $oSet->OptimizeColumnLoad(array('User' => array('login'))); - while($oUser = $oSet->Fetch()) - { + $oSet->OptimizeColumnLoad(['User' => ['login']]); + while ($oUser = $oSet->Fetch()) { $this->m_aAdministrators[] = $oUser->GetKey(); } } @@ -743,7 +692,6 @@ class UserRightsProfile extends UserRightsAddOnAPI return ((bool)MetaModel::GetConfig()->Get('security.hide_administrators')); } - // This verb has been made public to allow the development of an accurate feedback for the current configuration public function GetProfileActionGrant($iProfile, $sClass, $sAction) { @@ -760,33 +708,29 @@ class UserRightsProfile extends UserRightsAddOnAPI // load and cache permissions for the current user on the given class // $iUser = $oUser->GetKey(); - if (isset($this->m_aObjectActionGrants[$iUser][$sClass][$iActionCode])){ + if (isset($this->m_aObjectActionGrants[$iUser][$sClass][$iActionCode])) { $aTest = $this->m_aObjectActionGrants[$iUser][$sClass][$iActionCode]; - if (is_array($aTest)) return $aTest; + if (is_array($aTest)) { + return $aTest; + } } $sAction = self::$m_aActionCodes[$iActionCode]; $bStatus = null; - // Cache user's profiles - if(false === array_key_exists($iUser, $this->aUsersProfilesList)){ - $this->aUsersProfilesList[$iUser] = UserRights::ListProfiles($oUser); + // Cache user's profiles + if (false === array_key_exists($iUser, $this->aUsersProfilesList)) { + $this->aUsersProfilesList[$iUser] = UserRights::ListProfiles($oUser); } // Call the API of UserRights because it caches the list for us - foreach($this->aUsersProfilesList[$iUser] as $iProfile => $oProfile) - { + foreach ($this->aUsersProfilesList[$iUser] as $iProfile => $oProfile) { $bGrant = $this->GetProfileActionGrant($iProfile, $sClass, $sAction); - if (!is_null($bGrant)) - { - if ($bGrant) - { - if (is_null($bStatus)) - { + if (!is_null($bGrant)) { + if ($bGrant) { + if (is_null($bStatus)) { $bStatus = true; } - } - else - { + } else { $bStatus = false; } } @@ -794,9 +738,9 @@ class UserRightsProfile extends UserRightsAddOnAPI $iPermission = $bStatus ? UR_ALLOWED_YES : UR_ALLOWED_NO; - $aRes = array( + $aRes = [ 'permission' => $iPermission, - ); + ]; $this->m_aObjectActionGrants[$iUser][$sClass][$iActionCode] = $aRes; return $aRes; } @@ -811,20 +755,13 @@ class UserRightsProfile extends UserRightsAddOnAPI // Note: In most cases the object set is ignored because it was interesting to optimize for huge data sets // and acceptable to consider only the root class of the object set - if ($iPermission != UR_ALLOWED_YES) - { + if ($iPermission != UR_ALLOWED_YES) { // It is already NO for everyone... that's the final word! - } - elseif ($iActionCode == UR_ACTION_READ) - { + } elseif ($iActionCode == UR_ACTION_READ) { // We are protected by GetSelectFilter: the object set contains objects allowed or shared for reading - } - elseif ($iActionCode == UR_ACTION_BULK_READ) - { + } elseif ($iActionCode == UR_ACTION_BULK_READ) { // We are protected by GetSelectFilter: the object set contains objects allowed or shared for reading - } - elseif ($oInstanceSet) - { + } elseif ($oInstanceSet) { // We are protected by GetSelectFilter: the object set contains objects allowed or shared for reading // We have to answer NO for objects shared for reading purposes if (self::HasSharing() && SharedObject::GetSharedClassProperties($sClass)) { @@ -888,8 +825,8 @@ class UserRightsProfile extends UserRightsAddOnAPI // Note: this code is VERY close to the code of IsActionAllowed() $iUser = $oUser->GetKey(); - // Cache user's profiles - if(false === array_key_exists($iUser, $this->aUsersProfilesList)){ + // Cache user's profiles + if (false === array_key_exists($iUser, $this->aUsersProfilesList)) { $this->aUsersProfilesList[$iUser] = UserRights::ListProfiles($oUser); } @@ -897,20 +834,14 @@ class UserRightsProfile extends UserRightsAddOnAPI // and acceptable to consider only the root class of the object set $bStatus = null; // Call the API of UserRights because it caches the list for us - foreach($this->aUsersProfilesList[$iUser] as $iProfile => $oProfile) - { + foreach ($this->aUsersProfilesList[$iUser] as $iProfile => $oProfile) { $bGrant = $this->GetClassStimulusGrant($iProfile, $sClass, $sStimulusCode); - if (!is_null($bGrant)) - { - if ($bGrant) - { - if (is_null($bStatus)) - { + if (!is_null($bGrant)) { + if ($bGrant) { + if (is_null($bStatus)) { $bStatus = true; } - } - else - { + } else { $bStatus = false; } } @@ -934,22 +865,16 @@ class UserRightsProfile extends UserRightsAddOnAPI { $sAttCode = null; - $aCallSpec = array($sClass, 'MapContextParam'); - if (($sClass == 'Organization') || is_subclass_of($sClass, 'Organization')) - { + $aCallSpec = [$sClass, 'MapContextParam']; + if (($sClass == 'Organization') || is_subclass_of($sClass, 'Organization')) { $sAttCode = 'id'; - } - elseif (is_callable($aCallSpec)) - { + } elseif (is_callable($aCallSpec)) { $sAttCode = call_user_func($aCallSpec, 'org_id'); // Returns null when there is no mapping for this parameter - if (!MetaModel::IsValidAttCode($sClass, $sAttCode)) - { + if (!MetaModel::IsValidAttCode($sClass, $sAttCode)) { // Skip silently. The data model checker will tell you something about this... $sAttCode = null; } - } - elseif(MetaModel::IsValidAttCode($sClass, 'org_id')) - { + } elseif (MetaModel::IsValidAttCode($sClass, 'org_id')) { $sAttCode = 'org_id'; } @@ -962,14 +887,11 @@ class UserRightsProfile extends UserRightsAddOnAPI protected static function HasSharing() { static $bHasSharing; - if (!isset($bHasSharing)) - { + if (!isset($bHasSharing)) { $bHasSharing = class_exists('SharedObject'); } return $bHasSharing; } } - UserRights::SelectModule('UserRightsProfile'); - diff --git a/application/applicationextension.inc.php b/application/applicationextension.inc.php index 76737d811..5759db1a6 100644 --- a/application/applicationextension.inc.php +++ b/application/applicationextension.inc.php @@ -74,7 +74,3 @@ require_once(APPROOT.'application/applicationextension/rest/iRestInputSanitizer. require_once(APPROOT.'application/applicationextension/rest/iRestServiceProvider.php'); require_once(APPROOT.'application/applicationextension/rest/RestResult.php'); require_once(APPROOT.'application/applicationextension/rest/RestUtils.php'); - - - - diff --git a/application/applicationextension/backoffice/AbstractApplicationUIExtension.php b/application/applicationextension/backoffice/AbstractApplicationUIExtension.php index 2b6ce1d1f..4ef62a9cc 100644 --- a/application/applicationextension/backoffice/AbstractApplicationUIExtension.php +++ b/application/applicationextension/backoffice/AbstractApplicationUIExtension.php @@ -9,64 +9,64 @@ */ abstract class AbstractApplicationUIExtension implements iApplicationUIExtension { - /** - * @inheritDoc - */ - public function OnDisplayProperties($oObject, \Combodo\iTop\Application\WebPage\WebPage $oPage, $bEditMode = false) - { - } + /** + * @inheritDoc + */ + public function OnDisplayProperties($oObject, \Combodo\iTop\Application\WebPage\WebPage $oPage, $bEditMode = false) + { + } - /** - * @inheritDoc - */ - public function OnDisplayRelations($oObject, \Combodo\iTop\Application\WebPage\WebPage $oPage, $bEditMode = false) - { - } + /** + * @inheritDoc + */ + public function OnDisplayRelations($oObject, \Combodo\iTop\Application\WebPage\WebPage $oPage, $bEditMode = false) + { + } - /** - * @inheritDoc - */ - public function OnFormSubmit($oObject, $sFormPrefix = '') - { - } + /** + * @inheritDoc + */ + public function OnFormSubmit($oObject, $sFormPrefix = '') + { + } - /** - * @inheritDoc - */ - public function OnFormCancel($sTempId) - { - } + /** + * @inheritDoc + */ + public function OnFormCancel($sTempId) + { + } - /** - * @inheritDoc - */ - public function EnumUsedAttributes($oObject) - { - return array(); - } + /** + * @inheritDoc + */ + public function EnumUsedAttributes($oObject) + { + return []; + } - /** - * @inheritDoc - */ - public function GetIcon($oObject) - { - return ''; - } + /** + * @inheritDoc + */ + public function GetIcon($oObject) + { + return ''; + } - /** - * @inheritDoc - */ - public function GetHilightClass($oObject) - { - return HILIGHT_CLASS_NONE; - } + /** + * @inheritDoc + */ + public function GetHilightClass($oObject) + { + return HILIGHT_CLASS_NONE; + } - /** - * @inheritDoc - */ - public function EnumAllowedActions(DBObjectSet $oSet) - { - return array(); - } + /** + * @inheritDoc + */ + public function EnumAllowedActions(DBObjectSet $oSet) + { + return []; + } -} \ No newline at end of file +} diff --git a/application/applicationextension/backoffice/AbstractPageUIBlockExtension.php b/application/applicationextension/backoffice/AbstractPageUIBlockExtension.php index 9a8a91a9d..b21beb4ca 100644 --- a/application/applicationextension/backoffice/AbstractPageUIBlockExtension.php +++ b/application/applicationextension/backoffice/AbstractPageUIBlockExtension.php @@ -9,27 +9,27 @@ */ abstract class AbstractPageUIBlockExtension implements iPageUIBlockExtension { - /** - * @inheritDoc - */ - public function GetBannerBlock() - { - return null; - } + /** + * @inheritDoc + */ + public function GetBannerBlock() + { + return null; + } - /** - * @inheritDoc - */ - public function GetHeaderBlock() - { - return null; - } + /** + * @inheritDoc + */ + public function GetHeaderBlock() + { + return null; + } - /** - * @inheritDoc - */ - public function GetFooterBlock() - { - return null; - } -} \ No newline at end of file + /** + * @inheritDoc + */ + public function GetFooterBlock() + { + return null; + } +} diff --git a/application/applicationextension/backoffice/AbstractPreferencesExtension.php b/application/applicationextension/backoffice/AbstractPreferencesExtension.php index 5a1ff7011..66e133eba 100644 --- a/application/applicationextension/backoffice/AbstractPreferencesExtension.php +++ b/application/applicationextension/backoffice/AbstractPreferencesExtension.php @@ -9,20 +9,20 @@ */ abstract class AbstractPreferencesExtension implements iPreferencesExtension { - /** - * @inheritDoc - */ - public function DisplayPreferences(\Combodo\iTop\Application\WebPage\WebPage $oPage) - { - // Do nothing - } + /** + * @inheritDoc + */ + public function DisplayPreferences(\Combodo\iTop\Application\WebPage\WebPage $oPage) + { + // Do nothing + } - /** - * @inheritDoc - */ - public function ApplyPreferences(\Combodo\iTop\Application\WebPage\WebPage $oPage, $sOperation) - { - // Do nothing - } + /** + * @inheritDoc + */ + public function ApplyPreferences(\Combodo\iTop\Application\WebPage\WebPage $oPage, $sOperation) + { + // Do nothing + } -} \ No newline at end of file +} diff --git a/application/applicationextension/backoffice/AbstractWelcomePopupExtension.php b/application/applicationextension/backoffice/AbstractWelcomePopupExtension.php index 6c0e7be1d..25fe70e8c 100644 --- a/application/applicationextension/backoffice/AbstractWelcomePopupExtension.php +++ b/application/applicationextension/backoffice/AbstractWelcomePopupExtension.php @@ -8,28 +8,28 @@ */ abstract class AbstractWelcomePopupExtension implements iWelcomePopupExtension { - /** - * @inheritDoc - */ - public function GetIconRelPath(): string - { - return \Combodo\iTop\Application\Branding::$aLogoPaths[\Combodo\iTop\Application\Branding::ENUM_LOGO_TYPE_MAIN_LOGO_COMPACT]['default']; - } + /** + * @inheritDoc + */ + public function GetIconRelPath(): string + { + return \Combodo\iTop\Application\Branding::$aLogoPaths[\Combodo\iTop\Application\Branding::ENUM_LOGO_TYPE_MAIN_LOGO_COMPACT]['default']; + } - /** - * @inheritDoc - */ - public function GetMessages(): array - { - return []; - } + /** + * @inheritDoc + */ + public function GetMessages(): array + { + return []; + } - /** - * @inheritDoc - */ - public function AcknowledgeMessage(string $sMessageId): void - { - // No need to process the acknowledgment notice by default - return; - } -} \ No newline at end of file + /** + * @inheritDoc + */ + public function AcknowledgeMessage(string $sMessageId): void + { + // No need to process the acknowledgment notice by default + return; + } +} diff --git a/application/applicationextension/backoffice/ApplicationPopupMenuItem.php b/application/applicationextension/backoffice/ApplicationPopupMenuItem.php index a762e0ae3..0a1baaf6b 100644 --- a/application/applicationextension/backoffice/ApplicationPopupMenuItem.php +++ b/application/applicationextension/backoffice/ApplicationPopupMenuItem.php @@ -9,142 +9,141 @@ */ abstract class ApplicationPopupMenuItem { - /** @ignore */ - protected $sUID; - /** @ignore */ - protected $sLabel; - /** @ignore */ - protected $sTooltip; - /** @ignore */ - protected $sIconClass; - /** @ignore */ - protected $aCssClasses; + /** @ignore */ + protected $sUID; + /** @ignore */ + protected $sLabel; + /** @ignore */ + protected $sTooltip; + /** @ignore */ + protected $sIconClass; + /** @ignore */ + protected $aCssClasses; - /** - * Constructor - * - * @param string $sUID The unique identifier of this menu in iTop... make sure you pass something unique enough - * @param string $sLabel The display label of the menu (must be localized) - * @api - */ - public function __construct($sUID, $sLabel) - { - $this->sUID = $sUID; - $this->sLabel = $sLabel; - $this->sTooltip = ''; - $this->sIconClass = ''; - $this->aCssClasses = array(); - } + /** + * Constructor + * + * @param string $sUID The unique identifier of this menu in iTop... make sure you pass something unique enough + * @param string $sLabel The display label of the menu (must be localized) + * @api + */ + public function __construct($sUID, $sLabel) + { + $this->sUID = $sUID; + $this->sLabel = $sLabel; + $this->sTooltip = ''; + $this->sIconClass = ''; + $this->aCssClasses = []; + } - /** - * Get the UID - * - * @return string The unique identifier - * @ignore - */ - public function GetUID() - { - return $this->sUID; - } + /** + * Get the UID + * + * @return string The unique identifier + * @ignore + */ + public function GetUID() + { + return $this->sUID; + } - /** - * Get the label - * - * @return string The label - * @ignore - */ - public function GetLabel() - { - return $this->sLabel; - } + /** + * Get the label + * + * @return string The label + * @ignore + */ + public function GetLabel() + { + return $this->sLabel; + } - /** - * Get the CSS classes - * - * @return array - * @ignore - */ - public function GetCssClasses() - { - return $this->aCssClasses; - } + /** + * Get the CSS classes + * + * @return array + * @ignore + */ + public function GetCssClasses() + { + return $this->aCssClasses; + } - /** - * @param $aCssClasses - * @api - */ - public function SetCssClasses($aCssClasses) - { - $this->aCssClasses = $aCssClasses; - } + /** + * @param $aCssClasses + * @api + */ + public function SetCssClasses($aCssClasses) + { + $this->aCssClasses = $aCssClasses; + } - /** - * Adds a CSS class to the CSS classes that will be put on the menu item - * - * @param $sCssClass - * @api - */ - public function AddCssClass($sCssClass) - { - $this->aCssClasses[] = $sCssClass; - } + /** + * Adds a CSS class to the CSS classes that will be put on the menu item + * + * @param $sCssClass + * @api + */ + public function AddCssClass($sCssClass) + { + $this->aCssClasses[] = $sCssClass; + } + /** + * @param $sTooltip + * + * @api + * @since 3.0.0 + */ + public function SetTooltip($sTooltip) + { + $this->sTooltip = $sTooltip; + } - /** - * @param $sTooltip - * - * @api - * @since 3.0.0 - */ - public function SetTooltip($sTooltip) - { - $this->sTooltip = $sTooltip; - } + /** + * @return string + * + * @api + * @since 3.0.0 + */ + public function GetTooltip() + { + return $this->sTooltip; + } - /** - * @return string - * - * @api - * @since 3.0.0 - */ - public function GetTooltip() - { - return $this->sTooltip; - } + /** + * @param $sIconClass + * + * @api + * @since 3.0.0 + */ + public function SetIconClass($sIconClass) + { + $this->sIconClass = $sIconClass; + } - /** - * @param $sIconClass - * - * @api - * @since 3.0.0 - */ - public function SetIconClass($sIconClass) - { - $this->sIconClass = $sIconClass; - } + /** + * @return string + * + * @api + * @since 3.0.0 + */ + public function GetIconClass() + { + return $this->sIconClass; + } - /** - * @return string - * - * @api - * @since 3.0.0 - */ - public function GetIconClass() - { - return $this->sIconClass; - } + /** + * Returns the components to create a popup menu item in HTML + * + * @return array A hash array: array('label' => , 'url' => , 'target' => , 'onclick' => ) + * @ignore + */ + abstract public function GetMenuItem(); - /** - * Returns the components to create a popup menu item in HTML - * - * @return array A hash array: array('label' => , 'url' => , 'target' => , 'onclick' => ) - * @ignore - */ - abstract public function GetMenuItem(); - - /** @ignore */ - public function GetLinkedScripts() - { - return array(); - } -} \ No newline at end of file + /** @ignore */ + public function GetLinkedScripts() + { + return []; + } +} diff --git a/application/applicationextension/backoffice/JSButtonItem.php b/application/applicationextension/backoffice/JSButtonItem.php index dab951ca4..ec674f358 100644 --- a/application/applicationextension/backoffice/JSButtonItem.php +++ b/application/applicationextension/backoffice/JSButtonItem.php @@ -9,5 +9,4 @@ */ class JSButtonItem extends JSPopupMenuItem { - -} \ No newline at end of file +} diff --git a/application/applicationextension/backoffice/JSPopupMenuItem.php b/application/applicationextension/backoffice/JSPopupMenuItem.php index 684670314..03f68af61 100644 --- a/application/applicationextension/backoffice/JSPopupMenuItem.php +++ b/application/applicationextension/backoffice/JSPopupMenuItem.php @@ -11,60 +11,60 @@ */ class JSPopupMenuItem extends ApplicationPopupMenuItem { - /** @ignore */ - protected $sJsCode; - /** @ignore */ - protected $sUrl; - /** @ignore */ - protected $aIncludeJSFiles; + /** @ignore */ + protected $sJsCode; + /** @ignore */ + protected $sUrl; + /** @ignore */ + protected $aIncludeJSFiles; - /** - * Class for adding an item that triggers some Javascript code - * - * @param string $sUID The unique identifier of this menu in iTop... make sure you pass something unique enough - * @param string $sLabel The display label of the menu (must be localized) - * @param string $sJSCode In case the menu consists in executing some havascript code inside the page, pass it here. If supplied $sURL - * ans $sTarget will be ignored - * @param array $aIncludeJSFiles An array of file URLs to be included (once) to provide some JS libraries for the page. - * @api - */ - public function __construct($sUID, $sLabel, $sJSCode, $aIncludeJSFiles = array()) - { - parent::__construct($sUID, $sLabel); - $this->sJsCode = $sJSCode; - $this->sUrl = '#'; - $this->aIncludeJSFiles = $aIncludeJSFiles; - } + /** + * Class for adding an item that triggers some Javascript code + * + * @param string $sUID The unique identifier of this menu in iTop... make sure you pass something unique enough + * @param string $sLabel The display label of the menu (must be localized) + * @param string $sJSCode In case the menu consists in executing some havascript code inside the page, pass it here. If supplied $sURL + * ans $sTarget will be ignored + * @param array $aIncludeJSFiles An array of file URLs to be included (once) to provide some JS libraries for the page. + * @api + */ + public function __construct($sUID, $sLabel, $sJSCode, $aIncludeJSFiles = []) + { + parent::__construct($sUID, $sLabel); + $this->sJsCode = $sJSCode; + $this->sUrl = '#'; + $this->aIncludeJSFiles = $aIncludeJSFiles; + } - /** @ignore */ - public function GetMenuItem() - { - // Note: the semicolumn is a must here! - return array( - 'label' => $this->GetLabel(), - 'onclick' => $this->GetJsCode() . '; return false;', - 'url' => $this->GetUrl(), - 'css_classes' => $this->GetCssClasses(), - 'icon_class' => $this->sIconClass, - 'tooltip' => $this->sTooltip - ); - } + /** @ignore */ + public function GetMenuItem() + { + // Note: the semicolumn is a must here! + return [ + 'label' => $this->GetLabel(), + 'onclick' => $this->GetJsCode().'; return false;', + 'url' => $this->GetUrl(), + 'css_classes' => $this->GetCssClasses(), + 'icon_class' => $this->sIconClass, + 'tooltip' => $this->sTooltip, + ]; + } - /** @ignore */ - public function GetLinkedScripts() - { - return $this->aIncludeJSFiles; - } + /** @ignore */ + public function GetLinkedScripts() + { + return $this->aIncludeJSFiles; + } - /** @ignore */ - public function GetJsCode() - { - return $this->sJsCode; - } + /** @ignore */ + public function GetJsCode() + { + return $this->sJsCode; + } - /** @ignore */ - public function GetUrl() - { - return $this->sUrl; - } -} \ No newline at end of file + /** @ignore */ + public function GetUrl() + { + return $this->sUrl; + } +} diff --git a/application/applicationextension/backoffice/SeparatorPopupMenuItem.php b/application/applicationextension/backoffice/SeparatorPopupMenuItem.php index 735356144..3be00a0f7 100644 --- a/application/applicationextension/backoffice/SeparatorPopupMenuItem.php +++ b/application/applicationextension/backoffice/SeparatorPopupMenuItem.php @@ -10,20 +10,20 @@ */ class SeparatorPopupMenuItem extends ApplicationPopupMenuItem { - static $idx = 0; + public static $idx = 0; - /** - * Constructor - * @api - */ - public function __construct() - { - parent::__construct('_separator_' . (self::$idx++), ''); - } + /** + * Constructor + * @api + */ + public function __construct() + { + parent::__construct('_separator_'.(self::$idx++), ''); + } - /** @ignore */ - public function GetMenuItem() - { - return array('label' => '', 'url' => '', 'css_classes' => $this->aCssClasses); - } -} \ No newline at end of file + /** @ignore */ + public function GetMenuItem() + { + return ['label' => '', 'url' => '', 'css_classes' => $this->aCssClasses]; + } +} diff --git a/application/applicationextension/backoffice/URLButtonItem.php b/application/applicationextension/backoffice/URLButtonItem.php index 97d8b2e67..31662e83b 100644 --- a/application/applicationextension/backoffice/URLButtonItem.php +++ b/application/applicationextension/backoffice/URLButtonItem.php @@ -9,5 +9,4 @@ */ class URLButtonItem extends URLPopupMenuItem { - -} \ No newline at end of file +} diff --git a/application/applicationextension/backoffice/URLPopupMenuItem.php b/application/applicationextension/backoffice/URLPopupMenuItem.php index 69a9ba8d8..bd330bf6a 100644 --- a/application/applicationextension/backoffice/URLPopupMenuItem.php +++ b/application/applicationextension/backoffice/URLPopupMenuItem.php @@ -11,48 +11,48 @@ */ class URLPopupMenuItem extends ApplicationPopupMenuItem { - /** @ignore */ - protected $sUrl; - /** @ignore */ - protected $sTarget; + /** @ignore */ + protected $sUrl; + /** @ignore */ + protected $sTarget; - /** - * Constructor - * - * @param string $sUID The unique identifier of this menu in iTop... make sure you pass something unique enough - * @param string $sLabel The display label of the menu (must be localized) - * @param string $sUrl If the menu is an hyperlink, provide the absolute hyperlink here - * @param string $sTarget In case the menu is an hyperlink and a specific target is needed (_blank for example), pass it here - * @api - */ - public function __construct($sUID, $sLabel, $sUrl, $sTarget = '_top') - { - parent::__construct($sUID, $sLabel); - $this->sUrl = $sUrl; - $this->sTarget = $sTarget; - } + /** + * Constructor + * + * @param string $sUID The unique identifier of this menu in iTop... make sure you pass something unique enough + * @param string $sLabel The display label of the menu (must be localized) + * @param string $sUrl If the menu is an hyperlink, provide the absolute hyperlink here + * @param string $sTarget In case the menu is an hyperlink and a specific target is needed (_blank for example), pass it here + * @api + */ + public function __construct($sUID, $sLabel, $sUrl, $sTarget = '_top') + { + parent::__construct($sUID, $sLabel); + $this->sUrl = $sUrl; + $this->sTarget = $sTarget; + } - /** @ignore */ - public function GetMenuItem() - { - return array('label' => $this->GetLabel(), - 'url' => $this->GetUrl(), - 'target' => $this->GetTarget(), - 'css_classes' => $this->aCssClasses, - 'icon_class' => $this->sIconClass, - 'tooltip' => $this->sTooltip - ); - } + /** @ignore */ + public function GetMenuItem() + { + return ['label' => $this->GetLabel(), + 'url' => $this->GetUrl(), + 'target' => $this->GetTarget(), + 'css_classes' => $this->aCssClasses, + 'icon_class' => $this->sIconClass, + 'tooltip' => $this->sTooltip, + ]; + } - /** @ignore */ - public function GetUrl() - { - return $this->sUrl; - } + /** @ignore */ + public function GetUrl() + { + return $this->sUrl; + } - /** @ignore */ - public function GetTarget() - { - return $this->sTarget; - } -} \ No newline at end of file + /** @ignore */ + public function GetTarget() + { + return $this->sTarget; + } +} diff --git a/application/applicationextension/backoffice/iApplicationUIExtension.php b/application/applicationextension/backoffice/iApplicationUIExtension.php index 259289fcd..b54db23aa 100644 --- a/application/applicationextension/backoffice/iApplicationUIExtension.php +++ b/application/applicationextension/backoffice/iApplicationUIExtension.php @@ -27,147 +27,147 @@ */ interface iApplicationUIExtension { - /** - * Invoked when an object is being displayed (wiew or edit) - * - * The method is called right after the main tab has been displayed. - * You can add output to the page, either to change the display, or to add a form input - * - * Example: - * - * if ($bEditMode) - * { - * $oPage->p('Age of the captain: <input type="text" name="captain_age"/>'); - * } - * else - * { - * $oPage->p('Age of the captain: '.$iCaptainAge); - * } - * - * - * @api - * - *@param \Combodo\iTop\Application\WebPage\WebPage $oPage The output context - * @param boolean $bEditMode True if the edition form is being displayed - * - * @param DBObject $oObject The object being displayed - * - * @return void - */ - public function OnDisplayProperties($oObject, \Combodo\iTop\Application\WebPage\WebPage $oPage, $bEditMode = false); + /** + * Invoked when an object is being displayed (wiew or edit) + * + * The method is called right after the main tab has been displayed. + * You can add output to the page, either to change the display, or to add a form input + * + * Example: + * + * if ($bEditMode) + * { + * $oPage->p('Age of the captain: <input type="text" name="captain_age"/>'); + * } + * else + * { + * $oPage->p('Age of the captain: '.$iCaptainAge); + * } + * + * + * @api + * + *@param \Combodo\iTop\Application\WebPage\WebPage $oPage The output context + * @param boolean $bEditMode True if the edition form is being displayed + * + * @param DBObject $oObject The object being displayed + * + * @return void + */ + public function OnDisplayProperties($oObject, \Combodo\iTop\Application\WebPage\WebPage $oPage, $bEditMode = false); - /** - * Invoked when an object is being displayed (wiew or edit) - * - * The method is called rigth after all the tabs have been displayed - * - * @api - * - *@param \Combodo\iTop\Application\WebPage\WebPage $oPage The output context - * @param boolean $bEditMode True if the edition form is being displayed - * - * @param DBObject $oObject The object being displayed - * - * @return void - */ - public function OnDisplayRelations($oObject, \Combodo\iTop\Application\WebPage\WebPage $oPage, $bEditMode = false); + /** + * Invoked when an object is being displayed (wiew or edit) + * + * The method is called rigth after all the tabs have been displayed + * + * @api + * + *@param \Combodo\iTop\Application\WebPage\WebPage $oPage The output context + * @param boolean $bEditMode True if the edition form is being displayed + * + * @param DBObject $oObject The object being displayed + * + * @return void + */ + public function OnDisplayRelations($oObject, \Combodo\iTop\Application\WebPage\WebPage $oPage, $bEditMode = false); - /** - * Invoked when the end-user clicks on Modify from the object edition form - * - * The method is called after the changes from the standard form have been - * taken into account, and before saving the changes into the database. - * - * @param DBObject $oObject The object being edited - * @param string $sFormPrefix Prefix given to the HTML form inputs - * - * @return void - * @api - */ - public function OnFormSubmit($oObject, $sFormPrefix = ''); + /** + * Invoked when the end-user clicks on Modify from the object edition form + * + * The method is called after the changes from the standard form have been + * taken into account, and before saving the changes into the database. + * + * @param DBObject $oObject The object being edited + * @param string $sFormPrefix Prefix given to the HTML form inputs + * + * @return void + * @api + */ + public function OnFormSubmit($oObject, $sFormPrefix = ''); - /** - * Invoked when the end-user clicks on Cancel from the object edition form - * - * Implement here any cleanup. This is necessary when you have injected some - * javascript into the edition form, and if that code requires to store temporary data - * (this is the case when a file must be uploaded). - * - * @param string $sTempId Unique temporary identifier made of session_id and transaction_id. It identifies the object in a unique way. - * - * @return void - * @api - */ - public function OnFormCancel($sTempId); + /** + * Invoked when the end-user clicks on Cancel from the object edition form + * + * Implement here any cleanup. This is necessary when you have injected some + * javascript into the edition form, and if that code requires to store temporary data + * (this is the case when a file must be uploaded). + * + * @param string $sTempId Unique temporary identifier made of session_id and transaction_id. It identifies the object in a unique way. + * + * @return void + * @api + */ + public function OnFormCancel($sTempId); - /** - * Not yet called by the framework! - * - * Sorry, the verb has been reserved. You must implement it, but it is not called as of now. - * - * @param DBObject $oObject The object being displayed - * - * @return string[] desc - * @api - */ - public function EnumUsedAttributes($oObject); // Not yet implemented + /** + * Not yet called by the framework! + * + * Sorry, the verb has been reserved. You must implement it, but it is not called as of now. + * + * @param DBObject $oObject The object being displayed + * + * @return string[] desc + * @api + */ + public function EnumUsedAttributes($oObject); // Not yet implemented - /** - * Not yet called by the framework! - * - * Sorry, the verb has been reserved. You must implement it, but it is not called as of now. - * - * @param DBObject $oObject The object being displayed - * - * @return string Path of the icon, relative to the modules directory. - * @api - */ - public function GetIcon($oObject); // Not yet implemented + /** + * Not yet called by the framework! + * + * Sorry, the verb has been reserved. You must implement it, but it is not called as of now. + * + * @param DBObject $oObject The object being displayed + * + * @return string Path of the icon, relative to the modules directory. + * @api + */ + public function GetIcon($oObject); // Not yet implemented - /** - * Invoked when the object is displayed alone or within a list - * - * Returns a value influencing the appearance of the object depending on its - * state. - * - * Possible values are: - * - * * HILIGHT_CLASS_CRITICAL - * * HILIGHT_CLASS_WARNING - * * HILIGHT_CLASS_OK - * * HILIGHT_CLASS_NONE - * - * @param DBObject $oObject The object being displayed - * - * @return integer The value representing the mood of the object - * @api - */ - public function GetHilightClass($oObject); + /** + * Invoked when the object is displayed alone or within a list + * + * Returns a value influencing the appearance of the object depending on its + * state. + * + * Possible values are: + * + * * HILIGHT_CLASS_CRITICAL + * * HILIGHT_CLASS_WARNING + * * HILIGHT_CLASS_OK + * * HILIGHT_CLASS_NONE + * + * @param DBObject $oObject The object being displayed + * + * @return integer The value representing the mood of the object + * @api + */ + public function GetHilightClass($oObject); - /** - * Called when building the Actions menu for a single object or a list of objects - * - * Use this to add items to the Actions menu. You will have to specify a label and an URL. - * - * Example: - * - * $oObject = $oSet->fetch(); - * if ($oObject instanceof Sheep) - * { - * return array('View in my app' => 'http://myserver/view_sheeps?id='.$oObject->Get('name')); - * } - * else - * { - * return array(); - * } - * - * - * See also iPopupMenuExtension for greater flexibility - * - * @param DBObjectSet $oSet A set of persistent objects (DBObject) - * - * @return array - * @api - */ - public function EnumAllowedActions(DBObjectSet $oSet); -} \ No newline at end of file + /** + * Called when building the Actions menu for a single object or a list of objects + * + * Use this to add items to the Actions menu. You will have to specify a label and an URL. + * + * Example: + * + * $oObject = $oSet->fetch(); + * if ($oObject instanceof Sheep) + * { + * return array('View in my app' => 'http://myserver/view_sheeps?id='.$oObject->Get('name')); + * } + * else + * { + * return array(); + * } + * + * + * See also iPopupMenuExtension for greater flexibility + * + * @param DBObjectSet $oSet A set of persistent objects (DBObject) + * + * @return array + * @api + */ + public function EnumAllowedActions(DBObjectSet $oSet); +} diff --git a/application/applicationextension/backoffice/iBackofficeDictEntriesExtension.php b/application/applicationextension/backoffice/iBackofficeDictEntriesExtension.php index ba188a09d..bfd2953bb 100644 --- a/application/applicationextension/backoffice/iBackofficeDictEntriesExtension.php +++ b/application/applicationextension/backoffice/iBackofficeDictEntriesExtension.php @@ -10,10 +10,10 @@ */ interface iBackofficeDictEntriesExtension { - /** - * @return array - * @see \iTopWebPage::a_dict_entries - * @api - */ - public function GetDictEntries(): array; -} \ No newline at end of file + /** + * @return array + * @see \iTopWebPage::a_dict_entries + * @api + */ + public function GetDictEntries(): array; +} diff --git a/application/applicationextension/backoffice/iBackofficeDictEntriesPrefixesExtension.php b/application/applicationextension/backoffice/iBackofficeDictEntriesPrefixesExtension.php index d90759175..9590f99ec 100644 --- a/application/applicationextension/backoffice/iBackofficeDictEntriesPrefixesExtension.php +++ b/application/applicationextension/backoffice/iBackofficeDictEntriesPrefixesExtension.php @@ -10,10 +10,10 @@ */ interface iBackofficeDictEntriesPrefixesExtension { - /** - * @return array - * @see \iTopWebPage::a_dict_entries_prefixes - * @api - */ - public function GetDictEntriesPrefixes(): array; -} \ No newline at end of file + /** + * @return array + * @see \iTopWebPage::a_dict_entries_prefixes + * @api + */ + public function GetDictEntriesPrefixes(): array; +} diff --git a/application/applicationextension/backoffice/iBackofficeEarlyScriptExtension.php b/application/applicationextension/backoffice/iBackofficeEarlyScriptExtension.php index 1f54508b9..352071f9b 100644 --- a/application/applicationextension/backoffice/iBackofficeEarlyScriptExtension.php +++ b/application/applicationextension/backoffice/iBackofficeEarlyScriptExtension.php @@ -11,10 +11,10 @@ */ interface iBackofficeEarlyScriptExtension { - /** - * @return string - * @see \iTopWebPage::$a_early_scripts - * @api - */ - public function GetEarlyScript(): string; -} \ No newline at end of file + /** + * @return string + * @see \iTopWebPage::$a_early_scripts + * @api + */ + public function GetEarlyScript(): string; +} diff --git a/application/applicationextension/backoffice/iBackofficeInitScriptExtension.php b/application/applicationextension/backoffice/iBackofficeInitScriptExtension.php index 2bb6869e7..238458261 100644 --- a/application/applicationextension/backoffice/iBackofficeInitScriptExtension.php +++ b/application/applicationextension/backoffice/iBackofficeInitScriptExtension.php @@ -10,10 +10,10 @@ */ interface iBackofficeInitScriptExtension { - /** - * @return string - * @see \iTopWebPage::$a_init_scripts - * @api - */ - public function GetInitScript(): string; -} \ No newline at end of file + /** + * @return string + * @see \iTopWebPage::$a_init_scripts + * @api + */ + public function GetInitScript(): string; +} diff --git a/application/applicationextension/backoffice/iBackofficeLinkedScriptsExtension.php b/application/applicationextension/backoffice/iBackofficeLinkedScriptsExtension.php index f8d0ae6e9..f91f92742 100644 --- a/application/applicationextension/backoffice/iBackofficeLinkedScriptsExtension.php +++ b/application/applicationextension/backoffice/iBackofficeLinkedScriptsExtension.php @@ -10,11 +10,11 @@ */ interface iBackofficeLinkedScriptsExtension { - /** - * Each script will be included using this property - * @return array An array of absolute URLs to the files to include - * @see \iTopWebPage::$a_linked_scripts - * @api - */ - public function GetLinkedScriptsAbsUrls(): array; -} \ No newline at end of file + /** + * Each script will be included using this property + * @return array An array of absolute URLs to the files to include + * @see \iTopWebPage::$a_linked_scripts + * @api + */ + public function GetLinkedScriptsAbsUrls(): array; +} diff --git a/application/applicationextension/backoffice/iBackofficeLinkedStylesheetsExtension.php b/application/applicationextension/backoffice/iBackofficeLinkedStylesheetsExtension.php index 3fa9ee342..8bc5b39fc 100644 --- a/application/applicationextension/backoffice/iBackofficeLinkedStylesheetsExtension.php +++ b/application/applicationextension/backoffice/iBackofficeLinkedStylesheetsExtension.php @@ -10,10 +10,10 @@ */ interface iBackofficeLinkedStylesheetsExtension { - /** - * @return array An array of absolute URLs to the files to include - * @see \iTopWebPage::$a_linked_stylesheets - * @api - */ - public function GetLinkedStylesheetsAbsUrls(): array; -} \ No newline at end of file + /** + * @return array An array of absolute URLs to the files to include + * @see \iTopWebPage::$a_linked_stylesheets + * @api + */ + public function GetLinkedStylesheetsAbsUrls(): array; +} diff --git a/application/applicationextension/backoffice/iBackofficeReadyScriptExtension.php b/application/applicationextension/backoffice/iBackofficeReadyScriptExtension.php index e4e96bee6..f6332a058 100644 --- a/application/applicationextension/backoffice/iBackofficeReadyScriptExtension.php +++ b/application/applicationextension/backoffice/iBackofficeReadyScriptExtension.php @@ -10,10 +10,10 @@ */ interface iBackofficeReadyScriptExtension { - /** - * @return string - * @see \iTopWebPage::$a_ready_scripts - * @api - */ - public function GetReadyScript(): string; -} \ No newline at end of file + /** + * @return string + * @see \iTopWebPage::$a_ready_scripts + * @api + */ + public function GetReadyScript(): string; +} diff --git a/application/applicationextension/backoffice/iBackofficeSassExtension.php b/application/applicationextension/backoffice/iBackofficeSassExtension.php index 5102ec9c3..002a1a28d 100644 --- a/application/applicationextension/backoffice/iBackofficeSassExtension.php +++ b/application/applicationextension/backoffice/iBackofficeSassExtension.php @@ -10,10 +10,10 @@ */ interface iBackofficeSassExtension { - /** - * @return string - * @see \iTopWebPage::$a_styles - * @api - */ - public function GetSass(): string; -} \ No newline at end of file + /** + * @return string + * @see \iTopWebPage::$a_styles + * @api + */ + public function GetSass(): string; +} diff --git a/application/applicationextension/backoffice/iBackofficeScriptExtension.php b/application/applicationextension/backoffice/iBackofficeScriptExtension.php index 90c6b6a14..e2c58a50c 100644 --- a/application/applicationextension/backoffice/iBackofficeScriptExtension.php +++ b/application/applicationextension/backoffice/iBackofficeScriptExtension.php @@ -10,10 +10,10 @@ */ interface iBackofficeScriptExtension { - /** - * @return string - * @see \iTopWebPage::$a_scripts - * @api - */ - public function GetScript(): string; -} \ No newline at end of file + /** + * @return string + * @see \iTopWebPage::$a_scripts + * @api + */ + public function GetScript(): string; +} diff --git a/application/applicationextension/backoffice/iBackofficeStyleExtension.php b/application/applicationextension/backoffice/iBackofficeStyleExtension.php index fd1ec57c7..fd192db9a 100644 --- a/application/applicationextension/backoffice/iBackofficeStyleExtension.php +++ b/application/applicationextension/backoffice/iBackofficeStyleExtension.php @@ -10,10 +10,10 @@ */ interface iBackofficeStyleExtension { - /** - * @return string - * @see \iTopWebPage::$a_styles - * @api - */ - public function GetStyle(): string; -} \ No newline at end of file + /** + * @return string + * @see \iTopWebPage::$a_styles + * @api + */ + public function GetStyle(): string; +} diff --git a/application/applicationextension/backoffice/iFieldRendererMappingsExtension.php b/application/applicationextension/backoffice/iFieldRendererMappingsExtension.php index 78d21170a..c3090b0bc 100644 --- a/application/applicationextension/backoffice/iFieldRendererMappingsExtension.php +++ b/application/applicationextension/backoffice/iFieldRendererMappingsExtension.php @@ -11,25 +11,25 @@ */ interface iFieldRendererMappingsExtension { - /** - * @return array { - * array: { - * field: string, - * form_renderer: string, - * field_renderer: string - * } - * } List of field renderer mapping: FQCN field class, FQCN Form Renderer class, FQCN Field Renderer class - * - * Example: - * - * ```php - * [ - * ['field' => 'FQCN\FieldA', 'form_renderer' => 'Combodo\iTop\Renderer\Console\ConsoleFormRenderer', 'field_renderer' => 'FQCN\FieldRendererA'], - * ['field' => 'FQCN\FieldB', 'form_renderer' => 'Combodo\iTop\Renderer\Console\ConsoleFormRenderer', 'field_renderer' => 'FQCN\FieldRendererB'], - * ['field' => 'FQCN\FieldA', 'form_renderer' => 'Combodo\iTop\Renderer\Bootstrap\BsFormRenderer', 'field_renderer' => 'FQCN\FieldRendererA'], - * ['field' => 'FQCN\FieldB', 'form_renderer' => 'Combodo\iTop\Renderer\Bootstrap\BsFormRenderer', 'field_renderer' => 'FQCN\FieldRendererB'], - * ] - * ``` - */ - public static function RegisterSupportedFields(): array; -} \ No newline at end of file + /** + * @return array { + * array: { + * field: string, + * form_renderer: string, + * field_renderer: string + * } + * } List of field renderer mapping: FQCN field class, FQCN Form Renderer class, FQCN Field Renderer class + * + * Example: + * + * ```php + * [ + * ['field' => 'FQCN\FieldA', 'form_renderer' => 'Combodo\iTop\Renderer\Console\ConsoleFormRenderer', 'field_renderer' => 'FQCN\FieldRendererA'], + * ['field' => 'FQCN\FieldB', 'form_renderer' => 'Combodo\iTop\Renderer\Console\ConsoleFormRenderer', 'field_renderer' => 'FQCN\FieldRendererB'], + * ['field' => 'FQCN\FieldA', 'form_renderer' => 'Combodo\iTop\Renderer\Bootstrap\BsFormRenderer', 'field_renderer' => 'FQCN\FieldRendererA'], + * ['field' => 'FQCN\FieldB', 'form_renderer' => 'Combodo\iTop\Renderer\Bootstrap\BsFormRenderer', 'field_renderer' => 'FQCN\FieldRendererB'], + * ] + * ``` + */ + public static function RegisterSupportedFields(): array; +} diff --git a/application/applicationextension/backoffice/iPageUIBlockExtension.php b/application/applicationextension/backoffice/iPageUIBlockExtension.php index 9b02f9278..49c0cf087 100644 --- a/application/applicationextension/backoffice/iPageUIBlockExtension.php +++ b/application/applicationextension/backoffice/iPageUIBlockExtension.php @@ -21,27 +21,27 @@ */ interface iPageUIBlockExtension { - /** - * Add content to the "admin banner" - * - * @api - * @return \Combodo\iTop\Application\UI\Base\iUIBlock|null The Block to add into the page - */ - public function GetBannerBlock(); + /** + * Add content to the "admin banner" + * + * @api + * @return \Combodo\iTop\Application\UI\Base\iUIBlock|null The Block to add into the page + */ + public function GetBannerBlock(); - /** - * Add content to the header of the page - * - * @api - * @return \Combodo\iTop\Application\UI\Base\iUIBlock|null The Block to add into the page - */ - public function GetHeaderBlock(); + /** + * Add content to the header of the page + * + * @api + * @return \Combodo\iTop\Application\UI\Base\iUIBlock|null The Block to add into the page + */ + public function GetHeaderBlock(); - /** - * Add content to the footer of the page - * - * @api - * @return \Combodo\iTop\Application\UI\Base\iUIBlock|null The Block to add into the page - */ - public function GetFooterBlock(); -} \ No newline at end of file + /** + * Add content to the footer of the page + * + * @api + * @return \Combodo\iTop\Application\UI\Base\iUIBlock|null The Block to add into the page + */ + public function GetFooterBlock(); +} diff --git a/application/applicationextension/backoffice/iPopupMenuExtension.php b/application/applicationextension/backoffice/iPopupMenuExtension.php index a2aab8372..0f9f507ff 100644 --- a/application/applicationextension/backoffice/iPopupMenuExtension.php +++ b/application/applicationextension/backoffice/iPopupMenuExtension.php @@ -13,100 +13,100 @@ */ interface iPopupMenuExtension { - /** - * Insert an item into the Actions menu of a list - * - * $param is a DBObjectSet containing the list of objects - * @api - */ - const MENU_OBJLIST_ACTIONS = 1; - /** - * Insert an item into the Toolkit menu of a list - * - * $param is a DBObjectSet containing the list of objects - * @api - */ - const MENU_OBJLIST_TOOLKIT = 2; - /** - * Insert an item into the Actions menu on an object details page - * - * $param is a DBObject instance: the object currently displayed - * @api - */ - const MENU_OBJDETAILS_ACTIONS = 3; - /** - * Insert an item into the Dashboard menu - * - * The dashboad menu is shown on the top right corner when a dashboard - * is being displayed. - * - * $param is a Dashboard instance: the dashboard currently displayed - * @api - */ - const MENU_DASHBOARD_ACTIONS = 4; - /** - * Insert an item into the User menu (upper right corner) - * - * $param is null - * @api - */ - const MENU_USER_ACTIONS = 5; - /** - * Insert an item into the Action menu on an object item in an objects list in the portal - * - * $param is an array('portal_id' => $sPortalId, 'object' => $oObject) containing the portal id and a DBObject instance (the object on - * the current line) - * @api - */ - const PORTAL_OBJLISTITEM_ACTIONS = 7; - /** - * Insert an item into the Action menu on an object details page in the portal - * - * $param is an array('portal_id' => $sPortalId, 'object' => $oObject) containing the portal id and a DBObject instance (the object - * currently displayed) - * @api - */ - const PORTAL_OBJDETAILS_ACTIONS = 8; + /** + * Insert an item into the Actions menu of a list + * + * $param is a DBObjectSet containing the list of objects + * @api + */ + public const MENU_OBJLIST_ACTIONS = 1; + /** + * Insert an item into the Toolkit menu of a list + * + * $param is a DBObjectSet containing the list of objects + * @api + */ + public const MENU_OBJLIST_TOOLKIT = 2; + /** + * Insert an item into the Actions menu on an object details page + * + * $param is a DBObject instance: the object currently displayed + * @api + */ + public const MENU_OBJDETAILS_ACTIONS = 3; + /** + * Insert an item into the Dashboard menu + * + * The dashboad menu is shown on the top right corner when a dashboard + * is being displayed. + * + * $param is a Dashboard instance: the dashboard currently displayed + * @api + */ + public const MENU_DASHBOARD_ACTIONS = 4; + /** + * Insert an item into the User menu (upper right corner) + * + * $param is null + * @api + */ + public const MENU_USER_ACTIONS = 5; + /** + * Insert an item into the Action menu on an object item in an objects list in the portal + * + * $param is an array('portal_id' => $sPortalId, 'object' => $oObject) containing the portal id and a DBObject instance (the object on + * the current line) + * @api + */ + public const PORTAL_OBJLISTITEM_ACTIONS = 7; + /** + * Insert an item into the Action menu on an object details page in the portal + * + * $param is an array('portal_id' => $sPortalId, 'object' => $oObject) containing the portal id and a DBObject instance (the object + * currently displayed) + * @api + */ + public const PORTAL_OBJDETAILS_ACTIONS = 8; - /** - * Insert an item into the Actions menu of a list in the portal - * Note: This is not implemented yet ! - * - * $param is an array('portal_id' => $sPortalId, 'object_set' => $oSet) containing DBObjectSet containing the list of objects - * - * @todo - */ - const PORTAL_OBJLIST_ACTIONS = 6; - /** - * Insert an item into the user menu of the portal - * Note: This is not implemented yet ! - * - * $param is the portal id - * - * @todo - */ - const PORTAL_USER_ACTIONS = 9; - /** - * Insert an item into the navigation menu of the portal - * Note: This is not implemented yet ! - * - * $param is the portal id - * - * @todo - */ - const PORTAL_MENU_ACTIONS = 10; + /** + * Insert an item into the Actions menu of a list in the portal + * Note: This is not implemented yet ! + * + * $param is an array('portal_id' => $sPortalId, 'object_set' => $oSet) containing DBObjectSet containing the list of objects + * + * @todo + */ + public const PORTAL_OBJLIST_ACTIONS = 6; + /** + * Insert an item into the user menu of the portal + * Note: This is not implemented yet ! + * + * $param is the portal id + * + * @todo + */ + public const PORTAL_USER_ACTIONS = 9; + /** + * Insert an item into the navigation menu of the portal + * Note: This is not implemented yet ! + * + * $param is the portal id + * + * @todo + */ + public const PORTAL_MENU_ACTIONS = 10; - /** - * Get the list of items to be added to a menu. - * - * This method is called by the framework for each menu. - * The items will be inserted in the menu in the order of the returned array. - * - * @param int $iMenuId The identifier of the type of menu, as listed by the constants MENU_xxx - * @param mixed $param Depends on $iMenuId, see the constants defined above - * - * @return object[] An array of ApplicationPopupMenuItem or an empty array if no action is to be added to the menu - * @api - */ - public static function EnumItems($iMenuId, $param); -} \ No newline at end of file + /** + * Get the list of items to be added to a menu. + * + * This method is called by the framework for each menu. + * The items will be inserted in the menu in the order of the returned array. + * + * @param int $iMenuId The identifier of the type of menu, as listed by the constants MENU_xxx + * @param mixed $param Depends on $iMenuId, see the constants defined above + * + * @return object[] An array of ApplicationPopupMenuItem or an empty array if no action is to be added to the menu + * @api + */ + public static function EnumItems($iMenuId, $param); +} diff --git a/application/applicationextension/backoffice/iPreferencesExtension.php b/application/applicationextension/backoffice/iPreferencesExtension.php index f166b0b34..4310c251a 100644 --- a/application/applicationextension/backoffice/iPreferencesExtension.php +++ b/application/applicationextension/backoffice/iPreferencesExtension.php @@ -7,22 +7,22 @@ */ interface iPreferencesExtension { - /** - * @api - * - * @param \Combodo\iTop\Application\WebPage\WebPage $oPage - * - */ - public function DisplayPreferences(\Combodo\iTop\Application\WebPage\WebPage $oPage); + /** + * @api + * + * @param \Combodo\iTop\Application\WebPage\WebPage $oPage + * + */ + public function DisplayPreferences(\Combodo\iTop\Application\WebPage\WebPage $oPage); - /** - * @api - * - * @param string $sOperation - * - * @param \Combodo\iTop\Application\WebPage\WebPage $oPage - * - * @return bool true if the operation has been used - */ - public function ApplyPreferences(\Combodo\iTop\Application\WebPage\WebPage $oPage, $sOperation); -} \ No newline at end of file + /** + * @api + * + * @param string $sOperation + * + * @param \Combodo\iTop\Application\WebPage\WebPage $oPage + * + * @return bool true if the operation has been used + */ + public function ApplyPreferences(\Combodo\iTop\Application\WebPage\WebPage $oPage, $sOperation); +} diff --git a/application/applicationextension/backoffice/iWelcomePopupExtension.php b/application/applicationextension/backoffice/iWelcomePopupExtension.php index 12d8ae644..76e6d0525 100644 --- a/application/applicationextension/backoffice/iWelcomePopupExtension.php +++ b/application/applicationextension/backoffice/iWelcomePopupExtension.php @@ -8,31 +8,31 @@ */ interface iWelcomePopupExtension { - // Importance for ordering messages - // Just two levels since less important messages have nothing to do in the welcome popup - public const ENUM_IMPORTANCE_CRITICAL = 0; - public const ENUM_IMPORTANCE_HIGH = 1; - public const DEFAULT_IMPORTANCE = self::ENUM_IMPORTANCE_HIGH; + // Importance for ordering messages + // Just two levels since less important messages have nothing to do in the welcome popup + public const ENUM_IMPORTANCE_CRITICAL = 0; + public const ENUM_IMPORTANCE_HIGH = 1; + public const DEFAULT_IMPORTANCE = self::ENUM_IMPORTANCE_HIGH; - /** - * Overload this method if you need to display an icon representing the provider (eg. your own company logo, module icon, ...) - * - * @return string Relative path (from app. root) of the icon representing the provider - * @api - */ - public function GetIconRelPath(): string; + /** + * Overload this method if you need to display an icon representing the provider (eg. your own company logo, module icon, ...) + * + * @return string Relative path (from app. root) of the icon representing the provider + * @api + */ + public function GetIconRelPath(): string; - /** - * @return \Combodo\iTop\Application\WelcomePopup\Message[] - * @api - */ - public function GetMessages(): array; + /** + * @return \Combodo\iTop\Application\WelcomePopup\Message[] + * @api + */ + public function GetMessages(): array; - /** - * Overload this method if the provider needs to do some additional processing after the message ($sMessageId) has been acknowledged by the current user - * - * @param string $sMessageId - * @api - */ - public function AcknowledgeMessage(string $sMessageId): void; -} \ No newline at end of file + /** + * Overload this method if the provider needs to do some additional processing after the message ($sMessageId) has been acknowledged by the current user + * + * @param string $sMessageId + * @api + */ + public function AcknowledgeMessage(string $sMessageId): void; +} diff --git a/application/applicationextension/iBackupExtraFilesExtension.php b/application/applicationextension/iBackupExtraFilesExtension.php index 1ff59525d..1ed1f809f 100644 --- a/application/applicationextension/iBackupExtraFilesExtension.php +++ b/application/applicationextension/iBackupExtraFilesExtension.php @@ -8,9 +8,9 @@ */ interface iBackupExtraFilesExtension { - /** - * @return string[] Array of relative paths (from app root) for files and directories to be included in the backup - * @api - */ - public function GetExtraFilesRelPaths(): array; -} \ No newline at end of file + /** + * @return string[] Array of relative paths (from app root) for files and directories to be included in the backup + * @api + */ + public function GetExtraFilesRelPaths(): array; +} diff --git a/application/applicationextension/iKPILoggerExtension.php b/application/applicationextension/iKPILoggerExtension.php index 2a7f05c14..c8891a2bd 100644 --- a/application/applicationextension/iKPILoggerExtension.php +++ b/application/applicationextension/iKPILoggerExtension.php @@ -7,19 +7,19 @@ */ interface iKPILoggerExtension { - /** - * Init the statistics collected - * - * @return void - */ - public function InitStats(); + /** + * Init the statistics collected + * + * @return void + */ + public function InitStats(); - /** - * Add a new KPI to the stats - * - * @param \Combodo\iTop\Core\Kpi\KpiLogData $oKpiLogData - * - * @return mixed - */ - public function LogOperation($oKpiLogData); -} \ No newline at end of file + /** + * Add a new KPI to the stats + * + * @param \Combodo\iTop\Core\Kpi\KpiLogData $oKpiLogData + * + * @return mixed + */ + public function LogOperation($oKpiLogData); +} diff --git a/application/applicationextension/iModuleExtension.php b/application/applicationextension/iModuleExtension.php index dcfdba3a3..fb89a41a6 100644 --- a/application/applicationextension/iModuleExtension.php +++ b/application/applicationextension/iModuleExtension.php @@ -9,8 +9,8 @@ */ interface iModuleExtension { - /** - * @api - */ - public function __construct(); -} \ No newline at end of file + /** + * @api + */ + public function __construct(); +} diff --git a/application/applicationextension/login/AbstractLoginFSMExtension.php b/application/applicationextension/login/AbstractLoginFSMExtension.php index 8e0225c63..9f83b7b7d 100644 --- a/application/applicationextension/login/AbstractLoginFSMExtension.php +++ b/application/applicationextension/login/AbstractLoginFSMExtension.php @@ -16,144 +16,144 @@ */ abstract class AbstractLoginFSMExtension implements iLoginFSMExtension { - /** - * @inheritDoc - */ - abstract public function ListSupportedLoginModes(); + /** + * @inheritDoc + */ + abstract public function ListSupportedLoginModes(); - /** - * @inheritDoc - */ - public function LoginAction($sLoginState, &$iErrorCode) - { - switch ($sLoginState) { - case LoginWebPage::LOGIN_STATE_START: - return $this->OnStart($iErrorCode); + /** + * @inheritDoc + */ + public function LoginAction($sLoginState, &$iErrorCode) + { + switch ($sLoginState) { + case LoginWebPage::LOGIN_STATE_START: + return $this->OnStart($iErrorCode); - case LoginWebPage::LOGIN_STATE_MODE_DETECTION: - return $this->OnModeDetection($iErrorCode); + case LoginWebPage::LOGIN_STATE_MODE_DETECTION: + return $this->OnModeDetection($iErrorCode); - case LoginWebPage::LOGIN_STATE_READ_CREDENTIALS: - return $this->OnReadCredentials($iErrorCode); + case LoginWebPage::LOGIN_STATE_READ_CREDENTIALS: + return $this->OnReadCredentials($iErrorCode); - case LoginWebPage::LOGIN_STATE_CHECK_CREDENTIALS: - return $this->OnCheckCredentials($iErrorCode); + case LoginWebPage::LOGIN_STATE_CHECK_CREDENTIALS: + return $this->OnCheckCredentials($iErrorCode); - case LoginWebPage::LOGIN_STATE_CREDENTIALS_OK: - return $this->OnCredentialsOK($iErrorCode); + case LoginWebPage::LOGIN_STATE_CREDENTIALS_OK: + return $this->OnCredentialsOK($iErrorCode); - case LoginWebPage::LOGIN_STATE_USER_OK: - return $this->OnUsersOK($iErrorCode); + case LoginWebPage::LOGIN_STATE_USER_OK: + return $this->OnUsersOK($iErrorCode); - case LoginWebPage::LOGIN_STATE_CONNECTED: - return $this->OnConnected($iErrorCode); + case LoginWebPage::LOGIN_STATE_CONNECTED: + return $this->OnConnected($iErrorCode); - case LoginWebPage::LOGIN_STATE_ERROR: - return $this->OnError($iErrorCode); - } + case LoginWebPage::LOGIN_STATE_ERROR: + return $this->OnError($iErrorCode); + } - return LoginWebPage::LOGIN_FSM_CONTINUE; - } + return LoginWebPage::LOGIN_FSM_CONTINUE; + } - /** - * Initialization - * - * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) - * - * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE - * @api - */ - protected function OnStart(&$iErrorCode) - { - return LoginWebPage::LOGIN_FSM_CONTINUE; - } + /** + * Initialization + * + * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) + * + * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE + * @api + */ + protected function OnStart(&$iErrorCode) + { + return LoginWebPage::LOGIN_FSM_CONTINUE; + } - /** - * Detect login mode explicitly without respecting configured order (legacy mode) - * In most case do nothing here - * - * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) - * - * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE - * @api - */ - protected function OnModeDetection(&$iErrorCode) - { - return LoginWebPage::LOGIN_FSM_CONTINUE; - } + /** + * Detect login mode explicitly without respecting configured order (legacy mode) + * In most case do nothing here + * + * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) + * + * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE + * @api + */ + protected function OnModeDetection(&$iErrorCode) + { + return LoginWebPage::LOGIN_FSM_CONTINUE; + } - /** - * Obtain the credentials either if login mode is empty or set to yours. - * This step can be called multiple times by the FSM: - * for example: - * 1 - display login form - * 2 - read the values posted by the user (store that in session) - * - * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) - * - * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE - * @api - */ - protected function OnReadCredentials(&$iErrorCode) - { - return LoginWebPage::LOGIN_FSM_CONTINUE; - } + /** + * Obtain the credentials either if login mode is empty or set to yours. + * This step can be called multiple times by the FSM: + * for example: + * 1 - display login form + * 2 - read the values posted by the user (store that in session) + * + * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) + * + * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE + * @api + */ + protected function OnReadCredentials(&$iErrorCode) + { + return LoginWebPage::LOGIN_FSM_CONTINUE; + } - /** - * Control the validity of the data from the session - * Automatic user provisioning can be done here - * - * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) - * - * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE - * @api - */ - protected function OnCheckCredentials(&$iErrorCode) - { - return LoginWebPage::LOGIN_FSM_CONTINUE; - } + /** + * Control the validity of the data from the session + * Automatic user provisioning can be done here + * + * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) + * + * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE + * @api + */ + protected function OnCheckCredentials(&$iErrorCode) + { + return LoginWebPage::LOGIN_FSM_CONTINUE; + } - /** - * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) - * - * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE - * @api - */ - protected function OnCredentialsOK(&$iErrorCode) - { - return LoginWebPage::LOGIN_FSM_CONTINUE; - } + /** + * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) + * + * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE + * @api + */ + protected function OnCredentialsOK(&$iErrorCode) + { + return LoginWebPage::LOGIN_FSM_CONTINUE; + } - /** - * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) - * - * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE - * @api - */ - protected function OnUsersOK(&$iErrorCode) - { - return LoginWebPage::LOGIN_FSM_CONTINUE; - } + /** + * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) + * + * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE + * @api + */ + protected function OnUsersOK(&$iErrorCode) + { + return LoginWebPage::LOGIN_FSM_CONTINUE; + } - /** - * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) - * - * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE - * @api - */ - protected function OnConnected(&$iErrorCode) - { - return LoginWebPage::LOGIN_FSM_CONTINUE; - } + /** + * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) + * + * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE + * @api + */ + protected function OnConnected(&$iErrorCode) + { + return LoginWebPage::LOGIN_FSM_CONTINUE; + } - /** - * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) - * - * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE - * @api - */ - protected function OnError(&$iErrorCode) - { - return LoginWebPage::LOGIN_FSM_CONTINUE; - } -} \ No newline at end of file + /** + * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) + * + * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE + * @api + */ + protected function OnError(&$iErrorCode) + { + return LoginWebPage::LOGIN_FSM_CONTINUE; + } +} diff --git a/application/applicationextension/login/iLoginExtension.php b/application/applicationextension/login/iLoginExtension.php index 63c38f3c3..014323f38 100644 --- a/application/applicationextension/login/iLoginExtension.php +++ b/application/applicationextension/login/iLoginExtension.php @@ -7,11 +7,11 @@ */ interface iLoginExtension { - /** - * Return the list of supported login modes for this plugin - * - * @return array of supported login modes - * @api - */ - public function ListSupportedLoginModes(); -} \ No newline at end of file + /** + * Return the list of supported login modes for this plugin + * + * @return array of supported login modes + * @api + */ + public function ListSupportedLoginModes(); +} diff --git a/application/applicationextension/login/iLoginFSMExtension.php b/application/applicationextension/login/iLoginFSMExtension.php index 8dd782c75..9e89f5e2d 100644 --- a/application/applicationextension/login/iLoginFSMExtension.php +++ b/application/applicationextension/login/iLoginFSMExtension.php @@ -7,18 +7,18 @@ */ interface iLoginFSMExtension extends iLoginExtension { - /** - * Execute action for this login state - * If a page is displayed, the action must exit at this point - * if LoginWebPage::LOGIN_FSM_RETURN_ERROR is returned $iErrorCode must be set - * if LoginWebPage::LOGIN_FSM_RETURN_OK is returned then the login is OK and terminated - * if LoginWebPage::LOGIN_FSM_CONTINUE is returned then the FSM will proceed to next plugin or state - * - * @param string $sLoginState (see LoginWebPage::LOGIN_STATE_...) - * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) - * - * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE - * @api - */ - public function LoginAction($sLoginState, &$iErrorCode); -} \ No newline at end of file + /** + * Execute action for this login state + * If a page is displayed, the action must exit at this point + * if LoginWebPage::LOGIN_FSM_RETURN_ERROR is returned $iErrorCode must be set + * if LoginWebPage::LOGIN_FSM_RETURN_OK is returned then the login is OK and terminated + * if LoginWebPage::LOGIN_FSM_CONTINUE is returned then the FSM will proceed to next plugin or state + * + * @param string $sLoginState (see LoginWebPage::LOGIN_STATE_...) + * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) + * + * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE + * @api + */ + public function LoginAction($sLoginState, &$iErrorCode); +} diff --git a/application/applicationextension/login/iLoginUIExtension.php b/application/applicationextension/login/iLoginUIExtension.php index edea4e6b1..f0efe1be1 100644 --- a/application/applicationextension/login/iLoginUIExtension.php +++ b/application/applicationextension/login/iLoginUIExtension.php @@ -9,9 +9,9 @@ */ interface iLoginUIExtension extends iLoginExtension { - /** - * @return LoginTwigContext - * @api - */ - public function GetTwigContext(); -} \ No newline at end of file + /** + * @return LoginTwigContext + * @api + */ + public function GetTwigContext(); +} diff --git a/application/applicationextension/login/iLogoutExtension.php b/application/applicationextension/login/iLogoutExtension.php index 3e9fecb4b..7805cabbb 100644 --- a/application/applicationextension/login/iLogoutExtension.php +++ b/application/applicationextension/login/iLogoutExtension.php @@ -7,9 +7,9 @@ */ interface iLogoutExtension extends iLoginExtension { - /** - * Execute all actions to log out properly - * @api - */ - public function LogoutAction(); -} \ No newline at end of file + /** + * Execute all actions to log out properly + * @api + */ + public function LogoutAction(); +} diff --git a/application/applicationextension/portal/AbstractPortalUIExtension.php b/application/applicationextension/portal/AbstractPortalUIExtension.php index e1c3d869d..7f9c6d4c3 100644 --- a/application/applicationextension/portal/AbstractPortalUIExtension.php +++ b/application/applicationextension/portal/AbstractPortalUIExtension.php @@ -9,59 +9,59 @@ */ abstract class AbstractPortalUIExtension implements iPortalUIExtension { - /** - * @inheritDoc - */ - public function GetCSSFiles(\Symfony\Component\DependencyInjection\Container $oContainer) - { - return array(); - } + /** + * @inheritDoc + */ + public function GetCSSFiles(\Symfony\Component\DependencyInjection\Container $oContainer) + { + return []; + } - /** - * @inheritDoc - */ - public function GetCSSInline(\Symfony\Component\DependencyInjection\Container $oContainer) - { - return null; - } + /** + * @inheritDoc + */ + public function GetCSSInline(\Symfony\Component\DependencyInjection\Container $oContainer) + { + return null; + } - /** - * @inheritDoc - */ - public function GetJSFiles(\Symfony\Component\DependencyInjection\Container $oContainer) - { - return array(); - } + /** + * @inheritDoc + */ + public function GetJSFiles(\Symfony\Component\DependencyInjection\Container $oContainer) + { + return []; + } - /** - * @inheritDoc - */ - public function GetJSInline(\Symfony\Component\DependencyInjection\Container $oContainer) - { - return null; - } + /** + * @inheritDoc + */ + public function GetJSInline(\Symfony\Component\DependencyInjection\Container $oContainer) + { + return null; + } - /** - * @inheritDoc - */ - public function GetBodyHTML(\Symfony\Component\DependencyInjection\Container $oContainer) - { - return null; - } + /** + * @inheritDoc + */ + public function GetBodyHTML(\Symfony\Component\DependencyInjection\Container $oContainer) + { + return null; + } - /** - * @inheritDoc - */ - public function GetMainContentHTML(\Symfony\Component\DependencyInjection\Container $oContainer) - { - return null; - } + /** + * @inheritDoc + */ + public function GetMainContentHTML(\Symfony\Component\DependencyInjection\Container $oContainer) + { + return null; + } - /** - * @inheritDoc - */ - public function GetNavigationMenuHTML(\Symfony\Component\DependencyInjection\Container $oContainer) - { - return null; - } -} \ No newline at end of file + /** + * @inheritDoc + */ + public function GetNavigationMenuHTML(\Symfony\Component\DependencyInjection\Container $oContainer) + { + return null; + } +} diff --git a/application/applicationextension/portal/iPortalUIExtension.php b/application/applicationextension/portal/iPortalUIExtension.php index 4c87a9159..c4a2c969f 100644 --- a/application/applicationextension/portal/iPortalUIExtension.php +++ b/application/applicationextension/portal/iPortalUIExtension.php @@ -11,77 +11,77 @@ */ interface iPortalUIExtension { - const ENUM_PORTAL_EXT_UI_BODY = 'Body'; - const ENUM_PORTAL_EXT_UI_NAVIGATION_MENU = 'NavigationMenu'; - const ENUM_PORTAL_EXT_UI_MAIN_CONTENT = 'MainContent'; + public const ENUM_PORTAL_EXT_UI_BODY = 'Body'; + public const ENUM_PORTAL_EXT_UI_NAVIGATION_MENU = 'NavigationMenu'; + public const ENUM_PORTAL_EXT_UI_MAIN_CONTENT = 'MainContent'; - /** - * Returns an array of CSS file urls - * - * @param \Symfony\Component\DependencyInjection\Container $oContainer - * - * @return array - * @api - */ - public function GetCSSFiles(\Symfony\Component\DependencyInjection\Container $oContainer); + /** + * Returns an array of CSS file urls + * + * @param \Symfony\Component\DependencyInjection\Container $oContainer + * + * @return array + * @api + */ + public function GetCSSFiles(\Symfony\Component\DependencyInjection\Container $oContainer); - /** - * Returns inline (raw) CSS - * - * @param \Symfony\Component\DependencyInjection\Container $oContainer - * - * @return string - * @api - */ - public function GetCSSInline(\Symfony\Component\DependencyInjection\Container $oContainer); + /** + * Returns inline (raw) CSS + * + * @param \Symfony\Component\DependencyInjection\Container $oContainer + * + * @return string + * @api + */ + public function GetCSSInline(\Symfony\Component\DependencyInjection\Container $oContainer); - /** - * Returns an array of JS file urls - * - * @param \Symfony\Component\DependencyInjection\Container $oContainer - * - * @return array - * @api - */ - public function GetJSFiles(\Symfony\Component\DependencyInjection\Container $oContainer); + /** + * Returns an array of JS file urls + * + * @param \Symfony\Component\DependencyInjection\Container $oContainer + * + * @return array + * @api + */ + public function GetJSFiles(\Symfony\Component\DependencyInjection\Container $oContainer); - /** - * Returns raw JS code - * - * @param \Symfony\Component\DependencyInjection\Container $oContainer - * - * @return string - * @api - */ - public function GetJSInline(\Symfony\Component\DependencyInjection\Container $oContainer); + /** + * Returns raw JS code + * + * @param \Symfony\Component\DependencyInjection\Container $oContainer + * + * @return string + * @api + */ + public function GetJSInline(\Symfony\Component\DependencyInjection\Container $oContainer); - /** - * Returns raw HTML code to put at the end of the tag - * - * @param \Symfony\Component\DependencyInjection\Container $oContainer - * - * @return string - * @api - */ - public function GetBodyHTML(\Symfony\Component\DependencyInjection\Container $oContainer); + /** + * Returns raw HTML code to put at the end of the tag + * + * @param \Symfony\Component\DependencyInjection\Container $oContainer + * + * @return string + * @api + */ + public function GetBodyHTML(\Symfony\Component\DependencyInjection\Container $oContainer); - /** - * Returns raw HTML code to put at the end of the #main-wrapper element - * - * @param \Symfony\Component\DependencyInjection\Container $oContainer - * - * @return string - * @api - */ - public function GetMainContentHTML(\Symfony\Component\DependencyInjection\Container $oContainer); + /** + * Returns raw HTML code to put at the end of the #main-wrapper element + * + * @param \Symfony\Component\DependencyInjection\Container $oContainer + * + * @return string + * @api + */ + public function GetMainContentHTML(\Symfony\Component\DependencyInjection\Container $oContainer); - /** - * Returns raw HTML code to put at the end of the #topbar and #sidebar elements - * - * @param \Symfony\Component\DependencyInjection\Container $oContainer - * - * @return string - * @api - */ - public function GetNavigationMenuHTML(\Symfony\Component\DependencyInjection\Container $oContainer); -} \ No newline at end of file + /** + * Returns raw HTML code to put at the end of the #topbar and #sidebar elements + * + * @param \Symfony\Component\DependencyInjection\Container $oContainer + * + * @return string + * @api + */ + public function GetNavigationMenuHTML(\Symfony\Component\DependencyInjection\Container $oContainer); +} diff --git a/application/applicationextension/rest/RestResult.php b/application/applicationextension/rest/RestResult.php index e1e4c28d6..d49d044ef 100644 --- a/application/applicationextension/rest/RestResult.php +++ b/application/applicationextension/rest/RestResult.php @@ -9,94 +9,94 @@ */ class RestResult { - /** - * Result: no issue has been encountered - * @api - */ - const OK = 0; - /** - * Result: missing/wrong credentials or the user does not have enough rights to perform the requested operation - * @api - */ - const UNAUTHORIZED = 1; - /** - * Result: the parameter 'version' is missing - * @api - */ - const MISSING_VERSION = 2; - /** - * Result: the parameter 'json_data' is missing - * @api - */ - const MISSING_JSON = 3; - /** - * Result: the input structure is not a valid JSON string - * @api - */ - const INVALID_JSON = 4; - /** - * Result: the parameter 'auth_user' is missing, authentication aborted - * @api - */ - const MISSING_AUTH_USER = 5; - /** - * Result: the parameter 'auth_pwd' is missing, authentication aborted - * @api - */ - const MISSING_AUTH_PWD = 6; - /** - * Result: no operation is available for the specified version - * @api - */ - const UNSUPPORTED_VERSION = 10; - /** - * Result: the requested operation is not valid for the specified version - * @api - */ - const UNKNOWN_OPERATION = 11; - /** - * Result: the requested operation cannot be performed because it can cause data (integrity) loss - * @api - */ - const UNSAFE = 12; - /** - * Result: the request page number is not valid. It must be an integer greater than 0 - * @api - */ - const INVALID_PAGE = 13; - /** - * Result: the operation could not be performed, see the message for troubleshooting - * @api - */ - const INTERNAL_ERROR = 100; + /** + * Result: no issue has been encountered + * @api + */ + public const OK = 0; + /** + * Result: missing/wrong credentials or the user does not have enough rights to perform the requested operation + * @api + */ + public const UNAUTHORIZED = 1; + /** + * Result: the parameter 'version' is missing + * @api + */ + public const MISSING_VERSION = 2; + /** + * Result: the parameter 'json_data' is missing + * @api + */ + public const MISSING_JSON = 3; + /** + * Result: the input structure is not a valid JSON string + * @api + */ + public const INVALID_JSON = 4; + /** + * Result: the parameter 'auth_user' is missing, authentication aborted + * @api + */ + public const MISSING_AUTH_USER = 5; + /** + * Result: the parameter 'auth_pwd' is missing, authentication aborted + * @api + */ + public const MISSING_AUTH_PWD = 6; + /** + * Result: no operation is available for the specified version + * @api + */ + public const UNSUPPORTED_VERSION = 10; + /** + * Result: the requested operation is not valid for the specified version + * @api + */ + public const UNKNOWN_OPERATION = 11; + /** + * Result: the requested operation cannot be performed because it can cause data (integrity) loss + * @api + */ + public const UNSAFE = 12; + /** + * Result: the request page number is not valid. It must be an integer greater than 0 + * @api + */ + public const INVALID_PAGE = 13; + /** + * Result: the operation could not be performed, see the message for troubleshooting + * @api + */ + public const INTERNAL_ERROR = 100; - /** - * Default constructor - ok! - * @api - */ - public function __construct() - { - $this->code = RestResult::OK; - } + /** + * Default constructor - ok! + * @api + */ + public function __construct() + { + $this->code = RestResult::OK; + } - /** - * Result code - * @var int - * @api - */ - public $code; - /** - * Result message - * @var string - * @api - */ - public $message; + /** + * Result code + * @var int + * @api + */ + public $code; + /** + * Result message + * @var string + * @api + */ + public $message; - /** - * Sanitize the content of this result to hide sensitive information - */ - public function SanitizeContent() - { - // The default implementation does nothing - } -} \ No newline at end of file + /** + * Sanitize the content of this result to hide sensitive information + */ + public function SanitizeContent() + { + // The default implementation does nothing + } +} diff --git a/application/applicationextension/rest/RestUtils.php b/application/applicationextension/rest/RestUtils.php index ee0bc72aa..07779ecde 100644 --- a/application/applicationextension/rest/RestUtils.php +++ b/application/applicationextension/rest/RestUtils.php @@ -8,361 +8,357 @@ */ class RestUtils { - /** - * Registering tracking information. Any further object modification be associated with the given comment, when the modification gets - * recorded into the DB - * - * @param StdClass $oData Structured input data. Must contain 'comment'. - * - * @return void - * @throws Exception - * @api - * - */ - public static function InitTrackingComment($oData) - { - $sComment = self::GetMandatoryParam($oData, 'comment'); - CMDBObject::SetTrackInfo($sComment); - } + /** + * Registering tracking information. Any further object modification be associated with the given comment, when the modification gets + * recorded into the DB + * + * @param StdClass $oData Structured input data. Must contain 'comment'. + * + * @return void + * @throws Exception + * @api + * + */ + public static function InitTrackingComment($oData) + { + $sComment = self::GetMandatoryParam($oData, 'comment'); + CMDBObject::SetTrackInfo($sComment); + } - /** - * Read a mandatory parameter from from a Rest/Json structure. - * - * @param string $sParamName Name of the parameter to fetch from the input data - * @param StdClass $oData Structured input data. Must contain the entry defined by sParamName. - * - * @return mixed parameter value if present - * @throws Exception If the parameter is missing - * @api - */ - public static function GetMandatoryParam($oData, $sParamName) - { - if (isset($oData->$sParamName)) { - return $oData->$sParamName; - } else { - throw new Exception("Missing parameter '$sParamName'"); - } - } + /** + * Read a mandatory parameter from from a Rest/Json structure. + * + * @param string $sParamName Name of the parameter to fetch from the input data + * @param StdClass $oData Structured input data. Must contain the entry defined by sParamName. + * + * @return mixed parameter value if present + * @throws Exception If the parameter is missing + * @api + */ + public static function GetMandatoryParam($oData, $sParamName) + { + if (isset($oData->$sParamName)) { + return $oData->$sParamName; + } else { + throw new Exception("Missing parameter '$sParamName'"); + } + } + /** + * Read an optional parameter from a Rest/Json structure. + * + * @param string $sParamName Name of the parameter to fetch from the input data + * @param mixed $default Default value if the parameter is not found in the input data + * + * @param StdClass $oData Structured input data. + * + * @return mixed + * @throws Exception + * @api + */ + public static function GetOptionalParam($oData, $sParamName, $default) + { + if (isset($oData->$sParamName)) { + return $oData->$sParamName; + } else { + return $default; + } + } - /** - * Read an optional parameter from a Rest/Json structure. - * - * @param string $sParamName Name of the parameter to fetch from the input data - * @param mixed $default Default value if the parameter is not found in the input data - * - * @param StdClass $oData Structured input data. - * - * @return mixed - * @throws Exception - * @api - */ - public static function GetOptionalParam($oData, $sParamName, $default) - { - if (isset($oData->$sParamName)) { - return $oData->$sParamName; - } else { - return $default; - } - } + /** + * Read a class from a Rest/Json structure. + * + * @param string $sParamName Name of the parameter to fetch from the input data + * @param StdClass $oData Structured input data. Must contain the entry defined by sParamName. + * + * @return string + * @throws Exception If the parameter is missing or the class is unknown + * @api + */ + public static function GetClass($oData, $sParamName) + { + $sClass = self::GetMandatoryParam($oData, $sParamName); + if (!MetaModel::IsValidClass($sClass)) { + throw new Exception("$sParamName: '$sClass' is not a valid class'"); + } + return $sClass; + } - /** - * Read a class from a Rest/Json structure. - * - * @param string $sParamName Name of the parameter to fetch from the input data - * @param StdClass $oData Structured input data. Must contain the entry defined by sParamName. - * - * @return string - * @throws Exception If the parameter is missing or the class is unknown - * @api - */ - public static function GetClass($oData, $sParamName) - { - $sClass = self::GetMandatoryParam($oData, $sParamName); - if (!MetaModel::IsValidClass($sClass)) { - throw new Exception("$sParamName: '$sClass' is not a valid class'"); - } + /** + * Read a list of attribute codes from a Rest/Json structure. + * + * @param StdClass $oData Structured input data. + * @param string $sParamName Name of the parameter to fetch from the input data + * + * @param string $sClass Name of the class + * + * @return array of class => list of attributes (see RestResultWithObjects::AddObject that uses it) + * @throws Exception + * @api + */ + public static function GetFieldList($sClass, $oData, $sParamName) + { + $sFields = self::GetOptionalParam($oData, $sParamName, '*'); + $aShowFields = []; + if ($sFields == '*') { + foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) { + $aShowFields[$sClass][] = $sAttCode; + } + } elseif ($sFields == '*+') { + foreach (MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL) as $sRefClass) { + foreach (MetaModel::ListAttributeDefs($sRefClass) as $sAttCode => $oAttDef) { + $aShowFields[$sRefClass][] = $sAttCode; + } + } + } else { + foreach (explode(',', $sFields) as $sAttCode) { + $sAttCode = trim($sAttCode); + if (($sAttCode != 'id') && (!MetaModel::IsValidAttCode($sClass, $sAttCode))) { + throw new Exception("$sParamName: invalid attribute code '$sAttCode'"); + } + $aShowFields[$sClass][] = $sAttCode; + } + } - return $sClass; - } + return $aShowFields; + } + /** + * Read and interpret object search criteria from a Rest/Json structure + * + * @param string $sClass Name of the class + * @param StdClass $oCriteria Hash of attribute code => value (can be a substructure or a scalar, depending on the nature of the + * attriute) + * + * @return object The object found + * @throws Exception If the input structure is not valid or it could not find exactly one object + * @api + */ + protected static function FindObjectFromCriteria($sClass, $oCriteria) + { + $aCriteriaReport = []; + if (isset($oCriteria->finalclass)) { + if (!MetaModel::IsValidClass($oCriteria->finalclass)) { + throw new Exception("finalclass: Unknown class '".$oCriteria->finalclass."'"); + } + if (!MetaModel::IsParentClass($sClass, $oCriteria->finalclass)) { + throw new Exception("finalclass: '".$oCriteria->finalclass."' is not a child class of '$sClass'"); + } + $sClass = $oCriteria->finalclass; + } + $oSearch = new DBObjectSearch($sClass); + foreach ($oCriteria as $sAttCode => $value) { + $realValue = static::MakeValue($sClass, $sAttCode, $value); + $oSearch->AddCondition($sAttCode, $realValue, '='); + if (is_object($value) || is_array($value)) { + $value = json_encode($value); + } + $aCriteriaReport[] = "$sAttCode: $value ($realValue)"; + } + $oSet = new DBObjectSet($oSearch); + $iCount = $oSet->Count(); + if ($iCount == 0) { + throw new Exception("No item found with criteria: ".implode(', ', $aCriteriaReport)); + } elseif ($iCount > 1) { + throw new Exception("Several items found ($iCount) with criteria: ".implode(', ', $aCriteriaReport)); + } + $res = $oSet->Fetch(); - /** - * Read a list of attribute codes from a Rest/Json structure. - * - * @param StdClass $oData Structured input data. - * @param string $sParamName Name of the parameter to fetch from the input data - * - * @param string $sClass Name of the class - * - * @return array of class => list of attributes (see RestResultWithObjects::AddObject that uses it) - * @throws Exception - * @api - */ - public static function GetFieldList($sClass, $oData, $sParamName) - { - $sFields = self::GetOptionalParam($oData, $sParamName, '*'); - $aShowFields = array(); - if ($sFields == '*') { - foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) { - $aShowFields[$sClass][] = $sAttCode; - } - } elseif ($sFields == '*+') { - foreach (MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL) as $sRefClass) { - foreach (MetaModel::ListAttributeDefs($sRefClass) as $sAttCode => $oAttDef) { - $aShowFields[$sRefClass][] = $sAttCode; - } - } - } else { - foreach (explode(',', $sFields) as $sAttCode) { - $sAttCode = trim($sAttCode); - if (($sAttCode != 'id') && (!MetaModel::IsValidAttCode($sClass, $sAttCode))) { - throw new Exception("$sParamName: invalid attribute code '$sAttCode'"); - } - $aShowFields[$sClass][] = $sAttCode; - } - } + return $res; + } - return $aShowFields; - } + /** + * Find an object from a polymorph search specification (Rest/Json) + * + * @param mixed $key Either search criteria (substructure), or an object or an OQL string. + * @param bool $bAllowNullValue Allow the cases such as key = 0 or key = {null} and return null then + * @param string $sClass Name of the class + * + * @return DBObject The object found + * @throws Exception If the input structure is not valid or it could not find exactly one object + * + * @api + * @see DBObject::CheckChangedExtKeysValues() generic method to check that we can access the linked object isn't used in that use case because values can be literal, OQL, friendlyname + */ + public static function FindObjectFromKey($sClass, $key, $bAllowNullValue = false) + { + if (is_object($key)) { + $res = static::FindObjectFromCriteria($sClass, $key); + } elseif (is_numeric($key)) { + if ($bAllowNullValue && ($key == 0)) { + $res = null; + } else { + $res = MetaModel::GetObject($sClass, $key, false); + if (is_null($res)) { + throw new Exception("Invalid object $sClass::$key"); + } + } + } elseif (is_string($key)) { + // OQL + $oSearch = DBObjectSearch::FromOQL($key); + $oSet = new DBObjectSet($oSearch); + $iCount = $oSet->Count(); + if ($iCount == 0) { + throw new Exception("No item found for query: $key"); + } elseif ($iCount > 1) { + throw new Exception("Several items found ($iCount) for query: $key"); + } + $res = $oSet->Fetch(); + } else { + throw new Exception("Wrong format for key"); + } - /** - * Read and interpret object search criteria from a Rest/Json structure - * - * @param string $sClass Name of the class - * @param StdClass $oCriteria Hash of attribute code => value (can be a substructure or a scalar, depending on the nature of the - * attriute) - * - * @return object The object found - * @throws Exception If the input structure is not valid or it could not find exactly one object - * @api - */ - protected static function FindObjectFromCriteria($sClass, $oCriteria) - { - $aCriteriaReport = array(); - if (isset($oCriteria->finalclass)) { - if (!MetaModel::IsValidClass($oCriteria->finalclass)) { - throw new Exception("finalclass: Unknown class '" . $oCriteria->finalclass . "'"); - } - if (!MetaModel::IsParentClass($sClass, $oCriteria->finalclass)) { - throw new Exception("finalclass: '" . $oCriteria->finalclass . "' is not a child class of '$sClass'"); - } - $sClass = $oCriteria->finalclass; - } - $oSearch = new DBObjectSearch($sClass); - foreach ($oCriteria as $sAttCode => $value) { - $realValue = static::MakeValue($sClass, $sAttCode, $value); - $oSearch->AddCondition($sAttCode, $realValue, '='); - if (is_object($value) || is_array($value)) { - $value = json_encode($value); - } - $aCriteriaReport[] = "$sAttCode: $value ($realValue)"; - } - $oSet = new DBObjectSet($oSearch); - $iCount = $oSet->Count(); - if ($iCount == 0) { - throw new Exception("No item found with criteria: " . implode(', ', $aCriteriaReport)); - } elseif ($iCount > 1) { - throw new Exception("Several items found ($iCount) with criteria: " . implode(', ', $aCriteriaReport)); - } - $res = $oSet->Fetch(); + return $res; + } - return $res; - } + /** + * Search objects from a polymorph search specification (Rest/Json) + * + * @param string $sClass Name of the class + * @param mixed $key Either search criteria (substructure), or an object or an OQL string. + * @param int $iLimit The limit of results to return + * @param int $iOffset The offset of results to return + * + * @return DBObjectSet The search result set + * @throws Exception If the input structure is not valid + * @api + */ + public static function GetObjectSetFromKey($sClass, $key, $iLimit = 0, $iOffset = 0) + { + if (is_object($key)) { + if (isset($key->finalclass)) { + $sClass = $key->finalclass; + if (!MetaModel::IsValidClass($sClass)) { + throw new Exception("finalclass: Unknown class '$sClass'"); + } + } + $oSearch = new DBObjectSearch($sClass); + foreach ($key as $sAttCode => $value) { + $realValue = static::MakeValue($sClass, $sAttCode, $value); + $oSearch->AddCondition($sAttCode, $realValue, '='); + } + } elseif (is_numeric($key)) { + $oSearch = new DBObjectSearch($sClass); + $oSearch->AddCondition('id', $key); + } elseif (is_string($key)) { + // OQL + try { + $oSearch = DBObjectSearch::FromOQL($key); + } catch (Exception $e) { + throw new CoreOqlException('Query failed to execute', [ + 'query' => $key, + 'exception_class' => get_class($e), + 'exception_message' => $e->getMessage(), + ]); + } + } else { + throw new Exception("Wrong format for key"); + } + $oObjectSet = new DBObjectSet($oSearch, [], [], null, $iLimit, $iOffset); - /** - * Find an object from a polymorph search specification (Rest/Json) - * - * @param mixed $key Either search criteria (substructure), or an object or an OQL string. - * @param bool $bAllowNullValue Allow the cases such as key = 0 or key = {null} and return null then - * @param string $sClass Name of the class - * - * @return DBObject The object found - * @throws Exception If the input structure is not valid or it could not find exactly one object - * - * @api - * @see DBObject::CheckChangedExtKeysValues() generic method to check that we can access the linked object isn't used in that use case because values can be literal, OQL, friendlyname - */ - public static function FindObjectFromKey($sClass, $key, $bAllowNullValue = false) - { - if (is_object($key)) { - $res = static::FindObjectFromCriteria($sClass, $key); - } elseif (is_numeric($key)) { - if ($bAllowNullValue && ($key == 0)) { - $res = null; - } else { - $res = MetaModel::GetObject($sClass, $key, false); - if (is_null($res)) { - throw new Exception("Invalid object $sClass::$key"); - } - } - } elseif (is_string($key)) { - // OQL - $oSearch = DBObjectSearch::FromOQL($key); - $oSet = new DBObjectSet($oSearch); - $iCount = $oSet->Count(); - if ($iCount == 0) { - throw new Exception("No item found for query: $key"); - } elseif ($iCount > 1) { - throw new Exception("Several items found ($iCount) for query: $key"); - } - $res = $oSet->Fetch(); - } else { - throw new Exception("Wrong format for key"); - } + return $oObjectSet; + } - return $res; - } + /** + * Interpret the Rest/Json value and get a valid attribute value + * + * @param string $sAttCode Attribute code + * @param mixed $value Depending on the type of attribute (a scalar, or search criteria, or list of related objects...) + * @param string $sClass Name of the class + * + * @return mixed The value that can be used with DBObject::Set() + * @throws Exception If the specification of the value is not valid. + * @api + */ + public static function MakeValue($sClass, $sAttCode, $value) + { + try { + if (!MetaModel::IsValidAttCode($sClass, $sAttCode)) { + throw new Exception("Unknown attribute"); + } + $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode); + if ($oAttDef instanceof AttributeExternalKey) { + $oExtKeyObject = static::FindObjectFromKey($oAttDef->GetTargetClass(), $value, true /* allow null */); + $value = ($oExtKeyObject != null) ? $oExtKeyObject->GetKey() : 0; + } elseif ($oAttDef instanceof AttributeLinkedSet) { + if (!is_array($value)) { + throw new Exception("A link set must be defined by an array of objects"); + } + $sLnkClass = $oAttDef->GetLinkedClass(); + $aLinks = []; + foreach ($value as $oValues) { + $oLnk = static::MakeObjectFromFields($sLnkClass, $oValues); + // Fix for N°1939 + if (($oAttDef instanceof AttributeLinkedSetIndirect) && ($oLnk->Get($oAttDef->GetExtKeyToRemote()) == 0)) { + continue; + } + $aLinks[] = $oLnk; + } + $value = DBObjectSet::FromArray($sLnkClass, $aLinks); + } elseif ($oAttDef instanceof AttributeTagSet) { + if (!is_array($value)) { + throw new Exception("A tag set must be defined by an array of tag codes"); + } + $value = $oAttDef->FromJSONToValue($value); + } else { + $value = $oAttDef->FromJSONToValue($value); + } + } catch (Exception $e) { + throw new Exception("$sAttCode: ".$e->getMessage(), $e->getCode()); + } - /** - * Search objects from a polymorph search specification (Rest/Json) - * - * @param string $sClass Name of the class - * @param mixed $key Either search criteria (substructure), or an object or an OQL string. - * @param int $iLimit The limit of results to return - * @param int $iOffset The offset of results to return - * - * @return DBObjectSet The search result set - * @throws Exception If the input structure is not valid - * @api - */ - public static function GetObjectSetFromKey($sClass, $key, $iLimit = 0, $iOffset = 0) - { - if (is_object($key)) { - if (isset($key->finalclass)) { - $sClass = $key->finalclass; - if (!MetaModel::IsValidClass($sClass)) { - throw new Exception("finalclass: Unknown class '$sClass'"); - } - } + return $value; + } - $oSearch = new DBObjectSearch($sClass); - foreach ($key as $sAttCode => $value) { - $realValue = static::MakeValue($sClass, $sAttCode, $value); - $oSearch->AddCondition($sAttCode, $realValue, '='); - } - } elseif (is_numeric($key)) { - $oSearch = new DBObjectSearch($sClass); - $oSearch->AddCondition('id', $key); - } elseif (is_string($key)) { - // OQL - try { - $oSearch = DBObjectSearch::FromOQL($key); - } catch (Exception $e) { - throw new CoreOqlException('Query failed to execute', [ - 'query' => $key, - 'exception_class' => get_class($e), - 'exception_message' => $e->getMessage(), - ]); - } - } else { - throw new Exception("Wrong format for key"); - } - $oObjectSet = new DBObjectSet($oSearch, array(), array(), null, $iLimit, $iOffset); + /** + * Interpret a Rest/Json structure that defines attribute values, and build an object + * + * @param array $aFields A hash of attribute code => value specification. + * @param string $sClass Name of the class + * + * @return DBObject The newly created object + * @throws Exception If the specification of the values is not valid + * @api + */ + public static function MakeObjectFromFields($sClass, $aFields) + { + $oObject = MetaModel::NewObject($sClass); + foreach ($aFields as $sAttCode => $value) { + $realValue = static::MakeValue($sClass, $sAttCode, $value); + try { + $oObject->Set($sAttCode, $realValue); + } catch (Exception $e) { + throw new Exception("$sAttCode: ".$e->getMessage(), $e->getCode()); + } + } - return $oObjectSet; - } + return $oObject; + } - /** - * Interpret the Rest/Json value and get a valid attribute value - * - * @param string $sAttCode Attribute code - * @param mixed $value Depending on the type of attribute (a scalar, or search criteria, or list of related objects...) - * @param string $sClass Name of the class - * - * @return mixed The value that can be used with DBObject::Set() - * @throws Exception If the specification of the value is not valid. - * @api - */ - public static function MakeValue($sClass, $sAttCode, $value) - { - try { - if (!MetaModel::IsValidAttCode($sClass, $sAttCode)) { - throw new Exception("Unknown attribute"); - } - $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode); - if ($oAttDef instanceof AttributeExternalKey) { - $oExtKeyObject = static::FindObjectFromKey($oAttDef->GetTargetClass(), $value, true /* allow null */); - $value = ($oExtKeyObject != null) ? $oExtKeyObject->GetKey() : 0; - } elseif ($oAttDef instanceof AttributeLinkedSet) { - if (!is_array($value)) { - throw new Exception("A link set must be defined by an array of objects"); - } - $sLnkClass = $oAttDef->GetLinkedClass(); - $aLinks = array(); - foreach ($value as $oValues) { - $oLnk = static::MakeObjectFromFields($sLnkClass, $oValues); - // Fix for N°1939 - if (($oAttDef instanceof AttributeLinkedSetIndirect) && ($oLnk->Get($oAttDef->GetExtKeyToRemote()) == 0)) { - continue; - } - $aLinks[] = $oLnk; - } - $value = DBObjectSet::FromArray($sLnkClass, $aLinks); - } elseif ($oAttDef instanceof AttributeTagSet) { - if (!is_array($value)) { - throw new Exception("A tag set must be defined by an array of tag codes"); - } - $value = $oAttDef->FromJSONToValue($value); - } else { - $value = $oAttDef->FromJSONToValue($value); - } - } catch (Exception $e) { - throw new Exception("$sAttCode: " . $e->getMessage(), $e->getCode()); - } + /** + * Interpret a Rest/Json structure that defines attribute values, and update the given object + * + * @param array $aFields A hash of attribute code => value specification. + * @param DBObject $oObject The object being modified + * + * @return DBObject The object modified + * @throws Exception If the specification of the values is not valid + * @api + */ + public static function UpdateObjectFromFields($oObject, $aFields) + { + $sClass = get_class($oObject); + foreach ($aFields as $sAttCode => $value) { + $realValue = static::MakeValue($sClass, $sAttCode, $value); + try { + $oObject->Set($sAttCode, $realValue); + } catch (Exception $e) { + throw new Exception("$sAttCode: ".$e->getMessage(), $e->getCode()); + } + } - return $value; - } - - /** - * Interpret a Rest/Json structure that defines attribute values, and build an object - * - * @param array $aFields A hash of attribute code => value specification. - * @param string $sClass Name of the class - * - * @return DBObject The newly created object - * @throws Exception If the specification of the values is not valid - * @api - */ - public static function MakeObjectFromFields($sClass, $aFields) - { - $oObject = MetaModel::NewObject($sClass); - foreach ($aFields as $sAttCode => $value) { - $realValue = static::MakeValue($sClass, $sAttCode, $value); - try { - $oObject->Set($sAttCode, $realValue); - } catch (Exception $e) { - throw new Exception("$sAttCode: " . $e->getMessage(), $e->getCode()); - } - } - - return $oObject; - } - - /** - * Interpret a Rest/Json structure that defines attribute values, and update the given object - * - * @param array $aFields A hash of attribute code => value specification. - * @param DBObject $oObject The object being modified - * - * @return DBObject The object modified - * @throws Exception If the specification of the values is not valid - * @api - */ - public static function UpdateObjectFromFields($oObject, $aFields) - { - $sClass = get_class($oObject); - foreach ($aFields as $sAttCode => $value) { - $realValue = static::MakeValue($sClass, $sAttCode, $value); - try { - $oObject->Set($sAttCode, $realValue); - } catch (Exception $e) { - throw new Exception("$sAttCode: " . $e->getMessage(), $e->getCode()); - } - } - - return $oObject; - } -} \ No newline at end of file + return $oObject; + } +} diff --git a/application/applicationextension/rest/iRestInputSanitizer.php b/application/applicationextension/rest/iRestInputSanitizer.php index 4b7765df8..dac64a96f 100644 --- a/application/applicationextension/rest/iRestInputSanitizer.php +++ b/application/applicationextension/rest/iRestInputSanitizer.php @@ -8,5 +8,5 @@ */ interface iRestInputSanitizer { - public function SanitizeJsonInput(string $sJsonInput): string; -} \ No newline at end of file + public function SanitizeJsonInput(string $sJsonInput): string; +} diff --git a/application/applicationextension/rest/iRestServiceProvider.php b/application/applicationextension/rest/iRestServiceProvider.php index cd2085ce3..4166166d6 100644 --- a/application/applicationextension/rest/iRestServiceProvider.php +++ b/application/applicationextension/rest/iRestServiceProvider.php @@ -9,25 +9,25 @@ */ interface iRestServiceProvider { - /** - * Enumerate services delivered by this class - * - * @param string $sVersion The version (e.g. 1.0) supported by the services - * - * @return array An array of hash 'verb' => verb, 'description' => description - * @api - */ - public function ListOperations($sVersion); + /** + * Enumerate services delivered by this class + * + * @param string $sVersion The version (e.g. 1.0) supported by the services + * + * @return array An array of hash 'verb' => verb, 'description' => description + * @api + */ + public function ListOperations($sVersion); - /** - * Enumerate services delivered by this class - * - * @param string $sVersion The version (e.g. 1.0) supported by the services - * @param string $sVerb - * @param array $aParams - * - * @return RestResult The standardized result structure (at least a message) - * @api - */ - public function ExecOperation($sVersion, $sVerb, $aParams); -} \ No newline at end of file + /** + * Enumerate services delivered by this class + * + * @param string $sVersion The version (e.g. 1.0) supported by the services + * @param string $sVerb + * @param array $aParams + * + * @return RestResult The standardized result structure (at least a message) + * @api + */ + public function ExecOperation($sVersion, $sVerb, $aParams); +} diff --git a/application/cmdbabstract.class.inc.php b/application/cmdbabstract.class.inc.php index b4c0ed048..49fa41663 100644 --- a/application/cmdbabstract.class.inc.php +++ b/application/cmdbabstract.class.inc.php @@ -1,4 +1,5 @@ GetKey(); $sParams = ''; - foreach($aParams as $sName => $value) - { + foreach ($aParams as $sName => $value) { $sParams .= $sName.'='.urlencode($value).'&'; // Always add a trailing & } $sUrl = utils::GetAbsoluteUrlAppRoot().'pages/'.$oObj->GetUIPage().'?'.$sParams.'class='.get_class($oObj).'&id='.$oObj->getKey().$oAppContext->GetForLink(true).'&a=1'; - $oPage->add_early_script(<<add_early_script( + <<GetId()] = $oActionMenuBlock; } - $aTags = array(); + $aTags = []; // Master data sources if (!$oPage->IsPrintableVersion()) { $oCreatorTask = null; $bCanBeDeletedByTask = false; $bCanBeDeletedByUser = true; - $aMasterSources = array(); + $aMasterSources = []; $aSyncData = $this->GetSynchroData(MetaModel::GetConfig()->Get('synchro_obsolete_replica_locks_object')); if (count($aSyncData) > 0) { foreach ($aSyncData as $iSourceId => $aSourceData) { @@ -468,33 +466,24 @@ JS $sApplicationURL = $oDataSource->GetApplicationUrl($this, $oReplica); $sLink = $oDataSource->GetName(); - if (!empty($sApplicationURL)) - { + if (!empty($sApplicationURL)) { $sLink = "".$oDataSource->GetName().""; } - if ($oReplica->Get('status_dest_creator') == 1) - { + if ($oReplica->Get('status_dest_creator') == 1) { $oCreatorTask = $oDataSource; $bCreatedByTask = true; - } - else - { + } else { $bCreatedByTask = false; } - if ($bCreatedByTask) - { + if ($bCreatedByTask) { $sDeletePolicy = $oDataSource->Get('delete_policy'); - if (($sDeletePolicy == 'delete') || ($sDeletePolicy == 'update_then_delete')) - { + if (($sDeletePolicy == 'delete') || ($sDeletePolicy == 'update_then_delete')) { $bCanBeDeletedByTask = true; } $sUserDeletePolicy = $oDataSource->Get('user_delete_policy'); - if ($sUserDeletePolicy == 'nobody') - { + if ($sUserDeletePolicy == 'nobody') { $bCanBeDeletedByUser = false; - } - elseif (($sUserDeletePolicy == 'administrators') && !UserRights::IsAdministrator()) - { + } elseif (($sUserDeletePolicy == 'administrators') && !UserRights::IsAdministrator()) { $bCanBeDeletedByUser = false; } } @@ -503,31 +492,25 @@ JS $aMasterSources[$iSourceId]['last_synchro'] = $oReplica->Get('status_last_seen'); } - if (is_object($oCreatorTask)) - { + if (is_object($oCreatorTask)) { $sTaskUrl = $aMasterSources[$oCreatorTask->GetKey()]['url']; - if (!$bCanBeDeletedByUser) - { - $sTip = "
".Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', - $sTaskUrl)."
"; - } - else - { + if (!$bCanBeDeletedByUser) { + $sTip = "
".Dict::Format( + 'Core:Synchro:TheObjectCannotBeDeletedByUser_Source', + $sTaskUrl + )."
"; + } else { $sTip = "
".Dict::Format('Core:Synchro:TheObjectWasCreatedBy_Source', $sTaskUrl)."
"; } - if ($bCanBeDeletedByTask) - { + if ($bCanBeDeletedByTask) { $sTip .= "
".Dict::Format('Core:Synchro:TheObjectCanBeDeletedBy_Source', $sTaskUrl)."
"; } - } - else - { + } else { $sTip = "
".Dict::S('Core:Synchro:ThisObjectIsSynchronized')."
"; } $sTip .= "
".Dict::S('Core:Synchro:ListOfDataSources')."
"; - foreach($aMasterSources as $aStruct) - { + foreach ($aMasterSources as $aStruct) { // Formatting last synchro date $oDateTime = DateTime::createFromFormat('Y-m-d H:i:s', $aStruct['last_synchro']); $oDateTimeFormat = AttributeDateTime::GetFormat(); @@ -556,7 +539,8 @@ JS foreach ($aTags as $sIconId => $aIconData) { $sTagTooltipContent = utils::EscapeHtml($aIconData['title']); - $aHeaderBlocks['subtitle'][static::HEADER_BLOCKS_SUBTITLE_TAG_PREFIX.$sIconId] = new Html(<<{$aIconData['label']} HTML ); @@ -578,16 +562,13 @@ HTML * * @since 3.0.0 $bEditMode is deprecated and no longer used */ - public function DisplayBareProperties(WebPage $oPage, $bEditMode = false, $sPrefix = '', $aExtraParams = array()) + public function DisplayBareProperties(WebPage $oPage, $bEditMode = false, $sPrefix = '', $aExtraParams = []) { $aFieldsMap = $this->GetBareProperties($oPage, $bEditMode, $sPrefix, $aExtraParams); - - if (!isset($aExtraParams['disable_plugins']) || !$aExtraParams['disable_plugins']) - { + if (!isset($aExtraParams['disable_plugins']) || !$aExtraParams['disable_plugins']) { /** @var iApplicationUIExtension $oExtensionInstance */ - foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance) - { + foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance) { $oExtensionInstance->OnDisplayProperties($this, $oPage, $bEditMode); } } @@ -639,10 +620,10 @@ HTML $oPage->AddUiBlock(AlertUIBlockFactory::MakeForInformation(Dict::S('UI:Dashboard:NotUpToDateUntilContainerSaved'))); } $oPage->add('
'); - $aExtraParams = array( + $aExtraParams = [ 'query_params' => $this->ToArgsForQuery(), 'dashboard_div_id' => $sDivId, - ); + ]; $oDashboard->Render($oPage, false, $aExtraParams, $bCanEdit); $oPage->add('
'); } @@ -669,13 +650,12 @@ HTML // Related objects: display all the linkset attributes, each as a separate tab // In the order described by the 'display' ZList $aList = $this->FlattenZList(MetaModel::GetZListItems(get_class($this), 'details')); - if (count($aList) == 0) - { + if (count($aList) == 0) { // Empty ZList defined, display all the linkedset attributes defined $aList = array_keys(MetaModel::ListAttributeDefs(get_class($this))); } $sClass = get_class($this); - foreach($aList as $sAttCode) { + foreach ($aList as $sAttCode) { $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode); if ($oAttDef instanceof AttributeDashboard) { if (!$this->IsNew()) { @@ -706,9 +686,9 @@ HTML $sLinkedClass = $oAttDef->GetLinkedClass(); // Filter out links pointing to obsolete objects (if relevant) - $oOrmLinkSet = $this->Get($sAttCode); - $oLinkSet = $oOrmLinkSet->ToDBObjectSet(utils::ShowObsoleteData()); - $iCount = $oLinkSet->Count(); + $oOrmLinkSet = $this->Get($sAttCode); + $oLinkSet = $oOrmLinkSet->ToDBObjectSet(utils::ShowObsoleteData()); + $iCount = $oLinkSet->Count(); if ($this->IsNew()) { $iFlags = $this->GetInitialStateAttributeFlags($sAttCode); @@ -716,39 +696,35 @@ HTML $iFlags = $this->GetAttributeFlags($sAttCode); } // Adjust the flags according to user rights - if ($oAttDef->IsIndirect()) - { + if ($oAttDef->IsIndirect()) { $oLinkingAttDef = MetaModel::GetAttributeDef($sLinkedClass, $oAttDef->GetExtKeyToRemote()); $sTargetClass = $oLinkingAttDef->GetTargetClass(); // n:n links => must be allowed to modify the linking class AND read the target class in order to edit the linkedset - if (!UserRights::IsActionAllowed($sLinkedClass, - UR_ACTION_MODIFY) || !UserRights::IsActionAllowed($sTargetClass, UR_ACTION_READ)) - { + if (!UserRights::IsActionAllowed( + $sLinkedClass, + UR_ACTION_MODIFY + ) || !UserRights::IsActionAllowed($sTargetClass, UR_ACTION_READ)) { $iFlags |= OPT_ATT_READONLY; } // n:n links => must be allowed to read the linking class AND the target class in order to display the linkedset - if (!UserRights::IsActionAllowed($sLinkedClass, - UR_ACTION_READ) || !UserRights::IsActionAllowed($sTargetClass, UR_ACTION_READ)) - { + if (!UserRights::IsActionAllowed( + $sLinkedClass, + UR_ACTION_READ + ) || !UserRights::IsActionAllowed($sTargetClass, UR_ACTION_READ)) { $iFlags |= OPT_ATT_HIDDEN; } - } - else - { + } else { // 1:n links => must be allowed to modify the linked class in order to edit the linkedset - if (!UserRights::IsActionAllowed($sLinkedClass, UR_ACTION_MODIFY)) - { + if (!UserRights::IsActionAllowed($sLinkedClass, UR_ACTION_MODIFY)) { $iFlags |= OPT_ATT_READONLY; } // 1:n links => must be allowed to read the linked class in order to display the linkedset - if (!UserRights::IsActionAllowed($sLinkedClass, UR_ACTION_READ)) - { + if (!UserRights::IsActionAllowed($sLinkedClass, UR_ACTION_READ)) { $iFlags |= OPT_ATT_HIDDEN; } } // Non-readable/hidden linkedset... don't display anything - if ($iFlags & OPT_ATT_HIDDEN) - { + if ($iFlags & OPT_ATT_HIDDEN) { continue; } @@ -757,7 +733,7 @@ HTML $sCount = ($iCount != 0) ? " ($iCount)" : ""; $oPage->SetCurrentTab($sTabCode, $oAttDef->GetLabel().$sCount, $sTabDescription); - $aArgs = array('this' => $this); + $aArgs = ['this' => $this]; $sEditWhen = $oAttDef->GetEditWhen(); // Calculate if edit_when allows to edit based on current $bEditMode @@ -768,8 +744,18 @@ HTML if ($bEditMode && (!$bReadOnly)) { $sInputId = $this->m_iFormId.'_'.$sAttCode; $sDisplayValue = ''; // not used - $sHTMLValue = "".self::GetFormElementForField($oPage, $sClass, $sAttCode, - $oAttDef, $oLinkSet, $sDisplayValue, $sInputId, '', $iFlags, $aArgs).''; + $sHTMLValue = "".self::GetFormElementForField( + $oPage, + $sClass, + $sAttCode, + $oAttDef, + $oLinkSet, + $sDisplayValue, + $sInputId, + '', + $iFlags, + $aArgs + ).''; $this->AddToFieldsMap($sAttCode, $sInputId); $oPage->add($sHTMLValue); } else { @@ -793,9 +779,18 @@ HTML if ($bEditMode && (!$bRedundancyReadOnly)) { $sInputId = $this->m_iFormId.'_'.$sRedundancyAttCode; - $oFieldSet->AddSubBlock(new Html("".self::GetFormElementForField($oPage, $sClass, - $sRedundancyAttCode, $oRedundancyAttDef, $sValue, '', $sInputId, '', $iFlags, - $aArgs).'')); + $oFieldSet->AddSubBlock(new Html("".self::GetFormElementForField( + $oPage, + $sClass, + $sRedundancyAttCode, + $oRedundancyAttDef, + $sValue, + '', + $sInputId, + '', + $iFlags, + $aArgs + ).'')); } else { $oFieldSet->AddSubBlock(new Html($oRedundancyAttDef->GetDisplayForm($sValue, $oPage, false, $this->m_iFormId))); } @@ -817,14 +812,14 @@ HTML $aTriggers = $this->GetRelatedTriggersIDs(); if (count($aTriggers) > 0) { $iId = $this->GetKey(); - $aParams = array('class' => get_class($this), 'id' => $iId); - $aNotifSearches = array(); + $aParams = ['class' => get_class($this), 'id' => $iId]; + $aNotifSearches = []; $iNotifsCount = 0; $aNotificationClasses = MetaModel::EnumChildClasses('EventNotification'); foreach ($aNotificationClasses as $sNotifClass) { $aNotifSearches[$sNotifClass] = DBObjectSearch::FromOQL("SELECT $sNotifClass AS Ev WHERE Ev.object_id = :id AND Ev.object_class = :class"); $aNotifSearches[$sNotifClass]->SetInternalParams($aParams); - $oNotifSet = new DBObjectSet($aNotifSearches[$sNotifClass], array()); + $oNotifSet = new DBObjectSet($aNotifSearches[$sNotifClass], []); $iNotifsCount += $oNotifSet->Count(); } // Display notifications regarding the object: on block per subclass to have the interesting columns @@ -891,15 +886,15 @@ HTML * * @since 3.0.0 $bEditMode is deprecated and no longer used */ - public function GetBareProperties(WebPage $oPage, $bEditMode, $sPrefix, $aExtraParams = array()) + public function GetBareProperties(WebPage $oPage, $bEditMode, $sPrefix, $aExtraParams = []) { $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this)); $sClass = get_class($this); $aDetailsList = MetaModel::GetZListItems($sClass, 'details'); - $aDetailsStruct = self::ProcessZlist($aDetailsList, array('UI:PropertiesTab' => array()), 'UI:PropertiesTab', 'col1', ''); - $aFieldsMap = array(); - $aFieldsComments = (isset($aExtraParams['fieldsComments'])) ? $aExtraParams['fieldsComments'] : array(); - $aExtraFlags = (isset($aExtraParams['fieldsFlags'])) ? $aExtraParams['fieldsFlags'] : array(); + $aDetailsStruct = self::ProcessZlist($aDetailsList, ['UI:PropertiesTab' => []], 'UI:PropertiesTab', 'col1', ''); + $aFieldsMap = []; + $aFieldsComments = (isset($aExtraParams['fieldsComments'])) ? $aExtraParams['fieldsComments'] : []; + $aExtraFlags = (isset($aExtraParams['fieldsFlags'])) ? $aExtraParams['fieldsFlags'] : []; $bHasFieldsWithRichTextEditor = false; foreach ($aDetailsStruct as $sTab => $aCols) { @@ -945,23 +940,23 @@ HTML if (($sStateAttCode === $sAttCode) && (MetaModel::HasLifecycle($sClass))) { // State attribute is always read-only from the UI $sHTMLValue = $this->GetAsHTML($sAttCode); - $val = array( + $val = [ 'label' => '', 'value' => $sHTMLValue, 'input_id' => $sInputId, 'comments' => $sComments, 'infos' => $sInfos, - ); + ]; } else { if ($iFlags & (OPT_ATT_READONLY | OPT_ATT_SLAVE)) { // Check if the attribute is not read-only because of a synchro... if ($iFlags & OPT_ATT_SLAVE) { - $aReasons = array(); + $aReasons = []; $this->GetSynchroReplicaFlags($sAttCode, $aReasons); $sTip = ''; foreach ($aReasons as $aRow) { $sDescription = utils::EscapeHtml($aRow['description']); - $sDescription = str_replace(array("\r\n", "\n"), "
", $sDescription); + $sDescription = str_replace(["\r\n", "\n"], "
", $sDescription); $sTip .= "
"; $sTip .= "
Synchronized with {$aRow['name']}
"; $sTip .= "
$sDescription
"; @@ -977,15 +972,24 @@ HTML $sValue = $this->Get($sAttCode); $sDisplayValue = $this->GetEditValue($sAttCode); // transfer bulk context to components as it can be needed (linked set) - $aArgs = array('this' => $this, 'formPrefix' => $sPrefix); + $aArgs = ['this' => $this, 'formPrefix' => $sPrefix]; if (array_key_exists('bulk_context', $aExtraParams)) { $aArgs['bulk_context'] = $aExtraParams['bulk_context']; } $sHTMLValue = "".self::GetFormElementForField( - $oPage, $sClass, $sAttCode, $oAttDef, $sValue, - $sDisplayValue, $sInputId, '', $iFlags, $aArgs, - true, $sInputType - ).''; + $oPage, + $sClass, + $sAttCode, + $oAttDef, + $sValue, + $sDisplayValue, + $sInputId, + '', + $iFlags, + $aArgs, + true, + $sInputType + ).''; } $aFieldsMap[$sAttCode] = $sInputId; @@ -994,45 +998,38 @@ HTML $sDescriptionForHTMLTag = utils::HtmlEntities($sDescription); $sDescriptionHTMLTag = (empty($sDescriptionForHTMLTag) || $sDescription === $oAttDef->GetLabel()) ? '' : 'class="ibo-has-description" data-tooltip-content="'.$sDescriptionForHTMLTag.'" data-tooltip-max-width="600px"'; - $val = array( + $val = [ 'label' => ''.$oAttDef->GetLabel().'', 'value' => $sHTMLValue, 'input_id' => $sInputId, 'input_type' => $sInputType, 'comments' => $sComments, 'infos' => $sInfos, - ); + ]; } - } - else - { + } else { // Attribute description $sDescription = $oAttDef->GetDescription(); $sDescriptionForHTMLTag = utils::HtmlEntities($sDescription); $sDescriptionHTMLTag = (empty($sDescriptionForHTMLTag) || $sDescription === $oAttDef->GetLabel()) ? '' : 'class="ibo-has-description" data-tooltip-content="'.$sDescriptionForHTMLTag.' "data-tooltip-max-width="600px"'; - $val = array( + $val = [ 'label' => ''.$oAttDef->GetLabel().'', 'value' => "".$this->GetAsHTML($sAttCode)."", 'comments' => $sComments, 'infos' => $sInfos, - ); + ]; $aFieldsMap[$sAttCode] = $sInputId; } - } - else - { + } else { $val = null; // Skip this field } - } - else - { + } else { // !bEditMode $val = $this->GetFieldAsHtml($sClass, $sAttCode, $sStateAttCode); } - if ($val != null) - { + if ($val != null) { // Add extra data for markup generation // - Attribute code and AttributeDef. class $val['attcode'] = $sAttCode; @@ -1072,7 +1069,6 @@ HTML return $aFieldsMap; } - /** * @param WebPage $oPage * @param bool $bEditMode Note that this parameter is no longer used in this method, {@see static::$sDisplayMode} is used instead, but we cannot remove it as it part of the base interface (iDisplay)... @@ -1107,7 +1103,7 @@ HTML // the lock may be released by 'onunload' which is called AFTER loading the current page. //$bTryAgain = $oOwner->GetKey() == UserRights::GetUserId(); $bBlockReentrance = true; - self::ReloadAndDisplay($oPage, $this, array('operation' => 'details')); + self::ReloadAndDisplay($oPage, $this, ['operation' => 'details']); return; } @@ -1144,7 +1140,6 @@ HTML $this->DisplayBareRelations($oPage, $bEditMode); $oKPI->ComputeStatsForExtension($this, 'DisplayBareRelations'); - // Note: Adding the JS snippet which enables the image upload should have been done directly by the ActivityPanel which would have kept the independance principle // of the UIBlock. For now we keep it this way in order to move on and trace this known limitation in N°3736. // @@ -1171,15 +1166,14 @@ HTML */ public function DisplayPreview(WebPage $oPage) { - $aDetails = array(); + $aDetails = []; $sClass = get_class($this); $aList = MetaModel::GetZListItems($sClass, 'preview'); - foreach($aList as $sAttCode) - { - $aDetails[] = array( + foreach ($aList as $sAttCode) { + $aDetails[] = [ 'label' => MetaModel::GetLabel($sClass, $sAttCode), 'value' => $this->GetAsHTML($sAttCode), - ); + ]; } $oPage->details($aDetails); } @@ -1192,7 +1186,7 @@ HTML * @throws \ApplicationException * @throws \CoreException */ - public static function DisplaySet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array()) + public static function DisplaySet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = []) { $oPage->AddUiBlock(self::GetDisplaySetBlock($oPage, $oSet, $aExtraParams)); } @@ -1208,9 +1202,10 @@ HTML * @return string The HTML representation of the table * @throws \CoreException */ - public static function GetDisplaySetForPrinting(WebPage $oPage, DBObjectSet $oSet, $aExtraParams = array()) + public static function GetDisplaySetForPrinting(WebPage $oPage, DBObjectSet $oSet, $aExtraParams = []) { - $sTableId = isset($aExtraParams['table_id']) ? $aExtraParams['table_id'] : utils::GetUniqueId();; + $sTableId = isset($aExtraParams['table_id']) ? $aExtraParams['table_id'] : utils::GetUniqueId(); + ; $aExtraParams['view_link'] = true; $aExtraParams['select_mode'] = 'none'; @@ -1236,7 +1231,7 @@ HTML * * @since 3.0.0 */ - public static function GetDisplaySetBlock(WebPage $oPage, DBObjectSet $oSet, $aExtraParams = array()) + public static function GetDisplaySetBlock(WebPage $oPage, DBObjectSet $oSet, $aExtraParams = []) { if ($oPage->IsPrintableVersion() || $oPage->is_pdf()) { return self::GetDisplaySetForPrinting($oPage, $oSet, $aExtraParams); @@ -1250,7 +1245,7 @@ HTML return DataTableUIBlockFactory::MakeForResult($oPage, $iListId, $oSet, $aExtraParams); } - public static function GetDataTableFromDBObjectSet(DBObjectSet $oSet, $aParams = array()) + public static function GetDataTableFromDBObjectSet(DBObjectSet $oSet, $aParams = []) { $aFields = null; if (isset($aParams['fields']) && (strlen($aParams['fields']) > 0)) { @@ -1267,18 +1262,18 @@ HTML $bLocalize = (bool)$aParams['localize_values']; } - $aList = array(); + $aList = []; $aClasses = $oSet->GetFilter()->GetSelectedClasses(); - $aAuthorizedClasses = array(); + $aAuthorizedClasses = []; foreach ($aClasses as $sAlias => $sClassName) { if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) != UR_ALLOWED_NO) { $aAuthorizedClasses[$sAlias] = $sClassName; } } - $aHeader = array(); + $aHeader = []; foreach ($aAuthorizedClasses as $sAlias => $sClassName) { - $aList[$sAlias] = array(); + $aList[$sAlias] = []; foreach (MetaModel::GetZListItems($sClassName, 'list') as $sAttCode) { $oAttDef = Metamodel::GetAttributeDef($sClassName, $sAttCode); @@ -1292,8 +1287,10 @@ HTML if ($bFieldsAdvanced && $oAttDef->IsExternalKey(EXTKEY_RELATIVE)) { $sRemoteClass = $oAttDef->GetTargetClass(); foreach (MetaModel::GetReconcKeys($sRemoteClass) as $sRemoteAttCode) { - $aList[$sAlias][$sAttCode.'->'.$sRemoteAttCode] = MetaModel::GetAttributeDef($sRemoteClass, - $sRemoteAttCode); + $aList[$sAlias][$sAttCode.'->'.$sRemoteAttCode] = MetaModel::GetAttributeDef( + $sRemoteClass, + $sRemoteAttCode + ); } } } @@ -1309,14 +1306,16 @@ HTML if ($oAttDef->IsExternalKey()) { unset($aList[$sAlias][$sAttCode]); $sFriendlyNameAttCode = $sAttCode.'_friendlyname'; - if (!array_key_exists($sFriendlyNameAttCode, - $aList[$sAlias]) && MetaModel::IsValidAttCode($sClassName, $sFriendlyNameAttCode)) { + if (!array_key_exists( + $sFriendlyNameAttCode, + $aList[$sAlias] + ) && MetaModel::IsValidAttCode($sClassName, $sFriendlyNameAttCode)) { $oFriendlyNameAtt = MetaModel::GetAttributeDef($sClassName, $sFriendlyNameAttCode); $aList[$sAlias][$sFriendlyNameAttCode] = $oFriendlyNameAtt; } } } - $aHeader['friendlyname'] = ['label' => MetaModel::GetName($sClassName)]; + $aHeader['friendlyname'] = ['label' => MetaModel::GetName($sClassName)]; foreach ($aList[$sAlias] as $sAttCodeEx => $oAttDef) { $sColLabel = $bLocalize ? MetaModel::GetLabel($sClassName, $sAttCodeEx) : $sAttCodeEx; @@ -1330,14 +1329,13 @@ HTML } } - $oSet->Seek(0); $aRows = []; while ($aObjects = $oSet->FetchAssoc()) { $aRow = []; foreach ($aAuthorizedClasses as $sAlias => $sClassName) { $oObj = $aObjects[$sAlias]; - $aRow["friendlyname"] = $oObj->Get('friendlyname'); + $aRow["friendlyname"] = $oObj->Get('friendlyname'); foreach ($aList[$sAlias] as $sAttCodeEx => $oAttDef) { if (is_null($oObj)) { $aRow[$oAttDef->GetCode()] = ''; @@ -1402,7 +1400,7 @@ HTML * @throws \MySQLException * @throws \MySQLHasGoneAwayException */ - public static function DisplaySetAsCSV(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array(), $sCharset = 'UTF-8') + public static function DisplaySetAsCSV(WebPage $oPage, CMDBObjectSet $oSet, $aParams = [], $sCharset = 'UTF-8') { $oPage->add(self::GetSetAsCSV($oSet, $aParams, $sCharset)); } @@ -1420,123 +1418,98 @@ HTML * @throws \MySQLHasGoneAwayException * @throws \Exception */ - public static function GetSetAsCSV(DBObjectSet $oSet, $aParams = array(), $sCharset = 'UTF-8') + public static function GetSetAsCSV(DBObjectSet $oSet, $aParams = [], $sCharset = 'UTF-8') { $sSeparator = isset($aParams['separator']) ? $aParams['separator'] : ','; // default separator is comma $sTextQualifier = isset($aParams['text_qualifier']) ? $aParams['text_qualifier'] : '"'; // default text qualifier is double quote $aFields = null; - if (isset($aParams['fields']) && (strlen($aParams['fields']) > 0)) - { + if (isset($aParams['fields']) && (strlen($aParams['fields']) > 0)) { $aFields = explode(',', $aParams['fields']); } $bFieldsAdvanced = false; - if (isset($aParams['fields_advanced'])) - { + if (isset($aParams['fields_advanced'])) { $bFieldsAdvanced = (bool)$aParams['fields_advanced']; } $bLocalize = true; - if (isset($aParams['localize_values'])) - { + if (isset($aParams['localize_values'])) { $bLocalize = (bool)$aParams['localize_values']; } - $aList = array(); + $aList = []; $aClasses = $oSet->GetFilter()->GetSelectedClasses(); - $aAuthorizedClasses = array(); - foreach($aClasses as $sAlias => $sClassName) - { - if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) != UR_ALLOWED_NO) - { + $aAuthorizedClasses = []; + foreach ($aClasses as $sAlias => $sClassName) { + if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) != UR_ALLOWED_NO) { $aAuthorizedClasses[$sAlias] = $sClassName; } } - $aHeader = array(); - foreach($aAuthorizedClasses as $sAlias => $sClassName) - { - $aList[$sAlias] = array(); + $aHeader = []; + foreach ($aAuthorizedClasses as $sAlias => $sClassName) { + $aList[$sAlias] = []; - foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef) - { - if (is_null($aFields) || (count($aFields) == 0)) - { + foreach (MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef) { + if (is_null($aFields) || (count($aFields) == 0)) { // Standard list of attributes (no link sets) - if ($oAttDef->IsScalar() && ($oAttDef->IsWritable() || $oAttDef->IsExternalField())) - { + if ($oAttDef->IsScalar() && ($oAttDef->IsWritable() || $oAttDef->IsExternalField())) { $sAttCodeEx = $oAttDef->IsExternalField() ? $oAttDef->GetKeyAttCode().'->'.$oAttDef->GetExtAttCode() : $sAttCode; - if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) - { - if ($bFieldsAdvanced) - { + if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) { + if ($bFieldsAdvanced) { $aList[$sAlias][$sAttCodeEx] = $oAttDef; - if ($oAttDef->IsExternalKey(EXTKEY_RELATIVE)) - { + if ($oAttDef->IsExternalKey(EXTKEY_RELATIVE)) { $sRemoteClass = $oAttDef->GetTargetClass(); - foreach(MetaModel::GetReconcKeys($sRemoteClass) as $sRemoteAttCode) - { - $aList[$sAlias][$sAttCode.'->'.$sRemoteAttCode] = MetaModel::GetAttributeDef($sRemoteClass, - $sRemoteAttCode); + foreach (MetaModel::GetReconcKeys($sRemoteClass) as $sRemoteAttCode) { + $aList[$sAlias][$sAttCode.'->'.$sRemoteAttCode] = MetaModel::GetAttributeDef( + $sRemoteClass, + $sRemoteAttCode + ); } } } - } - else - { + } else { // Any other attribute $aList[$sAlias][$sAttCodeEx] = $oAttDef; } } - } - else - { + } else { // User defined list of attributes - if (in_array($sAttCode, $aFields) || in_array($sAlias.'.'.$sAttCode, $aFields)) - { + if (in_array($sAttCode, $aFields) || in_array($sAlias.'.'.$sAttCode, $aFields)) { $aList[$sAlias][$sAttCode] = $oAttDef; } } } - if ($bFieldsAdvanced) - { + if ($bFieldsAdvanced) { $aHeader[] = 'id'; } - foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef) - { - $aHeader[] = $bLocalize ? MetaModel::GetLabel($sClassName, $sAttCodeEx, - isset($aParams['showMandatoryFields'])) : $sAttCodeEx; + foreach ($aList[$sAlias] as $sAttCodeEx => $oAttDef) { + $aHeader[] = $bLocalize ? MetaModel::GetLabel( + $sClassName, + $sAttCodeEx, + isset($aParams['showMandatoryFields']) + ) : $sAttCodeEx; } } $sHtml = implode($sSeparator, $aHeader)."\n"; $oSet->Seek(0); - while ($aObjects = $oSet->FetchAssoc()) - { - $aRow = array(); - foreach($aAuthorizedClasses as $sAlias => $sClassName) - { + while ($aObjects = $oSet->FetchAssoc()) { + $aRow = []; + foreach ($aAuthorizedClasses as $sAlias => $sClassName) { $oObj = $aObjects[$sAlias]; - if ($bFieldsAdvanced) - { - if (is_null($oObj)) - { + if ($bFieldsAdvanced) { + if (is_null($oObj)) { $aRow[] = ''; - } - else - { + } else { $aRow[] = $oObj->GetKey(); } } - foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef) - { - if (is_null($oObj)) - { + foreach ($aList[$sAlias] as $sAttCodeEx => $oAttDef) { + if (is_null($oObj)) { $aRow[] = ''; - } - else - { + } else { $value = $oObj->Get($sAttCodeEx); $sCSVValue = $oAttDef->GetAsCSV($value, $sSeparator, $sTextQualifier, $oObj, $bLocalize); $aRow[] = iconv('UTF-8', $sCharset.'//IGNORE//TRANSLIT', $sCSVValue); @@ -1559,7 +1532,7 @@ HTML * * @internal Only to be used by `/webservices/export.php` : this is a legacy method that produces wrong HTML (no TR on table body rows) */ - public static function DisplaySetAsHTMLSpreadsheet(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array()) + public static function DisplaySetAsHTMLSpreadsheet(WebPage $oPage, CMDBObjectSet $oSet, $aParams = []) { $oPage->add(self::GetSetAsHTMLSpreadsheet($oSet, $aParams)); } @@ -1581,171 +1554,142 @@ HTML * * @internal Only to be used by `/webservices/export.php` : this is a legacy method that produces wrong HTML (no TR on table body rows) */ - public static function GetSetAsHTMLSpreadsheet(DBObjectSet $oSet, $aParams = array()) + public static function GetSetAsHTMLSpreadsheet(DBObjectSet $oSet, $aParams = []) { $aFields = null; - if (isset($aParams['fields']) && (strlen($aParams['fields']) > 0)) - { + if (isset($aParams['fields']) && (strlen($aParams['fields']) > 0)) { $aFields = explode(',', $aParams['fields']); } $bFieldsAdvanced = false; - if (isset($aParams['fields_advanced'])) - { + if (isset($aParams['fields_advanced'])) { $bFieldsAdvanced = (bool)$aParams['fields_advanced']; } $bLocalize = true; - if (isset($aParams['localize_values'])) - { + if (isset($aParams['localize_values'])) { $bLocalize = (bool)$aParams['localize_values']; } - $aList = array(); + $aList = []; $aClasses = $oSet->GetFilter()->GetSelectedClasses(); - $aAuthorizedClasses = array(); - foreach($aClasses as $sAlias => $sClassName) - { - if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) != UR_ALLOWED_NO) - { + $aAuthorizedClasses = []; + foreach ($aClasses as $sAlias => $sClassName) { + if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) != UR_ALLOWED_NO) { $aAuthorizedClasses[$sAlias] = $sClassName; } } - $aHeader = array(); - foreach($aAuthorizedClasses as $sAlias => $sClassName) - { - $aList[$sAlias] = array(); + $aHeader = []; + foreach ($aAuthorizedClasses as $sAlias => $sClassName) { + $aList[$sAlias] = []; - foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef) - { - if (is_null($aFields) || (count($aFields) == 0)) - { + foreach (MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef) { + if (is_null($aFields) || (count($aFields) == 0)) { // Standard list of attributes (no link sets) - if ($oAttDef->IsScalar() && ($oAttDef->IsWritable() || $oAttDef->IsExternalField())) - { + if ($oAttDef->IsScalar() && ($oAttDef->IsWritable() || $oAttDef->IsExternalField())) { $sAttCodeEx = $oAttDef->IsExternalField() ? $oAttDef->GetKeyAttCode().'->'.$oAttDef->GetExtAttCode() : $sAttCode; $aList[$sAlias][$sAttCodeEx] = $oAttDef; - if ($bFieldsAdvanced && $oAttDef->IsExternalKey(EXTKEY_RELATIVE)) - { + if ($bFieldsAdvanced && $oAttDef->IsExternalKey(EXTKEY_RELATIVE)) { $sRemoteClass = $oAttDef->GetTargetClass(); - foreach(MetaModel::GetReconcKeys($sRemoteClass) as $sRemoteAttCode) - { - $aList[$sAlias][$sAttCode.'->'.$sRemoteAttCode] = MetaModel::GetAttributeDef($sRemoteClass, - $sRemoteAttCode); + foreach (MetaModel::GetReconcKeys($sRemoteClass) as $sRemoteAttCode) { + $aList[$sAlias][$sAttCode.'->'.$sRemoteAttCode] = MetaModel::GetAttributeDef( + $sRemoteClass, + $sRemoteAttCode + ); } } } - } - else - { + } else { // User defined list of attributes - if (in_array($sAttCode, $aFields) || in_array($sAlias.'.'.$sAttCode, $aFields)) - { + if (in_array($sAttCode, $aFields) || in_array($sAlias.'.'.$sAttCode, $aFields)) { $aList[$sAlias][$sAttCode] = $oAttDef; } } } // Replace external key by the corresponding friendly name (if not already in the list) - foreach($aList[$sAlias] as $sAttCode => $oAttDef) - { - if ($oAttDef->IsExternalKey()) - { + foreach ($aList[$sAlias] as $sAttCode => $oAttDef) { + if ($oAttDef->IsExternalKey()) { unset($aList[$sAlias][$sAttCode]); $sFriendlyNameAttCode = $sAttCode.'_friendlyname'; - if (!array_key_exists($sFriendlyNameAttCode, - $aList[$sAlias]) && MetaModel::IsValidAttCode($sClassName, $sFriendlyNameAttCode)) - { + if (!array_key_exists( + $sFriendlyNameAttCode, + $aList[$sAlias] + ) && MetaModel::IsValidAttCode($sClassName, $sFriendlyNameAttCode)) { $oFriendlyNameAtt = MetaModel::GetAttributeDef($sClassName, $sFriendlyNameAttCode); $aList[$sAlias][$sFriendlyNameAttCode] = $oFriendlyNameAtt; } } } - foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef) - { + foreach ($aList[$sAlias] as $sAttCodeEx => $oAttDef) { $sColLabel = $bLocalize ? MetaModel::GetLabel($sClassName, $sAttCodeEx) : $sAttCodeEx; $oFinalAttDef = $oAttDef->GetFinalAttDef(); - if (get_class($oFinalAttDef) == 'AttributeDateTime') - { + if (get_class($oFinalAttDef) == 'AttributeDateTime') { $aHeader[] = $sColLabel.' ('.Dict::S('UI:SplitDateTime-Date').')'; $aHeader[] = $sColLabel.' ('.Dict::S('UI:SplitDateTime-Time').')'; - } - else - { + } else { $aHeader[] = $sColLabel; } } } - $sHtml = "\n"; $sHtml .= "\n"; $sHtml .= "\n"; $sHtml .= "\n"; $oSet->Seek(0); - while ($aObjects = $oSet->FetchAssoc()) - { - $aRow = array(); - foreach($aAuthorizedClasses as $sAlias => $sClassName) - { + while ($aObjects = $oSet->FetchAssoc()) { + $aRow = []; + foreach ($aAuthorizedClasses as $sAlias => $sClassName) { $oObj = $aObjects[$sAlias]; - foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef) - { - if (is_null($oObj)) - { + foreach ($aList[$sAlias] as $sAttCodeEx => $oAttDef) { + if (is_null($oObj)) { $aRow[] = ''; - } - else - { + } else { $oFinalAttDef = $oAttDef->GetFinalAttDef(); - if (get_class($oFinalAttDef) == 'AttributeDateTime') - { + if (get_class($oFinalAttDef) == 'AttributeDateTime') { $sDate = $oObj->Get($sAttCodeEx); - if ($sDate === null) - { + if ($sDate === null) { $aRow[] = ''; $aRow[] = ''; - } - else - { + } else { $iDate = AttributeDateTime::GetAsUnixSeconds($sDate); - $aRow[] = ''; // Format kept as-is for 100% backward compatibility of the exports - $aRow[] = ''; // Format kept as-is for 100% backward compatibility of the exports + $aRow[] = ''; // Format kept as-is for 100% backward compatibility of the exports + $aRow[] = ''; // Format kept as-is for 100% backward compatibility of the exports } - } - else - { - if ($oAttDef instanceof AttributeCaseLog) - { + } else { + if ($oAttDef instanceof AttributeCaseLog) { $rawValue = $oObj->Get($sAttCodeEx); - $outputValue = str_replace("\n", "
", - utils::EscapeHtml($rawValue->__toString())); + $outputValue = str_replace( + "\n", + "
", + utils::EscapeHtml($rawValue->__toString()) + ); // Trick for Excel: treat the content as text even if it begins with an equal sign $aRow[] = ''; - } - else - { + } else { $rawValue = $oObj->Get($sAttCodeEx); // Due to custom formatting rules, empty friendlynames may be rendered as non-empty strings // let's fix this and make sure we render an empty string if the key == 0 - if ($oAttDef instanceof AttributeExternalField && $oAttDef->IsFriendlyName()) - { + if ($oAttDef instanceof AttributeExternalField && $oAttDef->IsFriendlyName()) { $sKeyAttCode = $oAttDef->GetKeyAttCode(); - if ($oObj->Get($sKeyAttCode) == 0) - { + if ($oObj->Get($sKeyAttCode) == 0) { $rawValue = ''; } } if ($bLocalize) { $outputValue = utils::EscapeHtml($oFinalAttDef->GetEditValue($rawValue)); - } - else { + } else { $outputValue = utils::EscapeHtml($rawValue); } $aRow[] = ''; @@ -1773,57 +1717,42 @@ HTML * @throws \MySQLException * @throws \MySQLHasGoneAwayException */ - public static function DisplaySetAsXML(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array()) + public static function DisplaySetAsXML(WebPage $oPage, CMDBObjectSet $oSet, $aParams = []) { $bLocalize = true; - if (isset($aParams['localize_values'])) - { + if (isset($aParams['localize_values'])) { $bLocalize = (bool)$aParams['localize_values']; } $aClasses = $oSet->GetFilter()->GetSelectedClasses(); - $aAuthorizedClasses = array(); - foreach($aClasses as $sAlias => $sClassName) - { - if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) != UR_ALLOWED_NO) - { + $aAuthorizedClasses = []; + foreach ($aClasses as $sAlias => $sClassName) { + if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) != UR_ALLOWED_NO) { $aAuthorizedClasses[$sAlias] = $sClassName; } } - $aList = array(); + $aList = []; $aList[$sAlias] = MetaModel::GetZListItems($sClassName, 'details'); $oPage->add("\n"); $oSet->Seek(0); - while ($aObjects = $oSet->FetchAssoc()) - { - if (count($aAuthorizedClasses) > 1) - { + while ($aObjects = $oSet->FetchAssoc()) { + if (count($aAuthorizedClasses) > 1) { $oPage->add("\n"); } - foreach($aAuthorizedClasses as $sAlias => $sClassName) - { + foreach ($aAuthorizedClasses as $sAlias => $sClassName) { $oObj = $aObjects[$sAlias]; - if (is_null($oObj)) - { + if (is_null($oObj)) { $oPage->add("<$sClassName alias=\"$sAlias\" id=\"null\">\n"); - } - else - { + } else { $sClassName = get_class($oObj); $oPage->add("<$sClassName alias=\"$sAlias\" id=\"".$oObj->GetKey()."\">\n"); } - foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef) - { - if (is_null($oObj)) - { + foreach (MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef) { + if (is_null($oObj)) { $oPage->add("<$sAttCode>null\n"); - } - else - { - if ($oAttDef->IsWritable()) - { - if (!$oAttDef->IsLinkSet()) - { + } else { + if ($oAttDef->IsWritable()) { + if (!$oAttDef->IsLinkSet()) { $sValue = $oObj->GetAsXML($sAttCode, $bLocalize); $oPage->add("<$sAttCode>$sValue\n"); } @@ -1832,8 +1761,7 @@ HTML } $oPage->add("\n"); } - if (count($aAuthorizedClasses) > 1) - { + if (count($aAuthorizedClasses) > 1) { $oPage->add("\n"); } } @@ -1848,7 +1776,7 @@ HTML * @throws \CoreException * @throws \DictExceptionMissingString */ - public static function DisplaySearchForm(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array()) + public static function DisplaySearchForm(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = []) { $oPage->add(self::GetSearchForm($oPage, $oSet, $aExtraParams)); @@ -1863,14 +1791,13 @@ HTML * @throws CoreException * @throws DictExceptionMissingString */ - public static function GetSearchForm(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array()) + public static function GetSearchForm(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = []) { $oSearchForm = new SearchForm(); return $oSearchForm->GetSearchForm($oPage, $oSet, $aExtraParams); } - /** * @param WebPage $oPage * @param string $sClass @@ -1900,7 +1827,7 @@ HTML * @throws \Twig\Error\SyntaxError * @throws \Exception */ - public static function GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $value = '', $sDisplayValue = '', $iId = '', $sNameSuffix = '', $iFlags = 0, $aArgs = array(), $bPreserveCurrentValue = true, &$sInputType = '') + public static function GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $value = '', $sDisplayValue = '', $iId = '', $sNameSuffix = '', $iFlags = 0, $aArgs = [], $bPreserveCurrentValue = true, &$sInputType = '') { $sFormPrefix = isset($aArgs['formPrefix']) ? $aArgs['formPrefix'] : ''; $sFieldPrefix = isset($aArgs['prefix']) ? $sFormPrefix.$aArgs['prefix'] : $sFormPrefix; @@ -1938,7 +1865,7 @@ HTML $sHelpText = utils::EscapeHtml($oAttDef->GetHelpOnEdition()); // mandatory field control vars - $aEventsList = array(); // contains any native event (like change), plus 'validate' for the form submission + $aEventsList = []; // contains any native event (like change), plus 'validate' for the form submission $sNullValue = $oAttDef->GetNullValue(); // used for the ValidateField() call in js/forms-json-utils.js $sFieldToValidateId = $iId; // can be different than the displayed field (for example in TagSet) @@ -2016,7 +1943,7 @@ HTML; $sEditValueForHtml = utils::EscapeHtml($sEditValue); $sFullscreenLabelForHtml = utils::EscapeHtml(Dict::S('UI:ToggleFullScreen')); - $aStyles = array(); + $aStyles = []; $sStyle = ''; $sWidth = $oAttDef->GetWidth(); if (!empty($sWidth)) { @@ -2056,7 +1983,8 @@ JS $sAdditionalStuff = $oPredefQueryRenderer->RenderHtml(); $oPage->add_ready_script($oPredefQueryRenderer->RenderJsInline($oPredefQueryButton::ENUM_JS_TYPE_ON_INIT)); - $oPage->add_ready_script(<<add_ready_script( + <<GetWidth(); if (!empty($sWidth)) { @@ -2161,7 +2089,7 @@ JS $sHeader = '
'; // will be hidden in CSS (via :empty) if it remains empty $sEditValue = is_object($value) ? $value->GetModifiedEntry('html') : ''; - $sPreviousLog = is_object($value) ? $value->GetAsHTML($oPage, true /* bEditMode */, array('AttributeText', 'RenderWikiHtml')) : ''; + $sPreviousLog = is_object($value) ? $value->GetAsHTML($oPage, true /* bEditMode */, ['AttributeText', 'RenderWikiHtml']) : ''; $iEntriesCount = is_object($value) ? count($value->GetIndex()) : 0; $sHidden = ""; // To know how many entries the case log already contains @@ -2187,8 +2115,16 @@ JS case 'HTML': $sInputType = self::ENUM_INPUT_TYPE_HTML_EDITOR; $sEditValue = $oAttDef->GetEditValue($value); - $oWidget = new UIHTMLEditorWidget($iId, $oAttDef, $sNameSuffix, $sFieldPrefix, $sHelpText, - $sValidationSpan.$sReloadSpan, $sEditValue, $bMandatory); + $oWidget = new UIHTMLEditorWidget( + $iId, + $oAttDef, + $sNameSuffix, + $sFieldPrefix, + $sHelpText, + $sValidationSpan.$sReloadSpan, + $sEditValue, + $bMandatory + ); $sHTMLValue = $oWidget->Display($oPage, $aArgs); break; @@ -2208,14 +2144,19 @@ JS $sInputType = self::ENUM_INPUT_TYPE_LINKEDSET; $oObj = $aArgs['this'] ?? null; if ($oAttDef->IsIndirect()) { - $oWidget = new UILinksWidget($sClass, $sAttCode, $iId, $sNameSuffix, - $oAttDef->DuplicatesAllowed()); + $oWidget = new UILinksWidget( + $sClass, + $sAttCode, + $iId, + $sNameSuffix, + $oAttDef->DuplicatesAllowed() + ); } else { $oWidget = new UILinksWidgetDirect($sClass, $sAttCode, $iId, $sNameSuffix); } $aEventsList[] = 'validate'; $aEventsList[] = 'change'; - $sHTMLValue = $oWidget->Display($oPage, $value, array(), $sFormPrefix, $oObj); + $sHTMLValue = $oWidget->Display($oPage, $value, [], $sFormPrefix, $oObj); } break; @@ -2271,19 +2212,19 @@ HTML; $sHTMLValue = "
\n"; $sHTMLValue .= "{$sValidationSpan}{$sReloadSpan}\n"; - $aEditImage = array( + $aEditImage = [ 'input_name' => 'attr_'.$sFieldPrefix.$sAttCode.$sNameSuffix, 'max_file_size' => utils::ConvertToBytes(ini_get('upload_max_filesize')), 'max_width_px' => $oAttDef->Get('display_max_width'), 'max_height_px' => $oAttDef->Get('display_max_height'), 'current_image_url' => $sUrl, 'default_image_url' => $sDefaultUrl, - 'labels' => array( + 'labels' => [ 'reset_button' => utils::EscapeHtml(Dict::S('UI:Button:ResetImage')), 'remove_button' => utils::EscapeHtml(Dict::S('UI:Button:RemoveImage')), 'upload_button' => !empty($sHelpText) ? $sHelpText : utils::EscapeHtml(Dict::S('UI:Button:UploadImage')), - ), - ); + ], + ]; $sEditImageOptions = json_encode($aEditImage); $oPage->add_ready_script("$('#edit_$iInputId').edit_image($sEditImageOptions);"); break; @@ -2319,8 +2260,21 @@ HTML; $aExtKeyParams = $aArgs; $aExtKeyParams['iFieldSize'] = $oAttDef->GetMaxSize(); $aExtKeyParams['iMinChars'] = $oAttDef->GetMinAutoCompleteChars(); - $sHTMLValue = UIExtKeyWidget::DisplayFromAttCode($oPage, $sAttCode, $sClass, $oAttDef->GetLabel(), - $oAllowedValues, $value, $iId, $bMandatory, $sFieldName, $sFormPrefix, $aExtKeyParams, false, $sInputType); + $sHTMLValue = UIExtKeyWidget::DisplayFromAttCode( + $oPage, + $sAttCode, + $sClass, + $oAttDef->GetLabel(), + $oAllowedValues, + $value, + $iId, + $bMandatory, + $sFieldName, + $sFormPrefix, + $aExtKeyParams, + false, + $sInputType + ); $sHTMLValue .= "\n"; $bHasExtKeyUpdatingRemoteClassFields = ( @@ -2349,25 +2303,25 @@ HTML; if ($sAttDefEditClass === 'CustomFields') { /** @var \ormCustomFieldsValue $value */ $oForm = $value->GetForm($sFormPrefix); - } else if ($sAttDefEditClass === 'FormField') { + } elseif ($sAttDefEditClass === 'FormField') { $oForm = $oAttDef->GetForm($aArgs['this'], $sFormPrefix); } $oFormRenderer = new ConsoleFormRenderer($oForm); $aFormRenderedContent = $oFormRenderer->Render(); - $aFieldSetOptions = array( + $aFieldSetOptions = [ 'field_identifier_attr' => 'data-field-id', // convention: fields are rendered into a div and are identified by this attribute 'fields_list' => $aFormRenderedContent, 'fields_impacts' => $oForm->GetFieldsImpacts(), 'form_path' => $oForm->GetId(), - ); + ]; $sFieldSetOptions = json_encode($aFieldSetOptions); - $aFormHandlerOptions = array( + $aFormHandlerOptions = [ 'wizard_helper_var_name' => 'oWizardHelper'.$sFormPrefix, 'custom_field_attcode' => $sAttCode, - ); + ]; $sFormHandlerOptions = json_encode($aFormHandlerOptions); $sHTMLValue .= '
'; @@ -2436,19 +2390,17 @@ JS // #@# todo - add context information (depending on dimensions) $aAllowedValues = $oAttDef->GetAllowedValues($aArgs); $iFieldSize = $oAttDef->GetMaxSize(); - if ($aAllowedValues !== null) - { + if ($aAllowedValues !== null) { // convert AttributeBoolean value due to issue with radio style when value is false // @see N°2443 - Boolean don't accept yes/no value - if($oAttDef instanceof AttributeBoolean){ + if ($oAttDef instanceof AttributeBoolean) { $value = $value === false ? 0 : 1; } // Discrete list of values, use a SELECT or RADIO buttons depending on the config $sDisplayStyle = $oAttDef->GetDisplayStyle(); - switch ($sDisplayStyle) - { + switch ($sDisplayStyle) { case 'radio': case 'radio_horizontal': case 'radio_vertical': @@ -2456,8 +2408,15 @@ JS $aEventsList[] = 'change'; $sHTMLValue = "
"; $bVertical = ($sDisplayStyle != 'radio_horizontal'); - $sHTMLValue .= $oPage->GetRadioButtons($aAllowedValues, $value, $iId, - "attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}", $bMandatory, $bVertical, ''); + $sHTMLValue .= $oPage->GetRadioButtons( + $aAllowedValues, + $value, + $iId, + "attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}", + $bMandatory, + $bVertical, + '' + ); $sHTMLValue .= "
{$sValidationSpan}{$sReloadSpan}\n"; break; @@ -2486,17 +2445,16 @@ EOF $sHTMLValue .= "
{$sValidationSpan}{$sReloadSpan}\n"; break; } - } - else - { + } else { $sInputType = self::ENUM_INPUT_TYPE_SINGLE_INPUT; $sDisplayValueForHtml = utils::EscapeHtml($sDisplayValue); // Adding tooltip so we can read the whole value when its very long (eg. URL) - $sTip = ''; + $sTip = ''; if (!empty($sDisplayValue)) { $sTip = 'data-tooltip-content="'.$sDisplayValueForHtml.'"'; - $oPage->add_ready_script(<<add_ready_script( + << @@ -2530,15 +2487,14 @@ HTML; break; } $sPattern = addslashes($oAttDef->GetValidationPattern()); //'^([0-9]+)$'; - if (!empty($aEventsList)) - { - if (!is_numeric($sNullValue)) - { + if (!empty($aEventsList)) { + if (!is_numeric($sNullValue)) { $sNullValue = "'$sNullValue'"; // Add quotes to turn this into a JS string if it's not a number } $sOriginalValue = ($iFlags & OPT_ATT_MUSTCHANGE) ? json_encode($value) : 'undefined'; $sEventList = implode(' ', $aEventsList); - $oPage->add_ready_script(<<add_ready_script( + << 0) - { + if (count($aDependencies) > 0) { //--- Add an event handler to launch a custom event: validate // * Unbind first to avoid duplicate event handlers in case of reload of the whole (or part of the) form // * We were using off/on directly on the node before, but that was causing an issue when adding dynamically new nodes @@ -2559,7 +2514,8 @@ JS // So we're adding the handler on a node above, and we're using a selector to catch only the event we're interested in ! $sDependencies = implode("','", $aDependencies); - $oPage->add_ready_script(<<add_ready_script( + <<GetKey(); @@ -2611,31 +2567,23 @@ JS $this->SetDisplayMode(($iKey > 0) ? static::ENUM_DISPLAY_MODE_EDIT : static::ENUM_DISPLAY_MODE_CREATE); $sDisplayMode = $this->GetDisplayMode(); - if ($this->GetDisplayMode() === static::ENUM_DISPLAY_MODE_EDIT) - { + if ($this->GetDisplayMode() === static::ENUM_DISPLAY_MODE_EDIT) { // The concurrent access lock makes sense only for already existing objects $LockEnabled = MetaModel::GetConfig()->Get('concurrent_lock_enabled'); - if ($LockEnabled) - { + if ($LockEnabled) { $sOwnershipToken = utils::ReadPostedParam('ownership_token', null, 'raw_data'); - if ($sOwnershipToken !== null) - { + if ($sOwnershipToken !== null) { // We're probably inside something like "apply_modify" where the validation failed and we must prompt the user again to edit the object // let's extend our lock - } - else - { + } else { $aLockInfo = iTopOwnershipLock::AcquireLock($sClass, $iKey); - if ($aLockInfo['success']) - { + if ($aLockInfo['success']) { $sOwnershipToken = $aLockInfo['token']; - } - else - { + } else { // If the object is locked by the current user, it's worth trying again, since // the lock may be released by 'onunload' which is called AFTER loading the current page. //$bTryAgain = $oOwner->GetKey() == UserRights::GetUserId(); - self::ReloadAndDisplay($oPage, $this, array('operation' => 'modify')); + self::ReloadAndDisplay($oPage, $this, ['operation' => 'modify']); return; } @@ -2644,7 +2592,7 @@ JS } self::$iGlobalFormId++; - $this->aFieldsMap = array(); + $this->aFieldsMap = []; $sPrefix = ''; if (isset($aExtraParams['formPrefix'])) { $sPrefix = $aExtraParams['formPrefix']; @@ -2668,33 +2616,33 @@ JS } } // Custom operation for the form ? - if (isset($aExtraParams['custom_operation'])) { - $sOperation = $aExtraParams['custom_operation']; - } else { - if ($this->GetDisplayMode() === static::ENUM_DISPLAY_MODE_EDIT) { - $sOperation = 'apply_modify'; - } else { - $sOperation = 'apply_new'; - } - } + if (isset($aExtraParams['custom_operation'])) { + $sOperation = $aExtraParams['custom_operation']; + } else { + if ($this->GetDisplayMode() === static::ENUM_DISPLAY_MODE_EDIT) { + $sOperation = 'apply_modify'; + } else { + $sOperation = 'apply_new'; + } + } - $oContentBlock = new UIContentBlock(); - $oPage->AddUiBlock($oContentBlock); + $oContentBlock = new UIContentBlock(); + $oPage->AddUiBlock($oContentBlock); - $oForm = new Form("form_{$this->m_iFormId}"); - $oForm->SetAction($sFormAction); - $sOnSubmitForm = "let bOnSubmitForm = OnSubmit('form_{$this->m_iFormId}');"; - if (isset($aExtraParams['js_handlers']['form_on_submit'])) { - $oForm->SetOnSubmitJsCode($sOnSubmitForm . $aExtraParams['js_handlers']['form_on_submit']); - } else { - $oForm->SetOnSubmitJsCode($sOnSubmitForm . "return bOnSubmitForm;"); - } - $oContentBlock->AddSubBlock($oForm); + $oForm = new Form("form_{$this->m_iFormId}"); + $oForm->SetAction($sFormAction); + $sOnSubmitForm = "let bOnSubmitForm = OnSubmit('form_{$this->m_iFormId}');"; + if (isset($aExtraParams['js_handlers']['form_on_submit'])) { + $oForm->SetOnSubmitJsCode($sOnSubmitForm.$aExtraParams['js_handlers']['form_on_submit']); + } else { + $oForm->SetOnSubmitJsCode($sOnSubmitForm."return bOnSubmitForm;"); + } + $oContentBlock->AddSubBlock($oForm); - if ($this->GetDisplayMode() === static::ENUM_DISPLAY_MODE_EDIT) { - // The object already exists in the database, it's a modification - $oForm->AddSubBlock(InputUIBlockFactory::MakeForHidden('id', $iKey, "{$sPrefix}_id")); - } + if ($this->GetDisplayMode() === static::ENUM_DISPLAY_MODE_EDIT) { + // The object already exists in the database, it's a modification + $oForm->AddSubBlock(InputUIBlockFactory::MakeForHidden('id', $iKey, "{$sPrefix}_id")); + } $oForm->AddSubBlock(InputUIBlockFactory::MakeForHidden('operation', $sOperation)); $oForm->AddSubBlock(InputUIBlockFactory::MakeForHidden('class', $sClass)); @@ -2718,34 +2666,37 @@ JS } } - $oToolbarButtons = ToolbarUIBlockFactory::MakeStandard(null); + $oToolbarButtons = ToolbarUIBlockFactory::MakeStandard(null); - $oCancelButton = ButtonUIBlockFactory::MakeForCancel(); - $oCancelButton->AddCSSClasses(['action', 'cancel']); - $oToolbarButtons->AddSubBlock($oCancelButton); - $oApplyButton = ButtonUIBlockFactory::MakeForPrimaryAction($sApplyButton, null, null, true); - $oApplyButton->AddCSSClass('action'); - $oToolbarButtons->AddSubBlock($oApplyButton); - $bAreTransitionsHidden = isset($aExtraParams['hide_transitions']) && $aExtraParams['hide_transitions'] === true; - $aTransitions = $this->EnumTransitions(); - if (!isset($aExtraParams['custom_operation']) && !$bAreTransitionsHidden && count($aTransitions)) { - // Transitions are displayed only for the standard new/modify actions, not for modify_all or any other case... - $oSetToCheckRights = DBObjectSet::FromObject($this); + $oCancelButton = ButtonUIBlockFactory::MakeForCancel(); + $oCancelButton->AddCSSClasses(['action', 'cancel']); + $oToolbarButtons->AddSubBlock($oCancelButton); + $oApplyButton = ButtonUIBlockFactory::MakeForPrimaryAction($sApplyButton, null, null, true); + $oApplyButton->AddCSSClass('action'); + $oToolbarButtons->AddSubBlock($oApplyButton); + $bAreTransitionsHidden = isset($aExtraParams['hide_transitions']) && $aExtraParams['hide_transitions'] === true; + $aTransitions = $this->EnumTransitions(); + if (!isset($aExtraParams['custom_operation']) && !$bAreTransitionsHidden && count($aTransitions)) { + // Transitions are displayed only for the standard new/modify actions, not for modify_all or any other case... + $oSetToCheckRights = DBObjectSet::FromObject($this); - $oTransitionPopoverMenu = new PopoverMenu(); - $sTPMSectionId = 'transitions'; - $oTransitionPopoverMenu->AddSection($sTPMSectionId); - $aStimuli = Metamodel::EnumStimuli($sClass); - foreach ($aTransitions as $sStimulusCode => $aTransitionDef) { - $iActionAllowed = (get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction') ? UserRights::IsStimulusAllowed($sClass, - $sStimulusCode, $oSetToCheckRights) : UR_ALLOWED_NO; - switch ($iActionAllowed) { - case UR_ALLOWED_YES: - // Button to be displayed on its own on large screens - $oButton = ButtonUIBlockFactory::MakeForPrimaryAction($aStimuli[$sStimulusCode]->GetLabel(), 'next_action', $sStimulusCode, true); - $oButton->AddCSSClass('action'); - $oButton->SetColor(Button::ENUM_COLOR_SCHEME_NEUTRAL); - $oToolbarButtons->AddSubBlock($oButton); + $oTransitionPopoverMenu = new PopoverMenu(); + $sTPMSectionId = 'transitions'; + $oTransitionPopoverMenu->AddSection($sTPMSectionId); + $aStimuli = Metamodel::EnumStimuli($sClass); + foreach ($aTransitions as $sStimulusCode => $aTransitionDef) { + $iActionAllowed = (get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction') ? UserRights::IsStimulusAllowed( + $sClass, + $sStimulusCode, + $oSetToCheckRights + ) : UR_ALLOWED_NO; + switch ($iActionAllowed) { + case UR_ALLOWED_YES: + // Button to be displayed on its own on large screens + $oButton = ButtonUIBlockFactory::MakeForPrimaryAction($aStimuli[$sStimulusCode]->GetLabel(), 'next_action', $sStimulusCode, true); + $oButton->AddCSSClass('action'); + $oButton->SetColor(Button::ENUM_COLOR_SCHEME_NEUTRAL); + $oToolbarButtons->AddSubBlock($oButton); // Button to be displayed in a grouped button on smaller screens $oTPMPopupMenuItem = new JSPopupMenuItem('next_action--'.$oButton->GetId(), $oButton->GetLabel(), "$(`#{$oButton->GetId()}`).trigger(`click`);"); @@ -2767,26 +2718,28 @@ JS } $sStatesSelection = ''; - if (!isset($aExtraParams['custom_operation']) && $this->IsNew()) - { + if (!isset($aExtraParams['custom_operation']) && $this->IsNew()) { $aInitialStates = MetaModel::EnumInitialStates($sClass); //$aInitialStates = array('new' => 'foo', 'closed' => 'bar'); - if (count($aInitialStates) > 1) - { - $sStatesSelection = Dict::Format('UI:Create_Class_InState', - MetaModel::GetName($sClass)).''; + foreach ($aInitialStates as $sStateCode => $sStateData) { $sSelected = ''; if ($sStateCode == $this->GetState()) { $sSelected = ' selected'; } - $sStatesSelection .= ''; + $sStatesSelection .= ''; } $sStatesSelection .= ''; $sStatesSelection .= ''; - $oPage->add_ready_script(<<add_ready_script( + <<m_iFormId}').on('change', function() { if ($('#obj_state_orig').val() != $(this).val()) { $('.state_select_{$this->m_iFormId}').val($(this).val()); @@ -2802,7 +2755,8 @@ JS // Prepare blocker protection to avoid loosing data $sBlockerId = $sClass.':'.$iKey; // Important: This must have the synthax format as in js/layouts/activity-panel/activity-panel.js $sJSToken = json_encode($sOwnershipToken); - $oPage->add_ready_script(<<add_ready_script( + <<GetDisplayMode() === static::ENUM_DISPLAY_MODE_EDIT) { $aFieldsMap['id'] = $sPrefix.'_id'; @@ -2904,13 +2858,13 @@ JS $aWizardHelperStaticValues = []; // Add as hidden inputs values that we want displayed if they're readonly - if(isset($aExtraParams['forceFieldsSubmission'])){ + if (isset($aExtraParams['forceFieldsSubmission'])) { $aExtraFlags = $aExtraParams['fieldsFlags'] ?? []; foreach ($aExtraParams['forceFieldsSubmission'] as $sAttCode) { - if(FormHelper::GetAttributeFlagsForObject($this, $sAttCode, $aExtraFlags) & OPT_ATT_READONLY) { - $oForm->AddSubBlock(InputUIBlockFactory::MakeForHidden('attr_'.$sPrefix.$sAttCode, $this->Get($sAttCode))); - $aWizardHelperStaticValues[$sAttCode] = $this->Get($sAttCode); - } + if (FormHelper::GetAttributeFlagsForObject($this, $sAttCode, $aExtraFlags) & OPT_ATT_READONLY) { + $oForm->AddSubBlock(InputUIBlockFactory::MakeForHidden('attr_'.$sPrefix.$sAttCode, $this->Get($sAttCode))); + $aWizardHelperStaticValues[$sAttCode] = $this->Get($sAttCode); + } } } $sWizardHelperStaticValues = json_encode($aWizardHelperStaticValues); @@ -2931,7 +2885,7 @@ JS $sDefaultUrl = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=search_form&class='.$sClass.$oAppContext->GetForLink(true); $sCancelButtonOnClickScript = "let fOnClick{$this->m_iFormId}CancelButton = "; - if(isset($aExtraParams['js_handlers']['cancel_button_on_click'])){ + if (isset($aExtraParams['js_handlers']['cancel_button_on_click'])) { $sCancelButtonOnClickScript .= $aExtraParams['js_handlers']['cancel_button_on_click']; } else { $sCancelButtonOnClickScript .= "function() { BackToDetails('$sClass', $iKey, '$sDefaultUrl', $sJSToken)};"; @@ -2968,18 +2922,16 @@ EOF EOF ); - if ($sOwnershipToken !== null) - { + if ($sOwnershipToken !== null) { $this->GetOwnershipJSHandler($oPage, $sOwnershipToken); - } - else - { + } else { // Probably a new object (or no concurrent lock), let's add a watchdog so that the session is kept open while editing $iInterval = MetaModel::GetConfig()->Get('concurrent_lock_expiration_delay') * 1000 / 2; - if ($iInterval > 0) - { - $iInterval = max(MIN_WATCHDOG_INTERVAL * 1000, - $iInterval); // Minimum interval for the watchdog is MIN_WATCHDOG_INTERVAL + if ($iInterval > 0) { + $iInterval = max( + MIN_WATCHDOG_INTERVAL * 1000, + $iInterval + ); // Minimum interval for the watchdog is MIN_WATCHDOG_INTERVAL $oPage->add_ready_script( << $value) { if (is_array($value)) { foreach ($value as $key2 => $value2) { @@ -3072,9 +3024,9 @@ EOF * @return UIContentBlock * @throws \CoreException */ - public static function DisplayBlockSelectClassToCreate( string $sClass, string $sClassLabel,array $aPossibleClasses): UIContentBlock + public static function DisplayBlockSelectClassToCreate(string $sClass, string $sClassLabel, array $aPossibleClasses): UIContentBlock { - $oBlock= UIContentBlockUIBlockFactory::MakeStandard(); + $oBlock = UIContentBlockUIBlockFactory::MakeStandard(); $oBlock->AddSubBlock(HtmlFactory::MakeRaw(Dict::Format('UI:SelectTheTypeOf_Class_ToCreate', $sClassLabel))); $oSelect = SelectUIBlockFactory::MakeForSelect('class'); $oBlock->AddSubBlock($oSelect); @@ -3107,7 +3059,7 @@ EOF * @throws \MySQLException * @throws \MySQLHasGoneAwayException */ - public static function DisplayCreationForm(WebPage $oPage, $sClass, $oSourceObject = null, $aArgs = array(), $aExtraParams = array()) + public static function DisplayCreationForm(WebPage $oPage, $sClass, $oSourceObject = null, $aArgs = [], $aExtraParams = []) { $sClass = ($oSourceObject == null) ? $sClass : get_class($oSourceObject); @@ -3125,43 +3077,32 @@ EOF $aArgs['this'] = $oObj; $aDetailsList = self::FLattenZList(MetaModel::GetZListItems($sClass, 'details')); // Order the fields based on their dependencies - $aDeps = array(); - foreach($aDetailsList as $sAttCode) - { + $aDeps = []; + foreach ($aDetailsList as $sAttCode) { $aDeps[$sAttCode] = MetaModel::GetPrerequisiteAttributes($sClass, $sAttCode); } $aList = self::OrderDependentFields($aDeps); // Now fill-in the fields with default/supplied values - foreach($aList as $sAttCode) - { - if (isset($aArgs['default'][$sAttCode])) - { + foreach ($aList as $sAttCode) { + if (isset($aArgs['default'][$sAttCode])) { $oObj->Set($sAttCode, $aArgs['default'][$sAttCode]); - } - else - { + } else { $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode); // If the field is mandatory, set it to the only possible value $iFlags = $oObj->GetInitialStateAttributeFlags($sAttCode); - if ((!$oAttDef->IsNullAllowed()) || ($iFlags & OPT_ATT_MANDATORY)) - { - if ($oAttDef->IsExternalKey()) - { + if ((!$oAttDef->IsNullAllowed()) || ($iFlags & OPT_ATT_MANDATORY)) { + if ($oAttDef->IsExternalKey()) { /** @var DBObjectSet $oAllowedValues */ $oAllowedValues = MetaModel::GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs); - if ($oAllowedValues->CountWithLimit(2) == 1) - { + if ($oAllowedValues->CountWithLimit(2) == 1) { $oRemoteObj = $oAllowedValues->Fetch(); $oObj->Set($sAttCode, $oRemoteObj->GetKey()); } - } - else - { + } else { $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs); - if (is_array($aAllowedValues) && (count($aAllowedValues) == 1)) - { + if (is_array($aAllowedValues) && (count($aAllowedValues) == 1)) { $aValues = array_keys($aAllowedValues); $oObj->Set($sAttCode, $aValues[0]); } @@ -3200,29 +3141,28 @@ EOF $aTransitions = $this->EnumTransitions(); $aStimuli = MetaModel::EnumStimuli($sClass); - if (!isset($aTransitions[$sStimulus])) - { + if (!isset($aTransitions[$sStimulus])) { // Invalid stimulus - throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, - $this->GetName(), $this->GetStateLabel())); + throw new ApplicationException(Dict::Format( + 'UI:Error:Invalid_Stimulus_On_Object_In_State', + $sStimulus, + $this->GetName(), + $this->GetStateLabel() + )); } // Check for concurrent access lock $LockEnabled = MetaModel::GetConfig()->Get('concurrent_lock_enabled'); $sOwnershipToken = null; - if ($LockEnabled) - { + if ($LockEnabled) { $aLockInfo = iTopOwnershipLock::AcquireLock($sClass, $iKey); - if ($aLockInfo['success']) - { + if ($aLockInfo['success']) { $sOwnershipToken = $aLockInfo['token']; - } - else - { + } else { // If the object is locked by the current user, it's worth trying again, since // the lock may be released by 'onunload' which is called AFTER loading the current page. //$bTryAgain = $oOwner->GetKey() == UserRights::GetUserId(); - self::ReloadAndDisplay($oPage, $this, array('operation' => 'stimulus', 'stimulus' => $sStimulus)); + self::ReloadAndDisplay($oPage, $this, ['operation' => 'stimulus', 'stimulus' => $sStimulus]); return; } @@ -3235,14 +3175,13 @@ EOF $sTargetState = $aTransitions[$sStimulus]['target_state']; $aExpectedAttributes = $this->GetTransitionAttributes($sStimulus /*, current state*/); - if ($aPrefillFormParam != null) - { + if ($aPrefillFormParam != null) { $aPrefillFormParam['expected_attributes'] = $aExpectedAttributes; $this->PrefillForm('state_change', $aPrefillFormParam); $aExpectedAttributes = $aPrefillFormParam['expected_attributes']; } - $aDetails = array(); + $aDetails = []; $iFieldIndex = 0; $aFieldsMap = [ 'id' => 'id', @@ -3270,20 +3209,24 @@ EOF // - or the field is mandatory and currently empty if (($iExpectCode & (OPT_ATT_MUSTCHANGE | OPT_ATT_MUSTPROMPT)) || (($iExpectCode & OPT_ATT_MANDATORY) && (false === $this->HasAValue($sAttCode)))) { - $aArgs = array('this' => $this); + $aArgs = ['this' => $this]; $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode); // If the field is mandatory, set it to the only possible value if ((!$oAttDef->IsNullAllowed()) || ($iExpectCode & OPT_ATT_MANDATORY)) { if ($oAttDef->IsExternalKey()) { /** @var DBObjectSet $oAllowedValues */ - $oAllowedValues = MetaModel::GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs, '', - $this->Get($sAttCode)); + $oAllowedValues = MetaModel::GetAllowedValuesAsObjectSet( + $sClass, + $sAttCode, + $aArgs, + '', + $this->Get($sAttCode) + ); if ($oAllowedValues->CountWithLimit(2) == 1) { $oRemoteObj = $oAllowedValues->Fetch(); $this->Set($sAttCode, $oRemoteObj->GetKey()); } - } else - { + } else { if ($oAttDef instanceof \AttributeCaseLog) { // Add JS files for display caselog // Dummy collapsible section created in order to get JS files @@ -3293,8 +3236,7 @@ EOF } } $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs); - if (is_array($aAllowedValues) && count($aAllowedValues) == 1) - { + if (is_array($aAllowedValues) && count($aAllowedValues) == 1) { $aValues = array_keys($aAllowedValues); $this->Set($sAttCode, $aValues[0]); } @@ -3312,13 +3254,24 @@ EOF $sDisplayValue = $this->GetEditValue($sAttCode); } } - $sHTMLValue = cmdbAbstractObject::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, - $value, $sDisplayValue, $sInputId, '', $iExpectCode, - $aArgs, true, $sInputType); - $aAttrib = array( + $sHTMLValue = cmdbAbstractObject::GetFormElementForField( + $oPage, + $sClass, + $sAttCode, + $oAttDef, + $value, + $sDisplayValue, + $sInputId, + '', + $iExpectCode, + $aArgs, + true, + $sInputType + ); + $aAttrib = [ 'label' => ''.$oAttDef->GetLabel().'', 'value' => "$sHTMLValue", - ); + ]; //add attrib for data-attribute // Prepare metadata attributes @@ -3356,7 +3309,8 @@ EOF if ($bExistFieldToDisplay || MetaModel::GetConfig()->Get('force_transition_confirmation')) { $oPage->set_title($sActionLabel); - $oPage->add(<<add( + <<
HTML @@ -3404,7 +3358,8 @@ HTML $oSubmitButton = ButtonUIBlockFactory::MakeForPrimaryAction($sActionLabel, 'submit', 'submit', true); $oForm->AddSubBlock($oSubmitButton); - $oPage->add(<<add( + <<
HTML @@ -3447,14 +3402,12 @@ EOF // Catch any exception happening during the stimulus $sExceptionMessage = ($oException instanceof CoreCannotSaveObjectException) ? $oException->getHtmlMessage() : $oException->getMessage(); \IssueLog::Error(__METHOD__, null, [$oException->getTraceAsString(), $oException->getMessage()]); - } - catch (\Throwable $e) { + } catch (\Throwable $e) { //N°4720 : with deprecation removals: ease maintenance via additional logs // Catch any Throwable happening during the stimulus $sExceptionMessage = $e->getMessage(); \IssueLog::Error(__METHOD__, null, [$e->getTraceAsString(), $e->getMessage()]); - } - finally { + } finally { if ($sOwnershipToken !== null) { // Release the concurrent lock, if any iTopOwnershipLock::ReleaseLock($sClass, $iKey, $sOwnershipToken); @@ -3473,51 +3426,39 @@ EOF public static function ProcessZlist($aList, $aDetails, $sCurrentTab, $sCurrentCol, $sCurrentSet) { $index = 0; - foreach($aList as $sKey => $value) - { - if (is_array($value)) - { - if (preg_match('/^(.*):(.*)$/U', $sKey, $aMatches)) - { + foreach ($aList as $sKey => $value) { + if (is_array($value)) { + if (preg_match('/^(.*):(.*)$/U', $sKey, $aMatches)) { $sCode = $aMatches[1]; $sName = $aMatches[2]; - switch ($sCode) - { + switch ($sCode) { case 'tab': - if (!isset($aDetails[$sName])) - { - $aDetails[$sName] = array('col1' => array()); + if (!isset($aDetails[$sName])) { + $aDetails[$sName] = ['col1' => []]; } $aDetails = self::ProcessZlist($value, $aDetails, $sName, 'col1', ''); break; case 'fieldset': - if (!isset($aDetailsStruct[$sCurrentTab][$sCurrentCol][$sName])) - { - $aDetails[$sCurrentTab][$sCurrentCol][$sName] = array(); + if (!isset($aDetailsStruct[$sCurrentTab][$sCurrentCol][$sName])) { + $aDetails[$sCurrentTab][$sCurrentCol][$sName] = []; } $aDetails = self::ProcessZlist($value, $aDetails, $sCurrentTab, $sCurrentCol, $sName); break; default: case 'col': - if (!isset($aDetails[$sCurrentTab][$sName])) - { - $aDetails[$sCurrentTab][$sName] = array(); + if (!isset($aDetails[$sCurrentTab][$sName])) { + $aDetails[$sCurrentTab][$sName] = []; } $aDetails = self::ProcessZlist($value, $aDetails, $sCurrentTab, $sName, ''); break; } } - } - else - { - if (empty($sCurrentSet)) - { + } else { + if (empty($sCurrentSet)) { $aDetails[$sCurrentTab][$sCurrentCol]['_'.$index][] = $value; - } - else - { + } else { $aDetails[$sCurrentTab][$sCurrentCol][$sCurrentSet][] = $value; } } @@ -3529,15 +3470,11 @@ EOF public static function FlattenZList($aList) { - $aResult = array(); - foreach($aList as $value) - { - if (!is_array($value)) - { + $aResult = []; + foreach ($aList as $value) { + if (!is_array($value)) { $aResult[] = $value; - } - else - { + } else { $aResult = array_merge($aResult, self::FlattenZList($value)); } } @@ -3625,8 +3562,7 @@ HTML; $sClass = get_class($this); $sId = $this->GetKey(); $sDisplayUrl = $oDoc->GetDisplayURL($sClass, $sId, $sAttCode); - switch ($oDoc->GetMainMimeType()) - { + switch ($oDoc->GetMainMimeType()) { case 'text': case 'html': $data = $oDoc->GetData(); @@ -3641,8 +3577,7 @@ HTML; break; case 'application': - switch ($oDoc->GetMimeType()) - { + switch ($oDoc->GetMimeType()) { case 'application/pdf': $oPage->add("\n"); break; @@ -3663,32 +3598,32 @@ HTML; } // $m_highlightComparison[previous][new] => next value - protected static $m_highlightComparison = array( - HILIGHT_CLASS_CRITICAL => array( + protected static $m_highlightComparison = [ + HILIGHT_CLASS_CRITICAL => [ HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING => HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_OK => HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_NONE => HILIGHT_CLASS_CRITICAL, - ), - HILIGHT_CLASS_WARNING => array( + ], + HILIGHT_CLASS_WARNING => [ HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING => HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK => HILIGHT_CLASS_WARNING, HILIGHT_CLASS_NONE => HILIGHT_CLASS_WARNING, - ), - HILIGHT_CLASS_OK => array( + ], + HILIGHT_CLASS_OK => [ HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING => HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK => HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE => HILIGHT_CLASS_OK, - ), - HILIGHT_CLASS_NONE => array( + ], + HILIGHT_CLASS_NONE => [ HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING => HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK => HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE => HILIGHT_CLASS_NONE, - ), - ); + ], + ]; /** * This function returns a 'hilight' CSS class, used to hilight a given row in a table @@ -3708,8 +3643,7 @@ HTML; // Invoke extensions before the deletion (the deletion will do some cleanup and we might loose some information /** @var \iApplicationUIExtension $oExtensionInstance */ - foreach(MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance) - { + foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance) { $new = $oExtensionInstance->GetHilightClass($this); @$current = self::$m_highlightComparison[$current][$new]; } @@ -3728,33 +3662,25 @@ HTML; */ public static function OrderDependentFields($aFields) { - $aResult = array(); + $aResult = []; $iCount = 0; - do - { + do { $bSet = false; $iCount++; - foreach($aFields as $sFieldCode => $aDeps) - { - foreach($aDeps as $key => $sDependency) - { - if (in_array($sDependency, $aResult)) - { + foreach ($aFields as $sFieldCode => $aDeps) { + foreach ($aDeps as $key => $sDependency) { + if (in_array($sDependency, $aResult)) { // Dependency is resolved, remove it unset($aFields[$sFieldCode][$key]); - } - else - { - if (!array_key_exists($sDependency, $aFields)) - { + } else { + if (!array_key_exists($sDependency, $aFields)) { // The current fields depends on a field not present in the form // let's ignore it (since it cannot change) unset($aFields[$sFieldCode][$key]); } } } - if (count($aFields[$sFieldCode]) == 0) - { + if (count($aFields[$sFieldCode]) == 0) { // No more pending depencies for this field, add it to the list $aResult[] = $sFieldCode; unset($aFields[$sFieldCode]); @@ -3763,8 +3689,7 @@ HTML; } } while ($bSet && (count($aFields) > 0)); - if (count($aFields) > 0) - { + if (count($aFields) > 0) { $sMessage = "Error: Circular dependencies between the fields!
".print_r($aFields, true)."
"; throw(new Exception($sMessage)); } @@ -3800,12 +3725,9 @@ HTML; */ public static function MapContextParam($sContextParam) { - if ($sContextParam == 'menu') - { + if ($sContextParam == 'menu') { return null; - } - else - { + } else { return $sContextParam; } } @@ -3820,69 +3742,48 @@ HTML; * @return array of attcodes that can be used for writing on the current object * @throws \CoreException */ - public function GetWriteableAttList($aAttList, &$aErrors, $aAttFlags = array()) + public function GetWriteableAttList($aAttList, &$aErrors, $aAttFlags = []) { - if (!is_array($aAttList)) - { + if (!is_array($aAttList)) { $aAttList = $this->FlattenZList(MetaModel::GetZListItems(get_class($this), 'details')); // Special case to process the case log, if any... // WARNING: if you change this also check the functions DisplayModifyForm and DisplayCaseLog - foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) - { + foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) { - if (array_key_exists($sAttCode, $aAttFlags)) - { + if (array_key_exists($sAttCode, $aAttFlags)) { $iFlags = $aAttFlags[$sAttCode]; - } - elseif ($this->IsNew()) - { + } elseif ($this->IsNew()) { $iFlags = $this->GetInitialStateAttributeFlags($sAttCode); - } - else - { - $aVoid = array(); + } else { + $aVoid = []; $iFlags = $this->GetAttributeFlags($sAttCode, $aVoid); } - if ($oAttDef instanceof AttributeCaseLog) - { - if (!($iFlags & (OPT_ATT_HIDDEN | OPT_ATT_SLAVE | OPT_ATT_READONLY))) - { + if ($oAttDef instanceof AttributeCaseLog) { + if (!($iFlags & (OPT_ATT_HIDDEN | OPT_ATT_SLAVE | OPT_ATT_READONLY))) { // The case log is editable, append it to the list of fields to retrieve $aAttList[] = $sAttCode; } } } } - $aWriteableAttList = array(); - foreach($aAttList as $sAttCode) - { + $aWriteableAttList = []; + foreach ($aAttList as $sAttCode) { $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode); - if (array_key_exists($sAttCode, $aAttFlags)) - { + if (array_key_exists($sAttCode, $aAttFlags)) { $iFlags = $aAttFlags[$sAttCode]; - } - elseif ($this->IsNew()) - { + } elseif ($this->IsNew()) { $iFlags = $this->GetInitialStateAttributeFlags($sAttCode); - } - else - { - $aVoid = array(); + } else { + $aVoid = []; $iFlags = $this->GetAttributeFlags($sAttCode, $aVoid); } - if ($oAttDef->IsWritable()) - { - if ($iFlags & (OPT_ATT_HIDDEN | OPT_ATT_READONLY)) - { + if ($oAttDef->IsWritable()) { + if ($iFlags & (OPT_ATT_HIDDEN | OPT_ATT_READONLY)) { // Non-visible, or read-only attribute, do nothing - } - elseif ($iFlags & OPT_ATT_SLAVE) - { + } elseif ($iFlags & OPT_ATT_SLAVE) { $aErrors[$sAttCode] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $oAttDef->GetLabel(), $sAttCode); - } - else - { + } else { $aWriteableAttList[$sAttCode] = $oAttDef; } } @@ -3896,16 +3797,12 @@ HTML; */ public function GetFormAttributeFlags($sAttCode) { - if ($this->IsNew()) - { + if ($this->IsNew()) { $iFlags = $this->GetInitialStateAttributeFlags($sAttCode); - } - else - { + } else { $iFlags = $this->GetAttributeFlags($sAttCode); } - if (($iFlags & OPT_ATT_MANDATORY) && $this->IsNew()) - { + if (($iFlags & OPT_ATT_MANDATORY) && $this->IsNew()) { $iFlags = $iFlags & ~OPT_ATT_READONLY; // Mandatory fields cannot be read-only when creating an object } @@ -3924,23 +3821,17 @@ HTML; */ public function UpdateObjectFromArray($aValues) { - foreach($aValues as $sAttCode => $value) - { + foreach ($aValues as $sAttCode => $value) { $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode); - switch ($oAttDef->GetEditClass()) - { + switch ($oAttDef->GetEditClass()) { case 'Document': case 'Image': // There should be an uploaded file with the named attr_ - if ($value['remove']) - { + if ($value['remove']) { $this->Set($sAttCode, null); - } - else - { + } else { $oDocument = $value['fcontents']; - if (!$oDocument->IsEmpty()) - { + if (!$oDocument->IsEmpty()) { // A new file has been uploaded $this->Set($sAttCode, $oDocument); } @@ -3949,24 +3840,21 @@ HTML; case 'One Way Password': // Check if the password was typed/changed $aPwdData = $value; - if (!is_null($aPwdData) && $aPwdData['changed']) - { + if (!is_null($aPwdData) && $aPwdData['changed']) { // The password has been changed or set $this->Set($sAttCode, $aPwdData['value']); } break; case 'Duration': $aDurationData = $value; - if (!is_array($aDurationData)) - { + if (!is_array($aDurationData)) { break; } $iValue = (((24 * $aDurationData['d']) + $aDurationData['h']) * 60 + $aDurationData['m']) * 60 + $aDurationData['s']; $this->Set($sAttCode, $iValue); $previousValue = $this->Get($sAttCode); - if ($previousValue !== $iValue) - { + if ($previousValue !== $iValue) { $this->Set($sAttCode, $iValue); } break; @@ -3974,15 +3862,12 @@ HTML; $this->Set($sAttCode, $value); break; case 'LinkedSet': - if ($this->IsValueModified($value)) - { + if ($this->IsValueModified($value)) { $oLinkSet = $this->Get($sAttCode); $sLinkedClass = $oAttDef->GetLinkedClass(); - if (array_key_exists('to_be_created', $value) && (count($value['to_be_created']) > 0)) - { + if (array_key_exists('to_be_created', $value) && (count($value['to_be_created']) > 0)) { // Now handle the links to be created - foreach ($value['to_be_created'] as $aData) - { + foreach ($value['to_be_created'] as $aData) { $sSubClass = $aData['class']; if (($sLinkedClass == $sSubClass) || (is_subclass_of($sSubClass, $sLinkedClass))) { $aObjData = $aData['data']; @@ -4002,45 +3887,35 @@ HTML; $oLinkSet->AddItem($oLink); } } + } } - } - if (array_key_exists('to_be_added', $value) && (count($value['to_be_added']) > 0)) - { + if (array_key_exists('to_be_added', $value) && (count($value['to_be_added']) > 0)) { // Now handle the links to be added by making the remote object point to self - foreach ($value['to_be_added'] as $iObjKey) - { + foreach ($value['to_be_added'] as $iObjKey) { $oLink = MetaModel::GetObject($sLinkedClass, $iObjKey, false); - if ($oLink) - { + if ($oLink) { $oLinkSet->AddItem($oLink); } } } - if (array_key_exists('to_be_modified', $value) && (count($value['to_be_modified']) > 0)) - { + if (array_key_exists('to_be_modified', $value) && (count($value['to_be_modified']) > 0)) { // Now handle the links to be added by making the remote object point to self - foreach ($value['to_be_modified'] as $iObjKey => $aData) - { + foreach ($value['to_be_modified'] as $iObjKey => $aData) { $oLink = MetaModel::GetObject($sLinkedClass, $iObjKey, false); - if ($oLink) - { + if ($oLink) { $aObjData = $aData['data']; $oLink->UpdateObjectFromArray($aObjData); $oLinkSet->ModifyItem($oLink); } } } - if (array_key_exists('to_be_removed', $value) && (count($value['to_be_removed']) > 0)) - { - foreach ($value['to_be_removed'] as $iObjKey) - { + if (array_key_exists('to_be_removed', $value) && (count($value['to_be_removed']) > 0)) { + foreach ($value['to_be_removed'] as $iObjKey) { $oLinkSet->RemoveItem($iObjKey); } } - if (array_key_exists('to_be_deleted', $value) && (count($value['to_be_deleted']) > 0)) - { - foreach ($value['to_be_deleted'] as $iObjKey) - { + if (array_key_exists('to_be_deleted', $value) && (count($value['to_be_deleted']) > 0)) { + foreach ($value['to_be_deleted'] as $iObjKey) { $oLinkSet->RemoveItem($iObjKey); } } @@ -4051,8 +3926,7 @@ HTML; case 'TagSet': /** @var ormTagSet $oTagSet */ $oTagSet = $this->Get($sAttCode); - if (is_null($oTagSet)) - { + if (is_null($oTagSet)) { $oTagSet = new ormTagSet(get_class($this), $sAttCode, $oAttDef->GetMaxItems()); } $oTagSet->ApplyDelta($value); @@ -4062,8 +3936,7 @@ HTML; case 'Set': /** @var ormSet $oSet */ $oSet = $this->Get($sAttCode); - if (is_null($oSet)) - { + if (is_null($oSet)) { $oSet = new ormSet(get_class($this), $sAttCode, $oAttDef->GetMaxItems()); } $oSet->ApplyDelta($value); @@ -4071,12 +3944,10 @@ HTML; break; default: - if (!is_null($value)) - { + if (!is_null($value)) { $aAttributes[$sAttCode] = trim($value); $previousValue = $this->Get($sAttCode); - if ($previousValue !== $aAttributes[$sAttCode]) - { + if ($previousValue !== $aAttributes[$sAttCode]) { $this->Set($sAttCode, $aAttributes[$sAttCode]); } } @@ -4088,8 +3959,7 @@ HTML; { $aModifiedKeys = ['to_be_created', 'to_be_added', 'to_be_modified', 'to_be_removed', 'to_be_deleted']; foreach ($aModifiedKeys as $sModifiedKey) { - if (array_key_exists( $sModifiedKey, $value) && (count($value[$sModifiedKey]) > 0)) - { + if (array_key_exists($sModifiedKey, $value) && (count($value[$sModifiedKey]) > 0)) { return true; } } @@ -4099,45 +3969,36 @@ HTML; /** * Updates the object from the POSTed parameters (form) */ - public function UpdateObjectFromPostedForm($sFormPrefix = '', $aAttList = null, $aAttFlags = array()) + public function UpdateObjectFromPostedForm($sFormPrefix = '', $aAttList = null, $aAttFlags = []) { - if (is_null($aAttList)) - { + if (is_null($aAttList)) { $aAttList = array_keys(MetaModel::ListAttributeDefs(get_class($this))); } - $aValues = array(); - foreach($aAttList as $sAttCode) - { + $aValues = []; + foreach ($aAttList as $sAttCode) { $value = $this->PrepareValueFromPostedForm($sFormPrefix, $sAttCode); - if (!is_null($value)) - { + if (!is_null($value)) { $aValues[$sAttCode] = $value; } } - $aErrors = array(); - $aFinalValues = array(); - foreach($this->GetWriteableAttList(array_keys($aValues), $aErrors, $aAttFlags) as $sAttCode => $oAttDef) - { + $aErrors = []; + $aFinalValues = []; + foreach ($this->GetWriteableAttList(array_keys($aValues), $aErrors, $aAttFlags) as $sAttCode => $oAttDef) { $aFinalValues[$sAttCode] = $aValues[$sAttCode]; } - try - { + try { $this->UpdateObjectFromArray($aFinalValues); - } - catch (CoreException $e) - { + } catch (CoreException $e) { $aErrors[] = $e->getMessage(); } - if (!$this->IsNew()) // for new objects this is performed in DBInsertNoReload() - { + if (!$this->IsNew()) { // for new objects this is performed in DBInsertNoReload() InlineImage::FinalizeInlineImages($this); } // Invoke extensions after the update of the object from the form /** @var \iApplicationUIExtension $oExtensionInstance */ - foreach(MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance) - { + foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance) { $oExtensionInstance->OnFormSubmit($this, $sFormPrefix); } @@ -4155,20 +4016,18 @@ HTML; */ protected function PrepareValueFromPostedForm($sFormPrefix, $sAttCode, $sClass = null, $aPostedData = null) { - if ($sClass === null) - { + if ($sClass === null) { $sClass = get_class($this); } $value = null; $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode); - switch ($oAttDef->GetEditClass()) - { - case 'Document': + switch ($oAttDef->GetEditClass()) { + case 'Document': $aOtherData = utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}", null, 'raw_data'); if (is_array($aOtherData) && array_key_exists('remove', $aOtherData)) { - $value = array('fcontents' => utils::ReadPostedDocument("attr_{$sFormPrefix}{$sAttCode}", 'fcontents'), 'remove' => $aOtherData['remove']); + $value = ['fcontents' => utils::ReadPostedDocument("attr_{$sFormPrefix}{$sAttCode}", 'fcontents'), 'remove' => $aOtherData['remove']]; } break; @@ -4182,12 +4041,11 @@ HTML; $aDimensions ); if (is_null($aDimensions)) { - IssueLog::Warning($sClass . ':' . $this->GetKey() . '/' . $sAttCode . ': Image could not be resized. Mimetype: ' . $oImage->GetMimeType() . ', filename: ' . $oImage->GetFileName()); + IssueLog::Warning($sClass.':'.$this->GetKey().'/'.$sAttCode.': Image could not be resized. Mimetype: '.$oImage->GetMimeType().', filename: '.$oImage->GetFileName()); } $aOtherData = utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}", null, 'raw_data'); - if (is_array($aOtherData)) - { - $value = array('fcontents' => $oImage, 'remove' => $aOtherData['remove']); + if (is_array($aOtherData)) { + $value = ['fcontents' => $oImage, 'remove' => $aOtherData['remove']]; } break; @@ -4209,107 +4067,117 @@ HTML; $value = LinkSetDataTransformer::Encode($aOperations, $sLinkedClass, $sTargetField); break; } - $aRawToBeCreated = json_decode(utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}_tbc", '{}', - 'raw_data'), true); - $aToBeCreated = array(); + $aRawToBeCreated = json_decode(utils::ReadPostedParam( + "attr_{$sFormPrefix}{$sAttCode}_tbc", + '{}', + 'raw_data' + ), true); + $aToBeCreated = []; foreach ($aRawToBeCreated as $aData) { $sSubFormPrefix = $aData['formPrefix']; $sObjClass = isset($aData['class']) ? $aData['class'] : $oAttDef->GetLinkedClass(); - $aObjData = array(); + $aObjData = []; foreach ($aData as $sKey => $value) { if (preg_match("/^attr_$sSubFormPrefix(.*)$/", $sKey, $aMatches)) { $oLinkAttDef = MetaModel::GetAttributeDef($sObjClass, $aMatches[1]); // Recursing over n:n link datetime attributes // Note: We might need to do it with other attribute types, like Document or redundancy setting. if ($oLinkAttDef instanceof AttributeDateTime) { - $aObjData[$aMatches[1]] = $this->PrepareValueFromPostedForm($sSubFormPrefix, - $aMatches[1], $sObjClass, $aData); + $aObjData[$aMatches[1]] = $this->PrepareValueFromPostedForm( + $sSubFormPrefix, + $aMatches[1], + $sObjClass, + $aData + ); } else { $aObjData[$aMatches[1]] = $value; } } } - $aToBeCreated[] = array('class' => $sObjClass, 'data' => $aObjData); + $aToBeCreated[] = ['class' => $sObjClass, 'data' => $aObjData]; } - $aRawToBeModified = json_decode(utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}_tbm", '{}', - 'raw_data'), true); - $aToBeModified = array(); - foreach($aRawToBeModified as $iObjKey => $aData) { + $aRawToBeModified = json_decode(utils::ReadPostedParam( + "attr_{$sFormPrefix}{$sAttCode}_tbm", + '{}', + 'raw_data' + ), true); + $aToBeModified = []; + foreach ($aRawToBeModified as $iObjKey => $aData) { $sSubFormPrefix = $aData['formPrefix']; $sObjClass = isset($aData['class']) ? $aData['class'] : $oAttDef->GetLinkedClass(); - $aObjData = array(); - foreach($aData as $sKey => $value) { + $aObjData = []; + foreach ($aData as $sKey => $value) { if (preg_match("/^attr_$sSubFormPrefix(.*)$/", $sKey, $aMatches)) { $oLinkAttDef = MetaModel::GetAttributeDef($sObjClass, $aMatches[1]); // Recursing over n:n link datetime attributes // Note: We might need to do it with other attribute types, like Document or redundancy setting. if ($oLinkAttDef instanceof AttributeDateTime) { - $aObjData[$aMatches[1]] = $this->PrepareValueFromPostedForm($sSubFormPrefix, - $aMatches[1], $sObjClass, $aData); + $aObjData[$aMatches[1]] = $this->PrepareValueFromPostedForm( + $sSubFormPrefix, + $aMatches[1], + $sObjClass, + $aData + ); } else { $aObjData[$aMatches[1]] = $value; } } } - $aToBeModified[$iObjKey] = array('data' => $aObjData); + $aToBeModified[$iObjKey] = ['data' => $aObjData]; } - $value = array( + $value = [ 'to_be_created' => $aToBeCreated, 'to_be_modified' => $aToBeModified, - 'to_be_deleted' => json_decode(utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}_tbd", '[]', - 'raw_data'), true), - 'to_be_added' => json_decode(utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}_tba", '[]', - 'raw_data'), true), - 'to_be_removed' => json_decode(utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}_tbr", '[]', - 'raw_data'), true), - ); + 'to_be_deleted' => json_decode(utils::ReadPostedParam( + "attr_{$sFormPrefix}{$sAttCode}_tbd", + '[]', + 'raw_data' + ), true), + 'to_be_added' => json_decode(utils::ReadPostedParam( + "attr_{$sFormPrefix}{$sAttCode}_tba", + '[]', + 'raw_data' + ), true), + 'to_be_removed' => json_decode(utils::ReadPostedParam( + "attr_{$sFormPrefix}{$sAttCode}_tbr", + '[]', + 'raw_data' + ), true), + ]; break; case 'Set': case 'TagSet': $sTagSetJson = utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}", null, 'raw_data'); - if ($sTagSetJson !== null) { // bulk modify, direct linked set not handled - $value = json_decode($sTagSetJson, true); - } + if ($sTagSetJson !== null) { // bulk modify, direct linked set not handled + $value = json_decode($sTagSetJson, true); + } break; default: - if ($oAttDef instanceof AttributeDateTime) // AttributeDate is derived from AttributeDateTime - { + if ($oAttDef instanceof AttributeDateTime) { // AttributeDate is derived from AttributeDateTime // Retrieving value from array when present (means what we are in a recursion) - if ($aPostedData !== null && isset($aPostedData['attr_'.$sFormPrefix.$sAttCode])) - { + if ($aPostedData !== null && isset($aPostedData['attr_'.$sFormPrefix.$sAttCode])) { $value = $aPostedData['attr_'.$sFormPrefix.$sAttCode]; - } - else - { + } else { $value = utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}", null, 'raw_data'); } - if ($value != null) - { + if ($value != null) { $oDate = $oAttDef->GetFormat()->Parse($value); - if ($oDate instanceof DateTime) - { + if ($oDate instanceof DateTime) { $value = $oDate->format($oAttDef->GetInternalFormat()); - } - else - { + } else { $value = null; } } - } - else - { + } else { // Retrieving value from array when present (means what we are in a recursion) - if ($aPostedData !== null && isset($aPostedData['attr_'.$sFormPrefix.$sAttCode])) - { + if ($aPostedData !== null && isset($aPostedData['attr_'.$sFormPrefix.$sAttCode])) { $value = $aPostedData['attr_'.$sFormPrefix.$sAttCode]; - } - else - { + } else { $value = utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}", null, 'raw_data'); } } @@ -4341,41 +4209,31 @@ HTML; * @uses utils::ReadParam() * @uses self::UpdateObjectFromArray */ - public function UpdateObjectFromArg($sArgName, $aAttList = null, $aAttFlags = array()) + public function UpdateObjectFromArg($sArgName, $aAttList = null, $aAttFlags = []) { - if (is_null($aAttList)) - { + if (is_null($aAttList)) { $aAttList = array_keys(MetaModel::ListAttributeDefs(get_class($this))); } - $aRawValues = utils::ReadParam($sArgName, array(), '', 'raw_data'); - $aValues = array(); - foreach($aAttList as $sAttCode) - { - if (isset($aRawValues[$sAttCode])) - { + $aRawValues = utils::ReadParam($sArgName, [], '', 'raw_data'); + $aValues = []; + foreach ($aAttList as $sAttCode) { + if (isset($aRawValues[$sAttCode])) { $aValues[$sAttCode] = $aRawValues[$sAttCode]; } } - $aErrors = array(); - $aFinalValues = array(); - foreach($this->GetWriteableAttList(array_keys($aValues), $aErrors, $aAttFlags) as $sAttCode => $oAttDef) - { - if ($oAttDef->IsLinkSet()) - { + $aErrors = []; + $aFinalValues = []; + foreach ($this->GetWriteableAttList(array_keys($aValues), $aErrors, $aAttFlags) as $sAttCode => $oAttDef) { + if ($oAttDef->IsLinkSet()) { $aFinalValues[$sAttCode] = json_decode($aValues[$sAttCode], true); - } - else - { + } else { $aFinalValues[$sAttCode] = $aValues[$sAttCode]; } } - try - { + try { $this->UpdateObjectFromArray($aFinalValues); - } - catch (CoreException $e) - { + } catch (CoreException $e) { $aErrors[] = $e->getMessage(); } return $aErrors; @@ -4457,7 +4315,7 @@ HTML; $this->LogCRUDEnter(__METHOD__); try { parent::DBDelete($oDeletionPlan); - } finally { + } finally { if (static::IsCrudStackEmpty()) { // Avoid signaling the current object that links were modified static::RemoveObjectAwaitingEventDbLinksChanged(get_class($this), $this->GetKey()); @@ -4477,8 +4335,7 @@ HTML; public function IsModified() { - if (parent::IsModified()) - { + if (parent::IsModified()) { return true; } @@ -4540,28 +4397,29 @@ HTML; // User rights // - if (!$this->bAllowWrite) - { + if (!$this->bAllowWrite) { $aChanges = $this->ListChanges(); - if (count($aChanges) > 0) - { - $aForbiddenFields = array(); - foreach($this->ListChanges() as $sAttCode => $value) - { - $bUpdateAllowed = UserRights::IsActionAllowedOnAttribute(get_class($this), $sAttCode, - UR_ACTION_MODIFY, DBObjectSet::FromObject($this)); - if (!$bUpdateAllowed) - { + if (count($aChanges) > 0) { + $aForbiddenFields = []; + foreach ($this->ListChanges() as $sAttCode => $value) { + $bUpdateAllowed = UserRights::IsActionAllowedOnAttribute( + get_class($this), + $sAttCode, + UR_ACTION_MODIFY, + DBObjectSet::FromObject($this) + ); + if (!$bUpdateAllowed) { $oAttCode = MetaModel::GetAttributeDef(get_class($this), $sAttCode); $aForbiddenFields[] = $oAttCode->GetLabel(); } } - if (count($aForbiddenFields) > 0) - { + if (count($aForbiddenFields) > 0) { // Security issue $this->m_bSecurityIssue = true; - $this->m_aCheckIssues[] = Dict::Format('UI:Delete:NotAllowedToUpdate_Fields', - implode(', ', $aForbiddenFields)); + $this->m_aCheckIssues[] = Dict::Format( + 'UI:Delete:NotAllowedToUpdate_Fields', + implode(', ', $aForbiddenFields) + ); } } } @@ -4576,12 +4434,10 @@ HTML; // User rights // - if (! $this->bAllowDelete) - { + if (! $this->bAllowDelete) { $bDeleteAllowed = UserRights::IsActionAllowed(get_class($this), UR_ACTION_DELETE, DBObjectSet::FromObject($this)); - if (!$bDeleteAllowed) - { + if (!$bDeleteAllowed) { // Security issue $this->m_bSecurityIssue = true; $this->m_aDeleteIssues[] = Dict::S('UI:Delete:NotAllowedToDelete'); @@ -4626,7 +4482,7 @@ HTML; $sValue = $this->Get($sAttCode); $sDisplayValue = $this->GetEditValue($sAttCode); - $aArgs = array('this' => $this, 'formPrefix' => $sPrefix); + $aArgs = ['this' => $this, 'formPrefix' => $sPrefix]; $aFieldsMap[$sAttCode] = $sInputId; @@ -4670,10 +4526,9 @@ HTML; * @throws \MySQLException * @throws \OQLException */ - public static function DisplayBulkModifyForm($oP, $sClass, $aSelectedObj, $sCustomOperation, $sCancelUrl, $aExcludeAttributes = array(), $aContextData = array()) + public static function DisplayBulkModifyForm($oP, $sClass, $aSelectedObj, $sCustomOperation, $sCancelUrl, $aExcludeAttributes = [], $aContextData = []) { - if (count($aSelectedObj) > 0) - { + if (count($aSelectedObj) > 0) { $iAllowedCount = count($aSelectedObj); $sSelectedObj = implode(',', $aSelectedObj); @@ -4682,17 +4537,14 @@ HTML; // Compute the distribution of the values for each field to determine which of the "scalar or linked set" fields are homogeneous $aList = MetaModel::ListAttributeDefs($sClass); - $aValues = array(); - foreach($aList as $sAttCode => $oAttDef) - { + $aValues = []; + foreach ($aList as $sAttCode => $oAttDef) { if ($oAttDef->IsBulkModifyCompatible()) { - $aValues[$sAttCode] = array(); + $aValues[$sAttCode] = []; } } - while ($oObj = $oSet->Fetch()) - { - foreach($aList as $sAttCode => $oAttDef) - { + while ($oObj = $oSet->Fetch()) { + foreach ($aList as $sAttCode => $oAttDef) { if ($oAttDef->IsBulkModifyCompatible() && $oAttDef->IsWritable()) { $currValue = $oObj->Get($sAttCode); $editValue = ''; @@ -4700,7 +4552,7 @@ HTML; $currValue = ''; // Put a single scalar value to force caselog to mock a new entry. For more info see N°1059. } elseif ($currValue instanceof ormSet) { $currValue = $oAttDef->GetEditValue($currValue, $oObj); - } else if ($currValue instanceof ormLinkSet) { + } elseif ($currValue instanceof ormLinkSet) { $sHtmlValue = $oAttDef->GetAsHTML($currValue); $editValue = $oAttDef->GetEditValue($currValue, $oObj); $currValue = $sHtmlValue; @@ -4708,16 +4560,13 @@ HTML; if (is_object($currValue)) { continue; } // Skip non scalar values... - if (!array_key_exists($currValue, $aValues[$sAttCode])) - { - $aValues[$sAttCode][$currValue] = array( + if (!array_key_exists($currValue, $aValues[$sAttCode])) { + $aValues[$sAttCode][$currValue] = [ 'count' => 1, 'display' => $oObj->GetAsHTML($sAttCode), 'edit_value' => $editValue, - ); - } - else - { + ]; + } else { $aValues[$sAttCode][$currValue]['count']++; } } @@ -4727,7 +4576,7 @@ HTML; /** @var \cmdbAbstractObject $oDummyObj */ $oDummyObj = new $sClass(); // @@ What if the class is abstract ? $oDummyObj->SetDisplayMode(static::ENUM_DISPLAY_MODE_BULK_EDIT); - $aComments = array(); + $aComments = []; function MyComparison($a, $b) // Sort descending { if ($a['count'] == $b['count']) { @@ -4741,15 +4590,19 @@ HTML; $sReadyScript = ''; $sFormPrefix = '2_'; foreach ($aList as $sAttCode => $oAttDef) { - $aPrerequisites = MetaModel::GetPrerequisiteAttributes($sClass, - $sAttCode); // List of attributes that are needed for the current one + $aPrerequisites = MetaModel::GetPrerequisiteAttributes( + $sClass, + $sAttCode + ); // List of attributes that are needed for the current one if (count($aPrerequisites) > 0) { // When 'enabling' a field, all its prerequisites must be enabled too $sFieldList = "['{$sFormPrefix}".implode("','{$sFormPrefix}", $aPrerequisites)."']"; $oP->add_ready_script("$('#enable_{$sFormPrefix}{$sAttCode}').on('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, true); } );\n"); } - $aDependents = MetaModel::GetDependentAttributes($sClass, - $sAttCode); // List of attributes that are needed for the current one + $aDependents = MetaModel::GetDependentAttributes( + $sClass, + $sAttCode + ); // List of attributes that are needed for the current one if (count($aDependents) > 0) { // When 'disabling' a field, all its dependent fields must be disabled too $sFieldList = "['{$sFormPrefix}".implode("','{$sFormPrefix}", $aDependents)."']"; @@ -4772,7 +4625,7 @@ HTML; $aKeys = array_keys($aValues[$sAttCode]); $currValue = $aKeys[0]; // The only value is the first key if ($oAttDef->GetEditClass() == 'LinkedSet') { - $oOrmLinkSet = $oDummyObj->Get($sAttCode); + $oOrmLinkSet = $oDummyObj->Get($sAttCode); LinkSetDataTransformer::StringToOrmLinkSet($aValues[$sAttCode][$currValue]['edit_value'], $oOrmLinkSet); } else { @@ -4792,16 +4645,21 @@ HTML; $sTip = "

".Dict::Format('UI:BulkModify_Count_DistinctValues', $iCount)."

    "; $index = 0; foreach ($aMultiValues as $sCurrValue => $aVal) { - $sDisplayValue = empty($aVal['display']) ? ''.Dict::S('Enum:Undefined').'' : str_replace(array( + $sDisplayValue = empty($aVal['display']) ? ''.Dict::S('Enum:Undefined').'' : str_replace([ "\n", "\r", - ), " ", $aVal['display']); - $sTip .= "
  • ".Dict::Format('UI:BulkModify:Value_Exists_N_Times', $sDisplayValue, - $aVal['count'])."
  • "; + ], " ", $aVal['display']); + $sTip .= "
  • ".Dict::Format( + 'UI:BulkModify:Value_Exists_N_Times', + $sDisplayValue, + $aVal['count'] + )."
  • "; $index++; if ($iMaxCount == $index) { - $sTip .= "
  • ".Dict::Format('UI:BulkModify:N_MoreValues', - count($aMultiValues) - $iMaxCount)."
  • "; + $sTip .= "
  • ".Dict::Format( + 'UI:BulkModify:N_MoreValues', + count($aMultiValues) - $iMaxCount + )."
  • "; break; } } @@ -4825,8 +4683,8 @@ HTML; $oTagSet->GenerateDiffFromArray($aTagCodes); } $oDummyObj->Set($sAttCode, $oTagSet); - } else if ($oAttDef->GetEditClass() == 'LinkedSet') { - $oOrmLinkSet = $oDummyObj->Get($sAttCode); + } elseif ($oAttDef->GetEditClass() == 'LinkedSet') { + $oOrmLinkSet = $oDummyObj->Get($sAttCode); foreach ($aMultiValues as $key => $sValue) { LinkSetDataTransformer::StringToOrmLinkSet($sValue['edit_value'], $oOrmLinkSet); } @@ -4864,8 +4722,8 @@ HTML; $oP->add("
    \n"); $sDisableFields = json_encode($aExcludeAttributes); - $aParams = array - ( + $aParams = + [ 'fieldsComments' => $aComments, 'noRelations' => true, 'custom_operation' => $sCustomOperation, @@ -4878,7 +4736,7 @@ HTML; 'bulk_context' => [ 'oql' => $sOQL, ], - ); + ]; $aParams = $aParams + $aContextData; // merge keeping associations $oDummyObj->DisplayModifyForm($oP, $aParams); @@ -4892,8 +4750,7 @@ EOF ); } // Else no object selected ??? - else - { + else { $oP->p("No object selected !, nothing to do"); } } @@ -4915,27 +4772,25 @@ EOF * @throws \DictExceptionMissingString * @throws \OQLException */ - public static function DoBulkModify($oP, $sClass, $aSelectedObj, $sCustomOperation, $bPreview, $sCancelUrl, $aContextData = array()) + public static function DoBulkModify($oP, $sClass, $aSelectedObj, $sCustomOperation, $bPreview, $sCancelUrl, $aContextData = []) { /** @var string[] $aHeaders */ - $aHeaders = array( - 'object' => array('label' => MetaModel::GetName($sClass), 'description' => Dict::S('UI:ModifiedObject')), - 'status' => array( + $aHeaders = [ + 'object' => ['label' => MetaModel::GetName($sClass), 'description' => Dict::S('UI:ModifiedObject')], + 'status' => [ 'label' => Dict::S('UI:BulkModifyStatus'), 'description' => Dict::S('UI:BulkModifyStatus+'), - ), - 'errors' => array( + ], + 'errors' => [ 'label' => Dict::S('UI:BulkModifyErrors'), 'description' => Dict::S('UI:BulkModifyErrors+'), - ), - ); - $aRows = array(); - + ], + ]; + $aRows = []; $sHeaderTitle = Dict::Format('UI:Modify_N_ObjectsOf_Class', count($aSelectedObj), MetaModel::GetName($sClass)); $sClassIcon = MetaModel::GetClassIcon($sClass, false); - $oP->set_title(Dict::Format('UI:Modify_N_ObjectsOf_Class', count($aSelectedObj), $sClass)); if (!$bPreview) { // Not in preview mode, do the update for real @@ -4965,14 +4820,14 @@ EOF $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusModified') : Dict::S('UI:BulkModifyStatusSkipped'); } - $aErrorsToDisplay = array_map(function($sError) { + $aErrorsToDisplay = array_map(function ($sError) { return utils::HtmlEntities($sError); }, $aErrors); - $aRows[] = array( + $aRows[] = [ 'object' => $oObj->GetHyperlink(), 'status' => $sStatus, 'errors' => '

    '.($bResult ? '' : implode('

    ', $aErrorsToDisplay)).'

    ', - ); + ]; if ($bResult && (!$bPreview)) { // doing the check will load multiple times same objects :/ // but it shouldn't cost too much on execution time @@ -4996,7 +4851,6 @@ EOF $oPanel->AddCSSClass('ibo-datatable-panel'); $oPanel->AddSubBlock($oTable); - if ($bPreview) { $sFormAction = utils::GetAbsoluteUrlAppRoot().'pages/UI.php'; // No parameter in the URL, the only parameter will be the ones passed through the form // Form to submit: @@ -5052,7 +4906,7 @@ EOF * @throws \DictExceptionMissingString * @throws \Exception */ - public static function DeleteObjects(WebPage $oP, $sClass, $aObjects, $bPreview, $sCustomOperation, $aContextData = array()) + public static function DeleteObjects(WebPage $oP, $sClass, $aObjects, $bPreview, $sCustomOperation, $aContextData = []) { $oDeletionPlan = new DeletionPlan(); @@ -5077,119 +4931,106 @@ EOF $oObj = $aObjects[0]; $sTitle = Dict::Format('UI:Delete:ConfirmDeletionOf_Name', $oObj->GetRawName()); } else { - $sTitle = Dict::Format('UI:Delete:ConfirmDeletionOf_Count_ObjectsOf_Class', count($aObjects), - MetaModel::GetName($sClass)); + $sTitle = Dict::Format( + 'UI:Delete:ConfirmDeletionOf_Count_ObjectsOf_Class', + count($aObjects), + MetaModel::GetName($sClass) + ); } $oP->AddUiBlock(TitleUIBlockFactory::MakeForPage($sTitle)); // Explain what should be done // - $aDisplayData = array(); + $aDisplayData = []; foreach ($oDeletionPlan->ListDeletes() as $sTargetClass => $aDeletes) { foreach ($aDeletes as $iId => $aData) { $oToDelete = $aData['to_delete']; $bAutoDel = (($aData['mode'] == DEL_SILENT) || ($aData['mode'] == DEL_AUTO)); $sRowCssClass = ''; - if (array_key_exists('issue', $aData)) - { - if ($bAutoDel) - { - if (isset($aData['requested_explicitely'])) - { + if (array_key_exists('issue', $aData)) { + if ($bAutoDel) { + if (isset($aData['requested_explicitely'])) { $sConsequence = Dict::Format('UI:Delete:CannotDeleteBecause', $aData['issue']); + } else { + $sConsequence = Dict::Format( + 'UI:Delete:ShouldBeDeletedAtomaticallyButNotPossible', + $aData['issue'] + ); } - else - { - $sConsequence = Dict::Format('UI:Delete:ShouldBeDeletedAtomaticallyButNotPossible', - $aData['issue']); - } - } - else - { - $sConsequence = Dict::Format('UI:Delete:MustBeDeletedManuallyButNotPossible', - $aData['issue']); + } else { + $sConsequence = Dict::Format( + 'UI:Delete:MustBeDeletedManuallyButNotPossible', + $aData['issue'] + ); } $sRowCssClass = 'ibo-is-alert'; - } - else - { - if ($bAutoDel) - { - if (isset($aData['requested_explicitely'])) - { + } else { + if ($bAutoDel) { + if (isset($aData['requested_explicitely'])) { $sConsequence = ''; // not applicable - } - else - { + } else { $sConsequence = Dict::S('UI:Delete:WillBeDeletedAutomatically'); } - } - else - { + } else { $sConsequence = Dict::S('UI:Delete:MustBeDeletedManually'); $sRowCssClass = 'ibo-is-warning'; } } - $aDisplayData[] = array( + $aDisplayData[] = [ '@class' => $sRowCssClass, 'class' => MetaModel::GetName(get_class($oToDelete)), 'object' => $oToDelete->GetHyperLink(), 'consequence' => $sConsequence, - ); + ]; } } - foreach($oDeletionPlan->ListUpdates() as $sRemoteClass => $aToUpdate) - { - foreach($aToUpdate as $iId => $aData) - { + foreach ($oDeletionPlan->ListUpdates() as $sRemoteClass => $aToUpdate) { + foreach ($aToUpdate as $iId => $aData) { $oToUpdate = $aData['to_reset']; $sRowCssClass = ''; - if (array_key_exists('issue', $aData)) - { + if (array_key_exists('issue', $aData)) { $sConsequence = Dict::Format('UI:Delete:CannotUpdateBecause_Issue', $aData['issue']); $sRowCssClass = 'ibo-is-alert'; + } else { + $sConsequence = Dict::Format( + 'UI:Delete:WillAutomaticallyUpdate_Fields', + $aData['attributes_list'] + ); } - else - { - $sConsequence = Dict::Format('UI:Delete:WillAutomaticallyUpdate_Fields', - $aData['attributes_list']); - } - $aDisplayData[] = array( + $aDisplayData[] = [ '@class' => $sRowCssClass, 'class' => MetaModel::GetName(get_class($oToUpdate)), 'object' => $oToUpdate->GetHyperLink(), 'consequence' => $sConsequence, - ); + ]; } } $iImpactedIndirectly = $oDeletionPlan->GetTargetCount() - count($aObjects); $sImpactedTableTitle = ''; $sImpactedTableSubtitle = ''; - if ($iImpactedIndirectly > 0) - { - if (count($aObjects) == 1) - { + if ($iImpactedIndirectly > 0) { + if (count($aObjects) == 1) { $oObj = $aObjects[0]; - $sImpactedTableTitle = Dict::Format('UI:Delete:Count_Objects/LinksReferencing_Object', $iImpactedIndirectly, - $oObj->GetName()); - } - else - { + $sImpactedTableTitle = Dict::Format( + 'UI:Delete:Count_Objects/LinksReferencing_Object', + $iImpactedIndirectly, + $oObj->GetName() + ); + } else { $sImpactedTableTitle = Dict::Format('UI:Delete:Count_Objects/LinksReferencingTheObjects', $iImpactedIndirectly); } $sImpactedTableSubtitle = Dict::S('UI:Delete:ReferencesMustBeDeletedToEnsureIntegrity'); } - if (($iImpactedIndirectly > 0) || $oDeletionPlan->FoundStopper()) - { - $aDisplayConfig = array(); - $aDisplayConfig['class'] = array('label' => 'Class', 'description' => ''); - $aDisplayConfig['object'] = array('label' => 'Object', 'description' => ''); - $aDisplayConfig['consequence'] = array( + if (($iImpactedIndirectly > 0) || $oDeletionPlan->FoundStopper()) { + $aDisplayConfig = []; + $aDisplayConfig['class'] = ['label' => 'Class', 'description' => '']; + $aDisplayConfig['object'] = ['label' => 'Object', 'description' => '']; + $aDisplayConfig['consequence'] = [ 'label' => 'Consequence', 'description' => Dict::S('UI:Delete:Consequence+'), - ); + ]; $oBlock = PanelUIBlockFactory::MakeNeutral($sImpactedTableTitle, $sImpactedTableSubtitle); $oDataTable = DataTableUIBlockFactory::MakeForForm(utils::Sanitize(uniqid('form_', true), '', utils::ENUM_SANITIZATION_FILTER_ELEMENT_IDENTIFIER), $aDisplayConfig, $aDisplayData); @@ -5202,8 +5043,7 @@ EOF $oFailAlertBlock = AlertUIBlockFactory::MakeForDanger('', Dict::S('UI:Delete:SorryDeletionNotAllowed')); $oFailAlertBlock->SetIsClosable(false); $oP->AddUiBlock($oFailAlertBlock); - } - else { + } else { $oWarningAlertBlock = AlertUIBlockFactory::MakeForWarning('', Dict::S('UI:Delete:PleaseDoTheManualOperations')); $oWarningAlertBlock->SetIsClosable(false); $oP->AddUiBlock($oWarningAlertBlock); @@ -5219,14 +5059,16 @@ EOF $oToolbarButtons->AddSubBlock(ButtonUIBlockFactory::MakeForDestructiveAction(Dict::S('UI:Button:Delete'), null, null, true)->SetIsDisabled(true)); $oAppContext = new ApplicationContext(); $oForm->AddSubBlock($oAppContext->GetForFormBlock()); - } - else { + } else { if (count($aObjects) == 1) { $oObj = $aObjects[0]; $sSubtitle = Dict::Format('UI:Delect:Confirm_Object', $oObj->GetHyperLink()); } else { - $sSubtitle = Dict::Format('UI:Delect:Confirm_Count_ObjectsOf_Class', count($aObjects), - MetaModel::GetName($sClass)); + $sSubtitle = Dict::Format( + 'UI:Delect:Confirm_Count_ObjectsOf_Class', + count($aObjects), + MetaModel::GetName($sClass) + ); } foreach ($aObjects as $oObj) { @@ -5237,7 +5079,7 @@ EOF $oSet = new CMDBobjectSet($oFilter); $oDisplaySet = UIContentBlockUIBlockFactory::MakeStandard("0"); $oP->AddSubBlock($oDisplaySet); - $oDisplaySet->AddSubBlock(CMDBAbstractObject::GetDisplaySetBlock($oP, $oSet, array( + $oDisplaySet->AddSubBlock(CMDBAbstractObject::GetDisplaySetBlock($oP, $oSet, [ 'display_limit' => false, 'menu' => false, 'surround_with_panel' => true, @@ -5245,7 +5087,7 @@ EOF 'panel_title_is_html' => true, 'panel_icon' => MetaModel::GetClassIcon($sClass, false), 'panel_class' => $sClass, - ))); + ])); $oForm = FormUIBlockFactory::MakeStandard(''); $oP->AddSubBlock($oForm); @@ -5269,9 +5111,7 @@ EOF $oForm->AddSubBlock($oAppContext->GetForFormBlock()); } - } - else // if ($bPreview)... - { + } else { // if ($bPreview)... // Execute the deletion // if (count($aObjects) == 1) { @@ -5289,48 +5129,40 @@ EOF if ($oDeletionPlan->FoundManualOperation()) { throw new CoreException(Dict::S('UI:Error:CannotDeleteBecauseManualOpNeeded')); } - if ($oDeletionPlan->FoundManualDelete()) - { + if ($oDeletionPlan->FoundManualDelete()) { throw new CoreException(Dict::S('UI:Error:CannotDeleteBecauseOfDepencies')); } // Report deletions // - $aDisplayData = array(); - foreach($oDeletionPlan->ListDeletes() as $sTargetClass => $aDeletes) - { - foreach($aDeletes as $iId => $aData) - { + $aDisplayData = []; + foreach ($oDeletionPlan->ListDeletes() as $sTargetClass => $aDeletes) { + foreach ($aDeletes as $iId => $aData) { $oToDelete = $aData['to_delete']; - if (isset($aData['requested_explicitely'])) - { + if (isset($aData['requested_explicitely'])) { $sMessage = Dict::S('UI:Delete:Deleted'); - } - else - { + } else { $sMessage = Dict::S('UI:Delete:AutomaticallyDeleted'); } - $aDisplayData[] = array( + $aDisplayData[] = [ 'class' => MetaModel::GetName(get_class($oToDelete)), 'object' => $oToDelete->GetName(), 'consequence' => $sMessage, - ); + ]; } } // Report updates // - foreach($oDeletionPlan->ListUpdates() as $sTargetClass => $aToUpdate) - { - foreach($aToUpdate as $iId => $aData) - { + foreach ($oDeletionPlan->ListUpdates() as $sTargetClass => $aToUpdate) { + foreach ($aToUpdate as $iId => $aData) { $oToUpdate = $aData['to_reset']; - $aDisplayData[] = array( + $aDisplayData[] = [ 'class' => MetaModel::GetName(get_class($oToUpdate)), 'object' => $oToUpdate->GetHyperLink(), 'consequence' => Dict::Format('UI:Delete:AutomaticResetOf_Fields', $aData['attributes_list']), - ); + ]; } } @@ -5341,14 +5173,17 @@ EOF $oObj = $aObjects[0]; $sSubtitle = Dict::Format('UI:Delete:CleaningUpRefencesTo_Object', $oObj->GetName()); } else { - $sSubtitle = Dict::Format('UI:Delete:CleaningUpRefencesTo_Several_ObjectsOf_Class', count($aObjects), - MetaModel::GetName($sClass)); + $sSubtitle = Dict::Format( + 'UI:Delete:CleaningUpRefencesTo_Several_ObjectsOf_Class', + count($aObjects), + MetaModel::GetName($sClass) + ); } - $aDisplayConfig = array(); - $aDisplayConfig['class'] = array('label' => 'Class', 'description' => ''); - $aDisplayConfig['object'] = array('label' => 'Object', 'description' => ''); - $aDisplayConfig['consequence'] = array('label' => 'Done', 'description' => Dict::S('UI:Delete:Done+')); + $aDisplayConfig = []; + $aDisplayConfig['class'] = ['label' => 'Class', 'description' => '']; + $aDisplayConfig['object'] = ['label' => 'Object', 'description' => '']; + $aDisplayConfig['consequence'] = ['label' => 'Done', 'description' => Dict::S('UI:Delete:Done+')]; $oResultsPanel = PanelUIBlockFactory::MakeForInformation($sSubtitle); $oP->AddUiBlock($oResultsPanel); @@ -5366,21 +5201,18 @@ EOF */ protected function FindVisibleRedundancySettings() { - $aRet = array(); - foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) - { - if ($oAttDef instanceof AttributeRedundancySettings) - { - if ($oAttDef->IsVisible()) - { + $aRet = []; + foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) { + if ($oAttDef instanceof AttributeRedundancySettings) { + if ($oAttDef->IsVisible()) { $aQueryInfo = $oAttDef->GetRelationQueryData(); - if (isset($aQueryInfo['sAttribute'])) - { - $oUpperAttDef = MetaModel::GetAttributeDef($aQueryInfo['sFromClass'], - $aQueryInfo['sAttribute']); + if (isset($aQueryInfo['sAttribute'])) { + $oUpperAttDef = MetaModel::GetAttributeDef( + $aQueryInfo['sFromClass'], + $aQueryInfo['sAttribute'] + ); $oHostAttDef = $oUpperAttDef->GetMirrorLinkAttribute(); - if ($oHostAttDef) - { + if ($oHostAttDef) { $sHostAttCode = $oHostAttDef->GetCode(); $aRet[$sHostAttCode][] = $oAttDef; } @@ -5400,8 +5232,10 @@ EOF */ protected function GetOwnershipJSHandler($oPage, $sOwnershipToken) { - $iInterval = max(MIN_WATCHDOG_INTERVAL, - MetaModel::GetConfig()->Get('concurrent_lock_expiration_delay')) * 1000 / 2; // Minimum interval for the watchdog is MIN_WATCHDOG_INTERVAL + $iInterval = max( + MIN_WATCHDOG_INTERVAL, + MetaModel::GetConfig()->Get('concurrent_lock_expiration_delay') + ) * 1000 / 2; // Minimum interval for the watchdog is MIN_WATCHDOG_INTERVAL $sJSClass = json_encode(get_class($this)); $iKey = (int)$this->GetKey(); $sJSToken = json_encode($sOwnershipToken); @@ -5461,14 +5295,15 @@ JS * @return array * @since 2.7.0 */ - protected static function GetAttEditClassesToRenderAsLargeField(){ - return array( + protected static function GetAttEditClassesToRenderAsLargeField() + { + return [ 'CaseLog', 'CustomFields', 'HTML', 'OQLExpression', 'Text', - ); + ]; } /** @@ -5480,8 +5315,9 @@ JS * * @internal Do NOT use, this is experimental and most likely to be moved elsewhere when we find its rightful place. */ - public static function GetAttDefClassesToExcludeFromMarkupMetadataRawValue(){ - return array( + public static function GetAttDefClassesToExcludeFromMarkupMetadataRawValue() + { + return [ 'AttributeBlob', 'AttributeCustomFields', 'AttributeDashboard', @@ -5492,7 +5328,7 @@ JS 'AttributeText', 'AttributePassword', 'AttributeOneWayPassword', - ); + ]; } ////////////////// @@ -5616,7 +5452,7 @@ JS { /** @var AttributeLinkedSet $oAttDefMirrorLink */ $oAttDefMirrorLink = $oAttDef->GetMirrorLinkAttribute(); - if (is_null($oAttDefMirrorLink) || false === $oAttDefMirrorLink->HasPHPComputation()){ + if (is_null($oAttDefMirrorLink) || false === $oAttDefMirrorLink->HasPHPComputation()) { return false; } @@ -5849,7 +5685,6 @@ JS return $iFlags; } - /** * Append $iFlags to $sAttCode attribute in initial state * diff --git a/application/dashboard.class.inc.php b/application/dashboard.class.inc.php index 487040b43..115e4ff8b 100644 --- a/application/dashboard.class.inc.php +++ b/application/dashboard.class.inc.php @@ -1,4 +1,5 @@ sLayoutClass = 'DashboardLayoutOneCol'; $this->bAutoReload = false; $this->iAutoReloadSec = MetaModel::GetConfig()->GetStandardReloadInterval(); - $this->aCells = array(); + $this->aCells = []; $this->oDOMNode = null; $this->sId = $sId; } @@ -65,8 +66,8 @@ abstract class Dashboard */ public function FromXml($sXml) { - $this->aCells = array(); // reset the content of the dashboard - set_error_handler(array('Dashboard', 'ErrorHandler')); + $this->aCells = []; // reset the content of the dashboard + set_error_handler(['Dashboard', 'ErrorHandler']); $oDoc = new DOMDocument(); $oDoc->loadXML($sXml); restore_error_handler(); @@ -79,87 +80,69 @@ abstract class Dashboard public function FromDOMDocument(DOMDocument $oDoc) { $this->oDOMNode = $oDoc->getElementsByTagName('dashboard')->item(0); - - if ($oLayoutNode = $this->oDOMNode->getElementsByTagName('layout')->item(0)) - { + + if ($oLayoutNode = $this->oDOMNode->getElementsByTagName('layout')->item(0)) { $this->sLayoutClass = $oLayoutNode->textContent; - } - else - { + } else { $this->sLayoutClass = 'DashboardLayoutOneCol'; } - - if ($oTitleNode = $this->oDOMNode->getElementsByTagName('title')->item(0)) - { + + if ($oTitleNode = $this->oDOMNode->getElementsByTagName('title')->item(0)) { $this->sTitle = $oTitleNode->textContent; - } - else - { + } else { $this->sTitle = ''; } - + $this->bAutoReload = false; $this->iAutoReloadSec = MetaModel::GetConfig()->GetStandardReloadInterval(); - if ($oAutoReloadNode = $this->oDOMNode->getElementsByTagName('auto_reload')->item(0)) - { - if ($oAutoReloadEnabled = $oAutoReloadNode->getElementsByTagName('enabled')->item(0)) - { + if ($oAutoReloadNode = $this->oDOMNode->getElementsByTagName('auto_reload')->item(0)) { + if ($oAutoReloadEnabled = $oAutoReloadNode->getElementsByTagName('enabled')->item(0)) { $this->bAutoReload = ($oAutoReloadEnabled->textContent == 'true'); } - if ($oAutoReloadInterval = $oAutoReloadNode->getElementsByTagName('interval')->item(0)) - { + if ($oAutoReloadInterval = $oAutoReloadNode->getElementsByTagName('interval')->item(0)) { $this->iAutoReloadSec = max(MetaModel::GetConfig()->Get('min_reload_interval'), (int)$oAutoReloadInterval->textContent); } } - if ($oCellsNode = $this->oDOMNode->getElementsByTagName('cells')->item(0)) - { + if ($oCellsNode = $this->oDOMNode->getElementsByTagName('cells')->item(0)) { $oCellsList = $oCellsNode->getElementsByTagName('cell'); - $aCellOrder = array(); + $aCellOrder = []; $iCellRank = 0; /** @var \DOMElement $oCellNode */ - foreach($oCellsList as $oCellNode) - { + foreach ($oCellsList as $oCellNode) { $oCellRank = $oCellNode->getElementsByTagName('rank')->item(0); - if ($oCellRank) - { + if ($oCellRank) { $iCellRank = (float)$oCellRank->textContent; } $oDashletsNode = $oCellNode->getElementsByTagName('dashlets')->item(0); { $oDashletList = $oDashletsNode->getElementsByTagName('dashlet'); $iRank = 0; - $aDashletOrder = array(); + $aDashletOrder = []; /** @var \DOMElement $oDomNode */ - foreach($oDashletList as $oDomNode) - { + foreach ($oDashletList as $oDomNode) { $oRank = $oDomNode->getElementsByTagName('rank')->item(0); - if ($oRank) - { + if ($oRank) { $iRank = (float)$oRank->textContent; } $oNewDashlet = $this->InitDashletFromDOMNode($oDomNode); - $aDashletOrder[] = array('rank' => $iRank, 'dashlet' => $oNewDashlet); + $aDashletOrder[] = ['rank' => $iRank, 'dashlet' => $oNewDashlet]; } - usort($aDashletOrder, array(get_class($this), 'SortOnRank')); - $aDashletList = array(); - foreach($aDashletOrder as $aItem) - { + usort($aDashletOrder, [get_class($this), 'SortOnRank']); + $aDashletList = []; + foreach ($aDashletOrder as $aItem) { $aDashletList[] = $aItem['dashlet']; } - $aCellOrder[] = array('rank' => $iCellRank, 'dashlets' => $aDashletList); + $aCellOrder[] = ['rank' => $iCellRank, 'dashlets' => $aDashletList]; } } - usort($aCellOrder, array(get_class($this), 'SortOnRank')); - foreach($aCellOrder as $aItem) - { + usort($aCellOrder, [get_class($this), 'SortOnRank']); + foreach ($aCellOrder as $aItem) { $this->aCells[] = $aItem['dashlets']; } - } - else - { - $this->aCells = array(); + } else { + $this->aCells = []; } } @@ -169,20 +152,20 @@ abstract class Dashboard * @return mixed */ protected function InitDashletFromDOMNode($oDomNode) - { - $sId = $oDomNode->getAttribute('id'); + { + $sId = $oDomNode->getAttribute('id'); - $sDashletType = $oDomNode->getAttribute('xsi:type'); + $sDashletType = $oDomNode->getAttribute('xsi:type'); - // Test if dashlet can be instantiated, otherwise (uninstalled, broken, ...) we display a placeholder - $sClass = static::GetDashletClassFromType($sDashletType); - /** @var \Dashlet $oNewDashlet */ - $oNewDashlet = new $sClass($this->oMetaModel, $sId); - $oNewDashlet->SetDashletType($sDashletType); - $oNewDashlet->FromDOMNode($oDomNode); + // Test if dashlet can be instantiated, otherwise (uninstalled, broken, ...) we display a placeholder + $sClass = static::GetDashletClassFromType($sDashletType); + /** @var \Dashlet $oNewDashlet */ + $oNewDashlet = new $sClass($this->oMetaModel, $sId); + $oNewDashlet->SetDashletType($sDashletType); + $oNewDashlet->FromDOMNode($oDomNode); - return $oNewDashlet; - } + return $oNewDashlet; + } /** * @param array $aItem1 @@ -208,12 +191,9 @@ abstract class Dashboard */ public static function ErrorHandler($errno, $errstr, $errfile, $errline) { - if ($errno == E_WARNING && (substr_count($errstr,"DOMDocument::loadXML()")>0)) - { + if ($errno == E_WARNING && (substr_count($errstr, "DOMDocument::loadXML()") > 0)) { throw new DOMException($errstr); - } - else - { + } else { return false; } } @@ -231,7 +211,7 @@ abstract class Dashboard $oMainNode = $oDoc->createElement('dashboard'); $oMainNode->setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance"); $oDoc->appendChild($oMainNode); - + $this->ToDOMNode($oMainNode); $sXml = $oDoc->saveXML(); @@ -261,23 +241,21 @@ abstract class Dashboard $oCellsNode = $oDoc->createElement('cells'); $oDefinition->appendChild($oCellsNode); - + $iCellRank = 0; - foreach ($this->aCells as $aCell) - { + foreach ($this->aCells as $aCell) { $oCellNode = $oDoc->createElement('cell'); $oCellNode->setAttribute('id', $iCellRank); $oCellsNode->appendChild($oCellNode); $oCellRank = $oDoc->createElement('rank', $iCellRank); $oCellNode->appendChild($oCellRank); $iCellRank++; - + $iDashletRank = 0; $oDashletsNode = $oDoc->createElement('dashlets'); $oCellNode->appendChild($oDashletsNode); /** @var \Dashlet $oDashlet */ - foreach ($aCell as $oDashlet) - { + foreach ($aCell as $oDashlet) { $oNode = $oDoc->createElement('dashlet'); $oDashletsNode->appendChild($oNode); $oNode->setAttribute('id', $oDashlet->GetID()); @@ -296,16 +274,16 @@ abstract class Dashboard public function FromParams($aParams) { $this->sLayoutClass = $aParams['layout_class']; - if (!is_subclass_of($this->sLayoutClass,DashboardLayout::class)) { + if (!is_subclass_of($this->sLayoutClass, DashboardLayout::class)) { throw new InvalidParameterException('Invalid parameter layout_class "'.$aParams['layout_class'].'"'); } $this->sTitle = $aParams['title']; $this->bAutoReload = $aParams['auto_reload'] == 'true'; $this->iAutoReloadSec = max(MetaModel::GetConfig()->Get('min_reload_interval'), (int) $aParams['auto_reload_sec']); - - foreach($aParams['cells'] as $aCell) { - $aCellDashlets = array(); - foreach($aCell as $aDashletParams) { + + foreach ($aParams['cells'] as $aCell) { + $aCellDashlets = []; + foreach ($aCell as $aDashletParams) { $sDashletClass = $aDashletParams['dashlet_class']; $sId = $aDashletParams['dashlet_id']; /** @var \Dashlet $oNewDashlet */ @@ -322,12 +300,12 @@ abstract class Dashboard } $this->aCells[] = $aCellDashlets; } - + } public function Save() { - + } /** @@ -420,7 +398,7 @@ abstract class Dashboard { $sId = $this->GetNewDashletId(); $oDashlet->SetId($sId); - $this->aCells[] = array($oDashlet); + $this->aCells[] = [$oDashlet]; } /** @@ -430,7 +408,7 @@ abstract class Dashboard * @throws \ReflectionException * @throws \Exception */ - public function RenderProperties($oPage, $aExtraParams = array()) + public function RenderProperties($oPage, $aExtraParams = []) { // menu to pick a layout and edit other properties of the dashboard $oPage->add('
    '.Dict::S('UI:DashboardEdit:Properties').'
    '); @@ -442,7 +420,7 @@ abstract class Dashboard if (is_subclass_of($sLayoutClass, 'DashboardLayout')) { $oReflection = new ReflectionClass($sLayoutClass); if (!$oReflection->isAbstract()) { - $aCallSpec = array($sLayoutClass, 'GetInfo'); + $aCallSpec = [$sLayoutClass, 'GetInfo']; $aInfo = call_user_func($aCallSpec); $sChecked = ($this->sLayoutClass == $sLayoutClass) ? 'checked' : ''; $oPage->add(''); // title="" on either the img or the label does nothing ! @@ -466,7 +444,6 @@ abstract class Dashboard $oField->SetBoundaries(MetaModel::GetConfig()->Get('min_reload_interval'), null); // no upper limit $oForm->AddField($oField); - $this->SetFormParams($oForm, $aExtraParams); $oForm->RenderAsPropertySheet($oPage, false, '.itop-dashboard'); @@ -474,7 +451,7 @@ abstract class Dashboard $sRateTitle = addslashes(Dict::Format('UI:DashboardEdit:AutoReloadSec+', MetaModel::GetConfig()->Get('min_reload_interval'))); $oPage->add_ready_script( -<<GetId(), utils::ENUM_SANITIZATION_FILTER_ELEMENT_IDENTIFIER); @@ -551,7 +528,8 @@ EOF $oToolbar->AddHtml($sHtml); } else { - $oPage->add_script(<<add_script( + <<').html("$sTitleForHTML").text()); JS ); @@ -595,7 +573,7 @@ JS * @param WebPage $oPage * @param array $aExtraParams */ - public function RenderDashletsProperties(WebPage $oPage, $aExtraParams = array()) + public function RenderDashletsProperties(WebPage $oPage, $aExtraParams = []) { // Toolbox/palette to edit the properties of each dashlet $oPage->add('
    '.Dict::S('UI:DashboardEdit:DashletProperties').'
    '); @@ -604,13 +582,10 @@ JS $oLayout = new $this->sLayoutClass(); $oPage->add('
    '); - foreach($this->aCells as $iCellIdx => $aCell) - { + foreach ($this->aCells as $iCellIdx => $aCell) { /** @var \Dashlet $oDashlet */ - foreach($aCell as $oDashlet) - { - if ($oDashlet->IsVisible()) - { + foreach ($aCell as $oDashlet) { + if ($oDashlet->IsVisible()) { $oPage->add(''); - + $sDialogTitle = Dict::S('UI:DashletCreation:Title'); $sOkButtonLabel = Dict::S('UI:Button:Ok'); $sCancelButtonLabel = Dict::S('UI:Button:Cancel'); - + $oPage->add_ready_script( <<GetID(); $sDashboardSanitizedId = $this->GetSanitizedId(); @@ -1630,31 +1572,27 @@ JS private function UpdateDashletUserPrefs(Dashlet $oDashlet, $sDashletIdOrig, array $aExtraParams) { $bIsDashletWithListPref = ($oDashlet instanceof DashletObjectList); - if (!$bIsDashletWithListPref) - { + if (!$bIsDashletWithListPref) { return; } /** @var \DashletObjectList $oDashlet */ $bDashletIdInNewFormat = ($sDashletIdOrig === $oDashlet->GetID()); - if ($bDashletIdInNewFormat) - { + if ($bDashletIdInNewFormat) { return; } $sNewPrefKey = $this->GetDashletObjectListAppUserPreferencesPrefix($oDashlet, $aExtraParams, $oDashlet->GetID()); $sPrefValueForNewKey = appUserPreferences::GetPref($sNewPrefKey, null); $bHasPrefInNewFormat = ($sPrefValueForNewKey !== null); - if ($bHasPrefInNewFormat) - { + if ($bHasPrefInNewFormat) { return; } $sOldPrefKey = $this->GetDashletObjectListAppUserPreferencesPrefix($oDashlet, $aExtraParams, $sDashletIdOrig); $sPrefValueForOldKey = appUserPreferences::GetPref($sOldPrefKey, null); $bHasPrefInOldFormat = ($sPrefValueForOldKey !== null); - if (!$bHasPrefInOldFormat) - { + if (!$bHasPrefInOldFormat) { return; } @@ -1673,7 +1611,7 @@ JS private function GetDashletObjectListAppUserPreferencesPrefix(DashletObjectList $oDashlet, $aExtraParams, $sDashletId) { $sDataTableId = Dashlet::APPUSERPREFERENCES_PREFIX.$sDashletId; - $aClassAliases = array(); + $aClassAliases = []; try { $oFilter = $oDashlet->GetDBSearch($aExtraParams); $aClassAliases = $oFilter->GetSelectedClasses(); diff --git a/application/displayblock.class.inc.php b/application/displayblock.class.inc.php index 44626bf48..223703024 100644 --- a/application/displayblock.class.inc.php +++ b/application/displayblock.class.inc.php @@ -1,4 +1,5 @@ avoid duplicate conditions @@ -137,20 +138,18 @@ class DisplayBlock * * @throws \ApplicationException */ - public function __construct(DBSearch $oFilter, $sStyle = self::ENUM_STYLE_LIST, $bAsynchronous = false, $aParams = array(), $oSet = null) + public function __construct(DBSearch $oFilter, $sStyle = self::ENUM_STYLE_LIST, $bAsynchronous = false, $aParams = [], $oSet = null) { $this->m_oFilter = $oFilter->DeepClone(); - $this->m_aConditions = array(); + $this->m_aConditions = []; $this->m_sStyle = $sStyle; $this->m_bAsynchronous = $bAsynchronous; $this->m_aParams = $aParams; $this->m_oSet = $oSet; - if (array_key_exists('show_obsolete_data', $aParams)) - { + if (array_key_exists('show_obsolete_data', $aParams)) { $this->m_bShowObsoleteData = $aParams['show_obsolete_data']; } - if ($this->m_bShowObsoleteData === null) - { + if ($this->m_bShowObsoleteData === null) { // User defined $this->m_bShowObsoleteData = utils::ShowObsoleteData(); } @@ -412,22 +411,18 @@ class DisplayBlock * @throws \CoreException * @throws \Exception */ - public static function FromObjectSet(DBObjectSet $oSet, $sStyle, $aParams = array()) + public static function FromObjectSet(DBObjectSet $oSet, $sStyle, $aParams = []) { $oDummyFilter = new DBObjectSearch($oSet->GetClass()); - $aKeys = array(); - $oSet->OptimizeColumnLoad(array($oSet->GetClassAlias() => array())); // No need to load all the columns just to get the id - while($oObject = $oSet->Fetch()) - { + $aKeys = []; + $oSet->OptimizeColumnLoad([$oSet->GetClassAlias() => []]); // No need to load all the columns just to get the id + while ($oObject = $oSet->Fetch()) { $aKeys[] = $oObject->GetKey(); } $oSet->Rewind(); - if (count($aKeys) > 0) - { + if (count($aKeys) > 0) { $oDummyFilter->AddCondition('id', $aKeys, 'IN'); - } - else - { + } else { $oDummyFilter->AddCondition('id', 0, '='); } $oBlock = new DisplayBlock($oDummyFilter, $sStyle, false, $aParams); // DisplayBlocks built this way are synchronous @@ -448,7 +443,7 @@ class DisplayBlock $iStartPos = stripos($sTemplate, '<'.self::TAG_BLOCK.' ', 0); $iEndPos = stripos($sTemplate, '', $iStartPos); $iEndTag = stripos($sTemplate, '>', $iStartPos); - $aParams = array(); + $aParams = []; if (($iStartPos === false) || ($iEndPos === false)) { return null; @@ -456,7 +451,7 @@ class DisplayBlock $sITopData = substr($sTemplate, 1 + $iEndTag, $iEndPos - $iEndTag - 1); $sITopTag = substr($sTemplate, $iStartPos + strlen('<'.self::TAG_BLOCK), $iEndTag - $iStartPos - strlen('<'.self::TAG_BLOCK)); - $aMatches = array(); + $aMatches = []; $sBlockClass = "DisplayBlock"; $bAsynchronous = false; $sBlockType = 'list'; @@ -522,25 +517,28 @@ class DisplayBlock return new $sBlockClass($oFilter, $sBlockType, $bAsynchronous, $aParams); } - public function DisplayIntoContentBlock(UIContentBlock $oContentBlock, WebPage $oPage, $sId, $aExtraParams = array()) + public function DisplayIntoContentBlock(UIContentBlock $oContentBlock, WebPage $oPage, $sId, $aExtraParams = []) { $oContentBlock->AddSubBlock($this->GetDisplay($oPage, $sId, $aExtraParams)); } - public function Display(WebPage $oPage, $sId, $aExtraParams = array()) + public function Display(WebPage $oPage, $sId, $aExtraParams = []) { $oPage->AddUiBlock($this->GetDisplay($oPage, $sId, $aExtraParams)); } - public function GetDisplay(WebPage $oPage, $sId, $aExtraParams = array()): UIContentBlock + public function GetDisplay(WebPage $oPage, $sId, $aExtraParams = []): UIContentBlock { $oHtml = new UIContentBlock($sId); $oHtml->AddCSSClass("display_block"); $aExtraParams = array_merge($aExtraParams, $this->m_aParams); $aExtraParams['currentId'] = $sId; - $sExtraParams = addslashes(str_replace('"', "'", - json_encode($aExtraParams))); // JSON encode, change the style of the quotes and escape them + $sExtraParams = addslashes(str_replace( + '"', + "'", + json_encode($aExtraParams) + )); // JSON encode, change the style of the quotes and escape them if (isset($aExtraParams['query_params'])) { $aQueryParams = $aExtraParams['query_params']; @@ -549,9 +547,9 @@ class DisplayBlock $sClass = $aExtraParams['this->class']; $iKey = $aExtraParams['this->id']; $oObj = MetaModel::GetObject($sClass, $iKey); - $aQueryParams = array('this->object()' => $oObj); + $aQueryParams = ['this->object()' => $oObj]; } else { - $aQueryParams = array(); + $aQueryParams = []; } } @@ -587,8 +585,7 @@ class DisplayBlock '); } - if ($this->m_sStyle == static::ENUM_STYLE_LIST) // Search form need to extract result list extra data, the simplest way is to expose this configuration - { + if ($this->m_sStyle == static::ENUM_STYLE_LIST) { // Search form need to extract result list extra data, the simplest way is to expose this configuration $listJsonExtraParams = json_encode(json_encode($aExtraParams)); $oPage->add_ready_script(" $('#$sId').data('sExtraParams', ".$listJsonExtraParams."); @@ -608,7 +605,7 @@ class DisplayBlock * @throws \DictExceptionMissingString * @throws \MySQLException */ - public function RenderContent(WebPage $oPage, $aExtraParams = array()) + public function RenderContent(WebPage $oPage, $aExtraParams = []) { if (!isset($aExtraParams['currentId'])) { $sId = utils::GetUniqueId(); // Works only if the page is not an Ajax one ! @@ -640,7 +637,7 @@ class DisplayBlock $this->CheckParams($this->m_sStyle, $aExtraParams); // Add the extra params into the filter if they make sense for such a filter $bDoSearch = utils::ReadParam('dosearch', false); - $aQueryParams = array(); + $aQueryParams = []; if (isset($aExtraParams['query_params'])) { $aQueryParams = $aExtraParams['query_params']; } else { @@ -648,7 +645,7 @@ class DisplayBlock $sClass = $aExtraParams['this->class']; $iKey = $aExtraParams['this->id']; $oObj = MetaModel::GetObject($sClass, $iKey); - $aQueryParams = array('this->object()' => $oObj); + $aQueryParams = ['this->object()' => $oObj]; } } if ($this->m_oSet == null) { @@ -658,7 +655,7 @@ class DisplayBlock $oAppContext = new ApplicationContext(); $sClass = $this->m_oFilter->GetClass(); $aFilterCodes = MetaModel::GetFiltersList($sClass); - $aCallSpec = array($sClass, 'MapContextParam'); + $aCallSpec = [$sClass, 'MapContextParam']; if (is_callable($aCallSpec)) { foreach ($oAppContext->GetNames() as $sContextParam) { $sParamCode = call_user_func($aCallSpec, $sContextParam); //Map context parameter to the value/filter code depending on the class @@ -693,11 +690,9 @@ class DisplayBlock } } - if (!is_null($condition)) - { + if (!is_null($condition)) { $sOpCode = null; // default operator - if (is_array($condition)) - { + if (is_array($condition)) { // Multiple values, add them as AND X IN (v1, v2, v3...) $sOpCode = 'IN'; } @@ -705,26 +700,22 @@ class DisplayBlock $this->AddCondition($sFilterCode, $condition, $sOpCode, $bParseSearchString); } } - if ($bDoSearch) - { + if ($bDoSearch) { // Keep the table_id identifying this table if we're performing a search $sTableId = utils::ReadParam('_table_id_', null, false, utils::ENUM_SANITIZATION_FILTER_ELEMENT_IDENTIFIER); - if ($sTableId != null) - { + if ($sTableId != null) { $aExtraParams['table_id'] = $sTableId; } } } - $aOrderBy = array(); - if (isset($aExtraParams['order_by'])) - { + $aOrderBy = []; + if (isset($aExtraParams['order_by'])) { // Convert the string describing the order_by parameter into an array // The syntax is +attCode1,-attCode2 // attCode1 => ascending, attCode2 => descending $aTemp = explode(',', $aExtraParams['order_by']); - foreach($aTemp as $sTemp) - { - $aMatches = array(); + foreach ($aTemp as $sTemp) { + $aMatches = []; if (preg_match('/^([+-])?(.+)$/', $sTemp, $aMatches)) { $bAscending = true; if ($aMatches[1] == '-') { @@ -740,7 +731,7 @@ class DisplayBlock } $this->m_oSet->SetShowObsoleteData($this->m_bShowObsoleteData); - switch($this->m_sStyle) { + switch ($this->m_sStyle) { case static::ENUM_STYLE_LIST_SEARCH: case static::ENUM_STYLE_LIST: break; @@ -770,7 +761,7 @@ class DisplayBlock case static::ENUM_STYLE_LIST: case static::ENUM_STYLE_LIST_IN_OBJECT: $oBlock = $this->RenderList($aExtraParams, $oPage); - break; + break; case static::ENUM_STYLE_ACTIONS: $oBlock = $this->RenderActions($aExtraParams); @@ -797,47 +788,39 @@ class DisplayBlock break; default: - // Unsupported style, do nothing. - $sHtml .= Dict::format('UI:Error:UnsupportedStyleOfBlock', $this->m_sStyle); + // Unsupported style, do nothing. + $sHtml .= Dict::format('UI:Error:UnsupportedStyleOfBlock', $this->m_sStyle); } - $bAutoReload = false; - if (isset($aExtraParams['auto_reload'])) - { - if ($aExtraParams['auto_reload'] === true) - { + if (isset($aExtraParams['auto_reload'])) { + if ($aExtraParams['auto_reload'] === true) { // Note: does not work in the switch (case true) because a positive number evaluates to true!!! $aExtraParams['auto_reload'] = 'standard'; } - switch($aExtraParams['auto_reload']) - { + switch ($aExtraParams['auto_reload']) { case 'fast': $bAutoReload = true; - $iReloadInterval = MetaModel::GetConfig()->GetFastReloadInterval()*1000; + $iReloadInterval = MetaModel::GetConfig()->GetFastReloadInterval() * 1000; break; case 'standard': case 'true': $bAutoReload = true; - $iReloadInterval = MetaModel::GetConfig()->GetStandardReloadInterval()*1000; + $iReloadInterval = MetaModel::GetConfig()->GetStandardReloadInterval() * 1000; break; default: - if (is_numeric($aExtraParams['auto_reload']) && ($aExtraParams['auto_reload'] > 0)) - { + if (is_numeric($aExtraParams['auto_reload']) && ($aExtraParams['auto_reload'] > 0)) { $bAutoReload = true; - $iReloadInterval = max(MetaModel::GetConfig()->Get('min_reload_interval'), $aExtraParams['auto_reload'])*1000; - } - else - { + $iReloadInterval = max(MetaModel::GetConfig()->Get('min_reload_interval'), $aExtraParams['auto_reload']) * 1000; + } else { // incorrect config, ignore it $bAutoReload = false; } } } - if (($bAutoReload) && ($this->m_sStyle != static::ENUM_STYLE_SEARCH)) // Search form do NOT auto-reload - { + if (($bAutoReload) && ($this->m_sStyle != static::ENUM_STYLE_SEARCH)) { // Search form do NOT auto-reload // Used either for asynchronous or auto_reload // does a json_encode twice to get a string usable as function parameter $sFilterBefore = $this->m_oFilter->serialize(); @@ -884,8 +867,7 @@ JS { // Workaround to an issue revealed whenever a condition on org_id is applied twice (with a hierarchy of organizations) // Moreover, it keeps the query as simple as possible - if (isset($this->m_aConditions[$sFilterCode]) && $condition == $this->m_aConditions[$sFilterCode]) - { + if (isset($this->m_aConditions[$sFilterCode]) && $condition == $this->m_aConditions[$sFilterCode]) { // Skip return; } @@ -895,53 +877,42 @@ JS $bConditionAdded = false; // If the condition is an external key with a class having a hierarchy, use a "below" criteria - if (MetaModel::IsValidAttCode($sClass, $sFilterCode)) - { + if (MetaModel::IsValidAttCode($sClass, $sFilterCode)) { $oAttDef = MetaModel::GetAttributeDef($sClass, $sFilterCode); - if ($oAttDef->IsExternalKey()) - { + if ($oAttDef->IsExternalKey()) { $sHierarchicalKeyCode = MetaModel::IsHierarchicalClass($oAttDef->GetTargetClass()); - if ($sHierarchicalKeyCode !== false) - { + if ($sHierarchicalKeyCode !== false) { $oFilter = new DBObjectSearch($oAttDef->GetTargetClass()); - if (($sOpCode == 'IN') && is_array($condition)) - { + if (($sOpCode == 'IN') && is_array($condition)) { $oFilter->AddConditionExpression(self::GetConditionIN($oFilter, 'id', $condition)); - } - else - { + } else { $oFilter->AddCondition('id', $condition); } $oHKFilter = new DBObjectSearch($oAttDef->GetTargetClass()); $oHKFilter->AddCondition_PointingTo($oFilter, $sHierarchicalKeyCode, TREE_OPERATOR_BELOW); // Use the 'below' operator by default $this->m_oFilter->AddCondition_PointingTo($oHKFilter, $sFilterCode); $bConditionAdded = true; - } - else if (($sOpCode == 'IN') && is_array($condition)) - { + } elseif (($sOpCode == 'IN') && is_array($condition)) { $this->m_oFilter->AddConditionExpression(self::GetConditionIN($this->m_oFilter, $sFilterCode, $condition)); $bConditionAdded = true; } - } - else if (($sOpCode == 'IN') && is_array($condition)) - { + } elseif (($sOpCode == 'IN') && is_array($condition)) { $this->m_oFilter->AddConditionExpression(self::GetConditionIN($this->m_oFilter, $sFilterCode, $condition)); $bConditionAdded = true; } } // In all other cases, just add the condition directly - if (!$bConditionAdded) - { + if (!$bConditionAdded) { $this->m_oFilter->AddCondition($sFilterCode, $condition, null); // Use the default 'loose' operator } } - static protected function GetConditionIN($oFilter, $sFilterCode, $condition) + protected static function GetConditionIN($oFilter, $sFilterCode, $condition) { - $oField = new FieldExpression($sFilterCode, $oFilter->GetClassAlias()); + $oField = new FieldExpression($sFilterCode, $oFilter->GetClassAlias()); $sListExpr = '('.implode(', ', CMDBSource::Quote($condition)).')'; $sOQLCondition = $oField->RenderExpression()." IN $sListExpr"; $oNewCondition = Expression::FromOQL($sOQLCondition); @@ -972,13 +943,10 @@ JS protected function MakeGroupByQuery(&$aExtraParams, &$oGroupByExp, &$sGroupByLabel, &$aGroupBy, &$sAggregationFunction, &$sFctVar, &$sAggregationAttr, &$sSql) { $sAlias = $this->m_oFilter->GetClassAlias(); - if (isset($aExtraParams['group_by_label'])) - { + if (isset($aExtraParams['group_by_label'])) { $oGroupByExp = Expression::FromOQL($aExtraParams['group_by']); $sGroupByLabel = $aExtraParams['group_by_label']; - } - else - { + } else { // Backward compatibility: group_by is simply a field id $oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias); $sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']); @@ -986,61 +954,52 @@ JS // Security filtering $aFields = $oGroupByExp->ListRequiredFields(); - foreach($aFields as $sFieldAlias) - { - $aMatches = array(); - if (preg_match('/^([^.]+)\\.([^.]+)$/', $sFieldAlias, $aMatches)) - { + foreach ($aFields as $sFieldAlias) { + $aMatches = []; + if (preg_match('/^([^.]+)\\.([^.]+)$/', $sFieldAlias, $aMatches)) { $sFieldClass = $this->m_oFilter->GetClassName($aMatches[1]); $oAttDef = MetaModel::GetAttributeDef($sFieldClass, $aMatches[2]); - if ($oAttDef instanceof AttributeOneWayPassword) - { + if ($oAttDef instanceof AttributeOneWayPassword) { throw new Exception('Grouping on password fields is not supported.'); } } } - $aGroupBy = array(); + $aGroupBy = []; $aGroupBy['grouped_by_1'] = $oGroupByExp; - $aQueryParams = array(); - if (isset($aExtraParams['query_params'])) - { + $aQueryParams = []; + if (isset($aExtraParams['query_params'])) { $aQueryParams = $aExtraParams['query_params']; } - $aFunctions = array(); + $aFunctions = []; $sAggregationFunction = 'count'; $sFctVar = '_itop_count_'; $sAggregationAttr = ''; - if (isset($aExtraParams['aggregation_function']) && !empty($aExtraParams['aggregation_attribute'])) - { + if (isset($aExtraParams['aggregation_function']) && !empty($aExtraParams['aggregation_attribute'])) { $sAggregationFunction = $aExtraParams['aggregation_function']; $sAggregationAttr = $aExtraParams['aggregation_attribute']; $oAttrExpr = Expression::FromOQL('`'.$sAlias.'`.`'.$sAggregationAttr.'`'); - $oFctExpr = new FunctionExpression(strtoupper($sAggregationFunction), array($oAttrExpr)); + $oFctExpr = new FunctionExpression(strtoupper($sAggregationFunction), [$oAttrExpr]); $sFctVar = '_itop_'.$sAggregationFunction.'_'; - $aFunctions = array($sFctVar => $oFctExpr); + $aFunctions = [$sFctVar => $oFctExpr]; } - if (!empty($sAggregationAttr)) - { + if (!empty($sAggregationAttr)) { $sClass = $this->m_oFilter->GetClass(); $sAggregationAttr = MetaModel::GetLabel($sClass, $sAggregationAttr); } $iLimit = 0; - if (isset($aExtraParams['limit'])) - { + if (isset($aExtraParams['limit'])) { $iLimit = intval($aExtraParams['limit']); } - $aOrderBy = array(); - if (isset($aExtraParams['order_direction']) && isset($aExtraParams['order_by'])) - { - switch ($aExtraParams['order_by']) - { + $aOrderBy = []; + if (isset($aExtraParams['order_direction']) && isset($aExtraParams['order_by'])) { + switch ($aExtraParams['order_by']) { case 'attribute': - $aOrderBy = array('grouped_by_1' => ($aExtraParams['order_direction'] === 'asc')); + $aOrderBy = ['grouped_by_1' => ($aExtraParams['order_direction'] === 'asc')]; break; case 'function': - $aOrderBy = array($sFctVar => ($aExtraParams['order_direction'] === 'asc')); + $aOrderBy = [$sFctVar => ($aExtraParams['order_direction'] === 'asc')]; break; } } @@ -1076,31 +1035,31 @@ JS $this->AddCondition($sFilterCode, $sContextParamValue); } } - $aQueryParams = array(); + $aQueryParams = []; if (isset($aExtraParams['query_params'])) { $aQueryParams = $aExtraParams['query_params']; } - $this->m_oSet = new CMDBObjectSet($this->m_oFilter, array(), $aQueryParams); + $this->m_oSet = new CMDBObjectSet($this->m_oFilter, [], $aQueryParams); $this->m_oSet->SetShowObsoleteData($this->m_bShowObsoleteData); } // Summary details - $aCounts = array(); - $aStateLabels = array(); + $aCounts = []; + $aStateLabels = []; if (!empty($sStateAttrCode) && !empty($sStatesList)) { $aStates = explode(',', $sStatesList); // Generate one count + group by query [#1330] $sClassAlias = $this->m_oFilter->GetClassAlias(); $oGroupByExpr = Expression::FromOQL($sClassAlias.'.'.$sStateAttrCode); - $aGroupBy = array('group1' => $oGroupByExpr); + $aGroupBy = ['group1' => $oGroupByExpr]; $oGroupBySearch = $this->m_oFilter->DeepClone(); if (isset($this->m_bShowObsoleteData)) { $oGroupBySearch->SetShowObsoleteData($this->m_bShowObsoleteData); } $sCountGroupByQuery = $oGroupBySearch->MakeGroupByQuery($aQueryParams, $aGroupBy, false); $aCountGroupByResults = CMDBSource::QueryToArray($sCountGroupByQuery); - $aCountsQueryResults = array(); + $aCountsQueryResults = []; foreach ($aCountGroupByResults as $aCountGroupBySingleResult) { $aCountsQueryResults[$aCountGroupBySingleResult[0]] = $aCountGroupBySingleResult[1]; } @@ -1114,7 +1073,8 @@ JS : 0; if ($aCounts[$sStateValue] == 0) { - $aCounts[$sStateValue] = ['link' => '-', 'label' => $aCounts[$sStateValue]];; + $aCounts[$sStateValue] = ['link' => '-', 'label' => $aCounts[$sStateValue]]; + ; } else { $oSingleGroupByValueFilter = $this->m_oFilter->DeepClone(); $oSingleGroupByValueFilter->AddCondition($sStateAttrCode, $sStateValue, '='); @@ -1164,7 +1124,7 @@ JS $oBlock->AddSubBlock($oPill); } $aExtraParams['query_params'] = $this->m_oFilter->GetInternalParams(); - if(isset($aExtraParams['query_params']['this->object()'])){ + if (isset($aExtraParams['query_params']['this->object()'])) { $aExtraParams['query_params']['this->class'] = get_class($aExtraParams['query_params']['this->object()']); $aExtraParams['query_params']['this->id'] = $aExtraParams['query_params']['this->object()']->GetKey(); unset($aExtraParams['query_params']['this->object()']); @@ -1178,7 +1138,8 @@ JS $('#".$oBlock->GetId()."').html(data); $('#".$oBlock->GetId()."').unblock(); }); - $('#".$oBlock->GetId()."').unblock();"); + $('#".$oBlock->GetId()."').unblock();" + ); return $oBlock; } @@ -1188,7 +1149,7 @@ JS * * @return string[] */ - protected function GetAllowedActionsParams(array $aExtraParams) + protected function GetAllowedActionsParams(array $aExtraParams) { return [ 'context_filter', /** int if != 0 filter with user context */ @@ -1220,11 +1181,11 @@ JS $this->AddCondition($sFilterCode, $sContextParamValue); } } - $aQueryParams = array(); + $aQueryParams = []; if (isset($aExtraParams['query_params'])) { $aQueryParams = $aExtraParams['query_params']; } - $this->m_oSet = new CMDBObjectSet($this->m_oFilter, array(), $aQueryParams); + $this->m_oSet = new CMDBObjectSet($this->m_oFilter, [], $aQueryParams); $this->m_oSet->SetShowObsoleteData($this->m_bShowObsoleteData); } $iCount = $this->m_oSet->Count(); @@ -1241,8 +1202,15 @@ JS if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY)) { $sCreateActionUrl = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=new&class='.$sClass.$oAppContext->GetForLink(true); $sCreateActionLabel = Dict::Format('UI:Button:Create'); - $oBlock = DashletFactory::MakeForDashletBadge($sClassIconUrl, $sHyperlink, $iCount, $sClassLabel, $sCreateActionUrl, - $sCreateActionLabel, $aRefreshParams); + $oBlock = DashletFactory::MakeForDashletBadge( + $sClassIconUrl, + $sHyperlink, + $iCount, + $sClassLabel, + $sCreateActionUrl, + $sCreateActionLabel, + $aRefreshParams + ); } else { $oBlock = DashletFactory::MakeForDashletBadge($sClassIconUrl, $sHyperlink, $iCount, $sClassLabel, null, null, $aRefreshParams); } @@ -1272,9 +1240,9 @@ JS $aRes = CMDBSource::QueryToArray($sSql); - $aGroupBy = array(); - $aLabels = array(); - $aValues = array(); + $aGroupBy = []; + $aLabels = []; + $aValues = []; $iTotalCount = 0; foreach ($aRes as $iRow => $aRow) { $sValue = $aRow['grouped_by_1']; @@ -1285,7 +1253,7 @@ JS $iTotalCount += $aRow['_itop_count_']; } - $aData = array(); + $aData = []; $oAppContext = new ApplicationContext(); $sParams = $oAppContext->GetForLink(true); foreach ($aGroupBy as $iRow => $iCount) { @@ -1296,22 +1264,22 @@ JS if (isset($aExtraParams['query_params'])) { $aQueryParams = $aExtraParams['query_params']; } else { - $aQueryParams = array(); + $aQueryParams = []; } $sFilter = rawurlencode($oSubsetSearch->serialize(false, $aQueryParams)); - $aData[] = array( + $aData[] = [ 'group' => $aLabels[$iRow], - 'value' => "$iCount" - ); // TO DO: add the context information + 'value' => "$iCount", + ]; // TO DO: add the context information } - $aAttribs = array( - 'group' => array('label' => $sGroupByLabel, 'description' => ''), - 'value' => array( + $aAttribs = [ + 'group' => ['label' => $sGroupByLabel, 'description' => ''], + 'value' => [ 'label' => Dict::S('UI:GroupBy:'.$sAggregationFunction), 'description' => Dict::Format('UI:GroupBy:'.$sAggregationFunction.'+', $sAggregationAttr), - ), - ); + ], + ]; $sFormat = isset($aExtraParams['format']) ? $aExtraParams['format'] : 'UI:Pagination:HeaderNoSelection'; $aExtraParams['query_params'] = $this->m_oFilter->GetInternalParams(); @@ -1322,7 +1290,7 @@ JS $oBlock = PanelUIBlockFactory::MakeForClass($aExtraParams["panel_class"], $aExtraParams["panel_title"]); $oBlock->AddSubTitleBlock(new Html($sTitle)); $oBlock->AddCSSClass('ibo-datatable-panel'); - if(isset($aExtraParams["panel_icon"]) && strlen($aExtraParams["panel_icon"]) > 0){ + if (isset($aExtraParams["panel_icon"]) && strlen($aExtraParams["panel_icon"]) > 0) { $oBlock->SetIcon($aExtraParams["panel_icon"]); } $oDataTable = DataTableUIBlockFactory::MakeForStaticData("", $aAttribs, $aData, null, $aExtraParams, $this->m_oFilter->ToOQL(), $aOption); @@ -1341,7 +1309,7 @@ JS } if (isset($aExtraParams["surround_with_panel"]) && $aExtraParams["surround_with_panel"]) { $oBlock = PanelUIBlockFactory::MakeForClass($aExtraParams["panel_class"], $aExtraParams["panel_title"]); - if(isset($aExtraParams["panel_icon"]) && strlen($aExtraParams["panel_icon"]) > 0){ + if (isset($aExtraParams["panel_icon"]) && strlen($aExtraParams["panel_icon"]) > 0) { $oBlock->SetIcon($aExtraParams["panel_icon"]); } $oBlock->AddSubBlock(new Html('

    '.Dict::Format($sFormat, $iCount).'

    ')); @@ -1351,7 +1319,7 @@ JS } return $oBlock; -} + } /** * @param WebPage $oPage @@ -1409,7 +1377,6 @@ JS $oBlock->aExtraParams = $aExtraParams; $oBlock->sFilter = $this->m_oFilter->ToOQL(); - // Check the classes that can be read (i.e authorized) by this user... foreach ($aClasses as $sAlias => $sClassName) { if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $this->m_oSet) != UR_ALLOWED_NO) { @@ -1431,7 +1398,7 @@ JS $sSearchFilter = $this->m_oSet->GetFilter()->serialize(); // Limit the size of the URL (N°1585 - request uri too long) if (strlen($sSearchFilter) < SERVER_MAX_URL_LENGTH) { - $oBlock->sEventAttachedData = json_encode(array( + $oBlock->sEventAttachedData = json_encode([ 'filter' => $sSearchFilter, 'breadcrumb_id' => "ui-search-".$this->m_oSet->GetClass(), 'breadcrumb_label' => MetaModel::GetName($this->m_oSet->GetClass()), @@ -1439,7 +1406,7 @@ JS 'breadcrumb_instance_id' => MetaModel::GetConfig()->GetItopInstanceid(), 'breadcrumb_icon' => 'fas fa-search', 'breadcrumb_icon_type' => iTopWebPage::ENUM_BREADCRUMB_ENTRY_ICON_TYPE_CSS_CLASSES, - )); + ]); } } @@ -1472,25 +1439,25 @@ JS $oContentBlock = new UIContentBlock(); $oHtml = new Html(); $oContentBlock->AddSubBlock($oHtml); - $aDisplayAliases = isset($aExtraParams['display_aliases']) ? explode(',', $aExtraParams['display_aliases']) : array(); + $aDisplayAliases = isset($aExtraParams['display_aliases']) ? explode(',', $aExtraParams['display_aliases']) : []; if (!isset($aExtraParams['group_by'])) { $oHtml->AddHtml('

    '.Dict::S('UI:Error:MandatoryTemplateParameter_group_by').'

    '); } else { - $aGroupByFields = array(); + $aGroupByFields = []; $aGroupBy = explode(',', $aExtraParams['group_by']); foreach ($aGroupBy as $sGroupBy) { - $aMatches = array(); + $aMatches = []; if (preg_match('/^(.+)\.(.+)$/', $sGroupBy, $aMatches) > 0) { - $aGroupByFields[] = array('alias' => $aMatches[1], 'att_code' => $aMatches[2]); + $aGroupByFields[] = ['alias' => $aMatches[1], 'att_code' => $aMatches[2]]; } } if (count($aGroupByFields) == 0) { $oHtml->AddHtml('

    '.Dict::Format('UI:Error:InvalidGroupByFields', $aExtraParams['group_by']).'

    '); } else { - $aResults = array(); - $aCriteria = array(); + $aResults = []; + $aCriteria = []; while ($aObjects = $this->m_oSet->FetchAssoc()) { - $aKeys = array(); + $aKeys = []; foreach ($aGroupByFields as $aField) { $sAlias = $aField['alias']; if (is_null($aObjects[$sAlias])) { @@ -1507,7 +1474,7 @@ JS $oHtml->AddHtml("
".implode("", $aHeader)."
'.date('Y-m-d', - $iDate).''.date('H:i:s', - $iDate).''.date( + 'Y-m-d', + $iDate + ).''.date( + 'H:i:s', + $iDate + ).''.$outputValue.''.$outputValue.'
\n"); // Construct a new (parametric) query that will return the content of this block $oBlockFilter = $this->m_oFilter->DeepClone(); - $aExpressions = array(); + $aExpressions = []; $index = 0; foreach ($aGroupByFields as $aField) { $aExpressions[] = '`'.$aField['alias'].'`.`'.$aField['att_code'].'` = :param'.$index++; @@ -1519,7 +1486,7 @@ JS foreach ($aResults as $sCategory => $aObjects) { $oHtml->AddHtml("\n"); if (count($aDisplayAliases) == 1) { - $aSimpleArray = array(); + $aSimpleArray = []; foreach ($aObjects as $aRow) { $oObj = $aRow[$aDisplayAliases[0]]; if (!is_null($oObj)) { @@ -1535,12 +1502,12 @@ JS $oHtml->AddHtml("\n"); } else { $index = 0; - $aArgs = array(); + $aArgs = []; foreach ($aGroupByFields as $aField) { $aArgs['param'.$index] = $aCriteria[$sCategory][$aField['alias'].'.'.$aField['att_code']]; $index++; } - $oSet = new CMDBObjectSet($oBlockFilter, array(), $aArgs); + $oSet = new CMDBObjectSet($oBlockFilter, [], $aArgs); if (empty($aExtraParams['currentId'])) { $iListId = utils::GetUniqueId(); // Works only if not in an Ajax page !! } else { @@ -1603,7 +1570,7 @@ JS if (isset($aExtraParams["surround_with_panel"]) && $aExtraParams["surround_with_panel"]) { $oPanel = PanelUIBlockFactory::MakeForClass($aExtraParams["panel_class"], $aExtraParams["panel_title"]); - if(isset($aExtraParams["panel_icon"]) && strlen($aExtraParams["panel_icon"]) > 0){ + if (isset($aExtraParams["panel_icon"]) && strlen($aExtraParams["panel_icon"]) > 0) { $oPanel->SetIcon($aExtraParams["panel_icon"]); } $oPanel->AddSubBlock($oBlock); @@ -1627,7 +1594,7 @@ JS { $sChartType = isset($aExtraParams['chart_type']) ? $aExtraParams['chart_type'] : 'pie'; $sId = utils::ReadParam('id', ''); - $aValues = array(); + $aValues = []; $oBlock = null; $sJSURLs = ''; @@ -1638,21 +1605,18 @@ JS $this->MakeGroupByQuery($aExtraParams, $oGroupByExp, $sGroupByLabel, $aGroupBy, $sAggregationFunction, $sFctVar, $sAggregationAttr, $sSql); $aRes = CMDBSource::QueryToArray($sSql); - - $iTotalCount = 0; - $aURLs = array(); + $aURLs = []; foreach ($aRes as $iRow => $aRow) { $sValue = $aRow['grouped_by_1']; $sHtmlValue = $oGroupByExp->MakeValueLabel($this->m_oFilter, $sValue, $sValue); $iTotalCount += $aRow['_itop_count_']; - $aValues[] = array( + $aValues[] = [ 'label' => html_entity_decode(strip_tags($sHtmlValue), ENT_QUOTES, 'UTF-8'), 'label_html' => $sHtmlValue, 'value' => (float)$aRow[$sFctVar], - ); - + ]; // Build the search for this subset $oSubsetSearch = $this->m_oFilter->DeepClone(); @@ -1691,7 +1655,7 @@ JS $aColumns = []; $aNames = []; foreach ($aValues as $idx => $aValue) { - $aColumns[] = array('series_'.$idx, (float)$aValue['value']); + $aColumns[] = ['series_'.$idx, (float)$aValue['value']]; $aNames['series_'.$idx] = $aValue['label']; } @@ -1713,7 +1677,7 @@ JS } if (isset($aExtraParams["surround_with_panel"]) && $aExtraParams["surround_with_panel"]) { $oPanel = PanelUIBlockFactory::MakeForClass($aExtraParams["panel_class"], $aExtraParams["panel_title"]); - if(isset($aExtraParams["panel_icon"]) && strlen($aExtraParams["panel_icon"]) > 0){ + if (isset($aExtraParams["panel_icon"]) && strlen($aExtraParams["panel_icon"]) > 0) { $oPanel->SetIcon($aExtraParams["panel_icon"]); } $oPanel->AddSubBlock($oBlock); @@ -1740,12 +1704,12 @@ JS $oBlock->sDownloadLink = utils::GetAbsoluteUrlAppRoot().'webservices/export.php?expression='.urlencode($this->m_oFilter->ToOQL(true)).'&format=csv&filename='.urlencode($oBlock->sCsvFile); $oBlock->sLinkToToggle = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=search'.$oAppContext->GetForLink(true).'&filter='.rawurlencode($this->m_oFilter->serialize()).'&format=csv'; // Pass the parameters via POST, since expression may be very long - $aParamsToPost = array( + $aParamsToPost = [ 'expression' => $this->m_oFilter->ToOQL(true), 'format' => 'csv', 'filename' => $oBlock->sCsvFile, 'charset' => 'UTF-8', - ); + ]; if ($oBlock->bAdvancedMode) { $oBlock->sDownloadLink .= '&fields_advanced=1'; $aParamsToPost['fields_advanced'] = 1; @@ -1804,8 +1768,7 @@ class MenuBlock extends DisplayBlock $oRouter = Router::GetInstance(); $oRenderBlock = new UIContentBlock(); - if ($this->m_sStyle == 'popup') // popup is a synonym of 'list' for backward compatibility - { + if ($this->m_sStyle == 'popup') { // popup is a synonym of 'list' for backward compatibility $this->m_sStyle = static::ENUM_STYLE_LIST; } @@ -1813,7 +1776,7 @@ class MenuBlock extends DisplayBlock $aSelectedClasses = $this->GetFilter()->GetSelectedClasses(); $bIsForLinkset = isset($aExtraParams['target_attr']); $oSet = new CMDBObjectSet($this->GetFilter()); - if(isset($aExtraParams['object_count'])){ + if (isset($aExtraParams['object_count'])) { $iSetCount = $aExtraParams['object_count']; } else { $iSetCount = $oSet->Count(); @@ -1844,7 +1807,6 @@ class MenuBlock extends DisplayBlock $oAppContext = new ApplicationContext(); $sContext = $oAppContext->GetForLink(true); - $sFilter = $this->GetFilter()->serialize(); $sUIPage = cmdbAbstractObject::ComputeStandardUIPage($sClass); $sRootUrl = utils::GetAbsoluteUrlAppRoot(); @@ -1902,7 +1864,7 @@ class MenuBlock extends DisplayBlock $iLimit = MetaModel::GetConfig()->Get('complex_actions_limit'); if ( ($iSetCount > 0) && (false === $bLocked) && MetaModel::HasLifecycle($sClass) && - ( ($iLimit == 0) || ($iSetCount < $iLimit) ) + (($iLimit == 0) || ($iSetCount < $iLimit)) ) { $aTransitions = []; // Processing (optimizations) and endpoints are not exactly the same depending on if there is only 1 object or a set @@ -1922,8 +1884,8 @@ class MenuBlock extends DisplayBlock // Life cycle actions may be available... if all objects are in the same state // Group by $oGroupByExp = new FieldExpression(MetaModel::GetStateAttributeCode($sClass), $this->m_oFilter->GetClassAlias()); - $aGroupBy = array('__state__' => $oGroupByExp); - $aQueryParams = array(); + $aGroupBy = ['__state__' => $oGroupByExp]; + $aQueryParams = []; if (isset($aExtraParams['query_params'])) { $aQueryParams = $aExtraParams['query_params']; } @@ -1955,10 +1917,10 @@ class MenuBlock extends DisplayBlock switch ($iActionAllowed) { case UR_ALLOWED_YES: case UR_ALLOWED_DEPENDS: - $aTransitionActions[$sStimulusCode] = array( + $aTransitionActions[$sStimulusCode] = [ 'label' => $aStimuli[$sStimulusCode]->GetLabel(), 'url' => "{$sRootUrl}pages/UI.php?stimulus=$sStimulusCode&class=$sLifecycleClass&{$sUrlQueryString}", - ) + $aActionParams; + ] + $aActionParams; break; default: @@ -2020,16 +1982,16 @@ class MenuBlock extends DisplayBlock // Just one object in the set, possible actions are "new / clone / modify and delete" if (!isset($aExtraParams['link_attr'])) { if ($bIsModifyAllowed) { - $aRegularActions['UI:Menu:Modify'] = array( + $aRegularActions['UI:Menu:Modify'] = [ 'label' => Dict::S('UI:Menu:Modify'), - 'url' => $oRouter->GenerateUrl('object.modify', ['class' => $sClass, 'id' => $id]) . "{$sContext}#", - ) + $aActionParams; + 'url' => $oRouter->GenerateUrl('object.modify', ['class' => $sClass, 'id' => $id])."{$sContext}#", + ] + $aActionParams; } if ($bIsDeleteAllowed) { - $aRegularActions['UI:Menu:Delete'] = array( + $aRegularActions['UI:Menu:Delete'] = [ 'label' => Dict::S('UI:Menu:Delete'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=delete&class=$sClass&id=$id{$sContext}", - ) + $aActionParams; + ] + $aActionParams; } // Relations... @@ -2038,16 +2000,16 @@ class MenuBlock extends DisplayBlock $this->AddMenuSeparator($aRegularActions); foreach ($aRelations as $sRelationCode => $aRelationInfo) { if (array_key_exists('down', $aRelationInfo)) { - $aRegularActions[$sRelationCode.'_down'] = array( + $aRegularActions[$sRelationCode.'_down'] = [ 'label' => $aRelationInfo['down'], 'url' => "{$sRootUrl}pages/$sUIPage?operation=view_relations&relation=$sRelationCode&direction=down&class=$sClass&id=$id{$sContext}", - ) + $aActionParams; + ] + $aActionParams; } if (array_key_exists('up', $aRelationInfo)) { - $aRegularActions[$sRelationCode.'_up'] = array( + $aRegularActions[$sRelationCode.'_up'] = [ 'label' => $aRelationInfo['up'], 'url' => "{$sRootUrl}pages/$sUIPage?operation=view_relations&relation=$sRelationCode&direction=up&class=$sClass&id=$id{$sContext}", - ) + $aActionParams; + ] + $aActionParams; } } } @@ -2059,7 +2021,7 @@ class MenuBlock extends DisplayBlock $bCanKill = false; $oUser = UserRights::GetUserObject(); - $aUserProfiles = array(); + $aUserProfiles = []; if (!is_null($oUser)) { $oProfileSet = $oUser->Get('profile_list'); while ($oProfile = $oProfileSet->Fetch()) { @@ -2081,10 +2043,10 @@ class MenuBlock extends DisplayBlock if ($bCanKill) { $this->AddMenuSeparator($aRegularActions); - $aRegularActions['concurrent_lock_unlock'] = array( + $aRegularActions['concurrent_lock_unlock'] = [ 'label' => Dict::S('UI:Menu:KillConcurrentLock'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=kill_lock&class=$sClass&id=$id{$sContext}", - ); + ]; } } } @@ -2092,7 +2054,7 @@ class MenuBlock extends DisplayBlock $this->AddMenuSeparator($aRegularActions); $this->GetEnumAllowedActions($oSet, function ($sLabel, $data) use (&$aRegularActions, $aActionParams) { - $aRegularActions[$sLabel] = array('label' => $sLabel, 'url' => $data) + $aActionParams; + $aRegularActions[$sLabel] = ['label' => $sLabel, 'url' => $data] + $aActionParams; }); } break; @@ -2299,7 +2261,7 @@ class MenuBlock extends DisplayBlock $sTarget = isset($aAction['target']) ? $aAction['target'] : ''; if (!empty($aAction['onclick'])) { - $oActionButton = ButtonUIBlockFactory::MakeIconAction($sIconClass, $aAction['label'], $aAction['label'], $sLabel,false); //utils::Sanitize($sActionId.md5($aAction['onclick']), '', utils::ENUM_SANITIZATION_FILTER_ELEMENT_IDENTIFIER)) + $oActionButton = ButtonUIBlockFactory::MakeIconAction($sIconClass, $aAction['label'], $aAction['label'], $sLabel, false); //utils::Sanitize($sActionId.md5($aAction['onclick']), '', utils::ENUM_SANITIZATION_FILTER_ELEMENT_IDENTIFIER)) $oActionButton->SetOnClickJsCode($aAction['onclick']); } else { $oActionButton = ButtonUIBlockFactory::MakeLinkNeutral($sUrl, $sLabel, $sIconClass, $sTarget, utils::Sanitize($sActionId, '', utils::ENUM_SANITIZATION_FILTER_ELEMENT_IDENTIFIER)); @@ -2458,13 +2420,11 @@ class MenuBlock extends DisplayBlock protected function AddMenuSeparator(&$aActions) { $sSeparator = ''; - if (count($aActions) > 0) // Make sure that the separator is not the first item in the menu - { + if (count($aActions) > 0) { // Make sure that the separator is not the first item in the menu $aKeys = array_keys($aActions); $sLastKey = array_pop($aKeys); - if ($aActions[$sLastKey]['label'] != $sSeparator) // Make sure there are no 2 consecutive separators - { - $aActions['sep_'.(count($aActions)-1)] = array('label' => $sSeparator, 'url' => ''); + if ($aActions[$sLastKey]['label'] != $sSeparator) { // Make sure there are no 2 consecutive separators + $aActions['sep_'.(count($aActions) - 1)] = ['label' => $sSeparator, 'url' => '']; } } } @@ -2524,10 +2484,10 @@ class MenuBlock extends DisplayBlock */ protected function AddBulkDeleteObjectsMenuAction(array &$aActions, string $sClass, string $sFilter, string $sActionIdentifier = 'UI:Menu:BulkDelete', $sActionLabel = 'UI:Menu:BulkDelete') { - $aActions[$sActionIdentifier] = array( + $aActions[$sActionIdentifier] = [ 'label' => Dict::S($sActionLabel), 'url' => $this->PrepareUrlForStandardMenuAction($sClass, "operation=select_for_deletion&filter=".urlencode($sFilter)), - ) + $this->GetDefaultParamsForMenuAction(); + ] + $this->GetDefaultParamsForMenuAction(); } /** @@ -2564,6 +2524,6 @@ class MenuBlock extends DisplayBlock $oAppContext = new ApplicationContext(); $sContext = $oAppContext->GetForLink(true); - return $sUrl . $sContext; + return $sUrl.$sContext; } } diff --git a/application/excelexporter.class.inc.php b/application/excelexporter.class.inc.php index 71d16d06a..dc3b844ff 100644 --- a/application/excelexporter.class.inc.php +++ b/application/excelexporter.class.inc.php @@ -19,73 +19,67 @@ class ExcelExporter protected $iPosition; protected $sOutputFilePath; protected $bAdvancedMode; - + public function __construct($sToken = null) { - $this->aStatistics = array( + $this->aStatistics = [ 'objects_count' => 0, 'total_duration' => 0, 'data_retrieval_duration' => 0, 'excel_build_duration' => 0, 'excel_write_duration' => 0, - 'peak_memory_usage' => 0, - ); + 'peak_memory_usage' => 0, + ]; $this->fStartTime = microtime(true); $this->oSearch = null; - + $this->sState = 'new'; - $this->aObjectsIDs = array(); + $this->aObjectsIDs = []; $this->iPosition = 0; $this->aAuthorizedClasses = null; $this->aTableHeaders = null; $this->sOutputFilePath = null; $this->bAdvancedMode = false; $this->CheckDataDir(); - if ($sToken == null) - { + if ($sToken == null) { $this->sToken = $this->GetNewToken(); - } - else - { + } else { $this->sToken = $sToken; $this->ReloadState(); } } - + public function __destruct() { - if (($this->sState != 'done') && ($this->sState != 'error') && ($this->sToken != null)) - { + if (($this->sState != 'done') && ($this->sState != 'error') && ($this->sToken != null)) { // Operation in progress, save the state $this->SaveState(); - } - else - { + } else { // Operation completed, cleanup the temp files @unlink($this->GetStateFile()); @unlink($this->GetDataFile()); } - self::CleanupOldFiles(); + self::CleanupOldFiles(); } - + public function SetChunkSize($iChunkSize) { - $this->iChunkSize = $iChunkSize; + $this->iChunkSize = $iChunkSize; } - + public function SetOutputFilePath($sDestFilePath) { $this->sOutputFilePath = $sDestFilePath; } - + public function SetAdvancedMode($bAdvanced) { $this->bAdvancedMode = $bAdvanced; } - + public function SaveState() { - $aState = array( + $aState = [ 'state' => $this->sState, 'statistics' => $this->aStatistics, 'filter' => $this->oSearch->serialize(), @@ -94,31 +88,28 @@ class ExcelExporter 'object_ids' => $this->aObjectsIDs, 'output_file_path' => $this->sOutputFilePath, 'advanced_mode' => $this->bAdvancedMode, - ); - + ]; + file_put_contents($this->GetStateFile(), json_encode($aState)); - + return $this->sToken; } - + public function ReloadState() { - if ($this->sToken == null) - { + if ($this->sToken == null) { throw new Exception('ExcelExporter not initialized with a token, cannot reload state'); } - - if (!file_exists($this->GetStateFile())) - { + + if (!file_exists($this->GetStateFile())) { throw new Exception("ExcelExporter: missing status file '".$this->GetStateFile()."', cannot reload state."); } $sJson = file_get_contents($this->GetStateFile()); $aState = json_decode($sJson, true); - if ($aState === null) - { + if ($aState === null) { throw new Exception("ExcelExporter:corrupted status file '".$this->GetStateFile()."', not a JSON, cannot reload state."); } - + $this->sState = $aState['state']; $this->aStatistics = $aState['statistics']; $this->oSearch = DBObjectSearch::unserialize($aState['filter']); @@ -128,206 +119,183 @@ class ExcelExporter $this->sOutputFilePath = $aState['output_file_path']; $this->bAdvancedMode = $aState['advanced_mode']; } - + public function SetObjectList($oSearch) { $this->oSearch = $oSearch; } - + public function Run() { $sCode = 'error'; $iPercentage = 100; $sMessage = Dict::Format('ExcelExporter:ErrorUnexpected_State', $this->sState); $fTime = microtime(true); - - try - { - switch($this->sState) - { + + try { + switch ($this->sState) { case 'new': - $oIDSet = new DBObjectSet($this->oSearch); - $oIDSet->OptimizeColumnLoad(array('id')); - $this->aObjectsIDs = array(); - while($oObj = $oIDSet->Fetch()) - { - $this->aObjectsIDs[] = $oObj->GetKey(); - } - $sCode = 'retrieving-data'; - $iPercentage = 5; - $sMessage = Dict::S('ExcelExporter:RetrievingData'); - $this->iPosition = 0; - $this->aStatistics['objects_count'] = count($this->aObjectsIDs); - $this->aStatistics['data_retrieval_duration'] += microtime(true) - $fTime; - - // The first line of the file is the "headers" specifying the label and the type of each column - $this->GetFieldsList($oIDSet, $this->bAdvancedMode); - $sRow = json_encode($this->aTableHeaders); - $hFile = @fopen($this->GetDataFile(), 'ab'); - if ($hFile === false) - { - throw new Exception('ExcelExporter: Failed to open temporary data file: "'.$this->GetDataFile().'" for writing.'); - } - fwrite($hFile, $sRow."\n"); - fclose($hFile); - - // Next state - $this->sState = 'retrieving-data'; - break; - - case 'retrieving-data': - $oCurrentSearch = clone $this->oSearch; - $aIDs = array_slice($this->aObjectsIDs, $this->iPosition, $this->iChunkSize); - - $oCurrentSearch->AddCondition('id', $aIDs, 'IN'); - $hFile = @fopen($this->GetDataFile(), 'ab'); - if ($hFile === false) - { - throw new Exception('ExcelExporter: Failed to open temporary data file: "'.$this->GetDataFile().'" for writing.'); - } - $oSet = new DBObjectSet($oCurrentSearch); - $this->GetFieldsList($oSet, $this->bAdvancedMode); - while($aObjects = $oSet->FetchAssoc()) - { - $aRow = array(); - foreach($this->aAuthorizedClasses as $sAlias => $sClassName) - { - $oObj = $aObjects[$sAlias]; - if ($this->bAdvancedMode) - { - $aRow[] = $oObj->GetKey(); - } - foreach($this->aFieldsList[$sAlias] as $sAttCodeEx => $oAttDef) - { - $value = $oObj->Get($sAttCodeEx); - if ($value instanceOf ormCaseLog) - { - // 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! - $sExcelVal = trim(preg_replace('/========== ([^=]+) ============/', '********** $1 ************', $value->GetText())); - } - else - { - $sExcelVal = $oAttDef->GetEditValue($value, $oObj); - } - $aRow[] = $sExcelVal; - } + $oIDSet = new DBObjectSet($this->oSearch); + $oIDSet->OptimizeColumnLoad(['id']); + $this->aObjectsIDs = []; + while ($oObj = $oIDSet->Fetch()) { + $this->aObjectsIDs[] = $oObj->GetKey(); } - $sRow = json_encode($aRow); - fwrite($hFile, $sRow."\n"); - } - fclose($hFile); - - if (($this->iPosition + $this->iChunkSize) > count($this->aObjectsIDs)) - { - // Next state - $this->sState = 'building-excel'; - $sCode = 'building-excel'; - $iPercentage = 80; - $sMessage = Dict::S('ExcelExporter:BuildingExcelFile'); - } - else - { $sCode = 'retrieving-data'; - $this->iPosition += $this->iChunkSize; - $iPercentage = 5 + round(75 * ($this->iPosition / count($this->aObjectsIDs))); - $sMessage = Dict::S('ExcelExporter:RetrievingData'); - } - break; - + $iPercentage = 5; + $sMessage = Dict::S('ExcelExporter:RetrievingData'); + $this->iPosition = 0; + $this->aStatistics['objects_count'] = count($this->aObjectsIDs); + $this->aStatistics['data_retrieval_duration'] += microtime(true) - $fTime; + + // The first line of the file is the "headers" specifying the label and the type of each column + $this->GetFieldsList($oIDSet, $this->bAdvancedMode); + $sRow = json_encode($this->aTableHeaders); + $hFile = @fopen($this->GetDataFile(), 'ab'); + if ($hFile === false) { + throw new Exception('ExcelExporter: Failed to open temporary data file: "'.$this->GetDataFile().'" for writing.'); + } + fwrite($hFile, $sRow."\n"); + fclose($hFile); + + // Next state + $this->sState = 'retrieving-data'; + break; + + case 'retrieving-data': + $oCurrentSearch = clone $this->oSearch; + $aIDs = array_slice($this->aObjectsIDs, $this->iPosition, $this->iChunkSize); + + $oCurrentSearch->AddCondition('id', $aIDs, 'IN'); + $hFile = @fopen($this->GetDataFile(), 'ab'); + if ($hFile === false) { + throw new Exception('ExcelExporter: Failed to open temporary data file: "'.$this->GetDataFile().'" for writing.'); + } + $oSet = new DBObjectSet($oCurrentSearch); + $this->GetFieldsList($oSet, $this->bAdvancedMode); + while ($aObjects = $oSet->FetchAssoc()) { + $aRow = []; + foreach ($this->aAuthorizedClasses as $sAlias => $sClassName) { + $oObj = $aObjects[$sAlias]; + if ($this->bAdvancedMode) { + $aRow[] = $oObj->GetKey(); + } + foreach ($this->aFieldsList[$sAlias] as $sAttCodeEx => $oAttDef) { + $value = $oObj->Get($sAttCodeEx); + if ($value instanceof ormCaseLog) { + // 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! + $sExcelVal = trim(preg_replace('/========== ([^=]+) ============/', '********** $1 ************', $value->GetText())); + } else { + $sExcelVal = $oAttDef->GetEditValue($value, $oObj); + } + $aRow[] = $sExcelVal; + } + } + $sRow = json_encode($aRow); + fwrite($hFile, $sRow."\n"); + } + fclose($hFile); + + if (($this->iPosition + $this->iChunkSize) > count($this->aObjectsIDs)) { + // Next state + $this->sState = 'building-excel'; + $sCode = 'building-excel'; + $iPercentage = 80; + $sMessage = Dict::S('ExcelExporter:BuildingExcelFile'); + } else { + $sCode = 'retrieving-data'; + $this->iPosition += $this->iChunkSize; + $iPercentage = 5 + round(75 * ($this->iPosition / count($this->aObjectsIDs))); + $sMessage = Dict::S('ExcelExporter:RetrievingData'); + } + break; + case 'building-excel': - $hFile = @fopen($this->GetDataFile(), 'rb'); - if ($hFile === false) - { - throw new Exception('ExcelExporter: Failed to open temporary data file: "'.$this->GetDataFile().'" for reading.'); - } - $sHeaders = fgets($hFile); - $aHeaders = json_decode($sHeaders, true); - - $aData = array(); - while($sLine = fgets($hFile)) - { - $aRow = json_decode($sLine); - $aData[] = $aRow; - } - fclose($hFile); - @unlink($this->GetDataFile()); - - $fStartExcel = microtime(true); - $writer = new XLSXWriter(); - $writer->setAuthor(UserRights::GetUserFriendlyName()); - $writer->writeSheet($aData,'Sheet1', $aHeaders); - $fExcelTime = microtime(true) - $fStartExcel; - $this->aStatistics['excel_build_duration'] = $fExcelTime; - - $fTime = microtime(true); - $writer->writeToFile($this->GetExcelFilePath()); - $fExcelSaveTime = microtime(true) - $fTime; - $this->aStatistics['excel_write_duration'] = $fExcelSaveTime; - - // Next state - $this->sState = 'done'; - $sCode = 'done'; - $iPercentage = 100; - $sMessage = Dict::S('ExcelExporter:Done'); - break; - + $hFile = @fopen($this->GetDataFile(), 'rb'); + if ($hFile === false) { + throw new Exception('ExcelExporter: Failed to open temporary data file: "'.$this->GetDataFile().'" for reading.'); + } + $sHeaders = fgets($hFile); + $aHeaders = json_decode($sHeaders, true); + + $aData = []; + while ($sLine = fgets($hFile)) { + $aRow = json_decode($sLine); + $aData[] = $aRow; + } + fclose($hFile); + @unlink($this->GetDataFile()); + + $fStartExcel = microtime(true); + $writer = new XLSXWriter(); + $writer->setAuthor(UserRights::GetUserFriendlyName()); + $writer->writeSheet($aData, 'Sheet1', $aHeaders); + $fExcelTime = microtime(true) - $fStartExcel; + $this->aStatistics['excel_build_duration'] = $fExcelTime; + + $fTime = microtime(true); + $writer->writeToFile($this->GetExcelFilePath()); + $fExcelSaveTime = microtime(true) - $fTime; + $this->aStatistics['excel_write_duration'] = $fExcelSaveTime; + + // Next state + $this->sState = 'done'; + $sCode = 'done'; + $iPercentage = 100; + $sMessage = Dict::S('ExcelExporter:Done'); + break; + case 'done': - $this->sState = 'done'; - $sCode = 'done'; - $iPercentage = 100; - $sMessage = Dict::S('ExcelExporter:Done'); - break; + $this->sState = 'done'; + $sCode = 'done'; + $iPercentage = 100; + $sMessage = Dict::S('ExcelExporter:Done'); + break; } - } - catch(Exception $e) - { + } catch (Exception $e) { $sCode = 'error'; $sMessage = $e->getMessage(); } - + $this->aStatistics['total_duration'] += microtime(true) - $fTime; $peak_memory = memory_get_peak_usage(true); - if ($peak_memory > $this->aStatistics['peak_memory_usage']) - { + if ($peak_memory > $this->aStatistics['peak_memory_usage']) { $this->aStatistics['peak_memory_usage'] = $peak_memory; } - - return array( + + return [ 'code' => $sCode, 'message' => $sMessage, 'percentage' => $iPercentage, - ); + ]; } - + public function GetExcelFilePath() { - if ($this->sOutputFilePath == null) - { + if ($this->sOutputFilePath == null) { return utils::GetDataPath().'bulk_export/'.$this->sToken.'.xlsx'; - } - else - { + } else { return $this->sOutputFilePath; } } - + public static function GetExcelFileFromToken($sToken) { return @file_get_contents(utils::GetDataPath().'bulk_export/'.$sToken.'.xlsx'); } - + public static function CleanupFromToken($sToken) { @unlink(utils::GetDataPath().'bulk_export/'.$sToken.'.status'); @unlink(utils::GetDataPath().'bulk_export/'.$sToken.'.data'); @unlink(utils::GetDataPath().'bulk_export/'.$sToken.'.xlsx'); } - + public function Cleanup() { self::CleanupFromToken($this->sToken); } - + /** * Delete all files in the data/bulk_export directory which are older than 1 day * unless a different delay is configured. @@ -336,15 +304,12 @@ class ExcelExporter { $aFiles = glob(utils::GetDataPath().'bulk_export/*.*'); $iDelay = MetaModel::GetConfig()->Get('xlsx_exporter_cleanup_old_files_delay'); - - if($iDelay > 0) - { - foreach($aFiles as $sFile) - { + + if ($iDelay > 0) { + foreach ($aFiles as $sFile) { $iModificationTime = filemtime($sFile); - - if($iModificationTime < (time() - $iDelay)) - { + + if ($iModificationTime < (time() - $iDelay)) { // Temporary files older than one day are deleted //echo "Supposed to delete: '".$sFile." (Unix Modification Time: $iModificationTime)'\n"; @unlink($sFile); @@ -352,189 +317,155 @@ class ExcelExporter } } } - + public function DisplayStatistics(Page $oPage) { - $aStats = array( + $aStats = [ 'Number of objects exported' => $this->aStatistics['objects_count'], 'Total export duration' => sprintf('%.3f s', $this->aStatistics['total_duration']), 'Data retrieval duration' => sprintf('%.3f s', $this->aStatistics['data_retrieval_duration']), 'Excel build duration' => sprintf('%.3f s', $this->aStatistics['excel_build_duration']), 'Excel write duration' => sprintf('%.3f s', $this->aStatistics['excel_write_duration']), 'Peak memory usage' => self::HumanDisplay($this->aStatistics['peak_memory_usage']), - ); - - if ($oPage instanceof CLIPage) - { + ]; + + if ($oPage instanceof CLIPage) { $oPage->add($this->GetStatistics('text')); - } - else - { + } else { $oPage->add($this->GetStatistics('html')); } } - + public function GetStatistics($sFormat = 'html') { $sStats = ''; - $aStats = array( + $aStats = [ 'Number of objects exported' => $this->aStatistics['objects_count'], 'Total export duration' => sprintf('%.3f s', $this->aStatistics['total_duration']), 'Data retrieval duration' => sprintf('%.3f s', $this->aStatistics['data_retrieval_duration']), 'Excel build duration' => sprintf('%.3f s', $this->aStatistics['excel_build_duration']), 'Excel write duration' => sprintf('%.3f s', $this->aStatistics['excel_write_duration']), 'Peak memory usage' => self::HumanDisplay($this->aStatistics['peak_memory_usage']), - ); - - if ($sFormat == 'text') - { - foreach($aStats as $sLabel => $sValue) - { + ]; + + if ($sFormat == 'text') { + foreach ($aStats as $sLabel => $sValue) { $sStats .= "+------------------------------+----------+\n"; $sStats .= sprintf("|%-30s|%10s|\n", $sLabel, $sValue); } $sStats .= "+------------------------------+----------+"; - } - else - { + } else { $sStats .= '

$sCategory

'; - foreach($aStats as $sLabel => $sValue) - { + foreach ($aStats as $sLabel => $sValue) { $sStats .= ""; } $sStats .= '
$sLabel$sValue
'; - + } return $sStats; } - + public static function HumanDisplay($iSize) { - $aUnits = array('B','KB','MB','GB','TB','PB'); - return @round($iSize/pow(1024,($i=floor(log($iSize,1024)))),2).' '.$aUnits[$i]; + $aUnits = ['B','KB','MB','GB','TB','PB']; + return @round($iSize / pow(1024, ($i = floor(log($iSize, 1024)))), 2).' '.$aUnits[$i]; } - + protected function CheckDataDir() { - if(!is_dir(utils::GetDataPath()."bulk_export")) - { + if (!is_dir(utils::GetDataPath()."bulk_export")) { @mkdir(utils::GetDataPath()."bulk_export", 0777, true /* recursive */); clearstatcache(); } - if (!is_writable(utils::GetDataPath()."bulk_export")) - { + if (!is_writable(utils::GetDataPath()."bulk_export")) { throw new Exception('Data directory "'.utils::GetDataPath().'bulk_export" could not be written.'); } } - + protected function GetStateFile($sToken = null) { - if ($sToken == null) - { + if ($sToken == null) { $sToken = $this->sToken; } return utils::GetDataPath()."bulk_export/$sToken.status"; } - + protected function GetDataFile() { return utils::GetDataPath().'bulk_export/'.$this->sToken.'.data'; } - + protected function GetNewToken() { $iNum = rand(); - do - { + do { $iNum++; $sToken = sprintf("%08x", $iNum); $sFileName = $this->GetStateFile($sToken); $hFile = @fopen($sFileName, 'x'); - } - while($hFile === false); - + } while ($hFile === false); + fclose($hFile); return $sToken; } - + protected function GetFieldsList($oSet, $bFieldsAdvanced = false, $bLocalize = true, $aFields = null) { - $this->aFieldsList = array(); - + $this->aFieldsList = []; + $oAppContext = new ApplicationContext(); $aClasses = $oSet->GetFilter()->GetSelectedClasses(); - $this->aAuthorizedClasses = array(); - foreach($aClasses as $sAlias => $sClassName) - { - if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) != UR_ALLOWED_NO) - { + $this->aAuthorizedClasses = []; + foreach ($aClasses as $sAlias => $sClassName) { + if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) != UR_ALLOWED_NO) { $this->aAuthorizedClasses[$sAlias] = $sClassName; } } - $aAttribs = array(); - $this->aTableHeaders = array(); - foreach($this->aAuthorizedClasses as $sAlias => $sClassName) - { - $aList[$sAlias] = array(); - - foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef) - { - if (is_null($aFields) || (count($aFields) == 0)) - { + $aAttribs = []; + $this->aTableHeaders = []; + foreach ($this->aAuthorizedClasses as $sAlias => $sClassName) { + $aList[$sAlias] = []; + + foreach (MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef) { + if (is_null($aFields) || (count($aFields) == 0)) { // Standard list of attributes (no link sets) - if ($oAttDef->IsScalar() && ($oAttDef->IsWritable() || $oAttDef->IsExternalField())) - { + if ($oAttDef->IsScalar() && ($oAttDef->IsWritable() || $oAttDef->IsExternalField())) { $sAttCodeEx = $oAttDef->IsExternalField() ? $oAttDef->GetKeyAttCode().'->'.$oAttDef->GetExtAttCode() : $sAttCode; - - if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) - { - if ($bFieldsAdvanced) - { + + if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) { + if ($bFieldsAdvanced) { $aList[$sAlias][$sAttCodeEx] = $oAttDef; - - if ($oAttDef->IsExternalKey(EXTKEY_RELATIVE)) - { - $sRemoteClass = $oAttDef->GetTargetClass(); - foreach(MetaModel::GetReconcKeys($sRemoteClass) as $sRemoteAttCode) - { + + if ($oAttDef->IsExternalKey(EXTKEY_RELATIVE)) { + $sRemoteClass = $oAttDef->GetTargetClass(); + foreach (MetaModel::GetReconcKeys($sRemoteClass) as $sRemoteAttCode) { $this->aFieldsList[$sAlias][$sAttCode.'->'.$sRemoteAttCode] = MetaModel::GetAttributeDef($sRemoteClass, $sRemoteAttCode); - } + } } } - } - else - { + } else { // Any other attribute $this->aFieldsList[$sAlias][$sAttCodeEx] = $oAttDef; } } - } - else - { + } else { // User defined list of attributes - if (in_array($sAttCode, $aFields) || in_array($sAlias.'.'.$sAttCode, $aFields)) - { + if (in_array($sAttCode, $aFields) || in_array($sAlias.'.'.$sAttCode, $aFields)) { $this->aFieldsList[$sAlias][$sAttCode] = $oAttDef; } } } - if ($bFieldsAdvanced) - { + if ($bFieldsAdvanced) { $this->aTableHeaders['id'] = '0'; } - foreach($this->aFieldsList[$sAlias] as $sAttCodeEx => $oAttDef) - { + foreach ($this->aFieldsList[$sAlias] as $sAttCodeEx => $oAttDef) { $sLabel = $bLocalize ? MetaModel::GetLabel($sClassName, $sAttCodeEx, isset($aParams['showMandatoryFields'])) : $sAttCodeEx; - if($oAttDef instanceof AttributeDateTime) - { + if ($oAttDef instanceof AttributeDateTime) { $this->aTableHeaders[$sLabel] = 'datetime'; - } - else - { + } else { $this->aTableHeaders[$sLabel] = 'string'; } } } } } - diff --git a/application/iotask.class.inc.php b/application/iotask.class.inc.php index f0becff96..bf035ad04 100644 --- a/application/iotask.class.inc.php +++ b/application/iotask.class.inc.php @@ -1,9 +1,10 @@ - /** * Persistent class InputOutputTask * @@ -28,42 +28,43 @@ require_once(APPROOT.'/application/cmdbabstract.class.inc.php'); /** * This class manages the input/output tasks - * for synchronizing information with external data sources + * for synchronizing information with external data sources */ class InputOutputTask extends cmdbAbstractObject { public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "application", "key_type" => "autoincrement", "name_attcode" => "name", "state_attcode" => "", - "reconc_keys" => array(), + "reconc_keys" => [], "db_table" => "priv_iotask", "db_key_field" => "id", "db_finalclass_field" => "", - ); + ]; MetaModel::Init_Params($aParams); - MetaModel::Init_AddAttribute(new AttributeString("name", array("allowed_values" => null, "sql" => "name", "default_value" => "", "is_null_allowed" => false, "depends_on" => array()))); - MetaModel::Init_AddAttribute(new AttributeString("description", array("allowed_values" => null, "sql" => "description", "default_value" => "", "is_null_allowed" => true, "depends_on" => array()))); - MetaModel::Init_AddAttribute(new AttributeEnum("category", array("allowed_values" => new ValueSetEnum('Input, Ouput'), "sql" => "category", "default_value" => "Input", "is_null_allowed" => false, "depends_on" => array()))); - MetaModel::Init_AddAttribute(new AttributeEnum("source_type", array("allowed_values" => new ValueSetEnum('File, Database, Web Service'), "sql" => "source_type", "default_value" => "File", "is_null_allowed" => false, "depends_on" => array()))); - MetaModel::Init_AddAttribute(new AttributeEnum("source_subtype", - array("allowed_values" => new ValueSetEnum('Oracle, MySQL, Postgress, MSSQL, SOAP, HTTP-Get, HTTP-Post, XML/RPC, CSV, XML, Excel'), "sql" => "source_subtype", "default_value" => "CSV", "is_null_allowed" => false, "depends_on" => array()))); - MetaModel::Init_AddAttribute(new AttributeString("source_path", array("allowed_values" => null, "sql" => "source_path", "default_value" => "", "is_null_allowed" => false, "depends_on" => array()))); - MetaModel::Init_AddAttribute(new AttributeClass("objects_class", array("class_category" => "", "more_values" => "", "sql" => "objects_class", "default_value" => null, "is_null_allowed" => true, "depends_on" => array(), "class_exclusion_list" => null))); - MetaModel::Init_AddAttribute(new AttributeEnum("test_mode", array("allowed_values" => new ValueSetEnum('Yes,No'), "sql" => "test_mode", "default_value" => 'No', "is_null_allowed" => false, "depends_on" => array()))); - MetaModel::Init_AddAttribute(new AttributeEnum("verbose_mode", array("allowed_values" => new ValueSetEnum('Yes,No'), "sql" => "verbose_mode", "default_value" => 'No', "is_null_allowed" => false, "depends_on" => array()))); - MetaModel::Init_AddAttribute(new AttributeEnum("options", array("allowed_values" => new ValueSetEnum('Full, Update Only, Creation Only'), "sql" => "options", "default_value" => 'Full', "is_null_allowed" => true, "depends_on" => array()))); + MetaModel::Init_AddAttribute(new AttributeString("name", ["allowed_values" => null, "sql" => "name", "default_value" => "", "is_null_allowed" => false, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeString("description", ["allowed_values" => null, "sql" => "description", "default_value" => "", "is_null_allowed" => true, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeEnum("category", ["allowed_values" => new ValueSetEnum('Input, Ouput'), "sql" => "category", "default_value" => "Input", "is_null_allowed" => false, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeEnum("source_type", ["allowed_values" => new ValueSetEnum('File, Database, Web Service'), "sql" => "source_type", "default_value" => "File", "is_null_allowed" => false, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeEnum( + "source_subtype", + ["allowed_values" => new ValueSetEnum('Oracle, MySQL, Postgress, MSSQL, SOAP, HTTP-Get, HTTP-Post, XML/RPC, CSV, XML, Excel'), "sql" => "source_subtype", "default_value" => "CSV", "is_null_allowed" => false, "depends_on" => []] + )); + MetaModel::Init_AddAttribute(new AttributeString("source_path", ["allowed_values" => null, "sql" => "source_path", "default_value" => "", "is_null_allowed" => false, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeClass("objects_class", ["class_category" => "", "more_values" => "", "sql" => "objects_class", "default_value" => null, "is_null_allowed" => true, "depends_on" => [], "class_exclusion_list" => null])); + MetaModel::Init_AddAttribute(new AttributeEnum("test_mode", ["allowed_values" => new ValueSetEnum('Yes,No'), "sql" => "test_mode", "default_value" => 'No', "is_null_allowed" => false, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeEnum("verbose_mode", ["allowed_values" => new ValueSetEnum('Yes,No'), "sql" => "verbose_mode", "default_value" => 'No', "is_null_allowed" => false, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeEnum("options", ["allowed_values" => new ValueSetEnum('Full, Update Only, Creation Only'), "sql" => "options", "default_value" => 'Full', "is_null_allowed" => true, "depends_on" => []])); // Display lists - MetaModel::Init_SetZListItems('details', array('name', 'description', 'category', 'objects_class', 'source_type', 'source_subtype', 'source_path', 'options', 'test_mode', 'verbose_mode')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('description', 'category', 'objects_class', 'source_type', 'source_subtype', 'options')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['name', 'description', 'category', 'objects_class', 'source_type', 'source_subtype', 'source_path', 'options', 'test_mode', 'verbose_mode']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['description', 'category', 'objects_class', 'source_type', 'source_subtype', 'options']); // Attributes to be displayed for a list // Search criteria - MetaModel::Init_SetZListItems('standard_search', array('name', 'category', 'objects_class', 'source_type', 'source_subtype')); // Criteria of the std search form - MetaModel::Init_SetZListItems('advanced_search', array('name', 'description', 'category', 'objects_class', 'source_type', 'source_subtype')); // Criteria of the advanced search form + MetaModel::Init_SetZListItems('standard_search', ['name', 'category', 'objects_class', 'source_type', 'source_subtype']); // Criteria of the std search form + MetaModel::Init_SetZListItems('advanced_search', ['name', 'description', 'category', 'objects_class', 'source_type', 'source_subtype']); // Criteria of the advanced search form } } -?> diff --git a/application/menunode.class.inc.php b/application/menunode.class.inc.php index 4e67be849..eef87d461 100644 --- a/application/menunode.class.inc.php +++ b/application/menunode.class.inc.php @@ -1,4 +1,5 @@ PopulateChildMenus(); } @@ -124,8 +121,7 @@ class ApplicationMenu */ public static function CheckMenuIdEnabled($sMenuId) { - if (self::IsMenuIdEnabled($sMenuId) === false) - { + if (self::IsMenuIdEnabled($sMenuId) === false) { require_once(APPROOT.'/setup/setuppage.class.inc.php'); $oP = new ErrorPage(Dict::S('UI:PageTitle:FatalError')); $oP->add("

".Dict::S('UI:Login:Error:AccessRestricted')."

\n"); @@ -141,7 +137,7 @@ class ApplicationMenu * @return bool true if the menu exists and current user is allowed to see the menu * @since 3.2.0 */ - public static function IsMenuIdEnabled($sMenuId):bool + public static function IsMenuIdEnabled($sMenuId): bool { self::LoadAdditionalMenus(); $oMenuNode = self::GetMenuNode(self::GetMenuIndexById($sMenuId)); @@ -159,22 +155,18 @@ class ApplicationMenu public static function InsertMenu(MenuNode $oMenuNode, $iParentIndex, $fRank) { $index = self::GetMenuIndexById($oMenuNode->GetMenuId()); - if ($index == -1) - { + if ($index == -1) { // The menu does not already exist, insert it $index = count(self::$aMenusIndex); - if ($iParentIndex == -1) - { + if ($iParentIndex == -1) { $sParentId = ''; - self::$aRootMenus[] = array ('rank' => $fRank, 'index' => $index); - } - else - { + self::$aRootMenus[] = ['rank' => $fRank, 'index' => $index]; + } else { /** @var \MenuNode $oNode */ $oNode = self::$aMenusIndex[$iParentIndex]['node']; $sParentId = $oNode->GetMenuId(); - self::$aMenusIndex[$iParentIndex]['children'][] = array ('rank' => $fRank, 'index' => $index); + self::$aMenusIndex[$iParentIndex]['children'][] = ['rank' => $fRank, 'index' => $index]; } // Note: At the time when 'parent', 'rank' and 'source_file' have been added for the reflection API, @@ -182,11 +174,9 @@ class ApplicationMenu // $aBacktrace = debug_backtrace(); $sFile = isset($aBacktrace[2]["file"]) ? $aBacktrace[2]["file"] : $aBacktrace[1]["file"]; - self::$aMenusIndex[$index] = array('node' => $oMenuNode, 'children' => array(), 'parent' => $sParentId, 'rank' => $fRank, 'source_file' => $sFile); + self::$aMenusIndex[$index] = ['node' => $oMenuNode, 'children' => [], 'parent' => $sParentId, 'rank' => $fRank, 'source_file' => $sFile]; self::$aMenusById[$oMenuNode->GetMenuId()] = $index; - } - else - { + } else { // the menu already exists, let's combine the conditions that make it visible /** @var \MenuNode $oNode */ $oNode = self::$aMenusIndex[$index]['node']; @@ -216,7 +206,7 @@ class ApplicationMenu * @throws \DictExceptionMissingString * @since 3.0.0 */ - public static function GetMenusCount($aExtraParams = array()) + public static function GetMenusCount($aExtraParams = []) { $aMenuGroups = static::GetMenuGroups($aExtraParams); @@ -259,18 +249,16 @@ class ApplicationMenu * @throws \DictExceptionMissingString * @since 3.0.0 */ - public static function GetMenuGroups($aExtraParams = array()) + public static function GetMenuGroups($aExtraParams = []) { self::LoadAdditionalMenus(); // Sort the root menu based on the rank - usort(self::$aRootMenus, array('ApplicationMenu', 'CompareOnRank')); + usort(self::$aRootMenus, ['ApplicationMenu', 'CompareOnRank']); $aMenuGroups = []; - foreach(static::$aRootMenus as $aMenuGroup) - { - if(!static::CanDisplayMenu($aMenuGroup)) - { + foreach (static::$aRootMenus as $aMenuGroup) { + if (!static::CanDisplayMenu($aMenuGroup)) { continue; } @@ -321,26 +309,23 @@ class ApplicationMenu * @throws \Exception * @since 3.0.0 */ - public static function GetSubMenuNodes($sMenuGroupIdx, $aExtraParams = array()) + public static function GetSubMenuNodes($sMenuGroupIdx, $aExtraParams = []) { $aSubMenuItems = self::GetChildren($sMenuGroupIdx); // Sort the children based on the rank - usort($aSubMenuItems, array('ApplicationMenu', 'CompareOnRank')); + usort($aSubMenuItems, ['ApplicationMenu', 'CompareOnRank']); $aSubMenuNodes = []; - foreach($aSubMenuItems as $aSubMenuItem) - { - if(!static::CanDisplayMenu($aSubMenuItem)) - { + foreach ($aSubMenuItems as $aSubMenuItem) { + if (!static::CanDisplayMenu($aSubMenuItem)) { continue; } $sSubMenuItemIdx = $aSubMenuItem['index']; $oSubMenuNode = static::GetMenuNode($sSubMenuItemIdx); - if(!$oSubMenuNode->IsEnabled()) - { + if (!$oSubMenuNode->IsEnabled()) { continue; } @@ -366,21 +351,15 @@ class ApplicationMenu private static function CanDisplayMenu($aMenu) { $oMenuNode = self::GetMenuNode($aMenu['index']); - if ($oMenuNode->IsEnabled()) - { + if ($oMenuNode->IsEnabled()) { $aChildren = self::GetChildren($aMenu['index']); - if (count($aChildren) > 0) - { - foreach($aChildren as $aSubMenu) - { - if (self::CanDisplayMenu($aSubMenu)) - { + if (count($aChildren) > 0) { + foreach ($aChildren as $aSubMenu) { + if (self::CanDisplayMenu($aSubMenu)) { return true; } } - } - else - { + } else { return true; } } @@ -396,12 +375,10 @@ class ApplicationMenu public static function CompareOnRank($a, $b) { $result = 1; - if ($a['rank'] == $b['rank']) - { + if ($a['rank'] == $b['rank']) { $result = 0; } - if ($a['rank'] < $b['rank']) - { + if ($a['rank'] < $b['rank']) { $result = -1; } return $result; @@ -449,8 +426,7 @@ class ApplicationMenu { $oAppContext = new ApplicationContext(); $sMenuId = $oAppContext->GetCurrentValue('menu', null); - if ($sMenuId === null) - { + if ($sMenuId === null) { $sMenuId = self::GetDefaultMenuId(); } return $sMenuId; @@ -462,13 +438,12 @@ class ApplicationMenu public static function GetDefaultMenuId() { static $sDefaultMenuId = null; - if (is_null($sDefaultMenuId)) - { + if (is_null($sDefaultMenuId)) { // Make sure the root menu is sorted on 'rank' - usort(self::$aRootMenus, array('ApplicationMenu', 'CompareOnRank')); + usort(self::$aRootMenus, ['ApplicationMenu', 'CompareOnRank']); $oFirstGroup = self::GetMenuNode(self::$aRootMenus[0]['index']); $aChildren = self::$aMenusIndex[$oFirstGroup->GetIndex()]['children']; - usort($aChildren, array('ApplicationMenu', 'CompareOnRank')); + usort($aChildren, ['ApplicationMenu', 'CompareOnRank']); $oMenuNode = self::GetMenuNode($aChildren[0]['index']); $sDefaultMenuId = $oMenuNode->GetMenuId(); } @@ -482,13 +457,11 @@ class ApplicationMenu public static function GetRootMenuId($sMenuId) { $iMenuIndex = self::GetMenuIndexById($sMenuId); - if ($iMenuIndex == -1) - { + if ($iMenuIndex == -1) { return ''; } $oMenu = ApplicationMenu::GetMenuNode($iMenuIndex); - while ($oMenu->GetParentIndex() != -1) - { + while ($oMenu->GetParentIndex() != -1) { $oMenu = ApplicationMenu::GetMenuNode($oMenu->GetParentIndex()); } return $oMenu->GetMenuId(); @@ -575,17 +548,17 @@ abstract class MenuNode { $this->sMenuId = $sMenuId; $this->iParentIndex = $iParentIndex; - $this->aReflectionProperties = array(); + $this->aReflectionProperties = []; if (utils::IsNotNullOrEmptyString($sEnableClass)) { $this->aReflectionProperties['enable_class'] = $sEnableClass; $this->aReflectionProperties['enable_action'] = $iActionCode; $this->aReflectionProperties['enable_permission'] = $iAllowedResults; $this->aReflectionProperties['enable_stimulus'] = $sEnableStimulus; } - $this->m_aEnableClasses = array($sEnableClass); - $this->m_aEnableActions = array($iActionCode); - $this->m_aEnableActionResults = array($iAllowedResults); - $this->m_aEnableStimuli = array($sEnableStimulus); + $this->m_aEnableClasses = [$sEnableClass]; + $this->m_aEnableActions = [$iActionCode]; + $this->m_aEnableActionResults = [$iAllowedResults]; + $this->m_aEnableStimuli = [$sEnableStimulus]; $this->index = ApplicationMenu::InsertMenu($this, $iParentIndex, $fRank); } @@ -639,7 +612,6 @@ abstract class MenuNode $oSearch->SetShowObsoleteData(utils::ShowObsoleteData()); DBSearchHelper::AddContextFilter($oSearch); - $oSet = new DBObjectSet($oSearch); $iCount = $oSet->CountWithLimit(99); if ($iCount > 99) { @@ -690,8 +662,7 @@ abstract class MenuNode */ public function PopulateChildMenus() { - foreach (ApplicationMenu::GetChildren($this->GetIndex()) as $aMenu) - { + foreach (ApplicationMenu::GetChildren($this->GetIndex()) as $aMenu) { $index = $aMenu['index']; $oMenu = ApplicationMenu::GetMenuNode($index); $oMenu->PopulateChildMenus(); @@ -726,8 +697,7 @@ abstract class MenuNode */ public function AddCondition(MenuNode $oMenuNode) { - foreach($oMenuNode->m_aEnableClasses as $index => $sClass ) - { + foreach ($oMenuNode->m_aEnableClasses as $index => $sClass) { $this->m_aEnableClasses[] = $sClass; $this->m_aEnableActions[] = $oMenuNode->m_aEnableActions[$index]; $this->m_aEnableActionResults[] = $oMenuNode->m_aEnableActionResults[$index]; @@ -740,33 +710,24 @@ abstract class MenuNode */ public function IsEnabled() { - foreach($this->m_aEnableClasses as $index => $sClass) - { - if ($sClass != null) - { - if (MetaModel::IsValidClass($sClass)) - { - if ($this->m_aEnableStimuli[$index] != null) - { - if (!UserRights::IsStimulusAllowed($sClass, $this->m_aEnableStimuli[$index])) - { + foreach ($this->m_aEnableClasses as $index => $sClass) { + if ($sClass != null) { + if (MetaModel::IsValidClass($sClass)) { + if ($this->m_aEnableStimuli[$index] != null) { + if (!UserRights::IsStimulusAllowed($sClass, $this->m_aEnableStimuli[$index])) { return false; } } - if ($this->m_aEnableActions[$index] != null) - { + if ($this->m_aEnableActions[$index] != null) { // Menus access rights ignore the archive mode utils::PushArchiveMode(false); $iResult = UserRights::IsActionAllowed($sClass, $this->m_aEnableActions[$index]); utils::PopArchiveMode(); - if (!($iResult & $this->m_aEnableActionResults[$index])) - { + if (!($iResult & $this->m_aEnableActionResults[$index])) { return false; } } - } - else - { + } else { return false; } } @@ -779,7 +740,7 @@ abstract class MenuNode * @param array $aExtraParams * @return mixed */ - public abstract function RenderContent(WebPage $oPage, $aExtraParams = array()); + abstract public function RenderContent(WebPage $oPage, $aExtraParams = []); /** * @param string $sHyperlink @@ -788,16 +749,13 @@ abstract class MenuNode */ protected function AddParams($sHyperlink, $aExtraParams) { - if (count($aExtraParams) > 0) - { - $aQuery = array(); + if (count($aExtraParams) > 0) { + $aQuery = []; $sSeparator = '?'; - if (strpos($sHyperlink, '?') !== false) - { + if (strpos($sHyperlink, '?') !== false) { $sSeparator = '&'; } - foreach($aExtraParams as $sName => $sValue) - { + foreach ($aExtraParams as $sName => $sValue) { $aQuery[] = urlencode($sName).'='.urlencode($sValue); } $sHyperlink .= $sSeparator.implode('&', $aQuery); @@ -813,7 +771,7 @@ abstract class MenuNode class MenuGroup extends MenuNode { /** @var string DEFAULT_DECORATION_CLASSES Set to null by default so it is replaced by initials when none is specified */ - const DEFAULT_DECORATION_CLASSES = null; + public const DEFAULT_DECORATION_CLASSES = null; /** @var string The CSS classes used to display the menu group's icon */ protected $sDecorationClasses = self::DEFAULT_DECORATION_CLASSES; @@ -833,8 +791,7 @@ class MenuGroup extends MenuNode { parent::__construct($sMenuId, -1 /* no parent, groups are at root level */, $fRank, $sEnableClass, $iActionCode, $iAllowedResults, $sEnableStimulus); - if(!empty($sDecorationClasses)) - { + if (!empty($sDecorationClasses)) { $this->sDecorationClasses = $sDecorationClasses; } } @@ -875,7 +832,7 @@ class MenuGroup extends MenuNode /** * @inheritDoc */ - public function RenderContent(WebPage $oPage, $aExtraParams = array()) + public function RenderContent(WebPage $oPage, $aExtraParams = []) { assert(false); // Shall never be called, groups do not display any content } @@ -887,7 +844,6 @@ class MenuGroup extends MenuNode */ class TemplateMenuNode extends MenuNode { - /** * Create a menu item based on a custom template and inserts it into the application's main menu * @param string $sMenuId Unique identifier of the menu (used to identify the menu for bookmarking, and for getting the labels from the dictionary) @@ -914,7 +870,7 @@ class TemplateMenuNode extends MenuNode * @inheritDoc * @throws \Exception */ - public function RenderContent(WebPage $oPage, $aExtraParams = array()) + public function RenderContent(WebPage $oPage, $aExtraParams = []) { //DO NOTHING this type of menu is only used for title not clickable } @@ -948,7 +904,6 @@ class OQLMenuNode extends MenuNode */ protected $m_aParams; - /** * Create a menu item based on an OQL query and inserts it into the application's main menu * @param string $sMenuId Unique identifier of the menu (used to identify the menu for bookmarking, and for getting the labels from the dictionary) @@ -969,7 +924,7 @@ class OQLMenuNode extends MenuNode $this->sOQL = $sOQL; $this->bSearch = $bSearch; $this->bSearchFormOpen = $bSearchFormOpen; - $this->m_aParams = array(); + $this->m_aParams = []; $this->aReflectionProperties['oql'] = $sOQL; $this->aReflectionProperties['do_search'] = $bSearch; // Enhancement: we could set as the "enable" condition that the user has enough rights to "read" the objects @@ -983,8 +938,7 @@ class OQLMenuNode extends MenuNode public function SetParameters($aParams) { $this->m_aParams = $aParams; - foreach($aParams as $sKey => $value) - { + foreach ($aParams as $sKey => $value) { $this->aReflectionProperties[$sKey] = $value; } } @@ -993,12 +947,11 @@ class OQLMenuNode extends MenuNode * @inheritDoc * @throws \Exception */ - public function RenderContent(WebPage $oPage, $aExtraParams = array()) + public function RenderContent(WebPage $oPage, $aExtraParams = []) { $oTag = new ContextTag(ContextTag::TAG_OBJECT_SEARCH); ApplicationMenu::CheckMenuIdEnabled($this->GetMenuId()); - OQLMenuNode::RenderOQLSearch - ( + OQLMenuNode::RenderOQLSearch( $this->sOQL, Dict::S($this->sPageTitle), 'Menu_'.$this->GetMenuId(), @@ -1023,26 +976,25 @@ class OQLMenuNode extends MenuNode * @throws DictExceptionMissingString * @throws OQLException */ - public static function RenderOQLSearch($sOql, $sTitle, $sUsageId, $bSearchPane, $bSearchOpen, WebPage $oPage, $aExtraParams = array(), $bEnableBreadcrumb = false) + public static function RenderOQLSearch($sOql, $sTitle, $sUsageId, $bSearchPane, $bSearchOpen, WebPage $oPage, $aExtraParams = [], $bEnableBreadcrumb = false) { $sUsageId = utils::GetSafeId($sUsageId); $oSearch = DBObjectSearch::FromOQL($sOql); - $sClass= $oSearch->GetClass(); + $sClass = $oSearch->GetClass(); $sIcon = MetaModel::GetClassIcon($sClass, false); if ($bSearchPane) { $aParams = array_merge(['open' => $bSearchOpen, 'table_id' => $sUsageId, 'submit_on_load' => false], $aExtraParams); $oBlock = new DisplayBlock($oSearch, DisplayBlock::ENUM_STYLE_SEARCH, false /* Asynchronous */, $aParams); $oBlock->Display($oPage, 0); $oPage->add("
"); - } - else { + } else { $oPage->add("
"); } - $aExtraParams['panel_class'] =$sClass; + $aExtraParams['panel_class'] = $sClass; $aExtraParams['panel_title'] = $sTitle; $aExtraParams['panel_icon'] = $sIcon; - $aParams = array_merge(array('table_id' => $sUsageId), $aExtraParams); + $aParams = array_merge(['table_id' => $sUsageId], $aExtraParams); $oBlock = new DisplayBlock($oSearch, 'list', false /* Asynchronous */, $aParams); $oBlock->Display($oPage, $sUsageId); @@ -1107,14 +1059,14 @@ class SearchMenuNode extends MenuNode * @throws \DictExceptionMissingString * @throws \Exception */ - public function RenderContent(WebPage $oPage, $aExtraParams = array()) + public function RenderContent(WebPage $oPage, $aExtraParams = []) { ApplicationMenu::CheckMenuIdEnabled($this->GetMenuId()); $oPage->SetBreadCrumbEntry("menu-".$this->sMenuId, $this->GetTitle(), '', '', 'fas fa-search', iTopWebPage::ENUM_BREADCRUMB_ENTRY_ICON_TYPE_CSS_CLASSES); $oSearch = new DBObjectSearch($this->sClass); $sUsageId = 'Menu_'.utils::GetSafeId($this->GetMenuId()); - $aParams = array_merge(array('table_id' =>$sUsageId), $aExtraParams); + $aParams = array_merge(['table_id' => $sUsageId], $aExtraParams); $oBlock = new DisplayBlock($oSearch, 'search', false /* Asynchronous */, $aParams); $oBlock->Display($oPage, 0); } @@ -1151,10 +1103,16 @@ class WebPageMenuNode extends MenuNode * @param bool $bIsLinkInNewWindow for the {@link WebPageMenuNode::IsHyperLinkInNewWindow} method */ public function __construct( - $sMenuId, $sHyperlink, $iParentIndex, $fRank = 0.0, $sEnableClass = null, $iActionCode = null, - $iAllowedResults = UR_ALLOWED_YES, $sEnableStimulus = null, $bIsLinkInNewWindow = false - ) - { + $sMenuId, + $sHyperlink, + $iParentIndex, + $fRank = 0.0, + $sEnableClass = null, + $iActionCode = null, + $iAllowedResults = UR_ALLOWED_YES, + $sEnableStimulus = null, + $bIsLinkInNewWindow = false + ) { parent::__construct($sMenuId, $iParentIndex, $fRank, $sEnableClass, $iActionCode, $iAllowedResults, $sEnableStimulus); $this->sHyperlink = $sHyperlink; $this->aReflectionProperties['url'] = $sHyperlink; @@ -1167,7 +1125,7 @@ class WebPageMenuNode extends MenuNode public function GetHyperlink($aExtraParams) { $aExtraParams['c[menu]'] = $this->GetMenuId(); - return $this->AddParams( $this->sHyperlink, $aExtraParams); + return $this->AddParams($this->sHyperlink, $aExtraParams); } /** @@ -1181,7 +1139,7 @@ class WebPageMenuNode extends MenuNode /** * @inheritDoc */ - public function RenderContent(WebPage $oPage, $aExtraParams = array()) + public function RenderContent(WebPage $oPage, $aExtraParams = []) { assert(false); // Shall never be called, the external web page will handle the display by itself } @@ -1242,10 +1200,8 @@ class NewObjectMenuNode extends MenuNode $aSubClasses = MetaModel::EnumChildClasses($this->sClass, ENUM_CHILD_CLASSES_ALL); // Including the specified class itself $bActionIsAllowed = false; - foreach($aSubClasses as $sCandidateClass) - { - if (!MetaModel::IsAbstract($sCandidateClass) && (UserRights::IsActionAllowed($sCandidateClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES)) - { + foreach ($aSubClasses as $sCandidateClass) { + if (!MetaModel::IsAbstract($sCandidateClass) && (UserRights::IsActionAllowed($sCandidateClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES)) { $bActionIsAllowed = true; break; // Enough for now } @@ -1256,7 +1212,7 @@ class NewObjectMenuNode extends MenuNode /** * @inheritDoc */ - public function RenderContent(WebPage $oPage, $aExtraParams = array()) + public function RenderContent(WebPage $oPage, $aExtraParams = []) { assert(false); // Shall never be called, the external web page will handle the display by itself } @@ -1296,7 +1252,9 @@ class DashboardMenuNode extends MenuNode */ public function GetHyperlink($aExtraParams) { - if ($this->sDashboardFile == '') return ''; + if ($this->sDashboardFile == '') { + return ''; + } return parent::GetHyperlink($aExtraParams); } @@ -1314,12 +1272,11 @@ class DashboardMenuNode extends MenuNode * @inheritDoc * @throws \Exception */ - public function RenderContent(WebPage $oPage, $aExtraParams = array()) + public function RenderContent(WebPage $oPage, $aExtraParams = []) { ApplicationMenu::CheckMenuIdEnabled($this->GetMenuId()); $oDashboard = $this->GetDashboard(); - if ($oDashboard != null) - { + if ($oDashboard != null) { WebResourcesHelper::EnableC3JSToWebPage($oPage); $sDivId = utils::Sanitize($this->sMenuId, '', 'element_identifier'); @@ -1350,9 +1307,7 @@ class DashboardMenuNode extends MenuNode } $oPage->SetBreadCrumbEntry("ui-dashboard-".$this->sMenuId, $this->GetTitle(), $sDescription, '', $sIcon, iTopWebPage::ENUM_BREADCRUMB_ENTRY_ICON_TYPE_CSS_CLASSES); } - } - else - { + } else { $oPage->p("Error: failed to load dashboard file: '{$this->sDashboardFile}'"); } } @@ -1365,12 +1320,9 @@ class DashboardMenuNode extends MenuNode public function RenderEditor(WebPage $oPage) { $oDashboard = $this->GetDashboard(); - if ($oDashboard != null) - { + if ($oDashboard != null) { $oDashboard->RenderEditor($oPage); - } - else - { + } else { $oPage->p("Error: failed to load dashboard file: '{$this->sDashboardFile}'"); } } @@ -1382,13 +1334,10 @@ class DashboardMenuNode extends MenuNode public function AddDashlet($oDashlet) { $oDashboard = $this->GetDashboard(); - if ($oDashboard != null) - { + if ($oDashboard != null) { $oDashboard->AddDashlet($oDashlet); $oDashboard->Save(); - } - else - { + } else { throw new Exception("Error: failed to load dashboard file: '{$this->sDashboardFile}'"); } } @@ -1411,7 +1360,7 @@ class ShortcutContainerMenuNode extends MenuNode /** * @inheritDoc */ - public function RenderContent(WebPage $oPage, $aExtraParams = array()) + public function RenderContent(WebPage $oPage, $aExtraParams = []) { } @@ -1426,10 +1375,9 @@ class ShortcutContainerMenuNode extends MenuNode // $oBMSearch = new DBObjectSearch('Shortcut'); $oBMSearch->AddCondition('user_id', UserRights::GetUserId(), '='); - $oBMSet = new DBObjectSet($oBMSearch, array('friendlyname' => true)); // ascending on friendlyname + $oBMSet = new DBObjectSet($oBMSearch, ['friendlyname' => true]); // ascending on friendlyname $fRank = 1; - while ($oShortcut = $oBMSet->Fetch()) - { + while ($oShortcut = $oBMSet->Fetch()) { $sName = $this->GetMenuId().'_'.$oShortcut->GetKey(); new ShortcutMenuNode($sName, $oShortcut, $this->GetIndex(), $fRank++); } @@ -1440,7 +1388,6 @@ class ShortcutContainerMenuNode extends MenuNode } } - require_once(APPROOT.'application/shortcut.class.inc.php'); /** * This class defines a menu item which content is a shortcut. @@ -1477,12 +1424,10 @@ class ShortcutMenuNode extends MenuNode { $sContext = $this->oShortcut->Get('context'); $aContext = unserialize($sContext); - if (isset($aContext['menu'])) - { + if (isset($aContext['menu'])) { unset($aContext['menu']); } - foreach ($aContext as $sArgName => $sArgValue) - { + foreach ($aContext as $sArgName => $sArgValue) { $aExtraParams[$sArgName] = $sArgValue; } return parent::GetHyperlink($aExtraParams); @@ -1492,7 +1437,7 @@ class ShortcutMenuNode extends MenuNode * @inheritDoc * @throws \Exception */ - public function RenderContent(WebPage $oPage, $aExtraParams = array()) + public function RenderContent(WebPage $oPage, $aExtraParams = []) { ApplicationMenu::CheckMenuIdEnabled($this->GetMenuId()); $this->oShortcut->RenderContent($oPage, $aExtraParams); @@ -1529,11 +1474,9 @@ class ShortcutMenuNode extends MenuNode return true; } - public function GetEntriesCount() { return $this->GetEntriesCountFromOQL($this->oShortcut->Get('oql')); } } - diff --git a/application/query.class.inc.php b/application/query.class.inc.php index a4e199139..21554480f 100644 --- a/application/query.class.inc.php +++ b/application/query.class.inc.php @@ -1,4 +1,5 @@ "core/cmdb,view_in_gui,application,grant_by_profile", "key_type" => "autoincrement", "name_attcode" => "name", "state_attcode" => "", - "reconc_keys" => array(), + "reconc_keys" => [], "db_table" => "priv_query", "db_key_field" => "id", "db_finalclass_field" => "realclass", - ); + ]; MetaModel::Init_Params($aParams); - MetaModel::Init_AddAttribute(new AttributeString("name", array( + MetaModel::Init_AddAttribute(new AttributeString("name", [ "allowed_values" => null, "sql" => "name", "default_value" => null, "is_null_allowed" => false, - "depends_on" => array(), - ))); + "depends_on" => [], + ])); - MetaModel::Init_AddAttribute(new AttributeText("description", array( + MetaModel::Init_AddAttribute(new AttributeText("description", [ "allowed_values" => null, "sql" => "description", "default_value" => null, "is_null_allowed" => false, - "depends_on" => array(), - ))); + "depends_on" => [], + ])); - MetaModel::Init_AddAttribute(new AttributeEnum("is_template", array( + MetaModel::Init_AddAttribute(new AttributeEnum("is_template", [ 'allowed_values' => new ValueSetEnum('yes,no'), 'sql' => 'is_template', 'default_value' => 'no', 'is_null_allowed' => false, 'depends_on' => [], 'display_style' => 'radio_horizontal', - ))); + ])); - MetaModel::Init_AddAttribute(new AttributeInteger("export_count", array( + MetaModel::Init_AddAttribute(new AttributeInteger("export_count", [ "allowed_values" => null, "sql" => "export_count", "default_value" => 0, "is_null_allowed" => false, - "depends_on" => array(), + "depends_on" => [], "tracking_level" => ATTRIBUTE_TRACKING_NONE, - ))); + ])); - MetaModel::Init_AddAttribute(new AttributeDateTime("export_last_date", array( + MetaModel::Init_AddAttribute(new AttributeDateTime("export_last_date", [ "allowed_values" => null, "sql" => "export_last_date", "default_value" => null, "is_null_allowed" => true, - "depends_on" => array(), + "depends_on" => [], "tracking_level" => ATTRIBUTE_TRACKING_NONE, - ))); + ])); - MetaModel::Init_AddAttribute(new AttributeExternalKey("export_last_user_id", - array( - "targetclass"=>'User', - "allowed_values"=>null, - "sql"=>'user_id', - "is_null_allowed"=>true, - "depends_on"=>array(), - "display_style"=>'select', - "always_load_in_tables"=>false, - "on_target_delete"=>DEL_SILENT, + MetaModel::Init_AddAttribute(new AttributeExternalKey( + "export_last_user_id", + [ + "targetclass" => 'User', + "allowed_values" => null, + "sql" => 'user_id', + "is_null_allowed" => true, + "depends_on" => [], + "display_style" => 'select', + "always_load_in_tables" => false, + "on_target_delete" => DEL_SILENT, "tracking_level" => ATTRIBUTE_TRACKING_NONE, - ))); + ] + )); - MetaModel::Init_AddAttribute(new AttributeExternalField("export_last_user_contact", - array( - "allowed_values"=>null, - "extkey_attcode"=> "export_last_user_id", - "target_attcode"=>"contactid", + MetaModel::Init_AddAttribute(new AttributeExternalField( + "export_last_user_contact", + [ + "allowed_values" => null, + "extkey_attcode" => "export_last_user_id", + "target_attcode" => "contactid", "tracking_level" => ATTRIBUTE_TRACKING_NONE, - ))); + ] + )); // Display lists - MetaModel::Init_SetZListItems('details', - array('name', 'is_template', 'description')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('description')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems( + 'details', + ['name', 'is_template', 'description'] + ); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['description']); // Attributes to be displayed for a list // Search criteria - MetaModel::Init_SetZListItems('standard_search', array('name', 'description', 'is_template')); // Criteria of the std search form - MetaModel::Init_SetZListItems('default_search', - array('name', 'description', 'is_template')); // Criteria of the default search form + MetaModel::Init_SetZListItems('standard_search', ['name', 'description', 'is_template']); // Criteria of the std search form + MetaModel::Init_SetZListItems( + 'default_search', + ['name', 'description', 'is_template'] + ); // Criteria of the default search form // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form } - /** * @inheritdoc * * @since 3.1.0 */ - public function GetAttributeFlags($sAttCode, &$aReasons = array(), $sTargetState = '') + public function GetAttributeFlags($sAttCode, &$aReasons = [], $sTargetState = '') { // read only attribute - if (in_array($sAttCode, ['export_count', 'export_last_date', 'export_last_user_id'])){ + if (in_array($sAttCode, ['export_count', 'export_last_date', 'export_last_user_id'])) { return OPT_ATT_READONLY; } return parent::GetAttributeFlags($sAttCode, $aReasons, $sTargetState); } - /** * Return export url. * @@ -144,7 +151,7 @@ abstract class Query extends cmdbAbstractObject * @return string|null * @since 3.1.0 */ - abstract public function GetExportUrl(array $aValues = null) : ?string; + abstract public function GetExportUrl(array $aValues = null): ?string; /** * Update last export information. @@ -156,7 +163,7 @@ abstract class Query extends cmdbAbstractObject * @throws \MySQLException * @since 3.1.0 */ - public function UpdateLastExportInformation() : void + public function UpdateLastExportInformation(): void { // last export information $this->Set('export_last_date', date(AttributeDateTime::GetSQLFormat())); @@ -173,53 +180,56 @@ class QueryOQL extends Query { public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "core/cmdb,view_in_gui,application,grant_by_profile", "key_type" => "autoincrement", "name_attcode" => "name", "state_attcode" => "", - "reconc_keys" => array('oql', 'is_template'), + "reconc_keys" => ['oql', 'is_template'], "db_table" => "priv_query_oql", "db_key_field" => "id", "db_finalclass_field" => "", - ); + ]; MetaModel::Init_Params($aParams); MetaModel::Init_InheritAttributes(); - MetaModel::Init_AddAttribute(new AttributeOQL("oql", array( + MetaModel::Init_AddAttribute(new AttributeOQL("oql", [ "allowed_values" => null, "sql" => "oql", "default_value" => null, "is_null_allowed" => false, - "depends_on" => array(), - ))); - MetaModel::Init_AddAttribute(new AttributeText("fields", array( + "depends_on" => [], + ])); + MetaModel::Init_AddAttribute(new AttributeText("fields", [ "allowed_values" => null, "sql" => "fields", "default_value" => null, "is_null_allowed" => true, - "depends_on" => array(), - ))); + "depends_on" => [], + ])); // Rolled back to AttributeText until AttributeQueryAttCodeSet can manage fields order correctly //MetaModel::Init_AddAttribute(new AttributeQueryAttCodeSet("fields", array("allowed_values"=>null,"max_items" => 1000, "query_field" => "oql", "sql"=>"fields", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array('oql')))); // Display lists - MetaModel::Init_SetZListItems('details', - array( - 'col:col1' => array('fieldset:Query:baseinfo' => array('name', 'is_template', 'description', 'oql', 'fields')), - 'col:col2' => array('fieldset:Query:exportInfo' => array('export_count', 'export_last_date', 'export_last_user_id', 'export_last_user_contact')) - ) + MetaModel::Init_SetZListItems( + 'details', + [ + 'col:col1' => ['fieldset:Query:baseinfo' => ['name', 'is_template', 'description', 'oql', 'fields']], + 'col:col2' => ['fieldset:Query:exportInfo' => ['export_count', 'export_last_date', 'export_last_user_id', 'export_last_user_contact']], + ] ); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('description')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('list', ['description']); // Attributes to be displayed for a list // Search criteria - MetaModel::Init_SetZListItems('standard_search', - array('name', 'description', 'is_template', 'fields', 'oql')); // Criteria of the std search form + MetaModel::Init_SetZListItems( + 'standard_search', + ['name', 'description', 'is_template', 'fields', 'oql'] + ); // Criteria of the std search form } /** @inheritdoc */ - public function GetExportUrl(array $aValues = null) : ?string + public function GetExportUrl(array $aValues = null): ?string { - try{ + try { // retrieve attributes $sOql = $this->Get('oql'); @@ -233,17 +243,16 @@ class QueryOQL extends Query $aParameters = $oSearch->GetQueryParams(); foreach ($aParameters as $sParam => $val) { $paramValue = ($aValues === null || $aValues[$sParam] === null) ? $sParam : $aValues[$sParam]; - $sUrl .= '&arg_' . $sParam . '=' . $paramValue; + $sUrl .= '&arg_'.$sParam.'='.$paramValue; } return $sUrl; - } - catch(Exception $e){ + } catch (Exception $e) { return null; } } - function DisplayBareProperties(WebPage $oPage, $bEditMode = false, $sPrefix = '', $aExtraParams = array()) + public function DisplayBareProperties(WebPage $oPage, $bEditMode = false, $sPrefix = '', $aExtraParams = []) { $aFieldsMap = parent::DisplayBareProperties($oPage, $bEditMode, $sPrefix, $aExtraParams); $oPage->add_script("$('[name=\"attr_oql\"]').addClass('ibo-query-oql ibo-is-code'); $('[data-attribute-code=\"oql\"]').addClass('ibo-query-oql ibo-is-code');"); @@ -267,16 +276,14 @@ class QueryOQL extends Query if (count($aParameters) == 0) { $oBlock = new DisplayBlock($oSearch, 'list'); - $aExtraParams = array( + $aExtraParams = [ //'menu' => $sShowMenu, 'table_id' => 'query_preview_'.$this->getKey(), - ); + ]; $sBlockId = 'block_query_preview_'.$this->GetKey(); // make a unique id (edition occuring in the same DOM) $oBlock->Display($oPage, $sBlockId, $aExtraParams); } - } - catch - (OQLException $e) { + } catch (OQLException $e) { $oAlert = AlertUIBlockFactory::MakeForFailure(Dict::S('UI:RunQuery:Error'), $e->getHtmlDesc()) ->SetIsClosable(false) ->SetIsCollapsible(false); @@ -287,41 +294,38 @@ class QueryOQL extends Query return $aFieldsMap; } - -// Rolled back until 'fields' can be properly managed by AttributeQueryAttCodeSet -// -// public function ComputeValues() -// { -// parent::ComputeValues(); -// -// // Remove unwanted attribute codes -// $aChanges = $this->ListChanges(); -// if (isset($aChanges['fields'])) -// { -// $oAttDef = MetaModel::GetAttributeDef(get_class($this), 'fields'); -// $aArgs = array('this' => $this); -// $aAllowedValues = $oAttDef->GetAllowedValues($aArgs); -// -// /** @var \ormSet $oValue */ -// $oValue = $this->Get('fields'); -// $aValues = $oValue->GetValues(); -// $bChanged = false; -// foreach($aValues as $key => $sValue) -// { -// if (!isset($aAllowedValues[$sValue])) -// { -// unset($aValues[$key]); -// $bChanged = true; -// } -// } -// if ($bChanged) -// { -// $oValue->SetValues($aValues); -// $this->Set('fields', $oValue); -// } -// } -// } + // Rolled back until 'fields' can be properly managed by AttributeQueryAttCodeSet + // + // public function ComputeValues() + // { + // parent::ComputeValues(); + // + // // Remove unwanted attribute codes + // $aChanges = $this->ListChanges(); + // if (isset($aChanges['fields'])) + // { + // $oAttDef = MetaModel::GetAttributeDef(get_class($this), 'fields'); + // $aArgs = array('this' => $this); + // $aAllowedValues = $oAttDef->GetAllowedValues($aArgs); + // + // /** @var \ormSet $oValue */ + // $oValue = $this->Get('fields'); + // $aValues = $oValue->GetValues(); + // $bChanged = false; + // foreach($aValues as $key => $sValue) + // { + // if (!isset($aAllowedValues[$sValue])) + // { + // unset($aValues[$key]); + // $bChanged = true; + // } + // } + // if ($bChanged) + // { + // $oValue->SetValues($aValues); + // $this->Set('fields', $oValue); + // } + // } + // } } - -?> diff --git a/application/transaction.class.inc.php b/application/transaction.class.inc.php index d0572da12..6a6c3837f 100644 --- a/application/transaction.class.inc.php +++ b/application/transaction.class.inc.php @@ -1,9 +1,10 @@ Get('transactions_enabled'); - if (!$bTransactionsEnabled) - { + if (!$bTransactionsEnabled) { return 'notransactions'; // Any value will do } $sClass = 'privUITransaction'.MetaModel::GetConfig()->Get('transaction_storage'); - if (!class_exists($sClass, false)) - { + if (!class_exists($sClass, false)) { IssueLog::Error("Incorrect value '".MetaModel::GetConfig()->Get('transaction_storage')."' for 'transaction_storage', the class '$sClass' does not exists. Using privUITransactionSession instead for storing sessions."); $sClass = 'privUITransactionSession'; } @@ -62,16 +61,14 @@ class privUITransaction public static function IsTransactionValid($id, $bRemoveTransaction = true) { $bTransactionsEnabled = MetaModel::GetConfig()->Get('transactions_enabled'); - if (!$bTransactionsEnabled) - { + if (!$bTransactionsEnabled) { return true; // All values are valid } $sClass = 'privUITransaction'.MetaModel::GetConfig()->Get('transaction_storage'); - if (!class_exists($sClass, false)) - { + if (!class_exists($sClass, false)) { $sClass = 'privUITransactionSession'; } - + return $sClass::IsTransactionValid($id, $bRemoveTransaction); } @@ -83,16 +80,14 @@ class privUITransaction public static function RemoveTransaction($id) { $bTransactionsEnabled = MetaModel::GetConfig()->Get('transactions_enabled'); - if (!$bTransactionsEnabled) - { + if (!$bTransactionsEnabled) { return; // Nothing to do } $sClass = 'privUITransaction'.MetaModel::GetConfig()->Get('transaction_storage'); - if (!class_exists($sClass, false)) - { + if (!class_exists($sClass, false)) { $sClass = 'privUITransactionSession'; } - + $sClass::RemoveTransaction($id); } } @@ -114,17 +109,16 @@ class privUITransactionSession */ public static function GetNewTransactionId() { - if (!Session::IsSet('transactions')) - { + if (!Session::IsSet('transactions')) { Session::Set('transactions', []); } // Strictly speaking, the two lines below should be grouped together // by a critical section // sem_acquire($rSemIdentified); - $id = static::GetUserPrefix() . str_replace(array('.', ' '), '', microtime()); + $id = static::GetUserPrefix().str_replace(['.', ' '], '', microtime()); Session::Set(['transactions', $id], true); // sem_release($rSemIdentified); - + return (string)$id; } @@ -135,20 +129,17 @@ class privUITransactionSession * @param int $id Identifier of the transaction, as returned by GetNewTransactionId * @param bool $bRemoveTransaction True if the transaction must be removed * @return bool True if the transaction is valid, false otherwise - */ + */ public static function IsTransactionValid($id, $bRemoveTransaction = true) { $bResult = false; - if (Session::IsSet('transactions')) - { + if (Session::IsSet('transactions')) { // Strictly speaking, the eight lines below should be grouped together // inside the same critical section as above // sem_acquire($rSemIdentified); - if (Session::IsSet(['transactions', $id])) - { + if (Session::IsSet(['transactions', $id])) { $bResult = true; - if ($bRemoveTransaction) - { + if ($bRemoveTransaction) { Session::Unset(['transactions', $id]); } } @@ -156,7 +147,7 @@ class privUITransactionSession } return $bResult; } - + /** * Removes the transaction specified by its id * @param int $id The Identifier (as returned by GetNewTranscationId) of the transaction to be removed. @@ -164,17 +155,15 @@ class privUITransactionSession */ public static function RemoveTransaction($id) { - if (Session::IsSet('transactions')) - { + if (Session::IsSet('transactions')) { // Strictly speaking, the three lines below should be grouped together // inside the same critical section as above // sem_acquire($rSemIdentified); - if (Session::IsSet(['transactions', $id])) - { + if (Session::IsSet(['transactions', $id])) { Session::Unset(['transactions', $id]); } // sem_release($rSemIdentified); - } + } } /** @@ -197,7 +186,7 @@ class privUITransactionSession class privUITransactionFile { /** @var int Value to use when no user logged */ - const UNAUTHENTICATED_USER_ID = -666; + public const UNAUTHENTICATED_USER_ID = -666; /** * @return int current user id, or {@see self::UNAUTHENTICATED_USER_ID} if no user logged @@ -228,22 +217,18 @@ class privUITransactionFile */ public static function GetNewTransactionId() { - if (!is_dir(utils::GetDataPath().'transactions')) - { - if (!is_writable(APPROOT.'data')) - { + if (!is_dir(utils::GetDataPath().'transactions')) { + if (!is_writable(APPROOT.'data')) { throw new Exception('The directory "'.APPROOT.'data" must be writable to the application.'); } // condition avoids race condition N°2345 // See https://github.com/kalessil/phpinspectionsea/blob/master/docs/probable-bugs.md#mkdir-race-condition - if (!mkdir($concurrentDirectory = utils::GetDataPath().'transactions') && !is_dir($concurrentDirectory)) - { + if (!mkdir($concurrentDirectory = utils::GetDataPath().'transactions') && !is_dir($concurrentDirectory)) { throw new Exception('Failed to create the directory "'.utils::GetDataPath().'transactions". Ajust the rights on the parent directory or let an administrator create the transactions directory and give the web sever enough rights to write into it.'); } } - if (!is_writable(utils::GetDataPath().'transactions')) - { + if (!is_writable(utils::GetDataPath().'transactions')) { throw new Exception('The directory "'.utils::GetDataPath().'transactions" must be writable to the application.'); } @@ -277,8 +262,7 @@ class privUITransactionFile // Constraint the transaction file within utils::GetDataPath().'transactions' $sTransactionDir = realpath(utils::GetDataPath().'transactions'); $sFilepath = utils::RealPath($sTransactionDir.'/'.$id, $sTransactionDir); - if (($sFilepath === false) || (strlen($sTransactionDir) == strlen($sFilepath))) - { + if (($sFilepath === false) || (strlen($sTransactionDir) == strlen($sFilepath))) { return false; } @@ -297,15 +281,11 @@ class privUITransactionFile return false; } - if ($bRemoveTransaction) - { + if ($bRemoveTransaction) { $bResult = @unlink($sFilepath); - if (!$bResult) - { + if (!$bResult) { self::Error('IsTransactionValid: FAILED to remove transaction '.$id); - } - else - { + } else { self::Info('IsTransactionValid: OK. Removed transaction: '.$id); } } @@ -347,13 +327,11 @@ class privUITransactionFile } clearstatcache(); - $iLimit = time() - 24*3600; + $iLimit = time() - 24 * 3600; $sPattern = $sTransactionDir ? "$sTransactionDir/*" : utils::GetDataPath().'transactions/*'; $aTransactions = glob($sPattern); - foreach($aTransactions as $sFileName) - { - if (filemtime($sFileName) < $iLimit) - { + foreach ($aTransactions as $sFileName) { + if (filemtime($sFileName) < $iLimit) { @unlink($sFileName); self::Info('CleanupOldTransactions: Deleted transaction: '.$sFileName); } @@ -367,10 +345,9 @@ class privUITransactionFile protected static function GetPendingTransactions() { clearstatcache(); - $aResult = array(); + $aResult = []; $aTransactions = glob(utils::GetDataPath().'transactions/'.self::GetUserPrefix().'*'); - foreach($aTransactions as $sFileName) - { + foreach ($aTransactions as $sFileName) { $aResult[] = date('Y-m-d H:i:s', filemtime($sFileName)).' - '.basename($sFileName); } sort($aResult); @@ -398,13 +375,14 @@ class privUITransactionFile { self::Write('Warning | '.$sText); } - + protected static function Error($sText) { self::Write('Error | '.$sText); } - protected static function IsLogEnabled() { + protected static function IsLogEnabled() + { $oConfig = MetaModel::GetConfig(); if (is_null($oConfig)) { return false; diff --git a/application/utils.inc.php b/application/utils.inc.php index 21d5eb1e8..ea226e995 100644 --- a/application/utils.inc.php +++ b/application/utils.inc.php @@ -1,4 +1,5 @@ 0) - { + if (count(self::$aModes) > 0) { $bRet = end(self::$aModes); - } - else - { - if (self::$bPageMode === null) - { + } else { + if (self::$bPageMode === null) { self::InitArchiveMode(); } $bRet = self::$bPageMode; @@ -340,8 +322,7 @@ class utils { $bDefault = MetaModel::GetConfig()->Get('obsolescence.show_obsolete_data'); // default is false $bShow = appUserPreferences::GetPref('show_obsolete_data', $bDefault); - if (static::IsArchiveMode()) - { + if (static::IsArchiveMode()) { $bShow = true; } return $bShow; @@ -352,24 +333,17 @@ class utils global $argv; $retValue = $defaultValue; - if (!is_null(self::$m_aParamsFromFile)) - { - if (isset(self::$m_aParamsFromFile[$sName])) - { + if (!is_null(self::$m_aParamsFromFile)) { + if (isset(self::$m_aParamsFromFile[$sName])) { $retValue = self::$m_aParamsFromFile[$sName]; } } - if (isset($_REQUEST[$sName])) - { + if (isset($_REQUEST[$sName])) { $retValue = $_REQUEST[$sName]; - } - elseif ($bAllowCLI && isset($argv)) - { - foreach($argv as $iArg => $sArg) - { - if (preg_match('/^--'.$sName.'=(.*)$/', $sArg, $aMatches)) - { + } elseif ($bAllowCLI && isset($argv)) { + foreach ($argv as $iArg => $sArg) { + if (preg_match('/^--'.$sName.'=(.*)$/', $sArg, $aMatches)) { $retValue = $aMatches[1]; } } @@ -385,16 +359,12 @@ class utils public static function Sanitize($value, $defaultValue, $sSanitizationFilter) { - if ($value === $defaultValue) - { + if ($value === $defaultValue) { // Preserve the real default value (can be used to detect missing mandatory parameters) $retValue = $value; - } - else - { + } else { $retValue = self::Sanitize_Internal($value, $sSanitizationFilter); - if ($retValue === false) - { + if ($retValue === false) { $retValue = $defaultValue; } } @@ -425,22 +395,18 @@ class utils */ protected static function Sanitize_Internal($value, $sSanitizationFilter) { - if (is_array($value)) - { - $retValue = array(); - foreach ($value as $key => $val) - { + if (is_array($value)) { + $retValue = []; + foreach ($value as $key => $val) { $retValue[$key] = self::Sanitize_Internal($val, $sSanitizationFilter); // recursively check arrays - if ($retValue[$key] === false) - { + if ($retValue[$key] === false) { return false; } } return $retValue; } - switch ($sSanitizationFilter) - { + switch ($sSanitizationFilter) { case static::ENUM_SANITIZATION_FILTER_INTEGER: $retValue = filter_var($value, FILTER_SANITIZE_NUMBER_INT); break; @@ -469,57 +435,62 @@ class utils case static::ENUM_SANITIZATION_FILTER_PARAMETER: case static::ENUM_SANITIZATION_FILTER_FIELD_NAME: case static::ENUM_SANITIZATION_FILTER_TRANSACTION_ID: - switch ($sSanitizationFilter) - { + switch ($sSanitizationFilter) { case static::ENUM_SANITIZATION_FILTER_TRANSACTION_ID: // Same as parameter type but keep the dot character // transaction_id, the dot is mostly for Windows servers when using file storage as the tokens are named *.tmp // - See N°1835 // - Note: It must be included at the regexp beginning otherwise you'll get an invalid character error - $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => '/^[\. A-Za-z0-9_=-]*$/'))); + $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, ["options" => ["regexp" => '/^[\. A-Za-z0-9_=-]*$/']]); break; case static::ENUM_SANITIZATION_FILTER_ROUTE: case static::ENUM_SANITIZATION_FILTER_OPERATION: // - Routes should be of the "controller_namespace_code.controller_method_name" form // - Operations should be allowed to be namespaced as well even though then don't have dedicated controller yet - $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => '/^[\.A-Za-z0-9_-]*$/'))); + $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, ["options" => ["regexp" => '/^[\.A-Za-z0-9_-]*$/']]); break; case static::ENUM_SANITIZATION_FILTER_PARAMETER: - $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => '/^[ A-Za-z0-9_=-]*$/'))); // the '=', '%3D, '%2B', '%2F' + $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, ["options" => ["regexp" => '/^[ A-Za-z0-9_=-]*$/']]); // the '=', '%3D, '%2B', '%2F' // Characters are used in serialized filters (starting 2.5, only the url encoded versions are presents, but the "=" is kept for BC) break; case static::ENUM_SANITIZATION_FILTER_FIELD_NAME: - $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => '/^[A-Za-z0-9_]+(->[A-Za-z0-9_]+)*$/'))); // att_code or att_code->name or AttCode->Name or AttCode->Key2->Name + $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, ["options" => ["regexp" => '/^[A-Za-z0-9_]+(->[A-Za-z0-9_]+)*$/']]); // att_code or att_code->name or AttCode->Name or AttCode->Key2->Name break; case static::ENUM_SANITIZATION_FILTER_CONTEXT_PARAM: - $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => '/^[ A-Za-z0-9_=%:+-]*$/'))); + $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, ["options" => ["regexp" => '/^[ A-Za-z0-9_=%:+-]*$/']]); break; } break; - // For XML / HTML node identifiers + // For XML / HTML node identifiers case static::ENUM_SANITIZATION_FILTER_ELEMENT_IDENTIFIER: $retValue = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); - $retValue = filter_var($retValue, FILTER_VALIDATE_REGEXP, - ['options' => ['regexp' => '/^[A-Za-z0-9][A-Za-z0-9_-]*$/']]); + $retValue = filter_var( + $retValue, + FILTER_VALIDATE_REGEXP, + ['options' => ['regexp' => '/^[A-Za-z0-9][A-Za-z0-9_-]*$/']] + ); break; - // For XML / HTML node id selector + // For XML / HTML node id selector case static::ENUM_SANITIZATION_FILTER_ELEMENT_SELECTOR: - $retValue = filter_var($value, FILTER_VALIDATE_REGEXP, - ['options' => ['regexp' => '/^[#\.][A-Za-z0-9][A-Za-z0-9_-]*$/']]); + $retValue = filter_var( + $value, + FILTER_VALIDATE_REGEXP, + ['options' => ['regexp' => '/^[#\.][A-Za-z0-9][A-Za-z0-9_-]*$/']] + ); break; case static::ENUM_SANITIZATION_FILTER_VARIABLE_NAME: $retValue = preg_replace('/[^a-zA-Z0-9_]/', '', $value); break; - // For URL + // For URL case static::ENUM_SANITIZATION_FILTER_URL: $retValue = filter_var($value, FILTER_SANITIZE_URL); $retValue = filter_var($retValue, FILTER_VALIDATE_URL); @@ -528,7 +499,7 @@ class utils default: case static::ENUM_SANITIZATION_FILTER_RAW_DATA: $retValue = $value; - // Do nothing + // Do nothing } return $retValue; @@ -543,55 +514,53 @@ class utils * @return ormDocument The uploaded file (can be 'empty' if nothing was uploaded) * @throws \FileUploadException */ - public static function ReadPostedDocument($sName, $sIndex = null) + public static function ReadPostedDocument($sName, $sIndex = null) { $oDocument = new ormDocument(); // an empty document - if(isset($_FILES[$sName])) - { + if (isset($_FILES[$sName])) { $aFileInfo = $_FILES[$sName]; $sError = is_null($sIndex) ? $aFileInfo['error'] : $aFileInfo['error'][$sIndex]; - switch($sError) - { + switch ($sError) { case UPLOAD_ERR_OK: - $sTmpName = is_null($sIndex) ? $aFileInfo['tmp_name'] : $aFileInfo['tmp_name'][$sIndex]; - $sMimeType = is_null($sIndex) ? $aFileInfo['type'] : $aFileInfo['type'][$sIndex]; - $sName = is_null($sIndex) ? $aFileInfo['name'] : $aFileInfo['name'][$sIndex]; + $sTmpName = is_null($sIndex) ? $aFileInfo['tmp_name'] : $aFileInfo['tmp_name'][$sIndex]; + $sMimeType = is_null($sIndex) ? $aFileInfo['type'] : $aFileInfo['type'][$sIndex]; + $sName = is_null($sIndex) ? $aFileInfo['name'] : $aFileInfo['name'][$sIndex]; - $doc_content = file_get_contents($sTmpName); + $doc_content = file_get_contents($sTmpName); $sMimeType = self::GetFileMimeType($sTmpName); $oDocument = new ormDocument($doc_content, $sMimeType, $sName); - break; + break; case UPLOAD_ERR_NO_FILE: - // no file to load, it's a normal case, just return an empty document - break; + // no file to load, it's a normal case, just return an empty document + break; case UPLOAD_ERR_FORM_SIZE: case UPLOAD_ERR_INI_SIZE: - throw new FileUploadException(Dict::Format('UI:Error:UploadedFileTooBig', ini_get('upload_max_filesize'))); - break; + throw new FileUploadException(Dict::Format('UI:Error:UploadedFileTooBig', ini_get('upload_max_filesize'))); + break; case UPLOAD_ERR_PARTIAL: - throw new FileUploadException(Dict::S('UI:Error:UploadedFileTruncated.')); - break; + throw new FileUploadException(Dict::S('UI:Error:UploadedFileTruncated.')); + break; case UPLOAD_ERR_NO_TMP_DIR: - throw new FileUploadException(Dict::S('UI:Error:NoTmpDir')); - break; + throw new FileUploadException(Dict::S('UI:Error:NoTmpDir')); + break; case UPLOAD_ERR_CANT_WRITE: - throw new FileUploadException(Dict::Format('UI:Error:CannotWriteToTmp_Dir', ini_get('upload_tmp_dir'))); - break; + throw new FileUploadException(Dict::Format('UI:Error:CannotWriteToTmp_Dir', ini_get('upload_tmp_dir'))); + break; case UPLOAD_ERR_EXTENSION: - $sName = is_null($sIndex) ? $aFileInfo['name'] : $aFileInfo['name'][$sIndex]; - throw new FileUploadException(Dict::Format('UI:Error:UploadStoppedByExtension_FileName', $sName)); - break; + $sName = is_null($sIndex) ? $aFileInfo['name'] : $aFileInfo['name'][$sIndex]; + throw new FileUploadException(Dict::Format('UI:Error:UploadStoppedByExtension_FileName', $sName)); + break; default: - throw new FileUploadException(Dict::Format('UI:Error:UploadFailedUnknownCause_Code', $sError)); - break; + throw new FileUploadException(Dict::Format('UI:Error:UploadFailedUnknownCause_Code', $sError)); + break; } } @@ -610,26 +579,22 @@ class utils */ public static function ReadMultipleSelection($oFullSetFilter) { - $aSelectedObj = utils::ReadParam('selectObject', array()); + $aSelectedObj = utils::ReadParam('selectObject', []); $sSelectionMode = utils::ReadParam('selectionMode', ''); if ($sSelectionMode != '') { // Paginated selection - $aExceptions = utils::ReadParam('storedSelection', array()); + $aExceptions = utils::ReadParam('storedSelection', []); if ($sSelectionMode == 'positive') { // Only the explicitely listed items are selected $aSelectedObj = $aExceptions; - } - else - { + } else { // All items of the set are selected, except the one explicitely listed - $aSelectedObj = array(); + $aSelectedObj = []; $oFullSet = new DBObjectSet($oFullSetFilter); $sClassAlias = $oFullSetFilter->GetClassAlias(); - $oFullSet->OptimizeColumnLoad(array($sClassAlias => array('friendlyname'))); // We really need only the IDs but it does not work since id is not a real field - while($oObj = $oFullSet->Fetch()) - { - if (!in_array($oObj->GetKey(), $aExceptions)) - { + $oFullSet->OptimizeColumnLoad([$sClassAlias => ['friendlyname']]); // We really need only the IDs but it does not work since id is not a real field + while ($oObj = $oFullSet->Fetch()) { + if (!in_array($oObj->GetKey(), $aExceptions)) { $aSelectedObj[] = $oObj->GetKey(); } } @@ -650,45 +615,37 @@ class utils { $sSelectionMode = utils::ReadParam('selectionMode', ''); - if ($sSelectionMode != 'positive' && $sSelectionMode != 'negative') - { + if ($sSelectionMode != 'positive' && $sSelectionMode != 'negative') { throw new CoreException('selectionMode must be either positive or negative'); } // Paginated selection - $aSelectedIds = utils::ReadParam('storedSelection', array()); - $aSelectedObjIds = utils::ReadParam('selectObject', array()); + $aSelectedIds = utils::ReadParam('storedSelection', []); + $aSelectedObjIds = utils::ReadParam('selectObject', []); //it means that the user has selected all the results of the search query - if (count($aSelectedObjIds) > 0 ) - { - $sFilter=utils::ReadParam("sFilter",'',false,'raw_data'); - if ($sFilter!='') - { - $oFullSetFilter=DBSearch::unserialize($sFilter); + if (count($aSelectedObjIds) > 0) { + $sFilter = utils::ReadParam("sFilter", '', false, 'raw_data'); + if ($sFilter != '') { + $oFullSetFilter = DBSearch::unserialize($sFilter); } } - if (count($aSelectedIds) > 0 ) - { - if ($sSelectionMode == 'positive') - { + if (count($aSelectedIds) > 0) { + if ($sSelectionMode == 'positive') { // Only the explicitly listed items are selected $oFullSetFilter->AddCondition('id', $aSelectedIds, 'IN'); - } - else - { + } else { // All items of the set are selected, except the one explicitly listed $oFullSetFilter->AddCondition('id', $aSelectedIds, 'NOTIN'); } } - $aSelectedObj = array(); + $aSelectedObj = []; $oFullSet = new DBObjectSet($oFullSetFilter); $sClassAlias = $oFullSetFilter->GetClassAlias(); - $oFullSet->OptimizeColumnLoad(array($sClassAlias => array('friendlyname'))); // We really need only the IDs but it does not work since id is not a real field - while ($oObj = $oFullSet->Fetch()) - { + $oFullSet->OptimizeColumnLoad([$sClassAlias => ['friendlyname']]); // We really need only the IDs but it does not work since id is not a real field + while ($oObj = $oFullSet->Fetch()) { $aSelectedObj[$oObj->GetKey()] = $oObj->Get('friendlyname'); } @@ -719,8 +676,7 @@ class utils */ public static function GetUploadTempId($sTransactionId = null) { - if ($sTransactionId === null) - { + if ($sTransactionId === null) { $sTransactionId = static::GetNewTransactionId(); } return $sTransactionId; @@ -753,8 +709,10 @@ class utils switch ($sUnit) { case 'G': $iReturn *= 1024; + // no break case 'M': $iReturn *= 1024; + // no break case 'K': $iReturn *= 1024; } @@ -828,8 +786,7 @@ class utils { $sReturn = ''; // Kilobytes - if ($value >= 1024) - { + if ($value >= 1024) { $sReturn = 'K'; $value = $value / 1024; if ($iPrecision === 0) { @@ -837,27 +794,24 @@ class utils } } // Megabytes - if ($value >= 1024) - { + if ($value >= 1024) { $sReturn = 'M'; $value = $value / 1024; } // Gigabytes - if ($value >= 1024) - { + if ($value >= 1024) { $sReturn = 'G'; $value = $value / 1024; } // Terabytes - if ($value >= 1024) - { + if ($value >= 1024) { $sReturn = 'T'; $value = $value / 1024; } $value = round($value, $iPrecision); - return $value . '' . $sReturn . 'B'; + return $value.''.$sReturn.'B'; } /** @@ -876,7 +830,7 @@ class utils static $aDateTokens = null; static $aDateRegexps = null; if (is_null($aDateTokens)) { - $aSpec = array( + $aSpec = [ '%d' => '(?[0-9]{2})', '%m' => '(?[0-9]{2})', '%y' => '(?[0-9]{2})', @@ -884,15 +838,14 @@ class utils '%H' => '(?[0-2][0-9])', '%i' => '(?[0-5][0-9])', '%s' => '(?[0-5][0-9])', - ); + ]; $aDateTokens = array_keys($aSpec); $aDateRegexps = array_values($aSpec); } - $sDateRegexp = str_replace($aDateTokens, $aDateRegexps, $sFormat); + $sDateRegexp = str_replace($aDateTokens, $aDateRegexps, $sFormat); - if (preg_match('!^(?)'.$sDateRegexp.'(?)$!', $sDate, $aMatches)) - { + if (preg_match('!^(?)'.$sDateRegexp.'(?)$!', $sDate, $aMatches)) { $sYear = isset($aMatches['year']) ? $aMatches['year'] : 0; $sMonth = isset($aMatches['month']) ? $aMatches['month'] : 1; $sDay = isset($aMatches['day']) ? $aMatches['day'] : 1; @@ -900,12 +853,10 @@ class utils $sMinute = isset($aMatches['minute']) ? $aMatches['minute'] : 0; $sSecond = isset($aMatches['second']) ? $aMatches['second'] : 0; return strtotime("$sYear-$sMonth-$sDay $sHour:$sMinute:$sSecond"); + } else { + return false; } - else - { - return false; - } - // http://www.spaweditor.com/scripts/regex/index.php + // http://www.spaweditor.com/scripts/regex/index.php } /** @@ -1008,8 +959,7 @@ class utils } $sProductionEnvConfigPath = self::GetConfigFilePath('production'); - if (file_exists($sProductionEnvConfigPath)) - { + if (file_exists($sProductionEnvConfigPath)) { $oProductionEnvDiskConfig = new Config($sProductionEnvConfigPath); self::SetConfig($oProductionEnvDiskConfig); return self::$oConfig; @@ -1020,13 +970,11 @@ class utils public static function InitTimeZone($oConfig = null) { - if (is_null($oConfig)) - { + if (is_null($oConfig)) { $oConfig = self::GetConfig(); } $sItopTimeZone = $oConfig->Get('timezone'); - if (!empty($sItopTimeZone)) - { + if (!empty($sItopTimeZone)) { date_default_timezone_set($sItopTimeZone); } // else @@ -1065,21 +1013,14 @@ class utils */ public static function GetAbsoluteUrlAppRoot($bForceTrustProxy = false) { - if (static::$sAbsoluteUrlAppRootCache === null || $bForceTrustProxy) - { + if (static::$sAbsoluteUrlAppRootCache === null || $bForceTrustProxy) { static::$sAbsoluteUrlAppRootCache = self::GetConfig()->Get('app_root_url'); - if (static::$sAbsoluteUrlAppRootCache == '') - { + if (static::$sAbsoluteUrlAppRootCache == '') { static::$sAbsoluteUrlAppRootCache = self::GetDefaultUrlAppRoot($bForceTrustProxy); - } - elseif (strpos(static::$sAbsoluteUrlAppRootCache, SERVER_NAME_PLACEHOLDER) > -1) - { - if (isset($_SERVER['SERVER_NAME'])) - { + } elseif (strpos(static::$sAbsoluteUrlAppRootCache, SERVER_NAME_PLACEHOLDER) > -1) { + if (isset($_SERVER['SERVER_NAME'])) { $sServerName = $_SERVER['SERVER_NAME']; - } - else - { + } else { // CLI mode ? $sServerName = php_uname('n'); } @@ -1112,7 +1053,6 @@ class utils return self::GetAppRootUrl($sCurrentScript, $sAppRoot, $sAbsoluteUrl); } - /** * Build the current absolute URL from the server's variables. * @@ -1203,11 +1143,9 @@ class utils { // $_SERVER['REQUEST_URI'] is empty when running on IIS // Let's use Ivan Tcholakov's fix (found on www.dokeos.com) - if (empty($_SERVER['REQUEST_URI'])) - { + if (empty($_SERVER['REQUEST_URI'])) { $sPath = $_SERVER['SCRIPT_NAME']; - if (!empty($_SERVER['QUERY_STRING'])) - { + if (!empty($_SERVER['QUERY_STRING'])) { $sPath .= '?'.$_SERVER['QUERY_STRING']; } $_SERVER['REQUEST_URI'] = $sPath; @@ -1232,21 +1170,15 @@ class utils $sCurrentRelativePath = str_ireplace($sAppRoot, '', $sCurrentScript); $sAppRootPos = strpos($sAbsoluteUrl, $sCurrentRelativePath); - if ($sAppRootPos !== false) - { + if ($sAppRootPos !== false) { $sAppRootUrl = substr($sAbsoluteUrl, 0, $sAppRootPos); // remove the current page and path - } - else - { + } else { // Second attempt without index.php at the end... $sCurrentRelativePath = str_ireplace('index.php', '', $sCurrentRelativePath); $sAppRootPos = strpos($sAbsoluteUrl, $sCurrentRelativePath); - if ($sAppRootPos !== false) - { + if ($sAppRootPos !== false) { $sAppRootUrl = substr($sAbsoluteUrl, 0, $sAppRootPos); // remove the current page and path - } - else - { + } else { // No luck... throw new Exception("Failed to determine application root path $sAbsoluteUrl ($sCurrentRelativePath) APPROOT:'$sAppRoot'"); } @@ -1263,13 +1195,10 @@ class utils */ public static function GetAppRevisionNumber() { - if (ITOP_REVISION == 'svn') - { + if (ITOP_REVISION == 'svn') { // This is NOT a version built using the build system, just display the main version $sRevisionNumber = Dict::Format('UI:iTopVersion:Short', ITOP_APPLICATION, ITOP_VERSION); - } - else - { + } else { // This is a build made from SVN, let display the full information $sRevisionNumber = Dict::Format('UI:iTopVersion:Long', ITOP_APPLICATION, ITOP_VERSION, ITOP_REVISION, ITOP_BUILD_DATE); } @@ -1297,16 +1226,11 @@ class utils $bTrustProxy = $bForceTrustProxy || self::IsProxyTrusted(); - if ($bTrustProxy && !empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) - { + if ($bTrustProxy && !empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) { $bSecured = ($_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https'); - } - elseif ($bTrustProxy && !empty($_SERVER['HTTP_X_FORWARDED_PROTOCOL'])) - { + } elseif ($bTrustProxy && !empty($_SERVER['HTTP_X_FORWARDED_PROTOCOL'])) { $bSecured = ($_SERVER['HTTP_X_FORWARDED_PROTOCOL'] === 'https'); - } - elseif ((!empty($_SERVER['HTTPS'])) && (strtolower($_SERVER['HTTPS']) != 'off')) - { + } elseif ((!empty($_SERVER['HTTPS'])) && (strtolower($_SERVER['HTTPS']) != 'off')) { $bSecured = (strcasecmp($_SERVER['HTTPS'], 'off') !== 0); } @@ -1320,7 +1244,7 @@ class utils * 2) the user did not log-in using the "basic" mode (i.e basic authentication) or by passing credentials in the URL * @return boolean True if logoff is supported, false otherwise */ - static function CanLogOff() + public static function CanLogOff() { return Session::Get('can_logoff', false); } @@ -1334,16 +1258,15 @@ class utils return Session::GetLog(); } - static function DebugBacktrace($iLimit = 5) - { + public static function DebugBacktrace($iLimit = 5) + { $aFullTrace = debug_backtrace(); - $aLightTrace = array(); - for($i=1; ($i<=$iLimit && $i < count($aFullTrace)); $i++) // Skip the last function call... which is the call to this function ! - { + $aLightTrace = []; + for ($i = 1; ($i <= $iLimit && $i < count($aFullTrace)); $i++) { // Skip the last function call... which is the call to this function ! $aLightTrace[$i] = $aFullTrace[$i]['function'].'(), called from line '.$aFullTrace[$i]['line'].' in '.$aFullTrace[$i]['file']; } echo "

".print_r($aLightTrace, true)."

\n"; - } + } /** * Execute the given iTop PHP script, passing it the current credentials @@ -1385,7 +1308,7 @@ class utils $aArguments['param_file'] = $sParamFile; } - $aArgs = array(); + $aArgs = []; foreach ($aArguments as $sName => $value) { // Note: See comment from the 23-Apr-2004 03:30 in the PHP documentation // It suggests to rely on pctnl_* function instead of using escapeshellargs @@ -1416,7 +1339,7 @@ class utils throw new Exception(Dict::S('Core:ExecProcess:Code255')." - ".$sCommand.":\n".$sErrors); } - return array($iRes, $aOutput); + return [$iRes, $aOutput]; } /** @@ -1434,7 +1357,7 @@ class utils */ public static function GetCompiledEnvironmentPath(): string { - return APPROOT . 'env-' . MetaModel::GetEnvironment() . '/'; + return APPROOT.'env-'.MetaModel::GetEnvironment().'/'; } /** @@ -1507,8 +1430,7 @@ class utils // 1st - add standard built-in menu items // - switch($iMenuId) - { + switch ($iMenuId) { case iPopupMenuExtension::MENU_OBJLIST_ACTIONS: // No native action there yet break; @@ -1538,8 +1460,10 @@ class utils if (strlen($sUrl) < SERVER_MAX_URL_LENGTH) { // Static menus: Email this page, CSV Export & Add to Dashboard - $aResult[] = new URLPopupMenuItem('UI:Menu:EMail', Dict::S('UI:Menu:EMail'), - "mailto:?body=".urlencode($sUrl).' ' // Add an extra space to make it work in Outlook + $aResult[] = new URLPopupMenuItem( + 'UI:Menu:EMail', + Dict::S('UI:Menu:EMail'), + "mailto:?body=".urlencode($sUrl).' ' // Add an extra space to make it work in Outlook ); } @@ -1547,18 +1471,17 @@ class utils // Bulk export actions $aResult[] = new JSPopupMenuItem('UI:Menu:CSVExport', Dict::S('UI:Menu:CSVExport'), "ExportListDlg('$sOQL', '$sDataTableId', 'csv', ".json_encode(Dict::S('UI:Menu:CSVExport')).")"); $aResult[] = new JSPopupMenuItem('UI:Menu:ExportXLSX', Dict::S('ExcelExporter:ExportMenu'), "ExportListDlg('$sOQL', '$sDataTableId', 'xlsx', ".json_encode(Dict::S('ExcelExporter:ExportMenu')).")"); - if (extension_loaded('gd')) - { + if (extension_loaded('gd')) { // PDF export requires GD $aResult[] = new JSPopupMenuItem('UI:Menu:ExportPDF', Dict::S('UI:Menu:ExportPDF'), "ExportListDlg('$sOQL', '$sDataTableId', 'pdf', ".json_encode(Dict::S('UI:Menu:ExportPDF')).")"); } } $aResult[] = new JSPopupMenuItem('UI:Menu:AddToDashboard', Dict::S('UI:Menu:AddToDashboard'), "DashletCreationDlg('$sOQL', '$sContext')"); $aResult[] = new JSPopupMenuItem('UI:Menu:ShortcutList', Dict::S('UI:Menu:ShortcutList'), "ShortcutListDlg('$sOQL', '$sDataTableId', '$sContext')"); - if (ApplicationMenu::IsMenuIdEnabled('RunQueriesMenu')) { - $oMenuItemPlay = new JSPopupMenuItem('UI:Menu:OpenOQL', Dict::S('UI:Menu:OpenOQL'), "OpenOql('$sOQL')"); - $aResult[] = $oMenuItemPlay; - } + if (ApplicationMenu::IsMenuIdEnabled('RunQueriesMenu')) { + $oMenuItemPlay = new JSPopupMenuItem('UI:Menu:OpenOQL', Dict::S('UI:Menu:OpenOQL'), "OpenOql('$sOQL')"); + $aResult[] = $oMenuItemPlay; + } break; @@ -1571,7 +1494,7 @@ class utils $oContainerBlock->AddJsFileRelPath('js/jquery.dragtable.js'); $oContainerBlock->AddCssFileRelPath('css/dragtable.css'); - $aResult = array( + $aResult = [ new SeparatorPopupMenuItem(), // Static menus: Email this page & CSV Export new URLPopupMenuItem('UI:Menu:EMail', Dict::S('UI:Menu:EMail'), "mailto:?subject=".urlencode($oObj->GetRawName())."&body=".urlencode($sUrl).' '), // Add an extra space to make it work in Outlook @@ -1579,7 +1502,7 @@ class utils new JSPopupMenuItem('UI:Menu:ExportXLSX', Dict::S('ExcelExporter:ExportMenu'), "ExportListDlg('$sOQL', '', 'xlsx', ".json_encode(Dict::S('ExcelExporter:ExportMenu')).")"), new SeparatorPopupMenuItem(), new URLPopupMenuItem('UI:Menu:PrintableVersion', Dict::S('UI:Menu:PrintableVersion'), $sUrl.'&printable=1', '_blank'), - ); + ]; break; case iPopupMenuExtension::MENU_DASHBOARD_ACTIONS: @@ -1595,11 +1518,11 @@ class utils $sDashboardFileJS = addslashes($sDashboardFileRelative); $sDashboardFileURL = urlencode($sDashboardFileRelative); $sUploadDashboardTransactId = utils::GetNewTransactionId(); - $aResult = array( + $aResult = [ new SeparatorPopupMenuItem(), new URLPopupMenuItem('UI:ExportDashboard', Dict::S('UI:ExportDashBoard'), utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php?operation=export_dashboard&id='.$sDashboardId.'&file='.$sDashboardFileURL), new JSPopupMenuItem('UI:ImportDashboard', Dict::S('UI:ImportDashBoard'), "UploadDashboard({dashboard_id: '$sDashboardId', file: '$sDashboardFileJS', title: '$sDlgTitle', text: '$sDlgText', close_btn: '$sCloseBtn', transaction: '$sUploadDashboardTransactId' })"), - ); + ]; if ($oDashboard->GetReloadURL()) { $aResult[] = new SeparatorPopupMenuItem(); $aResult[] = new URLPopupMenuItem('UI:Menu:PrintableVersion', Dict::S('UI:Menu:PrintableVersion'), $oDashboard->GetReloadURL().'&printable=1', '_blank'); @@ -1786,8 +1709,7 @@ SQL; */ public static function GetConfigFilePathRelative($sEnvironment = null) { - if (is_null($sEnvironment)) - { + if (is_null($sEnvironment)) { $sEnvironment = self::GetCurrentEnvironment(); } return "conf/".$sEnvironment.'/'.ITOP_CONFIG_FILE; @@ -1824,7 +1746,7 @@ SQL; * * @throws \Exception */ - public static function GetAbsoluteUrlModulePage($sModule, $sPage, $aArguments = array(), $sEnvironment = null) + public static function GetAbsoluteUrlModulePage($sModule, $sPage, $aArguments = [], $sEnvironment = null) { $aArgs = self::GetExecPageArguments($sModule, $sPage, $aArguments, $sEnvironment); $sArgs = http_build_query($aArgs); @@ -1841,17 +1763,15 @@ SQL; * @return string[] key/value pair for the exec page query string. Warning : values are not url encoded ! * @throws \Exception if one of the argument has a reserved name */ - public static function GetExecPageArguments($sModule, $sPage, $aArguments = array(), $sEnvironment = null) + public static function GetExecPageArguments($sModule, $sPage, $aArguments = [], $sEnvironment = null) { $sEnvironment = is_null($sEnvironment) ? self::GetCurrentEnvironment() : $sEnvironment; - $aArgs = array(); + $aArgs = []; $aArgs['exec_module'] = $sModule; $aArgs['exec_page'] = $sPage; $aArgs['exec_env'] = $sEnvironment; - foreach($aArguments as $sName => $sValue) - { - if (($sName == 'exec_module') || ($sName == 'exec_page') || ($sName == 'exec_env')) - { + foreach ($aArguments as $sName => $sValue) { + if (($sName == 'exec_module') || ($sName == 'exec_page') || ($sName == 'exec_env')) { throw new Exception("Module page: $sName is a reserved page argument name"); } $aArgs[$sName] = $sValue; @@ -1877,17 +1797,13 @@ SQL; */ public static function MakeUniqueName($sProposed, $aExisting) { - if (in_array($sProposed, $aExisting)) - { + if (in_array($sProposed, $aExisting)) { $i = 1; - while (in_array($sProposed.$i, $aExisting) && ($i < 50)) - { + while (in_array($sProposed.$i, $aExisting) && ($i < 50)) { $i++; } return $sProposed.$i; - } - else - { + } else { return $sProposed; } } @@ -1899,7 +1815,7 @@ SQL; */ public static function GetSafeId($sId) { - return str_replace(array(':', '[', ']', '+', '-', ' '), '_', $sId); + return str_replace([':', '[', ']', '+', '-', ' '], '_', $sId); } /** @@ -1925,7 +1841,7 @@ SQL; * * @since 3.1.0 N°6172 as curl ext is now mandatory, method will crash with a ApplicationException if this PHP extension isn't available */ - public static function DoPostRequest($sUrl, $aData, $sOptionnalHeaders = null, &$aResponseHeaders = null, $aCurlOptions = array()) + public static function DoPostRequest($sUrl, $aData, $sOptionnalHeaders = null, &$aResponseHeaders = null, $aCurlOptions = []) { if (false === function_exists('curl_init')) { throw new ApplicationException('\utils::DoPostRequest method called whereas the CURL PHP extension isn\'t available !'); @@ -1938,12 +1854,12 @@ SQL; $aHeaders = explode("\n", $sOptionnalHeaders ?? ''); // N°3267 - Webservices: Fix optional headers not being taken into account // See https://www.php.net/curl_setopt CURLOPT_HTTPHEADER - $aHTTPHeaders = array(); + $aHTTPHeaders = []; foreach ($aHeaders as $sHeaderString) { $aHTTPHeaders[] = trim($sHeaderString); } // Default options, can be overloaded/extended with the 4th parameter of this method, see above $aCurlOptions - $aOptions = array( + $aOptions = [ CURLOPT_RETURNTRANSFER => true, // return the content of the request CURLOPT_HEADER => false, // don't return the headers in the output CURLOPT_FOLLOWLOCATION => true, // follow redirects @@ -1960,7 +1876,7 @@ SQL; CURLOPT_POST => count($aData), CURLOPT_POSTFIELDS => http_build_query($aData), CURLOPT_HTTPHEADER => $aHTTPHeaders, - ); + ]; $aAllOptions = $aCurlOptions + $aOptions; $ch = curl_init($sUrl); @@ -1987,22 +1903,22 @@ SQL; /** * Get a standard list of character sets * - * @param array $aAdditionalEncodings Additional values + * @param array $aAdditionalEncodings Additional values * @return array of iconv code => english label, sorted by label */ - public static function GetPossibleEncodings($aAdditionalEncodings = array()) + public static function GetPossibleEncodings($aAdditionalEncodings = []) { // Encodings supported: // ICONV_CODE => Display Name // Each iconv installation supports different encodings // Some reasonably common and useful encodings are listed here - $aPossibleEncodings = array( + $aPossibleEncodings = [ 'UTF-8' => 'Unicode (UTF-8)', 'ISO-8859-1' => 'Western (ISO-8859-1)', 'WINDOWS-1251' => 'Cyrilic (Windows 1251)', 'WINDOWS-1252' => 'Western (Windows 1252)', 'ISO-8859-15' => 'Western (ISO-8859-15)', - ); + ]; $aPossibleEncodings = array_merge($aPossibleEncodings, $aAdditionalEncodings); asort($aPossibleEncodings); return $aPossibleEncodings; @@ -2134,7 +2050,7 @@ SQL; } // else log the error if needed if ($bLogErrors) { - IssueLog::Warning("Format string requires $iExpectedCount arguments, but only $iActualCount provided. Format: '$sFormat'" ); + IssueLog::Warning("Format string requires $iExpectedCount arguments, but only $iActualCount provided. Format: '$sFormat'"); } // Create a replacement map @@ -2159,7 +2075,7 @@ SQL; } // Remove any remaining nulls (for positions that weren't referenced) - $aReplacements = array_filter($aReplacements, static function($val) { return $val !== null; }); + $aReplacements = array_filter($aReplacements, static function ($val) { return $val !== null; }); } else { // For non-positional, we need to map each position $aReplacements = []; @@ -2209,8 +2125,7 @@ SQL; try { //return ''.$sHtml; return Html2Text::convert(''.$sHtml, ['ignore_errors' => true]); - } - catch (Exception $e) { + } catch (Exception $e) { return $e->getMessage(); } } @@ -2223,7 +2138,7 @@ SQL; */ public static function TextToHtml($sText) { - if (static::IsNullOrEmptyString($sText)){ + if (static::IsNullOrEmptyString($sText)) { return ''; } $sText = str_replace("\r\n", "\n", $sText); @@ -2242,24 +2157,21 @@ SQL; public static function GetCSSFromSASS($sSassRelPath, $aImportPaths = null) { // Avoiding compilation if file is already a css file. - if (preg_match('/\.css(\?.*)?$/', $sSassRelPath)) - { + if (preg_match('/\.css(\?.*)?$/', $sSassRelPath)) { return $sSassRelPath; } // Setting import paths - if ($aImportPaths === null) - { - $aImportPaths = array(); + if ($aImportPaths === null) { + $aImportPaths = []; } - $aImportPaths[] = APPROOT . '/css'; + $aImportPaths[] = APPROOT.'/css'; $sSassPath = APPROOT.$sSassRelPath; $sCssRelPath = preg_replace('/\.scss$/', '.css', $sSassRelPath); $sCssPath = APPROOT.$sCssRelPath; clearstatcache(); - if (!file_exists($sCssPath) || (is_writable($sCssPath) && (filemtime($sCssPath) < filemtime($sSassPath)))) - { + if (!file_exists($sCssPath) || (is_writable($sCssPath) && (filemtime($sCssPath) < filemtime($sSassPath)))) { $sCss = static::CompileCSSFromSASS(file_get_contents($sSassPath), $aImportPaths); file_put_contents($sCssPath, $sCss); } @@ -2277,7 +2189,7 @@ SQL; * * @since 2.7.0 */ - public static function CompileCSSFromSASS($sSassContent, $aImportPaths = array(), $aVariables = array()) + public static function CompileCSSFromSASS($sSassContent, $aImportPaths = [], $aVariables = []) { $oSass = new Compiler(); $oSass->setOutputStyle(OutputStyle::COMPRESSED); @@ -2327,17 +2239,17 @@ SQL; $data = $sPrefix; $data .= __FILE__; $data .= mt_rand(); - $hash = strtoupper(hash('ripemd128', $uid . md5($data))); - $sUUID = '{' . - substr($hash, 0, 8) . - '-' . - substr($hash, 8, 4) . - '-' . - substr($hash, 12, 4) . - '-' . - substr($hash, 16, 4) . - '-' . - substr($hash, 20, 12) . + $hash = strtoupper(hash('ripemd128', $uid.md5($data))); + $sUUID = '{'. + substr($hash, 0, 8). + '-'. + substr($hash, 8, 4). + '-'. + substr($hash, 12, 4). + '-'. + substr($hash, 16, 4). + '-'. + substr($hash, 20, 12). '}'; return $sUUID; } @@ -2350,7 +2262,7 @@ SQL; */ public static function GetCurrentModuleName($iCallDepth = 0) { - return ModuleService::GetInstance()->GetCurrentModuleName($iCallDepth + 1); + return ModuleService::GetInstance()->GetCurrentModuleName($iCallDepth + 1); } /** @@ -2397,7 +2309,7 @@ SQL; */ public static function GetCurrentModuleSetting($sProperty, $defaultvalue = null) { - return ModuleService::GetInstance()->GetCurrentModuleSetting($sProperty, $defaultvalue); + return ModuleService::GetInstance()->GetCurrentModuleSetting($sProperty, $defaultvalue); } /** @@ -2406,7 +2318,7 @@ SQL; */ public static function GetCompiledModuleVersion($sModuleName) { - return ModuleService::GetInstance()->GetCompiledModuleVersion($sModuleName); + return ModuleService::GetInstance()->GetCompiledModuleVersion($sModuleName); } /** @@ -2417,8 +2329,7 @@ SQL; public static function IsURL($sPath) { $bRet = false; - if ((substr($sPath, 0, 7) == 'http://') || (substr($sPath, 0, 8) == 'https://') || (substr($sPath, 0, 8) == 'ftp://')) - { + if ((substr($sPath, 0, 7) == 'http://') || (substr($sPath, 0, 8) == 'https://') || (substr($sPath, 0, 8) == 'ftp://')) { $bRet = true; } return $bRet; @@ -2442,7 +2353,7 @@ SQL; // extract the "query" part of the URL and analyze it $sQuery = parse_url($sPath, PHP_URL_QUERY); if ($sQuery !== null) { - $aParams = array(); + $aParams = []; foreach (explode('&', $sQuery) as $sChunk) { $aParts = explode('=', $sChunk ?? ''); if (count($aParts) != 2) { @@ -2555,22 +2466,17 @@ TXT protected static function ParseHeaders($aHeaders) { - $aCleanHeaders = array(); - foreach( $aHeaders as $sKey => $sValue ) - { + $aCleanHeaders = []; + foreach ($aHeaders as $sKey => $sValue) { $aTokens = explode(':', $sValue ?? '', 2); - if(isset($aTokens[1])) - { + if (isset($aTokens[1])) { $aCleanHeaders[trim($aTokens[0])] = trim($aTokens[1]); - } - else - { + } else { // The header is not in the form Header-Code: Value $aCleanHeaders[] = $sValue; // Store the value as-is - $aMatches = array(); + $aMatches = []; // Check if it's not the HTTP response code - if( preg_match("|HTTP/[0-9\.]+\s+([0-9]+)|", $sValue, $aMatches) ) - { + if (preg_match("|HTTP/[0-9\.]+\s+([0-9]+)|", $sValue, $aMatches)) { $aCleanHeaders['reponse_code'] = intval($aMatches[1]); } } @@ -2619,8 +2525,7 @@ TXT */ public static function IsHighCardinality($sClass) { - if (utils::GetConfig()->Get('search_manual_submit')) - { + if (utils::GetConfig()->Get('search_manual_submit')) { return true; } $aHugeClasses = MetaModel::GetConfig()->Get('high_cardinality_classes'); @@ -2639,20 +2544,17 @@ TXT */ public static function GetFileMimeType($sFilePath, $sDefaultMimeType = 'application/octet-stream') { - if (!function_exists('finfo_file')) - { + if (!function_exists('finfo_file')) { return $sDefaultMimeType; } $sMimeType = $sDefaultMimeType; $rInfo = @finfo_open(FILEINFO_MIME_TYPE); - if ($rInfo !== false) - { + if ($rInfo !== false) { $sType = @finfo_file($rInfo, $sFilePath); if (($sType !== false) && is_string($sType) - && ($sType !== '')) - { + && ($sType !== '')) { $sMimeType = $sType; } } @@ -2682,14 +2584,12 @@ TXT final public static function RealPath($sPath, $sBasePath) { $sFileRealPath = realpath($sPath); - if ($sFileRealPath === false) - { + if ($sFileRealPath === false) { return false; } $sRealBasePath = realpath($sBasePath); // avoid problems when having '/' on Windows for example - if (!self::StartsWith($sFileRealPath, $sRealBasePath)) - { + if (!self::StartsWith($sFileRealPath, $sRealBasePath)) { return false; } @@ -2710,8 +2610,7 @@ TXT { $sRootPath = realpath($sBasePath); $sFullPath = realpath($sAbsolutePath); - if (($sFullPath === false) || !self::StartsWith($sFullPath, $sRootPath)) - { + if (($sFullPath === false) || !self::StartsWith($sFullPath, $sRootPath)) { return false; } $sLocalPath = substr($sFullPath, strlen($sRootPath.DIRECTORY_SEPARATOR)); @@ -2730,8 +2629,7 @@ TXT { $sRootPath = realpath(APPROOT); $sFullPath = realpath($sRootPath.DIRECTORY_SEPARATOR.$sPath); - if (($sFullPath === false) || !self::StartsWith($sFullPath, $sRootPath)) - { + if (($sFullPath === false) || !self::StartsWith($sFullPath, $sRootPath)) { return false; } return $sFullPath; @@ -2744,8 +2642,7 @@ TXT public static function GetCurrentUserName() { - if (function_exists('posix_getpwuid')) - { + if (function_exists('posix_getpwuid')) { return posix_getpwuid(posix_geteuid())['name']; } @@ -2767,13 +2664,12 @@ TXT public static function EnrichRaisedException($oCmdbAbstract, $oException) { if (is_null($oCmdbAbstract) || - ! is_a($oCmdbAbstract, \cmdbAbstractObject::class)) - { + ! is_a($oCmdbAbstract, \cmdbAbstractObject::class)) { throw $oException; } - $sCmdbAbstractInfo = str_replace("\n", '', "" . $oCmdbAbstract); - $sMessage = $oException->getMessage() . " (" . $sCmdbAbstractInfo . ")"; + $sCmdbAbstractInfo = str_replace("\n", '', "".$oCmdbAbstract); + $sMessage = $oException->getMessage()." (".$sCmdbAbstractInfo.")"; $e = new CoreException($sMessage, null, '', $oException); throw $e; @@ -3119,7 +3015,7 @@ TXT // Prepare array for matched class if not already present if (!array_key_exists($sMatchedClass, $aMentionedObjects)) { - $aMentionedObjects[$sMatchedClass] = array(); + $aMentionedObjects[$sMatchedClass] = []; } // Add matched ID if not already there if (!in_array($sMatchedId, $aMentionedObjects[$sMatchedClass])) { diff --git a/application/wizardhelper.class.inc.php b/application/wizardhelper.class.inc.php index 020227b51..866cfa2ce 100644 --- a/application/wizardhelper.class.inc.php +++ b/application/wizardhelper.class.inc.php @@ -1,4 +1,5 @@ - /** * Class WizardHelper * @@ -42,23 +42,17 @@ class WizardHelper */ public function GetTargetObject($bReadUploadedFiles = false) { - if (isset($this->m_aData['m_oCurrentValues']['id'])) - { + if (isset($this->m_aData['m_oCurrentValues']['id'])) { $oObj = MetaModel::GetObject($this->m_aData['m_sClass'], $this->m_aData['m_oCurrentValues']['id']); - } - else - { + } else { $oObj = MetaModel::NewObject($this->m_aData['m_sClass']); } - foreach($this->m_aData['m_oCurrentValues'] as $sAttCode => $value) - { + foreach ($this->m_aData['m_oCurrentValues'] as $sAttCode => $value) { // Because this is stored in a Javascript array, unused indexes // are filled with null values and unused keys (stored as strings) contain $$NULL$$ - if ( ($sAttCode !='id') && ($value !== '$$NULL$$')) - { + if (($sAttCode != 'id') && ($value !== '$$NULL$$')) { $oAttDef = MetaModel::GetAttributeDef($this->m_aData['m_sClass'], $sAttCode); - if (($oAttDef->IsLinkSet()) && ($value != '') ) - { + if (($oAttDef->IsLinkSet()) && ($value != '')) { // special handling for lists // assumes this is handled as an array of objects // thus encoded in json like: [ { name:'link1', 'id': 123}, { name:'link2', 'id': 124}...] @@ -71,47 +65,35 @@ class WizardHelper // Check what are the meaningful attributes $aFields = $this->GetLinkedWizardStructure($oAttDef); $sLinkedClass = $oAttDef->GetLinkedClass(); - $aLinkedObjectsArray = array(); + $aLinkedObjectsArray = []; if (!is_array($aData)) { echo("aData: '$aData' (value: '$value')\n"); } - foreach ($aData as $aLinkedObject) - { + foreach ($aData as $aLinkedObject) { $oLinkedObj = MetaModel::NewObject($sLinkedClass); - foreach($aFields as $sLinkedAttCode) - { - if ( isset($aLinkedObject[$sLinkedAttCode]) && ($aLinkedObject[$sLinkedAttCode] !== null) ) - { + foreach ($aFields as $sLinkedAttCode) { + if (isset($aLinkedObject[$sLinkedAttCode]) && ($aLinkedObject[$sLinkedAttCode] !== null)) { $sLinkedAttDef = MetaModel::GetAttributeDef($sLinkedClass, $sLinkedAttCode); - if (($sLinkedAttDef->IsExternalKey()) && ($aLinkedObject[$sLinkedAttCode] != '') && ($aLinkedObject[$sLinkedAttCode] > 0) ) - { + if (($sLinkedAttDef->IsExternalKey()) && ($aLinkedObject[$sLinkedAttCode] != '') && ($aLinkedObject[$sLinkedAttCode] > 0)) { // For external keys: load the target object so that external fields // get filled too $oTargetObj = MetaModel::GetObject($sLinkedAttDef->GetTargetClass(), $aLinkedObject[$sLinkedAttCode]); $oLinkedObj->Set($sLinkedAttCode, $oTargetObj); - } - elseif($sLinkedAttDef instanceof AttributeDateTime) - { - $sDateClass = get_class($sLinkedAttDef); - $sDate = $aLinkedObject[$sLinkedAttCode]; - if($sDate !== null && $sDate !== '') - { - $oDateTimeFormat = $sDateClass::GetFormat(); - $oDate = $oDateTimeFormat->Parse($sDate); - if ($sDateClass == "AttributeDate") - { - $sDate = $oDate->format('Y-m-d'); - } - else - { - $sDate = $oDate->format('Y-m-d H:i:s'); - } - } + } elseif ($sLinkedAttDef instanceof AttributeDateTime) { + $sDateClass = get_class($sLinkedAttDef); + $sDate = $aLinkedObject[$sLinkedAttCode]; + if ($sDate !== null && $sDate !== '') { + $oDateTimeFormat = $sDateClass::GetFormat(); + $oDate = $oDateTimeFormat->Parse($sDate); + if ($sDateClass == "AttributeDate") { + $sDate = $oDate->format('Y-m-d'); + } else { + $sDate = $oDate->format('Y-m-d H:i:s'); + } + } - $oLinkedObj->Set($sLinkedAttCode, $sDate); - } - else - { + $oLinkedObj->Set($sLinkedAttCode, $sDate); + } else { $oLinkedObj->Set($sLinkedAttCode, $aLinkedObject[$sLinkedAttCode]); } } @@ -120,98 +102,67 @@ class WizardHelper } $oSet = DBObjectSet::FromArray($sLinkedClass, $aLinkedObjectsArray); $oObj->Set($sAttCode, $oSet); - } - else if ( $oAttDef->GetEditClass() == 'Document' ) - { - if ($bReadUploadedFiles) - { + } elseif ($oAttDef->GetEditClass() == 'Document') { + if ($bReadUploadedFiles) { $oDocument = utils::ReadPostedDocument('attr_'.$sAttCode, 'fcontents'); $oObj->Set($sAttCode, $oDocument); - } - else - { + } else { // Create a new empty document, just for displaying the file name $oDocument = new ormDocument(null, '', $value); $oObj->Set($sAttCode, $oDocument); } - } - else if ( $oAttDef->GetEditClass() == 'Image' ) - { - if ($bReadUploadedFiles) - { + } elseif ($oAttDef->GetEditClass() == 'Image') { + if ($bReadUploadedFiles) { $oDocument = utils::ReadPostedDocument('attr_'.$sAttCode, 'fcontents'); $oObj->Set($sAttCode, $oDocument); - } - else - { + } else { // Create a new empty document, just for displaying the file name $oDocument = new ormDocument(null, '', $value); $oObj->Set($sAttCode, $oDocument); } - } - else if (($oAttDef->IsExternalKey()) && (!empty($value)) && ($value > 0) ) - { + } elseif (($oAttDef->IsExternalKey()) && (!empty($value)) && ($value > 0)) { // For external keys: load the target object so that external fields // get filled too $oTargetObj = MetaModel::GetObject($oAttDef->GetTargetClass(), $value, false); - if ($oTargetObj) - { + if ($oTargetObj) { $oObj->Set($sAttCode, $oTargetObj); - } - else - { + } else { // May happen for security reasons (portal, see ticket N°1074) $oObj->Set($sAttCode, $value); } - } - else if ($oAttDef instanceof AttributeDateTime) // AttributeDate is derived from AttributeDateTime - { - if ($value != null) - { + } elseif ($oAttDef instanceof AttributeDateTime) { // AttributeDate is derived from AttributeDateTime + if ($value != null) { $oDate = $oAttDef->GetFormat()->Parse($value); - if ($oDate instanceof DateTime) - { + if ($oDate instanceof DateTime) { $value = $oDate->format($oAttDef->GetInternalFormat()); - } - else - { + } else { $value = null; } } $oObj->Set($sAttCode, $value); - } - else if ($oAttDef instanceof AttributeTagSet) // AttributeDate is derived from AttributeDateTime - { - if (is_null($value)) - { + } elseif ($oAttDef instanceof AttributeTagSet) { // AttributeDate is derived from AttributeDateTime + if (is_null($value)) { // happens if field is hidden (see N°1827) - $value = array(); - } - else - { + $value = []; + } else { $value = json_decode($value, true); } $oTagSet = new ormTagSet(get_class($oObj), $sAttCode, $oAttDef->GetMaxItems()); $oTagSet->SetValues($value['orig_value']); $oTagSet->ApplyDelta($value); $oObj->Set($sAttCode, $oTagSet); - } - else if ($oAttDef instanceof AttributeSet) // AttributeDate is derived from AttributeDateTime - { + } elseif ($oAttDef instanceof AttributeSet) { // AttributeDate is derived from AttributeDateTime $value = json_decode($value, true); $oTagSet = new ormSet(get_class($oObj), $sAttCode, $oAttDef->GetMaxItems()); $oTagSet->SetValues($value['orig_value']); $oTagSet->ApplyDelta($value); $oObj->Set($sAttCode, $oTagSet); - } - else - { + } else { $oObj->Set($sAttCode, $value); } } } - if (isset($this->m_aData['m_sState']) && !empty($this->m_aData['m_sState'])) - { + if (isset($this->m_aData['m_sState']) && !empty($this->m_aData['m_sState'])) { $oObj->Set(MetaModel::GetStateAttributeCode($this->m_aData['m_sClass']), $this->m_aData['m_sState']); } $oObj->DoComputeValues(); @@ -226,31 +177,25 @@ class WizardHelper public function SetDefaultValue($sAttCode, $value) { // Protect against a request for a non existing field - if (isset($this->m_aData['m_oFieldsMap'][$sAttCode])) - { + if (isset($this->m_aData['m_oFieldsMap'][$sAttCode])) { $oAttDef = MetaModel::GetAttributeDef($this->m_aData['m_sClass'], $sAttCode); - if ($oAttDef->GetEditClass() == 'List') - { + if ($oAttDef->GetEditClass() == 'List') { // special handling for lists // this as to be handled as an array of objects // thus encoded in json like: [ { name:'link1', 'id': 123}, { name:'link2', 'id': 124}...] // NOT YET IMPLEMENTED !! $oSet = $value; - $aData = array(); + $aData = []; $aFields = $this->GetLinkedWizardStructure($oAttDef); - while($oLinkedObj = $oSet->fetch()) - { - foreach($aFields as $sLinkedAttCode) - { + while ($oLinkedObj = $oSet->fetch()) { + foreach ($aFields as $sLinkedAttCode) { $aRow[$sAttCode] = $oLinkedObj->Get($sLinkedAttCode); } $aData[] = $aRow; } $this->m_aData['m_oDefaultValue'][$sAttCode] = json_encode($aData); - } - else - { + } else { // Normal handling for all other scalar attributes $this->m_aData['m_oDefaultValue'][$sAttCode] = $value; } @@ -265,8 +210,7 @@ class WizardHelper public function SetAllowedValuesHtml($sAttCode, $sHtml) { // Protect against a request for a non existing field - if (isset($this->m_aData['m_oFieldsMap'][$sAttCode])) - { + if (isset($this->m_aData['m_oFieldsMap'][$sAttCode])) { $this->m_aData['m_oAllowedValues'][$sAttCode] = $sHtml; } } @@ -276,7 +220,7 @@ class WizardHelper return json_encode($this->m_aData); } - static public function FromJSON($sJSON) + public static function FromJSON($sJSON) { $oWizHelper = new WizardHelper(); $aData = json_decode($sJSON, true); // true means hash array instead of object @@ -288,21 +232,17 @@ class WizardHelper { $oWizard = new UIWizard(null, $oAttDef->GetLinkedClass()); $aWizardSteps = $oWizard->GetWizardStructure(); - $aFields = array(); + $aFields = []; $sExtKeyToMeCode = $oAttDef->GetExtKeyToMe(); // Retrieve as a flat list, all the attributes that are needed to create // an object of the linked class and put them into a flat array, except // the attribute 'ext_key_to_me' which is a constant in our case - foreach($aWizardSteps as $sDummy => $aMainSteps) - { + foreach ($aWizardSteps as $sDummy => $aMainSteps) { // 2 entries: 'mandatory' and 'optional' - foreach($aMainSteps as $aSteps) - { + foreach ($aMainSteps as $aSteps) { // One entry for each step of the wizard - foreach($aSteps as $sAttCode) - { - if ($sAttCode != $sExtKeyToMeCode) - { + foreach ($aSteps as $sAttCode) { + if ($sAttCode != $sExtKeyToMeCode) { $aFields[] = $sAttCode; } } @@ -316,20 +256,20 @@ class WizardHelper return $this->m_aData['m_sClass']; } - public function GetFormPrefix() - { - return $this->m_aData['m_sFormPrefix']; - } + public function GetFormPrefix() + { + return $this->m_aData['m_sFormPrefix']; + } - public function GetInitialState() - { - return isset($this->m_aData['m_sInitialState']) ? $this->m_aData['m_sInitialState'] : null; - } + public function GetInitialState() + { + return isset($this->m_aData['m_sInitialState']) ? $this->m_aData['m_sInitialState'] : null; + } - public function GetStimulus() - { - return isset($this->m_aData['m_sStimulus']) ? $this->m_aData['m_sStimulus'] : null; - } + public function GetStimulus() + { + return isset($this->m_aData['m_sStimulus']) ? $this->m_aData['m_sStimulus'] : null; + } public function GetIdForField($sFieldName) { @@ -337,8 +277,7 @@ class WizardHelper // It may happen that the field we'd like to update does not // exist in the form. For example, if the field should be hidden/read-only // in the current state of the object - if (isset($this->m_aData['m_oFieldsMap'][$sFieldName])) - { + if (isset($this->m_aData['m_oFieldsMap'][$sFieldName])) { $sResult = $this->m_aData['m_oFieldsMap'][$sFieldName]; } @@ -362,12 +301,14 @@ class WizardHelper $sWizardHelperJsVar = (!is_null($this->m_aData['m_sWizHelperJsVarName'])) ? utils::Sanitize($this->m_aData['m_sWizHelperJsVarName'], '', utils::ENUM_SANITIZATION_FILTER_PARAMETER) : 'oWizardHelper'.$this->GetFormPrefix(); $sWizardHelperJson = $this->ToJSON(); - $oPage->add_script(<<add_script( + <<add_ready_script(<<add_ready_script( + <<Set('trigger_id', $oTrigger->GetKey()); $oLog->Set('action_id', $this->GetKey()); $oLog->Set('object_id', $aContextArgs['this->object()']->GetKey()); - $oLog->Set('object_class', get_class($aContextArgs['this->object()'])); + $oLog->Set('object_class', get_class($aContextArgs['this->object()'])); // Must be inserted now so that it gets a valid id that will make the link // between an eventual asynchronous task (queued) and the log $oLog->DBInsertNoReload(); diff --git a/core/attributedef.class.inc.php b/core/attributedef.class.inc.php index fcc2c3cb1..808ad1ffa 100644 --- a/core/attributedef.class.inc.php +++ b/core/attributedef.class.inc.php @@ -1,4 +1,5 @@ m_proposedValue)) { + if (is_object($this->m_proposedValue)) { if ($this->m_proposedValue instanceof ReportValue) { return $this->m_proposedValue->GetAsCSV($bLocalizedValues, ',', '"'); } - throw new Exception('Unexpected class : '. get_class($this->m_proposedValue)); + throw new Exception('Unexpected class : '.get_class($this->m_proposedValue)); } return $this->m_proposedValue; } @@ -60,12 +60,11 @@ abstract class CellChangeSpec if ($this->m_proposedValue instanceof ReportValue) { return $this->m_proposedValue->GetAsHTML($bLocalizedValues); } - throw new Exception('Unexpected class : '. get_class($this->m_proposedValue)); + throw new Exception('Unexpected class : '.get_class($this->m_proposedValue)); } return utils::EscapeHtml($this->m_proposedValue); } - /** * @since 3.1.0 N°5305 */ @@ -84,7 +83,8 @@ abstract class CellChangeSpec */ public function GetCLIValueAndDescription(): string { - return sprintf("%s%s", + return sprintf( + "%s%s", $this->GetCLIValue(), $this->GetDescription() ); @@ -93,7 +93,6 @@ abstract class CellChangeSpec abstract public function GetDescription(); } - class CellStatus_Void extends CellChangeSpec { public function GetDescription() @@ -139,20 +138,18 @@ class CellStatus_Issue extends CellStatus_Modify if (is_null($this->m_proposedValue)) { return Dict::Format('UI:CSVReport-Value-SetIssue'); } - return Dict::Format('UI:CSVReport-Value-ChangeIssue',$this->m_proposedValue); + return Dict::Format('UI:CSVReport-Value-ChangeIssue', $this->m_proposedValue); } public function GetHTMLValue(bool $bLocalizedValues = false): string { - if (is_null($this->m_proposedValue)) - { + if (is_null($this->m_proposedValue)) { return Dict::Format('UI:CSVReport-Value-SetIssue'); } - if ($this->m_proposedValue instanceof ReportValue) - { + if ($this->m_proposedValue instanceof ReportValue) { return Dict::Format('UI:CSVReport-Value-ChangeIssue', $this->m_proposedValue->GetAsHTML($bLocalizedValues)); } - return Dict::Format('UI:CSVReport-Value-ChangeIssue',utils::EscapeHtml($this->m_proposedValue)); + return Dict::Format('UI:CSVReport-Value-ChangeIssue', utils::EscapeHtml($this->m_proposedValue)); } public function GetDescription() @@ -164,7 +161,8 @@ class CellStatus_Issue extends CellStatus_Modify */ public function GetCLIValueAndDescription(): string { - return sprintf("%s. %s", + return sprintf( + "%s. %s", $this->GetCLIValue(), $this->GetDescription() ); @@ -244,7 +242,8 @@ class CellStatus_SearchIssue extends CellStatus_Issue */ public function GetSearchLinkUrl() { - return sprintf("UI.php?operation=search&filter=%s", + return sprintf( + "UI.php?operation=search&filter=%s", rawurlencode($this->sSerializedSearch ?? "") ); } @@ -255,7 +254,8 @@ class CellStatus_SearchIssue extends CellStatus_Issue */ public function GetAllowedValuesLinkUrl(): ?string { - return sprintf("UI.php?operation=search&filter=%s", + return sprintf( + "UI.php?operation=search&filter=%s", rawurlencode($this->sAllowedValuesSearch ?? "") ); } @@ -284,7 +284,9 @@ class ReportValue * @param string $sAttCode * @param bool $bOriginal */ - public function __construct(protected DBObject $oObject, protected string $sAttCode, protected bool $bOriginal){} + public function __construct(protected DBObject $oObject, protected string $sAttCode, protected bool $bOriginal) + { + } public function GetAsHTML(bool $bLocalizedValues) { @@ -293,7 +295,8 @@ class ReportValue } return $this->oObject->GetAsHTML($this->sAttCode, $bLocalizedValues); } - public function GetAsCSV (bool $bLocalizedValues, string $sCsvSep, string $sCsvDelimiter) { + public function GetAsCSV(bool $bLocalizedValues, string $sCsvSep, string $sCsvDelimiter) + { if ($this->bOriginal) { return $this->oObject->GetOriginalAsCSV($this->sAttCode, $sCsvSep, $sCsvDelimiter, $bLocalizedValues); } @@ -301,7 +304,6 @@ class ReportValue } } - class CellStatus_Ambiguous extends CellStatus_Issue { protected $m_iCount; @@ -338,13 +340,13 @@ class CellStatus_Ambiguous extends CellStatus_Issue */ public function GetSearchLinkUrl() { - return sprintf("UI.php?operation=search&filter=%s", + return sprintf( + "UI.php?operation=search&filter=%s", rawurlencode($this->sSerializedSearch ?? "") ); } } - /** * RowStatus * A series of classes, keeping the information about a given row: could it be changed or not (and why)? @@ -486,22 +488,18 @@ class BulkChange $this->m_aOnDisappear = $aOnDisappear; $this->m_sDateFormat = $sDateFormat; $this->m_bLocalizedValues = $bLocalize; - $this->m_aExtKeysMappingCache = array(); - $this->m_iNbCol =$iNbCol; + $this->m_aExtKeysMappingCache = []; + $this->m_iNbCol = $iNbCol; } protected function ResolveExternalKey($aRowData, $sAttCode, &$aResults) { $oExtKey = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode); $oReconFilter = new DBObjectSearch($oExtKey->GetTargetClass()); - foreach ($this->m_aExtKeys[$sAttCode] as $sReconKeyAttCode => $iCol) - { - if ($sReconKeyAttCode == 'id') - { + foreach ($this->m_aExtKeys[$sAttCode] as $sReconKeyAttCode => $iCol) { + if ($sReconKeyAttCode == 'id') { $value = (int) $aRowData[$iCol]; - } - else - { + } else { // The foreign attribute is one of our reconciliation key $oForeignAtt = MetaModel::GetAttributeDef($oExtKey->GetTargetClass(), $sReconKeyAttCode); $value = $oForeignAtt->MakeValueFromString($aRowData[$iCol], $this->m_bLocalizedValues); @@ -512,18 +510,16 @@ class BulkChange $oExtObjects = new CMDBObjectSet($oReconFilter); $aKeys = $oExtObjects->ToArray(); - return array($oReconFilter, $aKeys); + return [$oReconFilter, $aKeys]; } // Returns true if the CSV data specifies that the external key must be left undefined protected function IsNullExternalKeySpec($aRowData, $sAttCode) { //$oExtKey = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode); - foreach ($this->m_aExtKeys[$sAttCode] as $sForeignAttCode => $iCol) - { + foreach ($this->m_aExtKeys[$sAttCode] as $sForeignAttCode => $iCol) { // The foreign attribute is one of our reconciliation key - if (isset($aRowData[$iCol]) && strlen($aRowData[$iCol]) > 0) - { + if (isset($aRowData[$iCol]) && strlen($aRowData[$iCol]) > 0) { return false; } } @@ -544,51 +540,39 @@ class BulkChange */ protected function PrepareObject(&$oTargetObj, $aRowData, &$aErrors) { - $aResults = array(); - $aErrors = array(); + $aResults = []; + $aErrors = []; // External keys reconciliation // - foreach($this->m_aExtKeys as $sAttCode => $aReconKeys) - { + foreach ($this->m_aExtKeys as $sAttCode => $aReconKeys) { // Skip external keys used for the reconciliation process // if (!array_key_exists($sAttCode, $this->m_aAttList)) continue; $oExtKey = MetaModel::GetAttributeDef(get_class($oTargetObj), $sAttCode); - if ($this->IsNullExternalKeySpec($aRowData, $sAttCode)) - { - foreach ($aReconKeys as $sReconKeyAttCode => $iCol) - { + if ($this->IsNullExternalKeySpec($aRowData, $sAttCode)) { + foreach ($aReconKeys as $sReconKeyAttCode => $iCol) { // Default reporting // $aRowData[$iCol] is always null $aResults[$iCol] = new CellStatus_Void($aRowData[$iCol]); } - if ($oExtKey->IsNullAllowed()) - { + if ($oExtKey->IsNullAllowed()) { $oTargetObj->Set($sAttCode, $oExtKey->GetNullValue()); - $aResults[$sAttCode]= new CellStatus_Void($oExtKey->GetNullValue()); - } - else - { + $aResults[$sAttCode] = new CellStatus_Void($oExtKey->GetNullValue()); + } else { $aErrors[$sAttCode] = Dict::S('UI:CSVReport-Value-Issue-Null'); - $aResults[$sAttCode]= new CellStatus_Issue(null, $oTargetObj->Get($sAttCode), Dict::S('UI:CSVReport-Value-Issue-Null')); + $aResults[$sAttCode] = new CellStatus_Issue(null, $oTargetObj->Get($sAttCode), Dict::S('UI:CSVReport-Value-Issue-Null')); } - } - else - { + } else { $oReconFilter = new DBObjectSearch($oExtKey->GetTargetClass()); - $aCacheKeys = array(); - foreach ($aReconKeys as $sReconKeyAttCode => $iCol) - { + $aCacheKeys = []; + foreach ($aReconKeys as $sReconKeyAttCode => $iCol) { // The foreign attribute is one of our reconciliation key - if ($sReconKeyAttCode == 'id') - { + if ($sReconKeyAttCode == 'id') { $value = $aRowData[$iCol]; - } - else - { + } else { $oForeignAtt = MetaModel::GetAttributeDef($oExtKey->GetTargetClass(), $sReconKeyAttCode); $value = $oForeignAtt->MakeValueFromString($aRowData[$iCol], $this->m_bLocalizedValues); } @@ -599,37 +583,31 @@ class BulkChange $sCacheKey = implode('_|_', $aCacheKeys); // Unique key for this query... $iForeignKey = null; // TODO: check if *too long* keys can lead to collisions... and skip the cache in such a case... - if (!array_key_exists($sAttCode, $this->m_aExtKeysMappingCache)) - { - $this->m_aExtKeysMappingCache[$sAttCode] = array(); + if (!array_key_exists($sAttCode, $this->m_aExtKeysMappingCache)) { + $this->m_aExtKeysMappingCache[$sAttCode] = []; } - if (array_key_exists($sCacheKey, $this->m_aExtKeysMappingCache[$sAttCode])) - { + if (array_key_exists($sCacheKey, $this->m_aExtKeysMappingCache[$sAttCode])) { // Cache hit $iObjectFoundCount = $this->m_aExtKeysMappingCache[$sAttCode][$sCacheKey]['c']; $iForeignKey = $this->m_aExtKeysMappingCache[$sAttCode][$sCacheKey]['k']; // Record the hit $this->m_aExtKeysMappingCache[$sAttCode][$sCacheKey]['h']++; - } - else - { + } else { // Cache miss, let's initialize it $oExtObjects = new CMDBObjectSet($oReconFilter); $iObjectFoundCount = $oExtObjects->Count(); - if ($iObjectFoundCount == 1) - { + if ($iObjectFoundCount == 1) { $oForeignObj = $oExtObjects->Fetch(); $iForeignKey = $oForeignObj->GetKey(); } - $this->m_aExtKeysMappingCache[$sAttCode][$sCacheKey] = array( + $this->m_aExtKeysMappingCache[$sAttCode][$sCacheKey] = [ 'c' => $iObjectFoundCount, 'k' => $iForeignKey, 'oql' => $oReconFilter->ToOql(), 'h' => 0, // number of hits on this cache entry - ); + ]; } - switch($iObjectFoundCount) - { + switch ($iObjectFoundCount) { case 0: $oCellStatus_SearchIssue = $this->GetCellSearchIssue($oReconFilter); $aResults[$sAttCode] = $oCellStatus_SearchIssue; @@ -643,41 +621,32 @@ class BulkChange default: $aErrors[$sAttCode] = Dict::Format('UI:CSVReport-Value-Issue-FoundMany', $iObjectFoundCount); - $aResults[$sAttCode]= new CellStatus_Ambiguous($oTargetObj->Get($sAttCode), $iObjectFoundCount, $oReconFilter->serialize()); + $aResults[$sAttCode] = new CellStatus_Ambiguous($oTargetObj->Get($sAttCode), $iObjectFoundCount, $oReconFilter->serialize()); } } // Report - if (!array_key_exists($sAttCode, $aResults)) - { + if (!array_key_exists($sAttCode, $aResults)) { $iForeignObj = $oTargetObj->Get($sAttCode); - if (array_key_exists($sAttCode, $oTargetObj->ListChanges())) - { - if ($oTargetObj->IsNew()) - { - $aResults[$sAttCode]= new CellStatus_Void($iForeignObj); - } - else - { - $aResults[$sAttCode]= new CellStatus_Modify($iForeignObj, $oTargetObj->GetOriginal($sAttCode)); - foreach ($aReconKeys as $sReconKeyAttCode => $iCol) - { + if (array_key_exists($sAttCode, $oTargetObj->ListChanges())) { + if ($oTargetObj->IsNew()) { + $aResults[$sAttCode] = new CellStatus_Void($iForeignObj); + } else { + $aResults[$sAttCode] = new CellStatus_Modify($iForeignObj, $oTargetObj->GetOriginal($sAttCode)); + foreach ($aReconKeys as $sReconKeyAttCode => $iCol) { // Report the change on reconciliation values as well $aResults[$iCol] = new CellStatus_Modify($aRowData[$iCol]); } } - } - else - { - $aResults[$sAttCode]= new CellStatus_Void($iForeignObj); + } else { + $aResults[$sAttCode] = new CellStatus_Void($iForeignObj); } } } // Set the object attributes // - foreach ($this->m_aAttList as $sAttCode => $iCol) - { + foreach ($this->m_aAttList as $sAttCode => $iCol) { // skip the private key, if any if (($sAttCode == 'id') || ($sAttCode == 'friendlyname')) { continue; @@ -690,47 +659,34 @@ class BulkChange continue; } - $aReasons = array(); + $aReasons = []; $iFlags = ($oTargetObj->IsNew()) ? $oTargetObj->GetInitialStateAttributeFlags($sAttCode, $aReasons) : $oTargetObj->GetAttributeFlags($sAttCode, $aReasons); if ((($iFlags & OPT_ATT_READONLY) == OPT_ATT_READONLY) && ($oTargetObj->Get($sAttCode) != $oAttDef->MakeValueFromString($aRowData[$iCol], $this->m_bLocalizedValues))) { $aErrors[$sAttCode] = Dict::Format('UI:CSVReport-Value-Issue-Readonly', $sAttCode, $oTargetObj->Get($sAttCode), $aRowData[$iCol]); - } - else if ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect()) - { - try - { + } elseif ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect()) { + try { $oSet = $oAttDef->MakeValueFromString($aRowData[$iCol], $this->m_bLocalizedValues); $oTargetObj->Set($sAttCode, $oSet); - } - catch(CoreException $e) - { + } catch (CoreException $e) { $aErrors[$sAttCode] = Dict::Format('UI:CSVReport-Value-Issue-Format', $e->getMessage()); } - } - else - { + } else { $value = $oAttDef->MakeValueFromString($aRowData[$iCol], $this->m_bLocalizedValues); - if (is_null($value) && (strlen($aRowData[$iCol]) > 0)) - { - if ($oAttDef instanceof AttributeEnum || $oAttDef instanceof AttributeTagSet){ + if (is_null($value) && (strlen($aRowData[$iCol]) > 0)) { + if ($oAttDef instanceof AttributeEnum || $oAttDef instanceof AttributeTagSet) { /** @var AttributeDefinition $oAttributeDefinition */ $oAttributeDefinition = $oAttDef; $aErrors[$sAttCode] = Dict::Format('UI:CSVReport-Value-Issue-AllowedValues', $sAttCode, implode(',', $oAttributeDefinition->GetAllowedValues())); } else { $aErrors[$sAttCode] = Dict::Format('UI:CSVReport-Value-Issue-NoMatch', $sAttCode); } - } - else - { + } else { $res = $oTargetObj->CheckValue($sAttCode, $value); - if ($res === true) - { + if ($res === true) { $oTargetObj->Set($sAttCode, $value); - } - else - { + } else { // $res is a string with the error description $aErrors[$sAttCode] = Dict::Format('UI:CSVReport-Value-Issue-Unknown', $sAttCode, $res); } @@ -743,30 +699,25 @@ class BulkChange $aChangedFields = $oTargetObj->ListChanges(); foreach ($this->m_aAttList as $sAttCode => $iCol) { if ($sAttCode == 'id') { - $aResults[$iCol]= new CellStatus_Void($aRowData[$iCol]); - } - else { + $aResults[$iCol] = new CellStatus_Void($aRowData[$iCol]); + } else { $sCurValue = new ReportValue($oTargetObj, $sAttCode, false); $sOrigValue = new ReportValue($oTargetObj, $sAttCode, true); if (isset($aErrors[$sAttCode])) { - $aResults[$iCol]= new CellStatus_Issue($aRowData[$iCol], $sOrigValue, $aErrors[$sAttCode]); - } - elseif (array_key_exists($sAttCode, $aChangedFields)){ - if ($oTargetObj->IsNew()) { - $aResults[$iCol]= new CellStatus_Void($sCurValue); + $aResults[$iCol] = new CellStatus_Issue($aRowData[$iCol], $sOrigValue, $aErrors[$sAttCode]); + } elseif (array_key_exists($sAttCode, $aChangedFields)) { + if ($oTargetObj->IsNew()) { + $aResults[$iCol] = new CellStatus_Void($sCurValue); + } else { + $aResults[$iCol] = new CellStatus_Modify($sCurValue, $sOrigValue); } - else { - $aResults[$iCol]= new CellStatus_Modify($sCurValue, $sOrigValue); - } - } - else { + } else { // By default... nothing happens $oAttDef = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode); if ($oAttDef instanceof AttributeDateTime) { - $aResults[$iCol]= new CellStatus_Void($oAttDef->GetFormat()->Format($aRowData[$iCol])); - } - else { - $aResults[$iCol]= new CellStatus_Void($aRowData[$iCol]); + $aResults[$iCol] = new CellStatus_Void($oAttDef->GetFormat()->Format($aRowData[$iCol])); + } else { + $aResults[$iCol] = new CellStatus_Void($aRowData[$iCol]); } } } @@ -775,8 +726,7 @@ class BulkChange // Checks // $res = $oTargetObj->CheckConsistency(); - if ($res !== true) - { + if ($res !== true) { // $res contains the error description $aErrors["GLOBAL"] = Dict::Format('UI:CSVReport-Row-Issue-Inconsistent', $res); } @@ -797,7 +747,8 @@ class BulkChange * * @since 3.1.0 N°5305 */ - protected function GetCellSearchIssue($oDbSearchWithConditions) : CellStatus_SearchIssue { + protected function GetCellSearchIssue($oDbSearchWithConditions): CellStatus_SearchIssue + { //current search with current permissions did not match //let's search why and give some more feedback to the user @@ -820,36 +771,38 @@ class BulkChange $iCurrentUserRightsObjectCount = $oExtObjectSetWithCurrentUserPermissions->Count(); $sAllowedValuesOql = $oDbSearchWithoutAnyCondition->serialize(); - if ($iCurrentUserRightsObjectCount === 0){ + if ($iCurrentUserRightsObjectCount === 0) { // No objects visible by current user $sReason = Dict::Format('UI:CSVReport-Value-NoMatch-NoObject-ForCurrentUser', $oDbSearchWithConditions->GetClass()); return new CellStatus_SearchIssue($sSerializedSearch, $sReason); } - try{ + try { $aDisplayedAllowedValues = []; // Possibles values are displayed to UI user. we have to limit the amount of displayed values $oExtObjectSetWithCurrentUserPermissions->SetLimit(4); - for($i = 0; $i < 3; $i++){ + for ($i = 0; $i < 3; $i++) { /** @var DBObject $oVisibleObject */ $oVisibleObject = $oExtObjectSetWithCurrentUserPermissions->Fetch(); - if (is_null($oVisibleObject)){ + if (is_null($oVisibleObject)) { break; } $aCurrentAllowedValueFields = []; - foreach ($oDbSearchWithConditions->GetInternalParams() as $sForeignAttCode => $sValue){ + foreach ($oDbSearchWithConditions->GetInternalParams() as $sForeignAttCode => $sValue) { $aCurrentAllowedValueFields[] = $oVisibleObject->Get($sForeignAttCode); } $aDisplayedAllowedValues[] = implode(" ", $aCurrentAllowedValueFields); } $allowedValues = implode(", ", $aDisplayedAllowedValues); - if ($oExtObjectSetWithCurrentUserPermissions->Count() > 3){ + if ($oExtObjectSetWithCurrentUserPermissions->Count() > 3) { $allowedValues .= "..."; } - } catch(Exception $e) { - IssueLog::Error("failure during CSV import when fetching few visible objects: ", null, + } catch (Exception $e) { + IssueLog::Error( + "failure during CSV import when fetching few visible objects: ", + null, [ 'target_class' => $oDbSearchWithConditions->GetClass(), 'criteria' => $oDbSearchWithConditions->GetCriteria(), 'message' => $e->getMessage()] ); $sReason = Dict::Format('UI:CSVReport-Value-NoMatch-NoObject-ForCurrentUser', $oDbSearchWithConditions->GetClass()); @@ -865,39 +818,35 @@ class BulkChange // No match. This is not linked to any right issue // Possible values: DD,DD $aCurrentValueFields = []; - foreach ($oDbSearchWithConditions->GetInternalParams() as $sValue){ + foreach ($oDbSearchWithConditions->GetInternalParams() as $sValue) { $aCurrentValueFields[] = $sValue; } - $value =implode(" ", $aCurrentValueFields); + $value = implode(" ", $aCurrentValueFields); $sReason = Dict::Format('UI:CSVReport-Value-NoMatch', $value); return new CellStatus_SearchIssue($sSerializedSearch, $sReason, $oDbSearchWithConditions->GetClass(), $allowedValues, $sAllowedValuesOql); } protected function PrepareMissingObject(&$oTargetObj, &$aErrors) { - $aResults = array(); - $aErrors = array(); + $aResults = []; + $aErrors = []; // External keys // - foreach($this->m_aExtKeys as $sAttCode => $aKeyConfig) - { + foreach ($this->m_aExtKeys as $sAttCode => $aKeyConfig) { //$oExtKey = MetaModel::GetAttributeDef(get_class($oTargetObj), $sAttCode); - $aResults[$sAttCode]= new CellStatus_Void($oTargetObj->Get($sAttCode)); + $aResults[$sAttCode] = new CellStatus_Void($oTargetObj->Get($sAttCode)); - foreach ($aKeyConfig as $sForeignAttCode => $iCol) - { + foreach ($aKeyConfig as $sForeignAttCode => $iCol) { $aResults[$iCol] = new CellStatus_Void('?'); } } // Update attributes // - foreach($this->m_aOnDisappear as $sAttCode => $value) - { - if (!MetaModel::IsValidAttCode(get_class($oTargetObj), $sAttCode)) - { - throw new BulkChangeException('Invalid attribute code', array('class' => get_class($oTargetObj), 'attcode' => $sAttCode)); + foreach ($this->m_aOnDisappear as $sAttCode => $value) { + if (!MetaModel::IsValidAttCode(get_class($oTargetObj), $sAttCode)) { + throw new BulkChangeException('Invalid attribute code', ['class' => get_class($oTargetObj), 'attcode' => $sAttCode]); } $oTargetObj->Set($sAttCode, $value); } @@ -905,61 +854,46 @@ class BulkChange // Reporting on fields // $aChangedFields = $oTargetObj->ListChanges(); - foreach ($this->m_aAttList as $sAttCode => $iCol) - { - if ($sAttCode == 'id') - { - $aResults[$iCol]= new CellStatus_Void($oTargetObj->GetKey()); + foreach ($this->m_aAttList as $sAttCode => $iCol) { + if ($sAttCode == 'id') { + $aResults[$iCol] = new CellStatus_Void($oTargetObj->GetKey()); } - if (array_key_exists($sAttCode, $aChangedFields)) - { - $aResults[$iCol]= new CellStatus_Modify($oTargetObj->Get($sAttCode), $oTargetObj->GetOriginal($sAttCode)); - } - else - { + if (array_key_exists($sAttCode, $aChangedFields)) { + $aResults[$iCol] = new CellStatus_Modify($oTargetObj->Get($sAttCode), $oTargetObj->GetOriginal($sAttCode)); + } else { // By default... nothing happens - $aResults[$iCol]= new CellStatus_Void($oTargetObj->Get($sAttCode)); + $aResults[$iCol] = new CellStatus_Void($oTargetObj->Get($sAttCode)); } } // Checks // $res = $oTargetObj->CheckConsistency(); - if ($res !== true) - { + if ($res !== true) { // $res contains the error description $aErrors["GLOBAL"] = Dict::Format('UI:CSVReport-Row-Issue-Inconsistent', $res); } return $aResults; } - protected function CreateObject(&$aResult, $iRow, $aRowData, CMDBChange $oChange = null) { $oTargetObj = MetaModel::NewObject($this->m_sClass); // Populate the cache for hierarchical keys (only if in verify mode) - if (is_null($oChange)) - { + if (is_null($oChange)) { // 1. determine if a hierarchical key exists - foreach($this->m_aExtKeys as $sAttCode => $aKeyConfig) - { + foreach ($this->m_aExtKeys as $sAttCode => $aKeyConfig) { $oExtKey = MetaModel::GetAttributeDef(get_class($oTargetObj), $sAttCode); - if (!$this->IsNullExternalKeySpec($aRowData, $sAttCode) && MetaModel::IsParentClass(get_class($oTargetObj), $this->m_sClass)) - { + if (!$this->IsNullExternalKeySpec($aRowData, $sAttCode) && MetaModel::IsParentClass(get_class($oTargetObj), $this->m_sClass)) { // 2. Populate the cache for further checks - $aCacheKeys = array(); - foreach ($aKeyConfig as $sForeignAttCode => $iCol) - { + $aCacheKeys = []; + foreach ($aKeyConfig as $sForeignAttCode => $iCol) { // The foreign attribute is one of our reconciliation key - if ($sForeignAttCode == 'id') - { + if ($sForeignAttCode == 'id') { $value = $aRowData[$iCol]; - } - else - { - if (!isset($this->m_aAttList[$sForeignAttCode]) || !isset($aRowData[$this->m_aAttList[$sForeignAttCode]])) - { + } else { + if (!isset($this->m_aAttList[$sForeignAttCode]) || !isset($aRowData[$this->m_aAttList[$sForeignAttCode]])) { // the key is not in the import break 2; } @@ -968,20 +902,19 @@ class BulkChange $aCacheKeys[] = $value; } $sCacheKey = implode('_|_', $aCacheKeys); // Unique key for this query... - $this->m_aExtKeysMappingCache[$sAttCode][$sCacheKey] = array( + $this->m_aExtKeysMappingCache[$sAttCode][$sCacheKey] = [ 'c' => 1, 'k' => -1, 'oql' => '', 'h' => 0, // number of hits on this cache entry - ); + ]; } } } $aResult[$iRow] = $this->PrepareObject($oTargetObj, $aRowData, $aErrors); - if (count($aErrors) > 0) - { + if (count($aErrors) > 0) { $sErrors = implode(', ', $aErrors); $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-Attribute')); //__ERRORS__ used by tests only @@ -990,19 +923,15 @@ class BulkChange } // Check that any external key will have a value proposed - $aMissingKeys = array(); - foreach (MetaModel::GetExternalKeys($this->m_sClass) as $sExtKeyAttCode => $oExtKey) - { - if (!$oExtKey->IsNullAllowed()) - { - if (!array_key_exists($sExtKeyAttCode, $this->m_aExtKeys) && !array_key_exists($sExtKeyAttCode, $this->m_aAttList)) - { + $aMissingKeys = []; + foreach (MetaModel::GetExternalKeys($this->m_sClass) as $sExtKeyAttCode => $oExtKey) { + if (!$oExtKey->IsNullAllowed()) { + if (!array_key_exists($sExtKeyAttCode, $this->m_aExtKeys) && !array_key_exists($sExtKeyAttCode, $this->m_aAttList)) { $aMissingKeys[] = $oExtKey->GetLabel(); } } } - if (count($aMissingKeys) > 0) - { + if (count($aMissingKeys) > 0) { $sMissingKeys = implode(', ', $aMissingKeys); $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue(Dict::Format('UI:CSVReport-Row-Issue-MissingExtKey', $sMissingKeys)); return $oTargetObj; @@ -1010,12 +939,9 @@ class BulkChange // Optionally record the results // - if ($oChange) - { + if ($oChange) { $newID = $oTargetObj->DBInsert(); - } - else - { + } else { $newID = 0; } @@ -1048,8 +974,7 @@ class BulkChange $aResult[$iRow]["finalclass"] = get_class($oTargetObj); $aResult[$iRow]["id"] = new CellStatus_Void($oTargetObj->GetKey()); - if (count($aErrors) > 0) - { + if (count($aErrors) > 0) { $sErrors = implode(', ', $aErrors); $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-Attribute')); //__ERRORS__ used by tests only @@ -1058,26 +983,19 @@ class BulkChange } $aChangedFields = $oTargetObj->ListChanges(); - if (count($aChangedFields) > 0) - { + if (count($aChangedFields) > 0) { $aResult[$iRow]["__STATUS__"] = new RowStatus_Modify(count($aChangedFields)); // Optionaly record the results // - if ($oChange) - { - try - { + if ($oChange) { + try { $oTargetObj->DBUpdate(); - } - catch(CoreException $e) - { + } catch (CoreException $e) { $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue($e->getMessage()); } } - } - else - { + } else { $aResult[$iRow]["__STATUS__"] = new RowStatus_NoChange(); } } @@ -1099,8 +1017,7 @@ class BulkChange $aResult[$iRow]["finalclass"] = get_class($oTargetObj); $aResult[$iRow]["id"] = new CellStatus_Void($oTargetObj->GetKey()); - if (count($aErrors) > 0) - { + if (count($aErrors) > 0) { $sErrors = implode(', ', $aErrors); $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-Attribute')); //__ERRORS__ used by tests only @@ -1109,34 +1026,26 @@ class BulkChange } $aChangedFields = $oTargetObj->ListChanges(); - if (count($aChangedFields) > 0) - { + if (count($aChangedFields) > 0) { $aResult[$iRow]["__STATUS__"] = new RowStatus_Disappeared(count($aChangedFields)); // Optionaly record the results // - if ($oChange) - { - try - { + if ($oChange) { + try { $oTargetObj->DBUpdate(); - } - catch(CoreException $e) - { + } catch (CoreException $e) { $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue($e->getMessage()); } } - } - else - { + } else { $aResult[$iRow]["__STATUS__"] = new RowStatus_Disappeared(0); } } public function Process(CMDBChange $oChange = null) { - if ($oChange) - { + if ($oChange) { CMDBObject::SetCurrentChange($oChange); } @@ -1144,8 +1053,7 @@ class BulkChange // Debug... // - if (false) - { + if (false) { echo "
\n";
 			echo "Attributes:\n";
 			print_r($this->m_aAttList);
@@ -1163,10 +1071,9 @@ class BulkChange
 			exit;
 		}
 
-		$aResult = array();
+		$aResult = [];
 
-		if (!is_null($this->m_sDateFormat) && (strlen($this->m_sDateFormat) > 0))
-		{
+		if (!is_null($this->m_sDateFormat) && (strlen($this->m_sDateFormat) > 0)) {
 			$sDateTimeFormat = $this->m_sDateFormat; // the specified format is actually the date AND time format
 			$oDateTimeFormat = new DateTimeFormat($sDateTimeFormat);
 			$sDateFormat = $oDateTimeFormat->ToDateFormat();
@@ -1174,55 +1081,44 @@ class BulkChange
 			AttributeDate::SetFormat(new DateTimeFormat($sDateFormat));
 			// Translate dates from the source data
 			//
-			foreach ($this->m_aAttList as $sAttCode => $iCol)
-			{
-				if ($sAttCode == 'id') continue;
+			foreach ($this->m_aAttList as $sAttCode => $iCol) {
+				if ($sAttCode == 'id') {
+					continue;
+				}
 
 				$oAttDef = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
-				if ($oAttDef instanceof AttributeDateTime) // AttributeDate is derived from AttributeDateTime
-				{
-					foreach($this->m_aData as $iRow => $aRowData)
-					{
+				if ($oAttDef instanceof AttributeDateTime) { // AttributeDate is derived from AttributeDateTime
+					foreach ($this->m_aData as $iRow => $aRowData) {
 						$sFormat = $sDateTimeFormat;
-						if(!isset($this->m_aData[$iRow][$iCol])){
+						if (!isset($this->m_aData[$iRow][$iCol])) {
 							continue;
 						}
 						$sValue = $this->m_aData[$iRow][$iCol];
-						if (!empty($sValue))
-						{
-							if ($oAttDef instanceof AttributeDate)
-							{
+						if (!empty($sValue)) {
+							if ($oAttDef instanceof AttributeDate) {
 								$sFormat = $sDateFormat;
 							}
 							$oFormat = new DateTimeFormat($sFormat);
 							$sDateExample = $oFormat->Format(new DateTime('2022-10-23 16:25:33'));
 							$sRegExp = $oFormat->ToRegExpr('/');
 							$sErrorMsg = Dict::Format('UI:CSVReport-Row-Issue-ExpectedDateFormat', $sDateExample);
-							if (!preg_match($sRegExp, $sValue))
-							{
-								$aResult[$iRow]["__STATUS__"]= new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-DateFormat'));
+							if (!preg_match($sRegExp, $sValue)) {
+								$aResult[$iRow]["__STATUS__"] = new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-DateFormat'));
 								$aResult[$iRow][$iCol] = new CellStatus_Issue($sValue, null, $sErrorMsg);
 
-							}
-							else
-							{
+							} else {
 								$oDate = DateTime::createFromFormat($sFormat, $sValue);
-								if ($oDate !== false)
-								{
+								if ($oDate !== false) {
 									$sNewDate = $oDate->format($oAttDef->GetInternalFormat());
 									$this->m_aData[$iRow][$iCol] = $sNewDate;
-								}
-								else
-								{
+								} else {
 									// almost impossible ti reproduce since even incorrect dates with correct formats are formated and $oDate will not be false
 									// Leave the cell unchanged
-									$aResult[$iRow]["__STATUS__"]= new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-DateFormat'));
+									$aResult[$iRow]["__STATUS__"] = new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-DateFormat'));
 									$aResult[$iRow][$iCol] = new CellStatus_Issue($sValue, null, $sErrorMsg);
 								}
 							}
-						}
-						else
-						{
+						} else {
 							$this->m_aData[$iRow][$iCol] = '';
 						}
 					}
@@ -1232,9 +1128,8 @@ class BulkChange
 
 		// Compute the results
 		//
-		if (!is_null($this->m_sSynchroScope))
-		{
-			$aVisited = array();
+		if (!is_null($this->m_sSynchroScope)) {
+			$aVisited = [];
 		}
 		$iPreviousTimeLimit = ini_get('max_execution_time');
 		$iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
@@ -1245,8 +1140,8 @@ class BulkChange
 			foreach ($this->m_aData as $iRow => $aRowData) {
 				set_time_limit(intval($iLoopTimeLimit));
 				// Stop if not the good number of cols in $aRowData
-				if($this->m_iNbCol>0 && count($aRowData) != $this->m_iNbCol){
-					$aResult[$iRow]["__STATUS__"] = new RowStatus_Issue(Dict::Format('UI:CSVReport-Row-Issue-NbField',count($aRowData),$this->m_iNbCol) );
+				if ($this->m_iNbCol > 0 && count($aRowData) != $this->m_iNbCol) {
+					$aResult[$iRow]["__STATUS__"] = new RowStatus_Issue(Dict::Format('UI:CSVReport-Row-Issue-NbField', count($aRowData), $this->m_iNbCol));
 					continue;
 				}
 
@@ -1354,31 +1249,24 @@ class BulkChange
 
 		// Fill in the blanks - the result matrix is expected to be 100% complete
 		//
-		foreach($this->m_aData as $iRow => $aRowData)
-		{
-			foreach($this->m_aAttList as $iCol)
-			{
-				if (!array_key_exists($iCol, $aResult[$iRow]))
-				{
-					if(isset($aRowData[$iCol])) {
+		foreach ($this->m_aData as $iRow => $aRowData) {
+			foreach ($this->m_aAttList as $iCol) {
+				if (!array_key_exists($iCol, $aResult[$iRow])) {
+					if (isset($aRowData[$iCol])) {
 						$aResult[$iRow][$iCol] = new CellStatus_Void($aRowData[$iCol]);
 					} else {
 						$aResult[$iRow][$iCol] = new CellStatus_Issue('', null, Dict::S('UI:CSVReport-Value-Issue-NoValue'));
 					}
 				}
 			}
-			foreach($this->m_aExtKeys as $sAttCode => $aForeignAtts)
-			{
-				if (!array_key_exists($sAttCode, $aResult[$iRow]))
-				{
+			foreach ($this->m_aExtKeys as $sAttCode => $aForeignAtts) {
+				if (!array_key_exists($sAttCode, $aResult[$iRow])) {
 					$aResult[$iRow][$sAttCode] = new CellStatus_Void('n/a');
 				}
-				foreach ($aForeignAtts as $sForeignAttCode => $iCol)
-				{
-					if (!array_key_exists($iCol, $aResult[$iRow]))
-					{
+				foreach ($aForeignAtts as $sForeignAttCode => $iCol) {
+					if (!array_key_exists($iCol, $aResult[$iRow])) {
 						// The foreign attribute is one of our reconciliation key
-						if(isset($aRowData[$iCol])) {
+						if (isset($aRowData[$iCol])) {
 							$aResult[$iRow][$iCol] = new CellStatus_Void($aRowData[$iCol]);
 						} else {
 							$aResult[$iRow][$iCol] = new CellStatus_Issue('', null, 'UI:CSVReport-Value-Issue-NoValue');
@@ -1394,11 +1282,10 @@ class BulkChange
 	/**
 	 * Display the history of bulk imports
 	 */
-	static function DisplayImportHistory(WebPage $oPage, $bFromAjax = false, $bShowAll = false)
+	public static function DisplayImportHistory(WebPage $oPage, $bFromAjax = false, $bShowAll = false)
 	{
 		$sAjaxDivId = "CSVImportHistory";
-		if (!$bFromAjax)
-		{
+		if (!$bFromAjax) {
 			$oPage->add('
'); } @@ -1407,53 +1294,45 @@ class BulkChange $oBulkChangeSearch = DBObjectSearch::FromOQL("SELECT CMDBChange WHERE origin IN ('csv-interactive', 'csv-import.php')"); $iQueryLimit = $bShowAll ? 0 : appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit()); - $oBulkChanges = new DBObjectSet($oBulkChangeSearch, array('date' => false), array(), null, $iQueryLimit); + $oBulkChanges = new DBObjectSet($oBulkChangeSearch, ['date' => false], [], null, $iQueryLimit); $oAppContext = new ApplicationContext(); $bLimitExceeded = false; - if ($oBulkChanges->Count() > (appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit()))) - { + if ($oBulkChanges->Count() > (appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit()))) { $bLimitExceeded = true; - if (!$bShowAll) - { + if (!$bShowAll) { $iMaxObjects = appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit()); $oBulkChanges->SetLimit($iMaxObjects); } } $oBulkChanges->Seek(0); - $aDetails = array(); - while ($oChange = $oBulkChanges->Fetch()) - { + $aDetails = []; + while ($oChange = $oBulkChanges->Fetch()) { $sDate = ''.$oChange->Get('date').''; $sUser = $oChange->GetUserName(); - if (preg_match('/^(.*)\\(CSV\\)$/i', $oChange->Get('userinfo'), $aMatches)) - { + if (preg_match('/^(.*)\\(CSV\\)$/i', $oChange->Get('userinfo'), $aMatches)) { $sUser = $aMatches[1]; - } - else - { + } else { $sUser = $oChange->Get('userinfo'); } $oOpSearch = DBObjectSearch::FromOQL("SELECT CMDBChangeOpCreate WHERE change = :change_id"); - $oOpSet = new DBObjectSet($oOpSearch, array(), array('change_id' => $oChange->GetKey())); + $oOpSet = new DBObjectSet($oOpSearch, [], ['change_id' => $oChange->GetKey()]); $iCreated = $oOpSet->Count(); // Get the class from the first item found (assumption: a CSV load is done for a single class) - if ($oCreateOp = $oOpSet->Fetch()) - { + if ($oCreateOp = $oOpSet->Fetch()) { $sClass = $oCreateOp->Get('objclass'); } $oOpSearch = DBObjectSearch::FromOQL("SELECT CMDBChangeOpSetAttribute WHERE change = :change_id"); - $oOpSet = new DBObjectSet($oOpSearch, array(), array('change_id' => $oChange->GetKey())); + $oOpSet = new DBObjectSet($oOpSearch, [], ['change_id' => $oChange->GetKey()]); - $aModified = array(); - $aAttList = array(); - while ($oModified = $oOpSet->Fetch()) - { + $aModified = []; + $aAttList = []; + while ($oModified = $oOpSet->Fetch()) { // Get the class (if not done earlier on object creation) $sClass = $oModified->Get('objclass'); $iKey = $oModified->Get('objkey'); @@ -1466,28 +1345,23 @@ class BulkChange // Assumption: there is only one class of objects being loaded // Then the last class found gives us the class for every object - if ( ($iModified > 0) || ($iCreated > 0)) - { - $aDetails[] = array('date' => $sDate, 'user' => $sUser, 'class' => $sClass, 'created' => $iCreated, 'modified' => $iModified); + if (($iModified > 0) || ($iCreated > 0)) { + $aDetails[] = ['date' => $sDate, 'user' => $sUser, 'class' => $sClass, 'created' => $iCreated, 'modified' => $iModified]; } } - $aConfig = array( 'date' => array('label' => Dict::S('UI:History:Date'), 'description' => Dict::S('UI:History:Date+')), - 'user' => array('label' => Dict::S('UI:History:User'), 'description' => Dict::S('UI:History:User+')), - 'class' => array('label' => Dict::S('Core:AttributeClass'), 'description' => Dict::S('Core:AttributeClass+')), - 'created' => array('label' => Dict::S('UI:History:StatsCreations'), 'description' => Dict::S('UI:History:StatsCreations+')), - 'modified' => array('label' => Dict::S('UI:History:StatsModifs'), 'description' => Dict::S('UI:History:StatsModifs+')), - ); + $aConfig = [ 'date' => ['label' => Dict::S('UI:History:Date'), 'description' => Dict::S('UI:History:Date+')], + 'user' => ['label' => Dict::S('UI:History:User'), 'description' => Dict::S('UI:History:User+')], + 'class' => ['label' => Dict::S('Core:AttributeClass'), 'description' => Dict::S('Core:AttributeClass+')], + 'created' => ['label' => Dict::S('UI:History:StatsCreations'), 'description' => Dict::S('UI:History:StatsCreations+')], + 'modified' => ['label' => Dict::S('UI:History:StatsModifs'), 'description' => Dict::S('UI:History:StatsModifs+')], + ]; - if ($bLimitExceeded) - { - if ($bShowAll) - { + if ($bLimitExceeded) { + if ($bShowAll) { // Collapsible list $oPage->add('

'.Dict::Format('UI:CountOfResults', $oBulkChanges->Count()).'  '.Dict::S('UI:CollapseList').'

'); - } - else - { + } else { // Truncated list $iMinDisplayLimit = appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit()); $sCollapsedLabel = Dict::Format('UI:TruncatedResults', $iMinDisplayLimit, $oBulkChanges->Count()); @@ -1501,7 +1375,6 @@ class BulkChange EOF ); - $sAppContext = $oAppContext->GetForLink(); $oPage->add_script( <<table($aConfig, $aDetails); - if (!$bFromAjax) - { + if (!$bFromAjax) { $oPage->add('
'); } } @@ -1537,137 +1407,104 @@ EOF * @param $iChange * @throws Exception */ - static function DisplayImportHistoryDetails(iTopWebPage $oPage, $iChange) + public static function DisplayImportHistoryDetails(iTopWebPage $oPage, $iChange) { - if ($iChange == 0) - { + if ($iChange == 0) { throw new Exception("Missing parameter changeid"); } $oChange = MetaModel::GetObject('CMDBChange', $iChange, false); - if (is_null($oChange)) - { + if (is_null($oChange)) { throw new Exception("Unknown change: $iChange"); } $oPage->add("

".Dict::Format('UI:History:BulkImportDetails', $oChange->Get('date'), $oChange->GetUserName())."

\n"); // Assumption : change made one single class of objects - $aObjects = array(); - $aAttributes = array(); // array of attcode => occurences + $aObjects = []; + $aAttributes = []; // array of attcode => occurences $oOpSearch = DBObjectSearch::FromOQL("SELECT CMDBChangeOp WHERE change = :change_id"); - $oOpSet = new DBObjectSet($oOpSearch, array(), array('change_id' => $iChange)); - while ($oOperation = $oOpSet->Fetch()) - { + $oOpSet = new DBObjectSet($oOpSearch, [], ['change_id' => $iChange]); + while ($oOperation = $oOpSet->Fetch()) { $sClass = $oOperation->Get('objclass'); $iKey = $oOperation->Get('objkey'); $iObjId = "$sClass::$iKey"; - if (!isset($aObjects[$iObjId])) - { - $aObjects[$iObjId] = array(); + if (!isset($aObjects[$iObjId])) { + $aObjects[$iObjId] = []; $aObjects[$iObjId]['__class__'] = $sClass; $aObjects[$iObjId]['__id__'] = $iKey; } - if (get_class($oOperation) == 'CMDBChangeOpCreate') - { + if (get_class($oOperation) == 'CMDBChangeOpCreate') { $aObjects[$iObjId]['__created__'] = true; - } - elseif ($oOperation instanceof CMDBChangeOpSetAttribute) - { + } elseif ($oOperation instanceof CMDBChangeOpSetAttribute) { $sAttCode = $oOperation->Get('attcode'); - if ((get_class($oOperation) == 'CMDBChangeOpSetAttributeScalar') || (get_class($oOperation) == 'CMDBChangeOpSetAttributeURL')) - { + if ((get_class($oOperation) == 'CMDBChangeOpSetAttributeScalar') || (get_class($oOperation) == 'CMDBChangeOpSetAttributeURL')) { $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode); - if ($oAttDef->IsExternalKey()) - { + if ($oAttDef->IsExternalKey()) { $sOldValue = Dict::S('UI:UndefinedObject'); - if ($oOperation->Get('oldvalue') != 0) - { + if ($oOperation->Get('oldvalue') != 0) { $oOldTarget = MetaModel::GetObject($oAttDef->GetTargetClass(), $oOperation->Get('oldvalue')); $sOldValue = $oOldTarget->GetHyperlink(); } $sNewValue = Dict::S('UI:UndefinedObject'); - if ($oOperation->Get('newvalue') != 0) - { + if ($oOperation->Get('newvalue') != 0) { $oNewTarget = MetaModel::GetObject($oAttDef->GetTargetClass(), $oOperation->Get('newvalue')); $sNewValue = $oNewTarget->GetHyperlink(); } - } - else - { + } else { $sOldValue = $oOperation->GetAsHTML('oldvalue'); $sNewValue = $oOperation->GetAsHTML('newvalue'); } $aObjects[$iObjId][$sAttCode] = $sOldValue.' -> '.$sNewValue; - } - else - { + } else { $aObjects[$iObjId][$sAttCode] = 'n/a'; } - if (isset($aAttributes[$sAttCode])) - { + if (isset($aAttributes[$sAttCode])) { $aAttributes[$sAttCode]++; - } - else - { + } else { $aAttributes[$sAttCode] = 1; } } } - $aDetails = array(); - foreach($aObjects as $iUId => $aObjData) - { - $aRow = array(); + $aDetails = []; + foreach ($aObjects as $iUId => $aObjData) { + $aRow = []; $oObject = MetaModel::GetObject($aObjData['__class__'], $aObjData['__id__'], false); - if (is_null($oObject)) - { + if (is_null($oObject)) { $aRow['object'] = $aObjData['__class__'].'::'.$aObjData['__id__'].' (deleted)'; - } - else - { + } else { $aRow['object'] = $oObject->GetHyperlink(); } - if (isset($aObjData['__created__'])) - { + if (isset($aObjData['__created__'])) { $aRow['operation'] = Dict::S('Change:ObjectCreated'); - } - else - { + } else { $aRow['operation'] = Dict::S('Change:ObjectModified'); } - foreach ($aAttributes as $sAttCode => $iOccurences) - { - if (isset($aObjData[$sAttCode])) - { + foreach ($aAttributes as $sAttCode => $iOccurences) { + if (isset($aObjData[$sAttCode])) { $aRow[$sAttCode] = $aObjData[$sAttCode]; - } - elseif (!is_null($oObject)) - { + } elseif (!is_null($oObject)) { // This is the current vaslue: $oObject->GetAsHtml($sAttCode) // whereas we are displaying the value that was set at the time // the object was created // This requires addtional coding...let's do that later $aRow[$sAttCode] = ''; - } - else - { + } else { $aRow[$sAttCode] = ''; } } $aDetails[] = $aRow; } - $aConfig = array(); - $aConfig['object'] = array('label' => MetaModel::GetName($sClass), 'description' => MetaModel::GetClassDescription($sClass)); - $aConfig['operation'] = array('label' => Dict::S('UI:History:Changes'), 'description' => Dict::S('UI:History:Changes+')); - foreach ($aAttributes as $sAttCode => $iOccurences) - { - $aConfig[$sAttCode] = array('label' => MetaModel::GetLabel($sClass, $sAttCode), 'description' => MetaModel::GetDescription($sClass, $sAttCode)); + $aConfig = []; + $aConfig['object'] = ['label' => MetaModel::GetName($sClass), 'description' => MetaModel::GetClassDescription($sClass)]; + $aConfig['operation'] = ['label' => Dict::S('UI:History:Changes'), 'description' => Dict::S('UI:History:Changes+')]; + foreach ($aAttributes as $sAttCode => $iOccurences) { + $aConfig[$sAttCode] = ['label' => MetaModel::GetLabel($sClass, $sAttCode), 'description' => MetaModel::GetDescription($sClass, $sAttCode)]; } $oPage->table($aConfig, $aDetails); } } - diff --git a/core/bulkexport.class.inc.php b/core/bulkexport.class.inc.php index 69d83a42b..d74370db0 100644 --- a/core/bulkexport.class.inc.php +++ b/core/bulkexport.class.inc.php @@ -1,4 +1,5 @@ 'core/cmdb', "key_type" => 'autoincrement', - "name_attcode" => array('created'), + "name_attcode" => ['created'], "state_attcode" => '', - "reconc_keys" => array(), + "reconc_keys" => [], "db_table" => 'priv_bulk_export_result', "db_key_field" => 'id', "db_finalclass_field" => '', "display_template" => '', - ); + ]; MetaModel::Init_Params($aParams); - MetaModel::Init_AddAttribute(new AttributeDateTime("created", array("allowed_values"=>null, "sql"=>"created", "default_value"=>"NOW()", "is_null_allowed"=>false, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeInteger("user_id", array("allowed_values"=>null, "sql"=>"user_id", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeInteger("chunk_size", array("allowed_values"=>null, "sql"=>"chunk_size", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeString("format", array("allowed_values"=>null, "sql"=>"format", "default_value"=>'', "is_null_allowed"=>false, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeString("temp_file_path", array("allowed_values"=>null, "sql"=>"temp_file_path", "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeLongText("search", array("allowed_values"=>null, "sql"=>"search", "default_value"=>'', "is_null_allowed"=>false, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeLongText("status_info", array("allowed_values"=>null, "sql"=>"status_info", "default_value"=>'', "is_null_allowed"=>false, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeBoolean("localize_output", array("allowed_values"=>null, "sql"=>"localize_output", "default_value"=>true, "is_null_allowed"=>true, "depends_on"=>array()))); + MetaModel::Init_AddAttribute(new AttributeDateTime("created", ["allowed_values" => null, "sql" => "created", "default_value" => "NOW()", "is_null_allowed" => false, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeInteger("user_id", ["allowed_values" => null, "sql" => "user_id", "default_value" => 0, "is_null_allowed" => false, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeInteger("chunk_size", ["allowed_values" => null, "sql" => "chunk_size", "default_value" => 0, "is_null_allowed" => true, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeString("format", ["allowed_values" => null, "sql" => "format", "default_value" => '', "is_null_allowed" => false, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeString("temp_file_path", ["allowed_values" => null, "sql" => "temp_file_path", "default_value" => '', "is_null_allowed" => true, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeLongText("search", ["allowed_values" => null, "sql" => "search", "default_value" => '', "is_null_allowed" => false, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeLongText("status_info", ["allowed_values" => null, "sql" => "status_info", "default_value" => '', "is_null_allowed" => false, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeBoolean("localize_output", ["allowed_values" => null, "sql" => "localize_output", "default_value" => true, "is_null_allowed" => true, "depends_on" => []])); } @@ -100,23 +101,21 @@ class BulkExportResultGC implements iBackgroundProcess { public function GetPeriodicity() { - return 24*3600; // seconds + return 24 * 3600; // seconds } public function Process($iTimeLimit) { - $sDateLimit = date(AttributeDateTime::GetSQLFormat(), time() - 24*3600); // Every BulkExportResult older than one day will be deleted + $sDateLimit = date(AttributeDateTime::GetSQLFormat(), time() - 24 * 3600); // Every BulkExportResult older than one day will be deleted $sOQL = "SELECT BulkExportResult WHERE created < '$sDateLimit'"; $iProcessed = 0; - while (time() < $iTimeLimit) - { + while (time() < $iTimeLimit) { // Next one ? - $oSet = new CMDBObjectSet(DBObjectSearch::FromOQL($sOQL), array('created' => true) /* order by*/, array(), null, 1 /* limit count */); - $oSet->OptimizeColumnLoad(array('BulkExportResult' => array('temp_file_path'))); + $oSet = new CMDBObjectSet(DBObjectSearch::FromOQL($sOQL), ['created' => true] /* order by*/, [], null, 1 /* limit count */); + $oSet->OptimizeColumnLoad(['BulkExportResult' => ['temp_file_path']]); $oResult = $oSet->Fetch(); - if (is_null($oResult)) - { + if (is_null($oResult)) { // Nothing to be done break; } @@ -160,28 +159,24 @@ abstract class BulkExport $this->bLocalizeOutput = false; } - /** - * Find the first class capable of exporting the data in the given format - * - * @param string $sFormatCode The lowercase format (e.g. html, csv, spreadsheet, xlsx, xml, json, pdf...) - * @param DBSearch $oSearch The search/filter defining the set of objects to export or null when listing the supported formats - * - * @return BulkExport|null - * @throws ReflectionException - */ - static public function FindExporter($sFormatCode, $oSearch = null) + /** + * Find the first class capable of exporting the data in the given format + * + * @param string $sFormatCode The lowercase format (e.g. html, csv, spreadsheet, xlsx, xml, json, pdf...) + * @param DBSearch $oSearch The search/filter defining the set of objects to export or null when listing the supported formats + * + * @return BulkExport|null + * @throws ReflectionException + */ + public static function FindExporter($sFormatCode, $oSearch = null) { - foreach(get_declared_classes() as $sPHPClass) - { + foreach (get_declared_classes() as $sPHPClass) { $oRefClass = new ReflectionClass($sPHPClass); - if ($oRefClass->isSubclassOf('BulkExport') && !$oRefClass->isAbstract()) - { + if ($oRefClass->isSubclassOf('BulkExport') && !$oRefClass->isAbstract()) { /** @var BulkExport $oBulkExporter */ $oBulkExporter = new $sPHPClass(); - if ($oBulkExporter->IsFormatSupported($sFormatCode, $oSearch)) - { - if ($oSearch) - { + if ($oBulkExporter->IsFormatSupported($sFormatCode, $oSearch)) { + if ($oSearch) { $oBulkExporter->SetObjectList($oSearch); } return $oBulkExporter; @@ -191,37 +186,34 @@ abstract class BulkExport return null; } - /** - * Find the exporter corresponding to the given persistent token - * - * @param int $iPersistentToken The identifier of the BulkExportResult object storing the information - * - * @return BulkExport|null - * @throws ArchivedObjectException - * @throws CoreException - * @throws ReflectionException - */ - static public function FindExporterFromToken($iPersistentToken = null) + /** + * Find the exporter corresponding to the given persistent token + * + * @param int $iPersistentToken The identifier of the BulkExportResult object storing the information + * + * @return BulkExport|null + * @throws ArchivedObjectException + * @throws CoreException + * @throws ReflectionException + */ + public static function FindExporterFromToken($iPersistentToken = null) { $oBulkExporter = null; $oInfo = MetaModel::GetObject('BulkExportResult', $iPersistentToken, false); - if ($oInfo && ($oInfo->Get('user_id') == UserRights::GetUserId())) - { + if ($oInfo && ($oInfo->Get('user_id') == UserRights::GetUserId())) { $sFormatCode = $oInfo->Get('format'); - $aStatusInfo = json_decode($oInfo->Get('status_info'),true); + $aStatusInfo = json_decode($oInfo->Get('status_info'), true); $oSearch = DBObjectSearch::unserialize($oInfo->Get('search')); $oSearch->SetShowObsoleteData($aStatusInfo['show_obsolete_data']); $oBulkExporter = self::FindExporter($sFormatCode, $oSearch); - if ($oBulkExporter) - { + if ($oBulkExporter) { $oBulkExporter->SetFormat($sFormatCode); $oBulkExporter->SetObjectList($oSearch); $oBulkExporter->SetChunkSize($oInfo->Get('chunk_size')); $oBulkExporter->SetStatusInfo($aStatusInfo); - $oBulkExporter->SetLocalizeOutput($oInfo->Get('localize_output')); - + $oBulkExporter->SetLocalizeOutput($oInfo->Get('localize_output')); $oBulkExporter->sTmpFile = $oInfo->Get('temp_file_path'); $oBulkExporter->oBulkExportResult = $oInfo; @@ -236,13 +228,11 @@ abstract class BulkExport */ public function AppendToTmpFile($data) { - if ($this->sTmpFile == '') - { + if ($this->sTmpFile == '') { $this->sTmpFile = $this->MakeTmpFile($this->GetFileExtension()); } $hFile = fopen($this->sTmpFile, 'ab'); - if ($hFile !== false) - { + if ($hFile !== false) { fwrite($hFile, $data); fclose($hFile); } @@ -257,15 +247,13 @@ abstract class BulkExport * Lists all possible export formats. The output is a hash array in the form: 'format_code' => 'localized format label' * @return array :string */ - static public function FindSupportedFormats() + public static function FindSupportedFormats() { - $aSupportedFormats = array(); - foreach(get_declared_classes() as $sPHPClass) - { + $aSupportedFormats = []; + foreach (get_declared_classes() as $sPHPClass) { $oRefClass = new ReflectionClass($sPHPClass); - if ($oRefClass->isSubClassOf('BulkExport') && !$oRefClass->isAbstract()) - { - $oBulkExporter = new $sPHPClass; + if ($oRefClass->isSubClassOf('BulkExport') && !$oRefClass->isAbstract()) { + $oBulkExporter = new $sPHPClass(); $aFormats = $oBulkExporter->GetSupportedFormats(); $aSupportedFormats = array_merge($aSupportedFormats, $aFormats); } @@ -282,13 +270,13 @@ abstract class BulkExport $this->iChunkSize = $iChunkSize; } - /** - * @param $bLocalizeOutput - */ - public function SetLocalizeOutput($bLocalizeOutput) - { - $this->bLocalizeOutput = $bLocalizeOutput; - } + /** + * @param $bLocalizeOutput + */ + public function SetLocalizeOutput($bLocalizeOutput) + { + $this->bLocalizeOutput = $bLocalizeOutput; + } /** * (non-PHPdoc) @@ -320,10 +308,9 @@ abstract class BulkExport */ public function GetSupportedFormats() { - return array(); // return array('csv' => Dict::S('UI:ExportFormatCSV')); + return []; // return array('csv' => Dict::S('UI:ExportFormatCSV')); } - public function SetHttpHeaders(WebPage $oPage) { } @@ -347,14 +334,13 @@ abstract class BulkExport public function SaveState() { - if ($this->oBulkExportResult === null) - { + if ($this->oBulkExportResult === null) { $this->oBulkExportResult = new BulkExportResult(); $this->oBulkExportResult->Set('format', $this->sFormatCode); $this->oBulkExportResult->Set('search', $this->oSearch->serialize()); $this->oBulkExportResult->Set('chunk_size', $this->iChunkSize); - $this->oBulkExportResult->Set('localize_output', $this->bLocalizeOutput); - } + $this->oBulkExportResult->Set('localize_output', $this->bLocalizeOutput); + } $this->oBulkExportResult->Set('status_info', json_encode($this->GetStatusInfo())); $this->oBulkExportResult->Set('temp_file_path', $this->sTmpFile); utils::PushArchiveMode(false); @@ -365,11 +351,9 @@ abstract class BulkExport public function Cleanup() { - if (($this->oBulkExportResult && (!$this->oBulkExportResult->IsNew()))) - { + if (($this->oBulkExportResult && (!$this->oBulkExportResult->IsNew()))) { $sFilename = $this->oBulkExportResult->Get('temp_file_path'); - if ($sFilename != '') - { + if ($sFilename != '') { @unlink($sFilename); } utils::PushArchiveMode(false); @@ -380,7 +364,7 @@ abstract class BulkExport public function EnumFormParts() { - return array(); + return []; } /** @@ -464,25 +448,21 @@ abstract class BulkExport */ protected function MakeTmpFile($sExtension) { - if(!is_dir(utils::GetDataPath()."bulk_export")) - { + if (!is_dir(utils::GetDataPath()."bulk_export")) { @mkdir(utils::GetDataPath()."bulk_export", 0777, true /* recursive */); clearstatcache(); } - if (!is_writable(utils::GetDataPath()."bulk_export")) - { + if (!is_writable(utils::GetDataPath()."bulk_export")) { throw new Exception('Data directory "'.utils::GetDataPath().'bulk_export" could not be written.'); } $iNum = rand(); - do - { + do { $iNum++; $sToken = sprintf("%08x", $iNum); $sFileName = utils::GetDataPath()."bulk_export/$sToken.".$sExtension; $hFile = @fopen($sFileName, 'x'); - } - while($hFile === false); + } while ($hFile === false); fclose($hFile); return $sFileName; @@ -492,8 +472,7 @@ abstract class BulkExport // The built-in exports require_once(APPROOT.'core/tabularbulkexport.class.inc.php'); require_once(APPROOT.'core/htmlbulkexport.class.inc.php'); -if (extension_loaded('gd')) -{ +if (extension_loaded('gd')) { // PDF export - via TCPDF - requires GD require_once(APPROOT.'core/pdfbulkexport.class.inc.php'); } @@ -501,4 +480,3 @@ require_once(APPROOT.'core/csvbulkexport.class.inc.php'); require_once(APPROOT.'core/excelbulkexport.class.inc.php'); require_once(APPROOT.'core/spreadsheetbulkexport.class.inc.php'); require_once(APPROOT.'core/xmlbulkexport.class.inc.php'); - diff --git a/core/cmdbobject.class.inc.php b/core/cmdbobject.class.inc.php index ea490edff..1d7a6065e 100644 --- a/core/cmdbobject.class.inc.php +++ b/core/cmdbobject.class.inc.php @@ -1,4 +1,5 @@ - /** * Class cmdbObject * @@ -24,7 +24,6 @@ * @license http://opensource.org/licenses/AGPL-3.0 */ - /** * cmdbObjectClass * the file to include, then the core is yours @@ -148,8 +147,7 @@ abstract class CMDBObject extends DBObject */ public static function GetCurrentChange($bAutoCreate = true) { - if ($bAutoCreate && is_null(self::$m_oCurrChange)) - { + if ($bAutoCreate && is_null(self::$m_oCurrChange)) { self::CreateChange(); } return self::$m_oCurrChange; @@ -214,7 +212,7 @@ abstract class CMDBObject extends DBObject return CMDBChange::GetCurrentUserName(); } else { //N°5135 - add impersonation information in activity log/current cmdb change - if (UserRights::IsImpersonated()){ + if (UserRights::IsImpersonated()) { return sprintf("%s (%s)", CMDBChange::GetCurrentUserName(), self::$m_sInfo); } else { return self::$m_sInfo; @@ -234,12 +232,9 @@ abstract class CMDBObject extends DBObject if (is_null(self::$m_sUserId) //N°5135 - indicate impersonation inside changelogs && (false === UserRights::IsImpersonated()) - ) - { + ) { return CMDBChange::GetCurrentUserId(); - } - else - { + } else { return self::$m_sUserId; } } @@ -249,12 +244,9 @@ abstract class CMDBObject extends DBObject */ protected static function GetTrackOrigin() { - if (is_null(self::$m_sOrigin)) - { + if (is_null(self::$m_sOrigin)) { return 'interactive'; - } - else - { + } else { return self::$m_sOrigin; } } @@ -382,14 +374,10 @@ abstract class CMDBObject extends DBObject // $aValues is an array of $sAttCode => $value // - foreach ($aValues as $sAttCode=> $value) - { - if (array_key_exists($sAttCode, $aOrigValues)) - { + foreach ($aValues as $sAttCode => $value) { + if (array_key_exists($sAttCode, $aOrigValues)) { $original = $aOrigValues[$sAttCode]; - } - else - { + } else { $original = null; } $this->RecordAttChange($sAttCode, $original, $value); @@ -431,8 +419,7 @@ abstract class CMDBObject extends DBObject $bOriginal = $this->Get('archive_flag'); parent::DBArchive(); - if (!$bOriginal) - { + if (!$bOriginal) { utils::PushArchiveMode(false); $this->RecordAttChange('archive_flag', false, true); utils::PopArchiveMode(); @@ -445,8 +432,7 @@ abstract class CMDBObject extends DBObject $bOriginal = $this->Get('archive_flag'); parent::DBUnarchive(); - if ($bOriginal) - { + if ($bOriginal) { utils::PushArchiveMode(false); $this->RecordAttChange('archive_flag', true, false); utils::PopArchiveMode(); @@ -454,8 +440,6 @@ abstract class CMDBObject extends DBObject } } - - /** * TODO: investigate how to get rid of this class that was made to workaround some language limitation... or a poor design! * @@ -471,7 +455,7 @@ class CMDBObjectSet extends DBObjectSet // just to get the right object class in return. // I have to think again to those things: maybe it will work fine if a have a constructor define here (?) - static public function FromScratch($sClass) + public static function FromScratch($sClass) { $oFilter = new DBObjectSearch($sClass); $oFilter->AddConditionExpression(new FalseExpression()); @@ -483,14 +467,14 @@ class CMDBObjectSet extends DBObjectSet // create an object set ex nihilo // input = array of objects - static public function FromArray($sClass, $aObjects) + public static function FromArray($sClass, $aObjects) { $oRetSet = self::FromScratch($sClass); $oRetSet->AddObjectArray($aObjects, $sClass); return $oRetSet; } - static public function FromArrayAssoc($aClasses, $aObjects) + public static function FromArrayAssoc($aClasses, $aObjects) { // In a perfect world, we should create a complete tree of DBObjectSearch, // but as we lack most of the information related to the objects, @@ -502,8 +486,7 @@ class CMDBObjectSet extends DBObjectSet $oRetSet = new CMDBObjectSet($oFilter); $oRetSet->m_bLoaded = true; // no DB load - foreach($aObjects as $rowIndex => $aObjectsByClassAlias) - { + foreach ($aObjects as $rowIndex => $aObjectsByClassAlias) { $oRetSet->AddObjectExtended($aObjectsByClassAlias); } return $oRetSet; diff --git a/core/cmdbsource.class.inc.php b/core/cmdbsource.class.inc.php index 0323d34e7..b688bc2bc 100644 --- a/core/cmdbsource.class.inc.php +++ b/core/cmdbsource.class.inc.php @@ -1,4 +1,5 @@ - /** * DB Server abstraction * @@ -29,7 +29,6 @@ use Combodo\iTop\Core\DbConnectionWrapper; require_once('MyHelpers.class.inc.php'); require_once(APPROOT.'core/kpi.class.inc.php'); - /** * CMDBSource * database access wrapper @@ -38,21 +37,20 @@ require_once(APPROOT.'core/kpi.class.inc.php'); */ class CMDBSource { - const ENUM_DB_VENDOR_MYSQL = 'MySQL'; - const ENUM_DB_VENDOR_MARIADB = 'MariaDB'; - const ENUM_DB_VENDOR_PERCONA = 'Percona'; - + public const ENUM_DB_VENDOR_MYSQL = 'MySQL'; + public const ENUM_DB_VENDOR_MARIADB = 'MariaDB'; + public const ENUM_DB_VENDOR_PERCONA = 'Percona'; /** * Error: 1205 SQLSTATE: HY000 (ER_LOCK_WAIT_TIMEOUT) * Message: Lock wait timeout exceeded; try restarting transaction */ - const MYSQL_ERRNO_WAIT_TIMEOUT = 1205; + public const MYSQL_ERRNO_WAIT_TIMEOUT = 1205; /** * Error: 1213 SQLSTATE: 40001 (ER_LOCK_DEADLOCK) * Message: Deadlock found when trying to get lock; try restarting transaction */ - const MYSQL_ERRNO_DEADLOCK = 1213; + public const MYSQL_ERRNO_DEADLOCK = 1213; protected static $m_sDBHost; protected static $m_sDBUser; @@ -123,9 +121,13 @@ class CMDBSource * @throws \MySQLException */ public static function Init( - $sServer, $sUser, $sPwd, $sSource = '', $bTlsEnabled = false, $sTlsCA = null - ) - { + $sServer, + $sUser, + $sPwd, + $sSource = '', + $bTlsEnabled = false, + $sTlsCA = null + ) { self::$m_sDBHost = $sServer; self::$m_sDBUser = $sUser; self::$m_sDBPwd = $sPwd; @@ -152,7 +154,13 @@ class CMDBSource * @uses IsOpenedDbConnectionUsingTls when asking for a TLS connection, to check if it was really opened using TLS */ public static function GetMysqliInstance( - $sDbHost, $sUser, $sPwd, $sSource = '', $bTlsEnabled = false, $sTlsCa = null, $bCheckTlsAfterConnection = false + $sDbHost, + $sUser, + $sPwd, + $sSource = '', + $bTlsEnabled = false, + $sTlsCa = null, + $bCheckTlsAfterConnection = false ) { $sServer = null; $iPort = null; @@ -164,12 +172,10 @@ class CMDBSource // but some other errors will still cause the query() method to return false !!! mysqli_report(MYSQLI_REPORT_STRICT); - try - { + try { $oMysqli = new mysqli(); - if ($bTlsEnabled) - { + if ($bTlsEnabled) { $iFlags = (empty($sTlsCa)) ? MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT : MYSQLI_CLIENT_SSL; @@ -179,31 +185,31 @@ class CMDBSource $oMysqli->ssl_set($bTlsEnabled, $sTlsCert, $sTlsCa, $sTlsCaPath, $sTlsCipher); } $oMysqli->real_connect($sServer, $sUser, $sPwd, '', $iPort, ini_get("mysqli.default_socket"), $iFlags); - } - catch(mysqli_sql_exception $e) - { - throw new MySQLException('Could not connect to the DB server', array('host' => $sServer, 'user' => $sUser),$e); + } catch (mysqli_sql_exception $e) { + throw new MySQLException('Could not connect to the DB server', ['host' => $sServer, 'user' => $sUser], $e); } if ($bTlsEnabled && $bCheckTlsAfterConnection - && !self::IsOpenedDbConnectionUsingTls($oMysqli)) - { - throw new MySQLException("Connection to the database is not encrypted whereas it was opened using TLS parameters", - null, null, $oMysqli); + && !self::IsOpenedDbConnectionUsingTls($oMysqli)) { + throw new MySQLException( + "Connection to the database is not encrypted whereas it was opened using TLS parameters", + null, + null, + $oMysqli + ); } - if (!empty($sSource)) - { - try - { + if (!empty($sSource)) { + try { mysqli_report(MYSQLI_REPORT_STRICT); // Errors, in the next query, will throw mysqli_sql_exception $oMysqli->query("USE `$sSource`"); - } - catch(mysqli_sql_exception $e) - { - throw new MySQLException('Could not select DB', - array('host' => $sServer, 'user' => $sUser, 'db_name' => $sSource), $e); + } catch (mysqli_sql_exception $e) { + throw new MySQLException( + 'Could not select DB', + ['host' => $sServer, 'user' => $sUser, 'db_name' => $sSource], + $e + ); } } @@ -235,7 +241,7 @@ class CMDBSource $iConnectInfoCount = count($aConnectInfo); if ($bUsePersistentConnection && ($iConnectInfoCount == 3)) { $iPort = (int)($aConnectInfo[2]); - } else if (!$bUsePersistentConnection && ($iConnectInfoCount == 2)) { + } elseif (!$bUsePersistentConnection && ($iConnectInfoCount == 2)) { $iPort = (int)($aConnectInfo[1]); } } @@ -278,12 +284,9 @@ class CMDBSource */ private static function IsMySqlVarNonEmpty($sVarName, $oMysqli) { - try - { + try { $sResult = self::QueryToScalar("SHOW SESSION STATUS LIKE '$sVarName'", 1, $oMysqli); - } - catch (MySQLQueryHasNoResultException $e) - { + } catch (MySQLQueryHasNoResultException $e) { $sResult = null; } @@ -292,14 +295,10 @@ class CMDBSource public static function SetCharacterSet($sCharset = DEFAULT_CHARACTER_SET, $sCollation = DEFAULT_COLLATION) { - if (strlen($sCharset) > 0) - { - if (strlen($sCollation) > 0) - { + if (strlen($sCharset) > 0) { + if (strlen($sCollation) > 0) { self::Query("SET NAMES '$sCharset' COLLATE '$sCollation'"); - } - else - { + } else { self::Query("SET NAMES '$sCharset'"); } } @@ -309,8 +308,7 @@ class CMDBSource { // Note: requires the installation of MySQL special tables, // otherwise, only 'SYSTEM' or "+10:00' may be specified which is NOT sufficient because of day light saving times - if (!is_null($sTimezone)) - { + if (!is_null($sTimezone)) { $sQuotedTimezone = self::Quote($sTimezone); self::Query("SET time_zone = $sQuotedTimezone"); } @@ -325,18 +323,16 @@ class CMDBSource public static function IsDB($sSource) { - try - { + try { $aDBs = self::ListDB(); - foreach($aDBs as $sDBName) - { - // perform a case insensitive test because on Windows the table names become lowercase :-( - if (strtolower($sDBName) == strtolower($sSource)) return true; + foreach ($aDBs as $sDBName) { + // perform a case insensitive test because on Windows the table names become lowercase :-( + if (strtolower($sDBName) == strtolower($sSource)) { + return true; + } } return false; - } - catch(Exception $e) - { + } catch (Exception $e) { // In case we don't have rights to enumerate the databases // Let's try to connect directly /** @noinspection NullPointerExceptionInspection this shouldn't be called with un-init DB */ @@ -368,13 +364,10 @@ class CMDBSource { $sDBVendor = static::ENUM_DB_VENDOR_MYSQL; - $sVersionComment = static::GetServerVariable('version') . ' - ' . static::GetServerVariable('version_comment'); - if(preg_match('/mariadb/i', $sVersionComment) === 1) - { + $sVersionComment = static::GetServerVariable('version').' - '.static::GetServerVariable('version_comment'); + if (preg_match('/mariadb/i', $sVersionComment) === 1) { $sDBVendor = static::ENUM_DB_VENDOR_MARIADB; - } - else if(preg_match('/percona/i', $sVersionComment) === 1) - { + } elseif (preg_match('/percona/i', $sVersionComment) === 1) { $sDBVendor = static::ENUM_DB_VENDOR_PERCONA; } @@ -390,7 +383,7 @@ class CMDBSource { /** @noinspection NullPointerExceptionInspection this shouldn't be called with un-init DB */ if (!((bool)DbConnectionWrapper::GetDbConnection(true)->query("USE `$sSource`"))) { - throw new MySQLException('Could not select DB', array('db_name' => $sSource)); + throw new MySQLException('Could not select DB', ['db_name' => $sSource]); } self::$m_sDBName = $sSource; } @@ -409,13 +402,11 @@ class CMDBSource public static function DropDB($sDBToDrop = '') { - if (empty($sDBToDrop)) - { + if (empty($sDBToDrop)) { $sDBToDrop = self::$m_sDBName; } self::Query("DROP DATABASE `$sDBToDrop`"); - if ($sDBToDrop == self::$m_sDBName) - { + if ($sDBToDrop == self::$m_sDBName) { self::$m_sDBName = ''; } self::_TablesInfoCacheReset(); // reset the table info cache! @@ -468,10 +459,22 @@ class CMDBSource } } - public static function DBHost() {return self::$m_sDBHost;} - public static function DBUser() {return self::$m_sDBUser;} - public static function DBPwd() {return self::$m_sDBPwd;} - public static function DBName() {return self::$m_sDBName;} + public static function DBHost() + { + return self::$m_sDBHost; + } + public static function DBUser() + { + return self::$m_sDBUser; + } + public static function DBPwd() + { + return self::$m_sDBPwd; + } + public static function DBName() + { + return self::$m_sDBName; + } /** * Quote variable and protect against SQL injection attacks @@ -486,24 +489,20 @@ class CMDBSource */ public static function Quote($value, $bAlways = false, $cQuoteStyle = "'") { - if (is_null($value)) - { + if (is_null($value)) { return 'NULL'; } - if (is_array($value)) - { - $aRes = array(); - foreach ($value as $key => $itemvalue) - { + if (is_array($value)) { + $aRes = []; + foreach ($value as $key => $itemvalue) { $aRes[$key] = self::Quote($itemvalue, $bAlways, $cQuoteStyle); } return $aRes; } // Quote if not a number or a numeric string - if ($bAlways || is_string($value)) - { + if ($bAlways || is_string($value)) { /** @noinspection NullPointerExceptionInspection this shouldn't be called with un-init DB */ $value = $cQuoteStyle.DbConnectionWrapper::GetDbConnection()->real_escape_string($value).$cQuoteStyle; } @@ -520,8 +519,7 @@ class CMDBSource */ private static function RemoveSurroundingQuotes($sValue) { - if (utils::StartsWith($sValue, '\'') && utils::EndsWith($sValue, '\'')) - { + if (utils::StartsWith($sValue, '\'') && utils::EndsWith($sValue, '\'')) { $sValue = substr($sValue, 1, -1); } @@ -531,34 +529,30 @@ class CMDBSource /** * @param string $sSQLQuery * - * @return mysqli_result|null - * @throws MySQLException - * @throws MySQLHasGoneAwayException + * @return mysqli_result|null + * @throws MySQLException + * @throws MySQLHasGoneAwayException * * @since 2.7.0 N°679 handles nested transactions */ public static function Query($sSQLQuery) { - if (preg_match('/^START TRANSACTION;?$/i', $sSQLQuery)) - { + if (preg_match('/^START TRANSACTION;?$/i', $sSQLQuery)) { self::StartTransaction(); return null; } - if (preg_match('/^COMMIT;?$/i', $sSQLQuery)) - { + if (preg_match('/^COMMIT;?$/i', $sSQLQuery)) { self::Commit(); return null; } - if (preg_match('/^ROLLBACK;?$/i', $sSQLQuery)) - { + if (preg_match('/^ROLLBACK;?$/i', $sSQLQuery)) { self::Rollback(); return null; } - return self::DBQuery($sSQLQuery); } @@ -585,20 +579,17 @@ class CMDBSource } $oKPI = new ExecutionKPI(); - try - { + try { /** @noinspection NullPointerExceptionInspection this shouldn't be called with un-init DB */ $oResult = DbConnectionWrapper::GetDbConnection(true)->query($sSql); - } - catch (mysqli_sql_exception $e) - { + } catch (mysqli_sql_exception $e) { self::LogDeadLock($e, true); - throw new MySQLException('Failed to issue SQL query', array('query' => $sSql, $e)); + throw new MySQLException('Failed to issue SQL query', ['query' => $sSql, $e]); } finally { - $oKPI->ComputeStats('Query exec (mySQL)', $sSql); - } + $oKPI->ComputeStats('Query exec (mySQL)', $sSql); + } if ($oResult === false) { - $aContext = array('query' => $sSql); + $aContext = ['query' => $sSql]; $iMySqlErrorNo = DbConnectionWrapper::GetDbConnection(true)->errno; $aMySqlHasGoneAwayErrorCodes = MySQLHasGoneAwayException::getErrorCodes(); @@ -627,7 +618,7 @@ class CMDBSource // checks MySQL error code if ($bCheckMysqliErrno) { $iMySqlErrorNo = DbConnectionWrapper::GetDbConnection($bForQuery)->errno; - if (!in_array($iMySqlErrorNo, array(self::MYSQL_ERRNO_WAIT_TIMEOUT, self::MYSQL_ERRNO_DEADLOCK))) { + if (!in_array($iMySqlErrorNo, [self::MYSQL_ERRNO_WAIT_TIMEOUT, self::MYSQL_ERRNO_DEADLOCK])) { return; } } else { @@ -641,21 +632,19 @@ class CMDBSource if ($oError !== false) { $aData = $oError->fetch_all(MYSQLI_ASSOC); $sInnodbStatus = $aData[0]; - } - else - { + } else { $sInnodbStatus = 'Get status query cannot execute'; } // log ! $sMessage = "deadlock detected: user= $sUser; errno=$iMySqlErrorNo"; - $aLogContext = array( + $aLogContext = [ 'userinfo' => $sUser, 'errno' => $iMySqlErrorNo, 'ex_msg' => $e->getMessage(), 'callstack' => $e->getTraceAsString(), 'data' => $sInnodbStatus, - ); + ]; DeadLockLog::Info($sMessage, $iMySqlErrorNo, $aLogContext); IssueLog::Error($sMessage, LogChannels::DEADLOCK, [ @@ -677,7 +666,7 @@ class CMDBSource */ private static function StartTransaction() { - $aStackTrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT , 3); + $aStackTrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 3); $bHasExistingTransactions = self::IsInsideTransaction(); if (!$bHasExistingTransactions) { @@ -702,8 +691,8 @@ class CMDBSource */ private static function Commit() { - $aStackTrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT , 3); - if(isset($aStackTrace[2]['class']) && isset($aStackTrace[2]['function'])) { + $aStackTrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 3); + if (isset($aStackTrace[2]['class']) && isset($aStackTrace[2]['function'])) { $sCaller = 'From '.$aStackTrace[1]['file'].'('.$aStackTrace[1]['line'].'): '.$aStackTrace[2]['class'].'->'.$aStackTrace[2]['function'].'()'; } else { $sCaller = 'From '.$aStackTrace[1]['file'].'('.$aStackTrace[1]['line'].') '; @@ -740,8 +729,8 @@ class CMDBSource */ private static function Rollback() { - $aStackTrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT , 3); - if(isset($aStackTrace[2]['class']) && isset($aStackTrace[2]['function'])) { + $aStackTrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 3); + if (isset($aStackTrace[2]['class']) && isset($aStackTrace[2]['function'])) { $sCaller = 'From '.$aStackTrace[1]['file'].'('.$aStackTrace[1]['line'].'): '.$aStackTrace[2]['class'].'->'.$aStackTrace[2]['function'].'()'; } else { $sCaller = 'From '.$aStackTrace[1]['file'].'('.$aStackTrace[1]['line'].') '; @@ -790,8 +779,7 @@ class CMDBSource */ private static function RemoveLastTransactionLevel() { - if (self::$m_iTransactionLevel === 0) - { + if (self::$m_iTransactionLevel === 0) { return; } @@ -819,12 +807,10 @@ class CMDBSource return false; } - public static function GetInsertId() { $iRes = DbConnectionWrapper::GetDbConnection()->insert_id; - if (is_null($iRes)) - { + if (is_null($iRes)) { return 0; } return $iRes; @@ -832,8 +818,7 @@ class CMDBSource public static function InsertInto($sSQLQuery) { - if (self::Query($sSQLQuery)) - { + if (self::Query($sSQLQuery)) { return self::GetInsertId(); } return false; @@ -869,31 +854,26 @@ class CMDBSource try { /** @noinspection NullPointerExceptionInspection this shouldn't happen : either cnx is passed or the DB was init */ $oResult = $oMysqliForQuery->query($sSql); - } - catch (mysqli_sql_exception $e) { + } catch (mysqli_sql_exception $e) { $oKPI->ComputeStats('Query exec (mySQL)', $sSql); - throw new MySQLException('Failed to issue SQL query', array('query' => $sSql, $e)); + throw new MySQLException('Failed to issue SQL query', ['query' => $sSql, $e]); } $oKPI->ComputeStats('Query exec (mySQL)', $sSql); if ($oResult === false) { - throw new MySQLException('Failed to issue SQL query', array('query' => $sSql)); + throw new MySQLException('Failed to issue SQL query', ['query' => $sSql]); } - if ($aRow = $oResult->fetch_array(MYSQLI_BOTH)) - { + if ($aRow = $oResult->fetch_array(MYSQLI_BOTH)) { $res = $aRow[$iCol]; - } - else - { + } else { $oResult->free(); - throw new MySQLQueryHasNoResultException('Found no result for query', array('query' => $sSql)); + throw new MySQLQueryHasNoResultException('Found no result for query', ['query' => $sSql]); } $oResult->free(); return $res; } - /** * @param string $sSql * @param int $iMode @@ -903,26 +883,21 @@ class CMDBSource */ public static function QueryToArray($sSql, $iMode = MYSQLI_BOTH) { - $aData = array(); + $aData = []; $oKPI = new ExecutionKPI(); - try - { + try { /** @noinspection NullPointerExceptionInspection this shouldn't be called with un-init DB */ $oResult = DbConnectionWrapper::GetDbConnection(true)->query($sSql); - } - catch(mysqli_sql_exception $e) - { + } catch (mysqli_sql_exception $e) { $oKPI->ComputeStats('Query exec (mySQL)', $sSql); - throw new MySQLException('Failed to issue SQL query', array('query' => $sSql, $e)); + throw new MySQLException('Failed to issue SQL query', ['query' => $sSql, $e]); } $oKPI->ComputeStats('Query exec (mySQL)', $sSql); - if ($oResult === false) - { - throw new MySQLException('Failed to issue SQL query', array('query' => $sSql)); + if ($oResult === false) { + throw new MySQLException('Failed to issue SQL query', ['query' => $sSql]); } - while ($aRow = $oResult->fetch_array($iMode)) - { + while ($aRow = $oResult->fetch_array($iMode)) { $aData[] = $aRow; } $oResult->free(); @@ -938,10 +913,9 @@ class CMDBSource */ public static function QueryToCol($sSql, $col) { - $aColumn = array(); + $aColumn = []; $aData = self::QueryToArray($sSql); - foreach($aData as $aRow) - { + foreach ($aData as $aRow) { @$aColumn[] = $aRow[$col]; } return $aColumn; @@ -955,26 +929,21 @@ class CMDBSource */ public static function ExplainQuery($sSql) { - $aData = array(); - try - { + $aData = []; + try { /** @noinspection NullPointerExceptionInspection this shouldn't be called with un-init DB */ $oResult = DbConnectionWrapper::GetDbConnection(true)->query($sSql); + } catch (mysqli_sql_exception $e) { + throw new MySQLException('Failed to issue SQL query', ['query' => $sSql, $e]); } - catch(mysqli_sql_exception $e) - { - throw new MySQLException('Failed to issue SQL query', array('query' => $sSql, $e)); - } - if ($oResult === false) - { - throw new MySQLException('Failed to issue SQL query', array('query' => $sSql)); + if ($oResult === false) { + throw new MySQLException('Failed to issue SQL query', ['query' => $sSql]); } $aNames = self::GetColumns($oResult, $sSql); $aData[] = $aNames; - while ($aRow = $oResult->fetch_array(MYSQLI_ASSOC)) - { + while ($aRow = $oResult->fetch_array(MYSQLI_ASSOC)) { $aData[] = $aRow; } $oResult->free(); @@ -989,22 +958,17 @@ class CMDBSource */ public static function TestQuery($sSql) { - try - { + try { /** @noinspection NullPointerExceptionInspection this shouldn't be called with un-init DB */ $oResult = DbConnectionWrapper::GetDbConnection(true)->query($sSql); + } catch (mysqli_sql_exception $e) { + throw new MySQLException('Failed to issue SQL query', ['query' => $sSql, $e]); } - catch(mysqli_sql_exception $e) - { - throw new MySQLException('Failed to issue SQL query', array('query' => $sSql, $e)); - } - if ($oResult === false) - { - throw new MySQLException('Failed to issue SQL query', array('query' => $sSql)); + if ($oResult === false) { + throw new MySQLException('Failed to issue SQL query', ['query' => $sSql]); } - if (is_object($oResult)) - { + if (is_object($oResult)) { $oResult->free(); } return ''; @@ -1034,16 +998,12 @@ class CMDBSource */ public static function GetColumns($oResult, $sSql) { - $aNames = array(); - for ($i = 0; $i < (($___mysqli_tmp = $oResult->field_count) ? $___mysqli_tmp : 0) ; $i++) - { + $aNames = []; + for ($i = 0; $i < (($___mysqli_tmp = $oResult->field_count) ? $___mysqli_tmp : 0) ; $i++) { $meta = $oResult->fetch_field_direct($i); - if (!$meta) - { - throw new MySQLException('mysql_fetch_field: No information available', array('query'=>$sSql, 'i'=>$i)); - } - else - { + if (!$meta) { + throw new MySQLException('mysql_fetch_field: No information available', ['query' => $sSql, 'i' => $i]); + } else { $aNames[] = $meta->name; } } @@ -1070,20 +1030,32 @@ class CMDBSource public static function IsKey($sTable, $iKey) { $aTableInfo = self::GetTableInfo($sTable); - if (empty($aTableInfo)) return false; - if (!array_key_exists($iKey, $aTableInfo["Fields"])) return false; + if (empty($aTableInfo)) { + return false; + } + if (!array_key_exists($iKey, $aTableInfo["Fields"])) { + return false; + } $aFieldData = $aTableInfo["Fields"][$iKey]; - if (!array_key_exists("Key", $aFieldData)) return false; + if (!array_key_exists("Key", $aFieldData)) { + return false; + } return ($aFieldData["Key"] == "PRI"); } public static function IsAutoIncrement($sTable, $sField) { $aTableInfo = self::GetTableInfo($sTable); - if (empty($aTableInfo)) return false; - if (!array_key_exists($sField, $aTableInfo["Fields"])) return false; + if (empty($aTableInfo)) { + return false; + } + if (!array_key_exists($sField, $aTableInfo["Fields"])) { + return false; + } $aFieldData = $aTableInfo["Fields"][$sField]; - if (!array_key_exists("Extra", $aFieldData)) return false; + if (!array_key_exists("Extra", $aFieldData)) { + return false; + } //MyHelpers::debug_breakpoint($aFieldData); return (strstr($aFieldData["Extra"], "auto_increment")); } @@ -1091,16 +1063,24 @@ class CMDBSource public static function IsField($sTable, $sField) { $aTableInfo = self::GetTableInfo($sTable); - if (empty($aTableInfo)) return false; - if (!array_key_exists($sField, $aTableInfo["Fields"])) return false; + if (empty($aTableInfo)) { + return false; + } + if (!array_key_exists($sField, $aTableInfo["Fields"])) { + return false; + } return true; } public static function IsNullAllowed($sTable, $sField) { $aTableInfo = self::GetTableInfo($sTable); - if (empty($aTableInfo)) return false; - if (!array_key_exists($sField, $aTableInfo["Fields"])) return false; + if (empty($aTableInfo)) { + return false; + } + if (!array_key_exists($sField, $aTableInfo["Fields"])) { + return false; + } $aFieldData = $aTableInfo["Fields"][$sField]; return (strtolower($aFieldData["Null"]) == "yes"); } @@ -1108,20 +1088,22 @@ class CMDBSource public static function GetFieldType($sTable, $sField) { $aTableInfo = self::GetTableInfo($sTable); - if (empty($aTableInfo)) return false; - if (!array_key_exists($sField, $aTableInfo["Fields"])) return false; + if (empty($aTableInfo)) { + return false; + } + if (!array_key_exists($sField, $aTableInfo["Fields"])) { + return false; + } $aFieldData = $aTableInfo["Fields"][$sField]; return ($aFieldData["Type"]); } private static function IsNumericType($aFieldData) { - $aNumericTypes = array('tinyint(', 'decimal(', 'int(' ); + $aNumericTypes = ['tinyint(', 'decimal(', 'int(' ]; $sType = strtolower($aFieldData["Type"]); - foreach ($aNumericTypes as $sNumericType) - { - if (strpos($sType, $sNumericType) === 0) - { + foreach ($aNumericTypes as $sNumericType) { + if (strpos($sType, $sNumericType) === 0) { return true; } } @@ -1154,21 +1136,18 @@ class CMDBSource [$sItopFieldDataType, $sItopFieldTypeOptions, $sItopFieldOtherOptions] = static::GetFieldDataTypeAndOptions($sItopGeneratedFieldType); [$sDbFieldDataType, $sDbFieldTypeOptions, $sDbFieldOtherOptions] = static::GetFieldDataTypeAndOptions($sDbFieldType); - if (strcasecmp($sItopFieldDataType, $sDbFieldDataType) !== 0) - { + if (strcasecmp($sItopFieldDataType, $sDbFieldDataType) !== 0) { return false; } - if (strcmp($sItopFieldTypeOptions, $sDbFieldTypeOptions) !== 0) - { + if (strcmp($sItopFieldTypeOptions, $sDbFieldTypeOptions) !== 0) { // case sensitive comp as we need to check case for enum possible values for example return false; } // remove the default value NULL added by MariadDB $sMariaDbDefaultNull = ' DEFAULT \'NULL\''; - if (utils::EndsWith($sDbFieldOtherOptions, $sMariaDbDefaultNull)) - { + if (utils::EndsWith($sDbFieldOtherOptions, $sMariaDbDefaultNull)) { $sDbFieldOtherOptions = substr($sDbFieldOtherOptions, 0, -strlen($sMariaDbDefaultNull)); } // remove quotes around default values (always present in MariaDB) @@ -1176,17 +1155,16 @@ class CMDBSource '/( DEFAULT )\'([^\']+)\'/', function ($aMatches) use ($sItopFieldDataType) { // ENUM default values should keep quotes, but all other numeric values don't have quotes - if (is_numeric($aMatches[2]) && ($sItopFieldDataType !== 'ENUM')) - { + if (is_numeric($aMatches[2]) && ($sItopFieldDataType !== 'ENUM')) { return $aMatches[1].$aMatches[2]; } return $aMatches[0]; }, - $sDbFieldOtherOptions); + $sDbFieldOtherOptions + ); - if (strcasecmp($sItopFieldOtherOptions, $sDbFieldOtherOptions) !== 0) - { + if (strcasecmp($sItopFieldOtherOptions, $sDbFieldOtherOptions) !== 0) { return false; } @@ -1211,10 +1189,10 @@ class CMDBSource $sDataType = isset($aMatches[1]) ? $aMatches[1] : ''; - if (strcasecmp($sDataType, 'ENUM') === 0){ - try{ + if (strcasecmp($sDataType, 'ENUM') === 0) { + try { return self::GetEnumOptions($sDataType, $sCompleteFieldType); - }catch(CoreException $e){ + } catch (CoreException $e) { //do nothing ; especially do not block setup. IssueLog::Warning("enum was not parsed properly: $sCompleteFieldType. it should not happen during setup."); } @@ -1223,7 +1201,7 @@ class CMDBSource $sTypeOptions = isset($aMatches[2]) ? $aMatches[3] : ''; $sOtherOptions = isset($aMatches[4]) ? $aMatches[4] : ''; - return array($sDataType, $sTypeOptions, $sOtherOptions); + return [$sDataType, $sTypeOptions, $sOtherOptions]; } /** @@ -1244,16 +1222,16 @@ class CMDBSource $iFirstOpeningParenthesis = strpos($sCompleteFieldType, '('); $iLastEndingParenthesis = strrpos($sCompleteFieldType, ')'); - if ($iFirstOpeningParenthesis === false || $iLastEndingParenthesis === false ){ + if ($iFirstOpeningParenthesis === false || $iLastEndingParenthesis === false) { //should never happen as GetFieldDataTypeAndOptions regexp matched. //except if regexp is modiied/broken somehow one day... - throw new CoreException("GetEnumOptions issue with $sDataType parsing : " . $sCompleteFieldType); + throw new CoreException("GetEnumOptions issue with $sDataType parsing : ".$sCompleteFieldType); } $sTypeOptions = substr($sCompleteFieldType, $iFirstOpeningParenthesis + 1, $iLastEndingParenthesis - 1); $sOtherOptions = substr($sCompleteFieldType, $iLastEndingParenthesis + 1); - return array($sDataType, $sTypeOptions, $sOtherOptions); + return [$sDataType, $sTypeOptions, $sOtherOptions]; } /** @@ -1266,47 +1244,40 @@ class CMDBSource public static function GetFieldSpec($sTable, $sField) { $aTableInfo = self::GetTableInfo($sTable); - if (empty($aTableInfo)) return false; - if (!array_key_exists($sField, $aTableInfo["Fields"])) return false; + if (empty($aTableInfo)) { + return false; + } + if (!array_key_exists($sField, $aTableInfo["Fields"])) { + return false; + } $aFieldData = $aTableInfo["Fields"][$sField]; $sRet = $aFieldData["Type"]; $sColumnCharset = $aFieldData["Charset"]; $sColumnCollation = $aFieldData["Collation"]; - if (!empty($sColumnCharset)) - { + if (!empty($sColumnCharset)) { $sRet .= ' CHARACTER SET '.$sColumnCharset; $sRet .= ' COLLATE '.$sColumnCollation; } - if ($aFieldData["Null"] == 'NO') - { + if ($aFieldData["Null"] == 'NO') { $sRet .= ' NOT NULL'; } - if (is_numeric($aFieldData["Default"])) - { - if (strtolower(substr($aFieldData["Type"], 0, 5)) == 'enum(') - { + if (is_numeric($aFieldData["Default"])) { + if (strtolower(substr($aFieldData["Type"], 0, 5)) == 'enum(') { // Force quotes to match the column declaration statement $sRet .= ' DEFAULT '.self::Quote($aFieldData["Default"], true); - } - else - { - if (self::IsNumericType($aFieldData)) - { + } else { + if (self::IsNumericType($aFieldData)) { $sRet .= ' DEFAULT '.$aFieldData["Default"]; - } - else - { + } else { $default = $aFieldData["Default"] + 0; // Coerce to a numeric variable $sRet .= ' DEFAULT '.self::Quote($default); } } - } - elseif (is_string($aFieldData["Default"]) == 'string') - { + } elseif (is_string($aFieldData["Default"]) == 'string') { $sDefaultValue = static::RemoveSurroundingQuotes($aFieldData["Default"]); $sRet .= ' DEFAULT '.self::Quote($sDefaultValue); } @@ -1317,28 +1288,29 @@ class CMDBSource public static function HasIndex($sTable, $sIndexId, $aFields = null, $aLength = null) { $aTableInfo = self::GetTableInfo($sTable); - if (empty($aTableInfo)) return false; - if (!array_key_exists($sIndexId, $aTableInfo['Indexes'])) return false; + if (empty($aTableInfo)) { + return false; + } + if (!array_key_exists($sIndexId, $aTableInfo['Indexes'])) { + return false; + } - if ($aFields == null) - { + if ($aFields == null) { // Just searching for the name return true; } // Compare the columns $sSearchedIndex = implode(',', $aFields); - $aColumnNames = array(); - $aSubParts = array(); - foreach($aTableInfo['Indexes'][$sIndexId] as $aIndexDef) - { + $aColumnNames = []; + $aSubParts = []; + foreach ($aTableInfo['Indexes'][$sIndexId] as $aIndexDef) { $aColumnNames[] = $aIndexDef['Column_name']; $aSubParts[] = $aIndexDef['Sub_part']; } $sExistingIndex = implode(',', $aColumnNames); - if (is_null($aLength)) - { + if (is_null($aLength)) { return ($sSearchedIndex == $sExistingIndex); } @@ -1354,21 +1326,20 @@ class CMDBSource assert(!empty($sTable)); $aTableInfo = self::GetTableInfo($sTable); - if (empty($aTableInfo)) return array(); // #@# or an error ? + if (empty($aTableInfo)) { + return []; + } // #@# or an error ? return array_keys($aTableInfo["Fields"]); } // Cache the information about existing tables, and their fields - private static $m_aTablesInfo = array(); + private static $m_aTablesInfo = []; private static function _TablesInfoCacheReset($sTableName = null) { - if (is_null($sTableName)) - { - self::$m_aTablesInfo = array(); - } - else - { + if (is_null($sTableName)) { + self::$m_aTablesInfo = []; + } else { self::$m_aTablesInfo[strtolower($sTableName)] = null; } } @@ -1381,8 +1352,7 @@ class CMDBSource private static function _TableInfoCacheInit($sTableName) { if (isset(self::$m_aTablesInfo[strtolower($sTableName)]) - && (self::$m_aTablesInfo[strtolower($sTableName)] != null)) - { + && (self::$m_aTablesInfo[strtolower($sTableName)] != null)) { return; } @@ -1392,7 +1362,7 @@ class CMDBSource // Get table informations // We were using SHOW COLUMNS FROM... but this don't return charset and collation info ! // so since 2.5 and #1001 (switch to utf8mb4) we're using INFORMATION_SCHEMA ! - $aMapping = array( + $aMapping = [ "Name" => "COLUMN_NAME", "Type" => "COLUMN_TYPE", "Null" => "IS_NULLABLE", @@ -1402,28 +1372,24 @@ class CMDBSource "Charset" => "CHARACTER_SET_NAME", "Collation" => "COLLATION_NAME", "CharMaxLength" => "CHARACTER_MAXIMUM_LENGTH", - ); + ]; $sColumns = implode(', ', $aMapping); $sDBName = self::$m_sDBName; $aFields = self::QueryToArray("SELECT $sColumns FROM information_schema.`COLUMNS` WHERE table_schema = '$sDBName' AND table_name = '$sTableName';"); - foreach ($aFields as $aFieldData) - { - $aFields = array(); - foreach($aMapping as $sKey => $sColumn) - { + foreach ($aFields as $aFieldData) { + $aFields = []; + foreach ($aMapping as $sKey => $sColumn) { $aFields[$sKey] = $aFieldData[$sColumn]; } $sFieldName = $aFieldData["COLUMN_NAME"]; self::$m_aTablesInfo[strtolower($sTableName)]["Fields"][$sFieldName] = $aFields; } - if (!is_null(self::$m_aTablesInfo[strtolower($sTableName)])) - { + if (!is_null(self::$m_aTablesInfo[strtolower($sTableName)])) { $aIndexes = self::QueryToArray("SHOW INDEXES FROM `$sTableName`"); - $aMyIndexes = array(); - foreach ($aIndexes as $aIndexColumn) - { - $aMyIndexes[$aIndexColumn['Key_name']][$aIndexColumn['Seq_in_index']-1] = $aIndexColumn; + $aMyIndexes = []; + foreach ($aIndexes as $aIndexColumn) { + $aMyIndexes[$aIndexColumn['Key_name']][$aIndexColumn['Seq_in_index'] - 1] = $aIndexColumn; } self::$m_aTablesInfo[strtolower($sTableName)]["Indexes"] = $aMyIndexes; } @@ -1459,12 +1425,10 @@ class CMDBSource $sTableCharset = $aTableInfo[0]['CHARACTER_SET_NAME']; $sTableCollation = $aTableInfo[0]['TABLE_COLLATION']; - if ((DEFAULT_CHARACTER_SET == $sTableCharset) && (DEFAULT_COLLATION == $sTableCollation)) - { + if ((DEFAULT_CHARACTER_SET == $sTableCharset) && (DEFAULT_COLLATION == $sTableCollation)) { return null; } - return 'ALTER TABLE `'.$sTableName.'` '.self::GetSqlStringColumnDefinition().';'; } @@ -1478,23 +1442,18 @@ class CMDBSource public static function DumpTable($sTable) { $sSql = "SELECT * FROM `$sTable`"; - try - { + try { /** @noinspection NullPointerExceptionInspection this shouldn't be called with un-init DB */ $oResult = DbConnectionWrapper::GetDbConnection(true)->query($sSql); + } catch (mysqli_sql_exception $e) { + throw new MySQLException('Failed to issue SQL query', ['query' => $sSql], $e); } - catch(mysqli_sql_exception $e) - { - throw new MySQLException('Failed to issue SQL query', array('query' => $sSql), $e); - } - if ($oResult === false) - { - throw new MySQLException('Failed to issue SQL query', array('query' => $sSql)); + if ($oResult === false) { + throw new MySQLException('Failed to issue SQL query', ['query' => $sSql]); } - $aRows = array(); - while ($aRow = $oResult->fetch_array(MYSQLI_ASSOC)) - { + $aRows = []; + while ($aRow = $oResult->fetch_array(MYSQLI_ASSOC)) { $aRows[] = $aRow; } $oResult->free(); @@ -1519,19 +1478,15 @@ class CMDBSource */ public static function GetRawPrivileges() { - try - { + try { $oResult = self::Query('SHOW GRANTS'); // [ FOR CURRENT_USER()] - } - catch(MySQLException $e) - { + } catch (MySQLException $e) { $iCode = self::GetErrNo(); return "Current user not allowed to see his own privileges (could not access to the database 'mysql' - $iCode)"; } - $aRes = array(); - while ($aRow = $oResult->fetch_array(MYSQLI_NUM)) - { + $aRes = []; + while ($aRow = $oResult->fetch_array(MYSQLI_NUM)) { // so far, only one column... $aRes[] = implode('/', $aRow); } @@ -1546,17 +1501,13 @@ class CMDBSource */ public static function IsSlaveServer() { - try - { + try { $oResult = self::Query('SHOW SLAVE STATUS'); - } - catch(MySQLException $e) - { - throw new CoreException("Current user not allowed to check the status", array('mysql_error' => $e->getMessage())); + } catch (MySQLException $e) { + throw new CoreException("Current user not allowed to check the status", ['mysql_error' => $e->getMessage()]); } - if ($oResult->num_rows == 0) - { + if ($oResult->num_rows == 0) { return false; } @@ -1564,40 +1515,35 @@ class CMDBSource $aRow = $oResult->fetch_array(MYSQLI_ASSOC); $oResult->free(); - if (!isset($aRow['Slave_IO_Running'])) - { + if (!isset($aRow['Slave_IO_Running'])) { return false; } - if (!isset($aRow['Slave_SQL_Running'])) - { + if (!isset($aRow['Slave_SQL_Running'])) { return false; } // If at least one slave thread is running, then we consider that the slave is enabled - if ($aRow['Slave_IO_Running'] == 'Yes') - { + if ($aRow['Slave_IO_Running'] == 'Yes') { return true; } - if ($aRow['Slave_SQL_Running'] == 'Yes') - { + if ($aRow['Slave_SQL_Running'] == 'Yes') { return true; } return false; } - public static function GetClusterNb() - { - $result = 0; - $sSql = "SHOW STATUS LIKE 'wsrep_cluster_size';"; - $aRows = self::QueryToArray($sSql); - if (count($aRows) > 0) - { - $result = $aRows[0]['Value']; - } - return intval($result); - } + public static function GetClusterNb() + { + $result = 0; + $sSql = "SHOW STATUS LIKE 'wsrep_cluster_size';"; + $aRows = self::QueryToArray($sSql); + if (count($aRows) > 0) { + $result = $aRows[0]['Value']; + } + return intval($result); + } - /** + /** * @see https://dev.mysql.com/doc/refman/5.7/en/charset-database.html * @return string query to upgrade database charset and collation if needed, null if not * @throws \MySQLException @@ -1613,8 +1559,7 @@ class CMDBSource $sDBCharset = $aDBInfo[0]['DEFAULT_CHARACTER_SET_NAME']; $sDBCollation = $aDBInfo[0]['DEFAULT_COLLATION_NAME']; - if ((DEFAULT_CHARACTER_SET == $sDBCharset) && (DEFAULT_COLLATION == $sDBCollation)) - { + if ((DEFAULT_CHARACTER_SET == $sDBCharset) && (DEFAULT_COLLATION == $sDBCollation)) { return null; } @@ -1631,8 +1576,7 @@ class CMDBSource */ public static function IsSslModeDBVersion() { - if (static::GetDBVendor() === static::ENUM_DB_VENDOR_MYSQL) - { + if (static::GetDBVendor() === static::ENUM_DB_VENDOR_MYSQL) { //Mysql 5.7.0 and upper deprecated --ssl and uses --ssl-mode instead return version_compare(static::GetDBVersion(), '5.7.11', '>='); } diff --git a/core/config.class.inc.php b/core/config.class.inc.php index 68e4d2d6f..079ae5385 100644 --- a/core/config.class.inc.php +++ b/core/config.class.inc.php @@ -1,4 +1,5 @@ true, ], 'export_pdf_font' => [ // @since 2.7.0 PR #49 / N°1947 - 'type' => 'string', - 'description' => 'Font used when generating a PDF file', - 'default' => 'DejaVuSans', // DejaVuSans is a UTF-8 Unicode font, embedded in the TCPPDF lib we're using - // Standard PDF fonts like helvetica or times newroman are NOT Unicode - // A new DroidSansFallback can be used to improve CJK support (se PR #49) - 'value' => '', - 'source_of_value' => '', - 'show_in_conf_sample' => false, + 'type' => 'string', + 'description' => 'Font used when generating a PDF file', + 'default' => 'DejaVuSans', // DejaVuSans is a UTF-8 Unicode font, embedded in the TCPPDF lib we're using + // Standard PDF fonts like helvetica or times newroman are NOT Unicode + // A new DroidSansFallback can be used to improve CJK support (se PR #49) + 'value' => '', + 'source_of_value' => '', + 'show_in_conf_sample' => false, ], 'access_mode' => [ 'type' => 'integer', @@ -891,7 +890,7 @@ class Config 'source_of_value' => '', 'show_in_conf_sample' => false, ], - 'forgot_password.url' => [ + 'forgot_password.url' => [ 'type' => 'string', 'description' => 'Set this value to your "forgot password" service URL if it should be handled out of '.ITOP_APPLICATION_SHORT.'. Note that it will apply to all users (iTop users, LDAP users, ...)', 'default' => '', @@ -1803,7 +1802,7 @@ class Config 'default' => ITOP_APPLICATION.'/'.ITOP_VERSION, 'source_of_value' => '', 'show_in_conf_sample' => false, - ] + ], ]; public function IsProperty($sPropCode) @@ -1811,7 +1810,6 @@ class Config return (array_key_exists($sPropCode, $this->m_aSettings)); } - /** * @return string identifier that can be used for example to name WebStorage/SessionStorage keys (they * are related to a whole domain, and a domain can host multiple itop) @@ -1845,8 +1843,7 @@ class Config $value = $this->oConfigPlaceholdersResolver->Resolve($value); - switch ($sType) - { + switch ($sType) { case 'bool': $value = (bool)$value; break; @@ -1854,7 +1851,7 @@ class Config $value = (string)$value; break; case 'integer': - $value = (integer)$value; + $value = (int)$value; break; case 'float': $value = (float)$value; @@ -1862,11 +1859,10 @@ class Config case 'array': break; default: - throw new CoreException('Unknown type for setting', array('property' => $sPropCode, 'type' => $sType)); + throw new CoreException('Unknown type for setting', ['property' => $sPropCode, 'type' => $sType]); } - if ($this->m_aSettings[$sPropCode]['value'] == $value) - { + if ($this->m_aSettings[$sPropCode]['value'] == $value) { //when you set the exact same value than the previous one, then, you still can preserve the non evaluated version and so on preserve vars/jokers. $bCanOverride = true; } @@ -2008,15 +2004,13 @@ class Config $this->oConfigPlaceholdersResolver = new ConfigPlaceholdersResolver(); $this->m_sFile = $sConfigFile; - if (is_null($sConfigFile)) - { + if (is_null($sConfigFile)) { $bLoadConfig = false; } $this->m_aAddons = []; - foreach ($this->m_aSettings as $sPropCode => $aSettingInfo) - { + foreach ($this->m_aSettings as $sPropCode => $aSettingInfo) { $this->m_aSettings[$sPropCode]['value'] = $aSettingInfo['default']; } @@ -2032,7 +2026,7 @@ class Config $this->m_sDefaultLanguage = 'EN US'; $this->m_sAllowedLoginTypes = DEFAULT_ALLOWED_LOGIN_TYPES; $this->m_sExtAuthVariable = DEFAULT_EXT_AUTH_VARIABLE; - $this->m_aCharsets = array(); + $this->m_aCharsets = []; $this->m_bQueryCacheEnabled = DEFAULT_QUERY_CACHE_ENABLED; $this->m_iPasswordHashAlgo = DEFAULT_HASH_ALGO; $this->m_sAppSecret = bin2hex(random_bytes(16)); @@ -2042,10 +2036,9 @@ class Config $this->m_sEncryptionLibrary = isset($aEncryptParams['lib']) ? $aEncryptParams['lib'] : DEFAULT_ENCRYPTION_LIB; $this->m_sEncryptionKey = isset($aEncryptParams['key']) ? $aEncryptParams['key'] : DEFAULT_ENCRYPTION_KEY; - $this->m_aModuleSettings = array(); + $this->m_aModuleSettings = []; - if ($bLoadConfig) - { + if ($bLoadConfig) { $this->Load($sConfigFile); $this->Verify(); } @@ -2074,14 +2067,14 @@ class Config */ protected function CheckFile($sPurpose, $sFileName) { - if (!file_exists($sFileName)) - { - throw new ConfigException("Could not find $sPurpose file", array('file' => $sFileName)); + if (!file_exists($sFileName)) { + throw new ConfigException("Could not find $sPurpose file", ['file' => $sFileName]); } - if (!is_readable($sFileName)) - { - throw new ConfigException("Could not read $sPurpose file (the file exists but cannot be read). Do you have the rights to access this file?", - array('file' => $sFileName)); + if (!is_readable($sFileName)) { + throw new ConfigException( + "Could not read $sPurpose file (the file exists but cannot be read). Do you have the rights to access this file?", + ['file' => $sFileName] + ); } } @@ -2108,64 +2101,58 @@ class Config // This does not work on several lines // preg_match('/^<\\?php(.*)\\?'.'>$/', $sConfigCode, $aMatches)... // So, I've implemented a solution suggested in the PHP doc (search for phpWrapper) - try - { + try { ob_start(); eval('?'.'>'.trim($sConfigCode)); $sNoise = trim(ob_get_contents()); ob_end_clean(); - } - catch (Error $e) - { + } catch (Error $e) { // PHP 7 - throw new ConfigException('Error in configuration file', - array('file' => $sConfigFile, 'error' => $e->getMessage().' at line '.$e->getLine())); - } - catch (Exception $e) - { + throw new ConfigException( + 'Error in configuration file', + ['file' => $sConfigFile, 'error' => $e->getMessage().' at line '.$e->getLine()] + ); + } catch (Exception $e) { // well, never reach in case of parsing error :-( // will be improved in PHP 6 ? - throw new ConfigException('Error in configuration file', - array('file' => $sConfigFile, 'error' => $e->getMessage())); + throw new ConfigException( + 'Error in configuration file', + ['file' => $sConfigFile, 'error' => $e->getMessage()] + ); } - if (strlen($sNoise) > 0) - { + if (strlen($sNoise) > 0) { // Note: sNoise is an html output, but so far it was ok for me (e.g. showing the entire call stack) - throw new ConfigException('Syntax error in configuration file', - array('file' => $sConfigFile, 'error' => ''.utils::EscapeHtml($sNoise, ENT_QUOTES).'')); + throw new ConfigException( + 'Syntax error in configuration file', + ['file' => $sConfigFile, 'error' => ''.utils::EscapeHtml($sNoise, ENT_QUOTES).''] + ); } - if (!isset($MySettings) || !is_array($MySettings)) - { - throw new ConfigException('Missing array in configuration file', - array('file' => $sConfigFile, 'expected' => '$MySettings')); + if (!isset($MySettings) || !is_array($MySettings)) { + throw new ConfigException( + 'Missing array in configuration file', + ['file' => $sConfigFile, 'expected' => '$MySettings'] + ); } - if (!array_key_exists('addons', $MyModules) || !array_key_exists('user rights', $MyModules['addons'])) - { + if (!array_key_exists('addons', $MyModules) || !array_key_exists('user rights', $MyModules['addons'])) { // Add one, by default $MyModules['addons']['user rights'] = 'addons/userrights/userrightsprofile.class.inc.php'; $this->m_aAddons = $MyModules['addons']; } - foreach ($MySettings as $sPropCode => $rawvalue) - { - if ($this->IsProperty($sPropCode)) - { - if (is_string($rawvalue)) - { + foreach ($MySettings as $sPropCode => $rawvalue) { + if ($this->IsProperty($sPropCode)) { + if (is_string($rawvalue)) { $value = trim($rawvalue); - } - else - { + } else { $value = $rawvalue; } $this->Set($sPropCode, $value, $sConfigFile, true); } } - if (file_exists(READONLY_MODE_FILE)) - { + if (file_exists(READONLY_MODE_FILE)) { $this->Set('access_mode', ACCESS_READONLY, READONLY_MODE_FILE); } @@ -2181,14 +2168,14 @@ class Config $this->m_iFastReloadInterval = isset($MySettings['fast_reload_interval']) ? trim($MySettings['fast_reload_interval']) : DEFAULT_FAST_RELOAD_INTERVAL; $this->m_bSecureConnectionRequired = isset($MySettings['secure_connection_required']) ? (bool)trim($MySettings['secure_connection_required']) : DEFAULT_SECURE_CONNECTION_REQUIRED; - $this->m_aModuleSettings = isset($MyModuleSettings) ? $MyModuleSettings : array(); + $this->m_aModuleSettings = isset($MyModuleSettings) ? $MyModuleSettings : []; $this->m_sDefaultLanguage = isset($MySettings['default_language']) ? trim($MySettings['default_language']) : 'EN US'; $this->m_sAllowedLoginTypes = isset($MySettings['allowed_login_types']) ? trim($MySettings['allowed_login_types']) : DEFAULT_ALLOWED_LOGIN_TYPES; $this->m_sExtAuthVariable = isset($MySettings['ext_auth_variable']) ? trim($MySettings['ext_auth_variable']) : DEFAULT_EXT_AUTH_VARIABLE; $this->m_sEncryptionKey = isset($MySettings['encryption_key']) ? trim($MySettings['encryption_key']) : $this->m_sEncryptionKey; $this->m_sEncryptionLibrary = isset($MySettings['encryption_library']) ? trim($MySettings['encryption_library']) : $this->m_sEncryptionLibrary; - $this->m_aCharsets = isset($MySettings['csv_import_charsets']) ? $MySettings['csv_import_charsets'] : array(); + $this->m_aCharsets = isset($MySettings['csv_import_charsets']) ? $MySettings['csv_import_charsets'] : []; $this->m_iPasswordHashAlgo = isset($MySettings['password_hash_algo']) ? $MySettings['password_hash_algo'] : $this->m_iPasswordHashAlgo; } @@ -2210,8 +2197,7 @@ class Config */ public function GetModuleSetting($sModule, $sProperty, $defaultvalue = null) { - if (isset($this->m_aModuleSettings[$sModule][$sProperty])) - { + if (isset($this->m_aModuleSettings[$sModule][$sProperty])) { return $this->m_aModuleSettings[$sModule][$sProperty]; } @@ -2233,11 +2219,9 @@ class Config public function GetModuleParameter($sModule, $sProperty, $defaultvalue = null) { $ret = $defaultvalue; - if (class_exists('ModulesXMLParameters')) - { + if (class_exists('ModulesXMLParameters')) { $aAllParams = ModulesXMLParameters::GetData($sModule); - if (array_key_exists($sProperty, $aAllParams)) - { + if (array_key_exists($sProperty, $aAllParams)) { $ret = $aAllParams[$sProperty]; } } @@ -2255,10 +2239,10 @@ class Config */ public function GetAddons() { - if (array_key_exists("user rights", $this->m_aAddons)) { + if (array_key_exists("user rights", $this->m_aAddons)) { return $this->m_aAddons; } else { - return array_merge($this->m_aAddons,['user rights' => 'addons/userrights/userrightsprofile.class.inc.php']); + return array_merge($this->m_aAddons, ['user rights' => 'addons/userrights/userrightsprofile.class.inc.php']); } } @@ -2438,7 +2422,7 @@ class Config public function AddAllowedLoginTypes($sLoginMode) { $aAllowedLoginTypes = $this->GetAllowedLoginTypes(); - if (in_array($sLoginMode, $aAllowedLoginTypes)){ + if (in_array($sLoginMode, $aAllowedLoginTypes)) { return; } @@ -2461,7 +2445,6 @@ class Config $this->m_sAppSecret = $sKey; } - public function SetCSVImportCharsets($aCharsets) { $this->m_aCharsets = $aCharsets; @@ -2474,12 +2457,9 @@ class Config public function GetLoadedFile() { - if (is_null($this->m_sFile)) - { + if (is_null($this->m_sFile)) { return ''; - } - else - { + } else { return $this->m_sFile; } } @@ -2491,9 +2471,8 @@ class Config */ public function ToArray() { - $aSettings = array(); - foreach ($this->m_aSettings as $sPropCode => $aSettingInfo) - { + $aSettings = []; + foreach ($this->m_aSettings as $sPropCode => $aSettingInfo) { $aSettings[$sPropCode] = $aSettingInfo['value']; } $aSettings['log_global'] = $this->m_bLogGlobal; @@ -2514,15 +2493,12 @@ class Config $aSettings['csv_import_charsets'] = $this->m_aCharsets; $aSettings['password_hash_algo'] = $this->m_iPasswordHashAlgo; - foreach ($this->m_aModuleSettings as $sModule => $aProperties) - { - foreach ($aProperties as $sProperty => $value) - { + foreach ($this->m_aModuleSettings as $sModule => $aProperties) { + foreach ($aProperties as $sProperty => $value) { $aSettings['module_settings'][$sModule][$sProperty] = $value; } } - foreach ($this->m_aAddons as $sKey => $sFile) - { + foreach ($this->m_aAddons as $sKey => $sFile) { $aSettings['addon_list'][] = $sFile; } @@ -2541,22 +2517,18 @@ class Config */ public function WriteToFile($sFileName = '') { - if (empty($sFileName)) - { + if (empty($sFileName)) { $sFileName = $this->m_sFile; } $oHandle = null; $sConfig = null; - if ($this->m_sFile !== null && is_file($this->m_sFile)) - { + if ($this->m_sFile !== null && is_file($this->m_sFile)) { $oHandle = fopen($this->m_sFile, 'r'); $index = 0; - while (!flock($oHandle, LOCK_SH)) - { - if ($index > 50) - { - throw new ConfigException("Could not read to configuration file", array('file' => $this->m_sFile)); + while (!flock($oHandle, LOCK_SH)) { + if ($index > 50) { + throw new ConfigException("Could not read to configuration file", ['file' => $this->m_sFile]); } usleep(100000); $index++; @@ -2564,61 +2536,59 @@ class Config $sConfig = file_get_contents($this->m_sFile); } $this->oItopConfigParser = new iTopConfigParser($sConfig); - if ($oHandle !==null) - { + if ($oHandle !== null) { flock($oHandle, LOCK_UN); } $hFile = @fopen($sFileName, 'w'); - if ($hFile !== false) - { + if ($hFile !== false) { fwrite($hFile, "m_aSettings; // Old fashioned boolean settings - $aBoolValues = array( + $aBoolValues = [ 'log_global' => $this->m_bLogGlobal, 'log_notification' => $this->m_bLogNotification, 'log_issue' => $this->m_bLogIssue, 'log_web_service' => $this->m_bLogWebService, 'secure_connection_required' => $this->m_bSecureConnectionRequired, - ); - foreach ($aBoolValues as $sKey => $bValue) - { - $aConfigSettings[$sKey] = array( + ]; + foreach ($aBoolValues as $sKey => $bValue) { + $aConfigSettings[$sKey] = [ 'show_in_conf_sample' => true, 'type' => 'bool', 'value' => $bValue, - ); + ]; } // Old fashioned integer settings - $aIntValues = array( + $aIntValues = [ 'fast_reload_interval' => $this->m_iFastReloadInterval, 'max_display_limit' => $this->m_iMaxDisplayLimit, 'min_display_limit' => $this->m_iMinDisplayLimit, 'standard_reload_interval' => $this->m_iStandardReloadInterval, - ); - foreach ($aIntValues as $sKey => $iValue) - { - $aConfigSettings[$sKey] = array( + ]; + foreach ($aIntValues as $sKey => $iValue) { + $aConfigSettings[$sKey] = [ 'show_in_conf_sample' => true, 'type' => 'integer', 'value' => $iValue, - ); + ]; } // Old fashioned remaining values - $aOtherValues = array( + $aOtherValues = [ 'default_language' => $this->m_sDefaultLanguage, 'allowed_login_types' => $this->m_sAllowedLoginTypes, 'ext_auth_variable' => $this->m_sExtAuthVariable, @@ -2626,45 +2596,37 @@ class Config 'encryption_library' => $this->m_sEncryptionLibrary, 'csv_import_charsets' => $this->m_aCharsets, 'password_hash_algo' => $this->m_iPasswordHashAlgo, - ); - foreach ($aOtherValues as $sKey => $value) - { - $aConfigSettings[$sKey] = array( + ]; + foreach ($aOtherValues as $sKey => $value) { + $aConfigSettings[$sKey] = [ 'show_in_conf_sample' => true, 'type' => is_string($value) ? 'string' : 'mixed', 'value' => $value, - ); + ]; } ksort($aConfigSettings); fwrite($hFile, "\$MySettings = array(\n"); - foreach ($aConfigSettings as $sPropCode => $aSettingInfo) - { + foreach ($aConfigSettings as $sPropCode => $aSettingInfo) { // Write all values that are either always visible or present in the cloned config file - if ($aSettingInfo['show_in_conf_sample'] || (!empty($aSettingInfo['source_of_value']) && ($aSettingInfo['source_of_value'] != 'unknown'))) - { + if ($aSettingInfo['show_in_conf_sample'] || (!empty($aSettingInfo['source_of_value']) && ($aSettingInfo['source_of_value'] != 'unknown'))) { fwrite($hFile, "\n"); - if (isset($aSettingInfo['description'])) - { + if (isset($aSettingInfo['description'])) { fwrite($hFile, "\t// $sPropCode: {$aSettingInfo['description']}\n"); } - if (isset($aSettingInfo['default'])) - { - $sComment = self::PrettyVarExport(null,$aSettingInfo['default'], "\t//\t\t", true); - fwrite($hFile,"\t//\tdefault: {$sComment}\n"); + if (isset($aSettingInfo['default'])) { + $sComment = self::PrettyVarExport(null, $aSettingInfo['default'], "\t//\t\t", true); + fwrite($hFile, "\t//\tdefault: {$sComment}\n"); } - if (isset($this->m_aCanOverrideSettings[$sPropCode]) && $this->m_aCanOverrideSettings[$sPropCode]) - { + if (isset($this->m_aCanOverrideSettings[$sPropCode]) && $this->m_aCanOverrideSettings[$sPropCode]) { $aParserValue = $this->oItopConfigParser->GetVarValue('MySettings', $sPropCode); - } - else - { + } else { $aParserValue = null; } - $sSeenAs = self::PrettyVarExport($aParserValue,$aSettingInfo['value'], "\t"); + $sSeenAs = self::PrettyVarExport($aParserValue, $aSettingInfo['value'], "\t"); fwrite($hFile, "\t'$sPropCode' => $sSeenAs,\n"); } } @@ -2673,11 +2635,9 @@ class Config fwrite($hFile, "\n"); fwrite($hFile, "/**\n *\n * Modules specific settings\n *\n */\n"); fwrite($hFile, "\$MyModuleSettings = array(\n"); - foreach ($this->m_aModuleSettings as $sModule => $aProperties) - { + foreach ($this->m_aModuleSettings as $sModule => $aProperties) { fwrite($hFile, "\t'$sModule' => array (\n"); - foreach ($aProperties as $sProperty => $value) - { + foreach ($aProperties as $sProperty => $value) { $sNiceExport = self::PrettyVarExport($this->oItopConfigParser->GetVarValue('MyModuleSettings', $sProperty), $value, "\t\t"); fwrite($hFile, "\t\t'$sProperty' => $sNiceExport,\n"); } @@ -2692,8 +2652,7 @@ class Config fwrite($hFile, " */\n"); fwrite($hFile, "\$MyModules = array(\n"); $aParserValue = $this->oItopConfigParser->GetVarValue('MyModules', 'addons'); - if ($aParserValue['found']) - { + if ($aParserValue['found']) { fwrite($hFile, "\t'addons' => {$aParserValue['value']},\n"); } fwrite($hFile, ");\n"); @@ -2704,10 +2663,8 @@ class Config utils::SetConfig($this); return $bReturn; - } - else - { - throw new ConfigException("Could not write to configuration file", array('file' => $sFileName)); + } else { + throw new ConfigException("Could not write to configuration file", ['file' => $sFileName]); } } @@ -2728,32 +2685,25 @@ class Config */ public function UpdateFromParams($aParamValues, $sModulesDir = null, $bPreserveModuleSettings = false) { - if (isset($aParamValues['application_path'])) - { + if (isset($aParamValues['application_path'])) { $this->Set('app_root_url', $aParamValues['application_path']); } - if (isset($aParamValues['graphviz_path'])) - { + if (isset($aParamValues['graphviz_path'])) { $this->Set('graphviz_path', $aParamValues['graphviz_path']); } - if (isset($aParamValues['mode']) && isset($aParamValues['language'])) - { - if (($aParamValues['mode'] == 'install') || $this->GetDefaultLanguage() == '') - { + if (isset($aParamValues['mode']) && isset($aParamValues['language'])) { + if (($aParamValues['mode'] == 'install') || $this->GetDefaultLanguage() == '') { $this->SetDefaultLanguage($aParamValues['language']); } } - if (isset($aParamValues['db_server'])) - { + if (isset($aParamValues['db_server'])) { $this->Set('db_host', $aParamValues['db_server']); $this->Set('db_user', $aParamValues['db_user']); $this->Set('db_pwd', $aParamValues['db_pwd']); $sDBName = $aParamValues['db_name']; - if ($sDBName == '') - { + if ($sDBName == '') { // Todo - obsolete after the transition to the new setup (2.0) is complete (WARNING: used by the designer) - if (isset($aParamValues['new_db_name'])) - { + if (isset($aParamValues['new_db_name'])) { $sDBName = $aParamValues['new_db_name']; } } @@ -2761,39 +2711,29 @@ class Config $this->Set('db_subname', $aParamValues['db_prefix']); $bDbTlsEnabled = (bool)$aParamValues['db_tls_enabled']; - if ($bDbTlsEnabled) - { + if ($bDbTlsEnabled) { $this->Set('db_tls.enabled', $bDbTlsEnabled, 'UpdateFromParams'); - } - else - { + } else { // disabled : we don't want parameter in the file $this->Set('db_tls.enabled', $bDbTlsEnabled, null); } $sDbTlsCa = $bDbTlsEnabled ? $aParamValues['db_tls_ca'] : null; - if (isset($sDbTlsCa) && !empty($sDbTlsCa)) - { + if (isset($sDbTlsCa) && !empty($sDbTlsCa)) { $this->Set('db_tls.ca', $sDbTlsCa, 'UpdateFromParams'); - } - else - { + } else { // empty parameter : we don't want it in the file $this->Set('db_tls.ca', null, null); } } - if (isset($aParamValues['selected_modules'])) - { + if (isset($aParamValues['selected_modules'])) { $aSelectedModules = explode(',', $aParamValues['selected_modules']); - } - else - { + } else { $aSelectedModules = null; } $this->UpdateIncludes($sModulesDir, $aSelectedModules); - if (isset($aParamValues['source_dir'])) - { + if (isset($aParamValues['source_dir'])) { $this->Set('source_dir', $aParamValues['source_dir']); } } @@ -2811,8 +2751,7 @@ class Config */ public function UpdateIncludes($sModulesDir, $aSelectedModules = null) { - if ($sModulesDir === null) - { + if ($sModulesDir === null) { return; } @@ -2820,23 +2759,16 @@ class Config $oEmptyConfig = new Config('dummy_file', false); // Do NOT load any config file, just set the default values $aAddOns = $oEmptyConfig->GetAddOns(); - $aModules = ModuleDiscovery::GetAvailableModules(array(APPROOT.$sModulesDir)); - foreach ($aModules as $sModuleId => $aModuleInfo) - { - list ($sModuleName, $sModuleVersion) = ModuleDiscovery::GetModuleName($sModuleId); - if (is_null($aSelectedModules) || in_array($sModuleName, $aSelectedModules)) - { - if (isset($aModuleInfo['settings'])) - { - list ($sName, $sVersion) = ModuleDiscovery::GetModuleName($sModuleId); - foreach ($aModuleInfo['settings'] as $sProperty => $value) - { - if (isset($this->m_aModuleSettings[$sName][$sProperty])) - { + $aModules = ModuleDiscovery::GetAvailableModules([APPROOT.$sModulesDir]); + foreach ($aModules as $sModuleId => $aModuleInfo) { + list($sModuleName, $sModuleVersion) = ModuleDiscovery::GetModuleName($sModuleId); + if (is_null($aSelectedModules) || in_array($sModuleName, $aSelectedModules)) { + if (isset($aModuleInfo['settings'])) { + list($sName, $sVersion) = ModuleDiscovery::GetModuleName($sModuleId); + foreach ($aModuleInfo['settings'] as $sProperty => $value) { + if (isset($this->m_aModuleSettings[$sName][$sProperty])) { // Do nothing keep the original value - } - else - { + } else { $this->SetModuleSetting($sName, $sProperty, $value); } } @@ -2857,10 +2789,8 @@ class Config */ protected static function ChangePrefix(&$aStrings, $sSearchPrefix, $sNewPrefix) { - foreach ($aStrings as &$sFile) - { - if (substr($sFile, 0, strlen($sSearchPrefix)) == $sSearchPrefix) - { + foreach ($aStrings as &$sFile) { + if (substr($sFile, 0, strlen($sSearchPrefix)) == $sSearchPrefix) { $sFile = $sNewPrefix.substr($sFile, strlen($sSearchPrefix)); } } @@ -2891,22 +2821,19 @@ class Config */ protected static function PrettyVarExport($aParserValue, $value, $sIndentation, $bForceIndentation = false) { - if (is_array($aParserValue) && $aParserValue['found']) - { + if (is_array($aParserValue) && $aParserValue['found']) { return $aParserValue['value']; } $sExport = var_export($value, true); - $sNiceExport = str_replace(array("\r\n", "\n", "\r"), "\n".$sIndentation, trim($sExport)); - if (!$bForceIndentation) - { + $sNiceExport = str_replace(["\r\n", "\n", "\r"], "\n".$sIndentation, trim($sExport)); + if (!$bForceIndentation) { /** @var array $aImported */ $aImported = null; eval('$aImported='.$sNiceExport.';'); // Check if adding the identations at the beginning of each line // did not modify the values (in case of a string containing a line break) - if ($aImported != $value) - { + if ($aImported != $value) { $sNiceExport = $sExport; } } @@ -2935,37 +2862,31 @@ class ConfigPlaceholdersResolver public function Resolve($rawValue) { - if (empty($this->aEnv['ITOP_CONFIG_PLACEHOLDERS']) && empty($this->aServer['ITOP_CONFIG_PLACEHOLDERS'])) - { + if (empty($this->aEnv['ITOP_CONFIG_PLACEHOLDERS']) && empty($this->aServer['ITOP_CONFIG_PLACEHOLDERS'])) { return $rawValue; } - if (is_array($rawValue)) - { - $aResolvedRawValue = array(); - foreach ($rawValue as $key => $value) - { + if (is_array($rawValue)) { + $aResolvedRawValue = []; + foreach ($rawValue as $key => $value) { $aResolvedRawValue[$key] = $this->Resolve($value); } return $aResolvedRawValue; } - if (!is_string($rawValue)) - { + if (!is_string($rawValue)) { return $rawValue; } $sPattern = '/\%(env|server)\((\w+)\)(?:\?:(\w*))?\%/'; //3 capturing groups, ie `%env(HTTP_PORT)?:8080%` produce: `env` `HTTP_PORT` and `8080`. - if (! preg_match_all($sPattern, $rawValue, $aMatchesCollection, PREG_SET_ORDER)) - { + if (! preg_match_all($sPattern, $rawValue, $aMatchesCollection, PREG_SET_ORDER)) { return $rawValue; } $sValue = $rawValue; - foreach ($aMatchesCollection as $aMatches) - { + foreach ($aMatchesCollection as $aMatches) { $sWholeMask = $aMatches[0]; $sSource = $aMatches[1]; $sKey = $aMatches[2]; @@ -2981,35 +2902,27 @@ class ConfigPlaceholdersResolver private function Get($sSourceName, $sKey, $sDefault, $sWholeMask) { - if ('env' == $sSourceName) - { + if ('env' == $sSourceName) { $aSource = $this->aEnv; - } - else if ('server' == $sSourceName) - { + } elseif ('server' == $sSourceName) { $aSource = $this->aServer; - } - else - { + } else { $sErrorMessage = sprintf('unsupported source name "%s" into "%s"', $sSourceName, $sWholeMask); - IssueLog::Error($sErrorMessage, self::class, array($sSourceName, $sKey, $sDefault, $sWholeMask)); + IssueLog::Error($sErrorMessage, self::class, [$sSourceName, $sKey, $sDefault, $sWholeMask]); throw new ConfigException($sErrorMessage); } - if (array_key_exists($sKey, $aSource)) - { + if (array_key_exists($sKey, $aSource)) { return $aSource[$sKey]; } - if (null !== $sDefault) - { + if (null !== $sDefault) { return $sDefault; } $sErrorMessage = sprintf('key "%s" not found into "%s" while expanding', $sSourceName, $sWholeMask); - IssueLog::Error($sErrorMessage, self::class, array($sSourceName, $sKey, $sDefault, $sWholeMask)); + IssueLog::Error($sErrorMessage, self::class, [$sSourceName, $sKey, $sDefault, $sWholeMask]); throw new ConfigException($sErrorMessage); } - } diff --git a/core/dbobject.class.php b/core/dbobject.class.php index e4b8a9ff4..5367f10ff 100644 --- a/core/dbobject.class.php +++ b/core/dbobject.class.php @@ -1,4 +1,5 @@ array of ('table' => array of (array of )) */ - private static $m_aBulkInsertItems = array(); + private static $m_aBulkInsertItems = []; /** @var array class => array of ('table' => array of ) */ - private static $m_aBulkInsertCols = array(); - private static $m_bBulkInsert = false; + private static $m_aBulkInsertCols = []; + private static $m_bBulkInsert = false; /** @var bool true IF the object is mapped to a DB record */ protected $m_bIsInDB = false; protected $m_iKey = null; /** @var array attcode => value : corresponding current value (the new value passed to {@see DBObject::Set()}). Reset during {@see DBObject::DBUpdate()} */ - private $m_aCurrValues = array(); + private $m_aCurrValues = []; /** @var array attcode => value : previous values before the {@see DBObject::Set()} call. Array is reset at the end of {@see DBObject::DBUpdate()} */ - protected $m_aOrigValues = array(); + protected $m_aOrigValues = []; protected $m_aExtendedData = null; - /** - * @var bool Is dirty (true) if a modification is ongoing. - * - * @internal The object may have incorrect external keys, then any attempt of reload must be avoided - */ + /** + * @var bool Is dirty (true) if a modification is ongoing. + * + * @internal The object may have incorrect external keys, then any attempt of reload must be avoided + */ private $m_bDirty = false; /** @@ -148,9 +147,9 @@ abstract class DBObject implements iDisplay /** @var bool Compound objects can be partially loaded */ private $m_bFullyLoaded = false; /** @var array Compound objects can be partially loaded, array of sAttCode */ - private $m_aLoadedAtt = array(); + private $m_aLoadedAtt = []; /** @var array list of (potentially) modified sAttCodes */ - protected $m_aTouchedAtt = array(); + protected $m_aTouchedAtt = []; /** * @var array real modification status * for each attCode can be: @@ -158,7 +157,7 @@ abstract class DBObject implements iDisplay * * true => modified, * * false => not modified (the same value as the original value was set) */ - protected $m_aModifiedAtt = array(); + protected $m_aModifiedAtt = []; /** * @var array attname => value : value before the last {@see DBObject::Set()} call. Set at the beginning of {@see DBObject::DBUpdate()}. * @see DBObject::ListPreviousValuesForUpdatedAttributes() getter for this attribute @@ -176,7 +175,7 @@ abstract class DBObject implements iDisplay */ protected $m_aSynchroData = null; protected $m_sHighlightCode = null; - protected $m_aCallbacks = array(); + protected $m_aCallbacks = []; /** * @var string local events suffix */ @@ -207,7 +206,7 @@ abstract class DBObject implements iDisplay // Protect DBUpdate against infinite loop protected $iUpdateLoopCount; - const MAX_UPDATE_LOOP_COUNT = 10; + public const MAX_UPDATE_LOOP_COUNT = 10; private $aEventListeners = []; private array $aAllowedTransitions = []; @@ -233,12 +232,11 @@ abstract class DBObject implements iDisplay public function __construct($aRow = null, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null) { $this->iUpdateLoopCount = 0; - if (!empty($aRow)) - { + if (!empty($aRow)) { $this->FromRow($aRow, $sClassAlias, $aAttToLoad, $aExtendedDataSpec); $this->m_bFullyLoaded = $this->IsFullyLoaded(); - $this->m_aTouchedAtt = array(); - $this->m_aModifiedAtt = array(); + $this->m_aTouchedAtt = []; + $this->m_aModifiedAtt = []; $this->m_sObjectUniqId = get_class($this).'::'.$this->GetKey().'_'.uniqId('', true); $this->RegisterEventListeners(); return; @@ -249,8 +247,7 @@ abstract class DBObject implements iDisplay $this->m_iKey = self::GetNextTempId(get_class($this)); // set default values - foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef) - { + foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) { $this->m_aCurrValues[$sAttCode] = $this->GetDefaultValue($sAttCode); $this->m_aOrigValues[$sAttCode] = null; if (!$oAttDef->IsExternalField() && !$oAttDef instanceof AttributeFriendlyName) { @@ -277,128 +274,124 @@ abstract class DBObject implements iDisplay /** * Update meta-attributes depending on the given attribute list * - * @internal - * - * @param array|null $aAttCodes List of att codes - * + * @internal + * + * @param array|null $aAttCodes List of att codes + * * @throws \CoreException */ protected function UpdateMetaAttributes($aAttCodes = null) { - if (is_null($aAttCodes)) - { + if (is_null($aAttCodes)) { $aAttCodes = MetaModel::GetAttributesList(get_class($this)); } - foreach ($aAttCodes as $sAttCode) - { - foreach (MetaModel::ListMetaAttributes(get_class($this), $sAttCode) as $sMetaAttCode => $oMetaAttDef) - { + foreach ($aAttCodes as $sAttCode) { + foreach (MetaModel::ListMetaAttributes(get_class($this), $sAttCode) as $sMetaAttCode => $oMetaAttDef) { /** @var \AttributeMetaEnum $oMetaAttDef */ $this->_Set($sMetaAttCode, $oMetaAttDef->MapValue($this)); } } } - /** - * Mark the object as dirty - * - * Once dirty the object may be written to the DB, it is NOT possible to reload it - * or at least not possible to reload it the same way - * - * @internal - */ + /** + * Mark the object as dirty + * + * Once dirty the object may be written to the DB, it is NOT possible to reload it + * or at least not possible to reload it the same way + * + * @internal + */ public function RegisterAsDirty() { $this->m_bDirty = true; } - /** - * Whether the object is already persisted in DB or not. - * - * @api - * - * @return bool - */ + /** + * Whether the object is already persisted in DB or not. + * + * @api + * + * @return bool + */ public function IsNew() { return (!$this->m_bIsInDB); } - /** - * Returns an Id for memory objects - * - * @internal - * - * @param string $sClass - * - * @return int - * @throws CoreException - */ - static protected function GetNextTempId($sClass) + /** + * Returns an Id for memory objects + * + * @internal + * + * @param string $sClass + * + * @return int + * @throws CoreException + */ + protected static function GetNextTempId($sClass) { $sRootClass = MetaModel::GetRootClass($sClass); - if (!array_key_exists($sRootClass, self::$m_aMemoryObjectsByClass)) - { + if (!array_key_exists($sRootClass, self::$m_aMemoryObjectsByClass)) { self::$m_aMemoryObjectsByClass[$sRootClass] = 0; } self::$m_aMemoryObjectsByClass[$sRootClass]++; return (- self::$m_aMemoryObjectsByClass[$sRootClass]); } - /** - * HTML String representation of the object - * - * Only a few meaningful information will be returned. - * This representation is for debugging purposes, and is subject to change. - * The returned string is raw HTML - * - * @return string - * @throws CoreException - */ + /** + * HTML String representation of the object + * + * Only a few meaningful information will be returned. + * This representation is for debugging purposes, and is subject to change. + * The returned string is raw HTML + * + * @return string + * @throws CoreException + */ public function __toString() { - $sRet = ''; - $sClass = get_class($this); - $sRootClass = MetaModel::GetRootClass($sClass); - $iPKey = $this->GetKey(); - $sFriendlyname = $this->GetAsHTML('friendlyname'); - $sRet .= "$sClass::$iPKey ($sFriendlyname)
\n"; - return $sRet; + $sRet = ''; + $sClass = get_class($this); + $sRootClass = MetaModel::GetRootClass($sClass); + $iPKey = $this->GetKey(); + $sFriendlyname = $this->GetAsHTML('friendlyname'); + $sRet .= "$sClass::$iPKey ($sFriendlyname)
\n"; + return $sRet; } - /** - * Alias of DBObject::Reload() - * - * Restore initial values - * - * @see Reload() - * - * @throws CoreException - */ + /** + * Alias of DBObject::Reload() + * + * Restore initial values + * + * @see Reload() + * + * @throws CoreException + */ public function DBRevert() { $this->Reload(); } - /** - * Is the current instance fully or partially loaded. - * - * This method compute the state in realtime. - * In almost every case it is preferable to use DBObject::m_bFullyLoaded. - * - * @internal - * @see m_bFullyLoaded - * - * @return bool - * @throws CoreException - */ + /** + * Is the current instance fully or partially loaded. + * + * This method compute the state in realtime. + * In almost every case it is preferable to use DBObject::m_bFullyLoaded. + * + * @internal + * @see m_bFullyLoaded + * + * @return bool + * @throws CoreException + */ protected function IsFullyLoaded() { - foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef) - { - if (!$oAttDef->LoadInObject()) continue; - if (!isset($this->m_aLoadedAtt[$sAttCode]) || !$this->m_aLoadedAtt[$sAttCode]) - { + foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) { + if (!$oAttDef->LoadInObject()) { + continue; + } + if (!isset($this->m_aLoadedAtt[$sAttCode]) || !$this->m_aLoadedAtt[$sAttCode]) { return false; } } @@ -406,11 +399,11 @@ abstract class DBObject implements iDisplay } /** - * Reload the object from the DB. - * - * This is mostly used after a lazy load (automatically performed by the framework) - * This will erase any pending changes. - * + * Reload the object from the DB. + * + * This is mostly used after a lazy load (automatically performed by the framework) + * This will erase any pending changes. + * * @throws CoreException */ public function Reload() @@ -418,21 +411,21 @@ abstract class DBObject implements iDisplay assert($this->m_bIsInDB); $this->FireEvent(EVENT_DB_OBJECT_RELOAD); $aRow = MetaModel::MakeSingleRow(get_class($this), $this->m_iKey, false /* must be found */, true /* AllowAllData */); - if (empty($aRow)) - { - $sErrorMessage = "Failed to reload object of class '".get_class($this)."', id = ".$this->m_iKey.', DBIsReadOnly = '.(int) MetaModel::DBIsReadOnly(); + if (empty($aRow)) { + $sErrorMessage = "Failed to reload object of class '".get_class($this)."', id = ".$this->m_iKey.', DBIsReadOnly = '.(int) MetaModel::DBIsReadOnly(); - IssueLog::Error("$sErrorMessage:\n".MyHelpers::get_callstack_text(1)); - throw new CoreException("$sErrorMessage (see the log for more information)"); + IssueLog::Error("$sErrorMessage:\n".MyHelpers::get_callstack_text(1)); + throw new CoreException("$sErrorMessage (see the log for more information)"); } $this->FromRow($aRow); // Process linked set attributes // - foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef) - { - if (!$oAttDef->IsLinkSet()) continue; + foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) { + if (!$oAttDef->IsLinkSet()) { + continue; + } $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue($this); $this->m_aOrigValues[$sAttCode] = clone $this->m_aCurrValues[$sAttCode]; @@ -440,37 +433,36 @@ abstract class DBObject implements iDisplay } $this->m_bFullyLoaded = true; - $this->m_aTouchedAtt = array(); - $this->m_aModifiedAtt = array(); + $this->m_aTouchedAtt = []; + $this->m_aModifiedAtt = []; } - /** - * Initialize the instance against a given structured array - * - * @internal - * @see GetExtendedData() extended data - * - * @param array $aRow an array under the form: ` => ` - * @param string $sClassAlias if not null, it is preprended to the `` part of $aRow - * @param null|array $aAttToLoad List of attribute that will be fetched against the database anyway - * @param null|array $aExtendedDataSpec List of attribute that will be marked as DBObject::GetExtendedData() - * - * @return bool - * @throws CoreException - */ + /** + * Initialize the instance against a given structured array + * + * @internal + * @see GetExtendedData() extended data + * + * @param array $aRow an array under the form: ` => ` + * @param string $sClassAlias if not null, it is preprended to the `` part of $aRow + * @param null|array $aAttToLoad List of attribute that will be fetched against the database anyway + * @param null|array $aExtendedDataSpec List of attribute that will be marked as DBObject::GetExtendedData() + * + * @return bool + * @throws CoreException + */ protected function FromRow($aRow, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null) { - if (strlen($sClassAlias) == 0) - { + if (strlen($sClassAlias) == 0) { // Default to the current class $sClassAlias = get_class($this); } $this->m_iKey = null; $this->m_bIsInDB = true; - $this->m_aCurrValues = array(); - $this->m_aOrigValues = array(); - $this->m_aLoadedAtt = array(); + $this->m_aCurrValues = []; + $this->m_aOrigValues = []; + $this->m_aLoadedAtt = []; $this->m_bCheckStatus = true; $this->m_aCheckIssues = []; $this->m_bSecurityIssue = []; @@ -478,21 +470,16 @@ abstract class DBObject implements iDisplay // Get the key // $sKeyField = $sClassAlias."id"; - if (!array_key_exists($sKeyField, $aRow)) - { + if (!array_key_exists($sKeyField, $aRow)) { // #@# Bug ? throw new CoreException("Missing key for class '".get_class($this)."'"); } $iPKey = $aRow[$sKeyField]; - if (!self::IsValidPKey($iPKey)) - { - if (is_null($iPKey)) - { + if (!self::IsValidPKey($iPKey)) { + if (is_null($iPKey)) { throw new CoreException("Missing object id in query result (found null)"); - } - else - { + } else { throw new CoreException("An object id must be an integer value ($iPKey)"); } } @@ -501,27 +488,26 @@ abstract class DBObject implements iDisplay // Build the object from an array of "attCode"=>"value") // $bFullyLoaded = true; // ... set to false if any attribute is not found - if (is_null($aAttToLoad) || !array_key_exists($sClassAlias, $aAttToLoad)) - { + if (is_null($aAttToLoad) || !array_key_exists($sClassAlias, $aAttToLoad)) { $aAttList = MetaModel::ListAttributeDefs(get_class($this)); - } - else - { + } else { $aAttList = $aAttToLoad[$sClassAlias]; } - foreach($aAttList as $sAttCode=>$oAttDef) - { + foreach ($aAttList as $sAttCode => $oAttDef) { // Skip links (could not be loaded by the mean of this query) /** @var \AttributeDefinition $oAttDef */ - if ($oAttDef->IsLinkSet()) continue; + if ($oAttDef->IsLinkSet()) { + continue; + } - if (!$oAttDef->LoadInObject()) continue; + if (!$oAttDef->LoadInObject()) { + continue; + } unset($value); $bIsDefined = false; - if ($oAttDef->LoadFromClassTables()) - { + if ($oAttDef->LoadFromClassTables()) { // Note: we assume that, for a given attribute, if it can be loaded, // then one column will be found with an empty suffix, the others have a suffix // Take care: the function isset will return false in case the value is null, @@ -538,46 +524,34 @@ abstract class DBObject implements iDisplay } } - if (!$bIsDefined && array_key_exists($sAttRef, $aRow)) - { + if (!$bIsDefined && array_key_exists($sAttRef, $aRow)) { $value = $oAttDef->FromSQLToValue($aRow, $sAttRef); $bIsDefined = true; } - } - else - { + } else { $value = $oAttDef->ReadExternalValues($this); $bIsDefined = true; } - if ($bIsDefined) - { + if ($bIsDefined) { $this->m_aCurrValues[$sAttCode] = $value; - if (is_object($value)) - { + if (is_object($value)) { $this->m_aOrigValues[$sAttCode] = clone $value; - } - else - { + } else { $this->m_aOrigValues[$sAttCode] = $value; } $this->m_aLoadedAtt[$sAttCode] = true; - } - else - { + } else { // This attribute was expected and not found in the query columns $bFullyLoaded = false; } } // Load extended data - if ($aExtendedDataSpec != null) - { - foreach($aExtendedDataSpec['fields'] as $sColumn) - { + if ($aExtendedDataSpec != null) { + foreach ($aExtendedDataSpec['fields'] as $sColumn) { $sColRef = $sClassAlias.'_extdata_'.$sColumn; - if (array_key_exists($sColRef, $aRow)) - { + if (array_key_exists($sColRef, $aRow)) { $this->m_aExtendedData[$sColumn] = $aRow[$sColRef]; } } @@ -585,18 +559,18 @@ abstract class DBObject implements iDisplay return $bFullyLoaded; } - /** - * Protected raw Setter - * - * This method is an internal plumbing : it sets the value without doing any of the required processes. - * The exposed API Setter is DBObject::Set() - * - * @internal - * @see Set() - * - * @param string $sAttCode - * @param mixed $value - */ + /** + * Protected raw Setter + * + * This method is an internal plumbing : it sets the value without doing any of the required processes. + * The exposed API Setter is DBObject::Set() + * + * @internal + * @see Set() + * + * @param string $sAttCode + * @param mixed $value + */ protected function _Set($sAttCode, $value) { $this->m_aCurrValues[$sAttCode] = $value; @@ -604,25 +578,24 @@ abstract class DBObject implements iDisplay unset($this->m_aModifiedAtt[$sAttCode]); } - - /** - * Attributes setter - * - * Set $sAttCode to $value. - * The value must be valid according to the type of attribute : see the different {@see AttributeDefinition::MakeRealValue()} implementations - * The value will not be recorded into the DB until DBObject::DBWrite() is called. - * - * @api - * - * @param string $sAttCode - * @param mixed $value - * - * @return bool - * @throws CoreException - * @throws CoreUnexpectedValue - * - * @see DBWrite() - */ + /** + * Attributes setter + * + * Set $sAttCode to $value. + * The value must be valid according to the type of attribute : see the different {@see AttributeDefinition::MakeRealValue()} implementations + * The value will not be recorded into the DB until DBObject::DBWrite() is called. + * + * @api + * + * @param string $sAttCode + * @param mixed $value + * + * @return bool + * @throws CoreException + * @throws CoreUnexpectedValue + * + * @see DBWrite() + */ public function Set($sAttCode, $value) { if (!utils::StartsWith(get_class($this), 'CMDBChange') && $this->GetKey() > 0) { @@ -676,8 +649,7 @@ abstract class DBObject implements iDisplay /** @var \DBObject $value */ $this->m_aCurrValues[$sCode] = $value->Get($oDef->GetExtAttCode()); $this->m_aLoadedAtt[$sCode] = true; - } - elseif ($oDef->IsBasedOnOQLExpression()) { + } elseif ($oDef->IsBasedOnOQLExpression()) { $this->m_aCurrValues[$sCode] = $this->GetDefaultValue($sCode); unset($this->m_aLoadedAtt[$sCode]); } @@ -704,7 +676,7 @@ abstract class DBObject implements iDisplay } $this->_Set($sAttCode, $realvalue); - $this->UpdateMetaAttributes(array($sAttCode)); + $this->UpdateMetaAttributes([$sAttCode]); // The object has changed, reset caches $this->m_bCheckStatus = null; @@ -717,13 +689,13 @@ abstract class DBObject implements iDisplay } /** - * Helper to set a value only if it is currently undefined - * - * Call Set() only of the internal representation of the attribute is null. - * - * @api - * @see Set() - * + * Helper to set a value only if it is currently undefined + * + * Call Set() only of the internal representation of the attribute is null. + * + * @api + * @see Set() + * * @param string $sAttCode * @param mixed $value * @@ -736,26 +708,25 @@ abstract class DBObject implements iDisplay { $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode); $oCurrentValue = $this->Get($sAttCode); - if ($oAttDef->IsNull($oCurrentValue)) - { + if ($oAttDef->IsNull($oCurrentValue)) { $this->Set($sAttCode, $value); } } - /** - * Helper to set a value that fits the attribute max size - * - * compare $sValue against the field's max size in the database, and truncate it's ending in order to make it fit. - * If $sValue is short enough, nothing is done. - * - * @api - * - * @param string $sAttCode - * @param string $sValue - * - * @throws CoreException - * @throws CoreUnexpectedValue - */ + /** + * Helper to set a value that fits the attribute max size + * + * compare $sValue against the field's max size in the database, and truncate it's ending in order to make it fit. + * If $sValue is short enough, nothing is done. + * + * @api + * + * @param string $sAttCode + * @param string $sValue + * + * @throws CoreException + * @throws CoreUnexpectedValue + */ public function SetTrim($sAttCode, $sValue) { $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode); @@ -785,20 +756,21 @@ abstract class DBObject implements iDisplay // Activate any existing trigger $sClass = get_class($this); - $aParams = array('class_list' => MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL)); - $oSet = new DBObjectSet(DBObjectSearch::FromOQL('SELECT TriggerOnObjectDelete AS t WHERE t.target_class IN (:class_list)'), array(), - $aParams); + $aParams = ['class_list' => MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL)]; + $oSet = new DBObjectSet( + DBObjectSearch::FromOQL('SELECT TriggerOnObjectDelete AS t WHERE t.target_class IN (:class_list)'), + [], + $aParams + ); while ($oTrigger = $oSet->Fetch()) { /** @var \TriggerOnObjectDelete $oTrigger */ try { $oKPI = new ExecutionKPI(); $oTrigger->DoActivate($this->ToArgs('this')); - } - catch (Exception $e) { + } catch (Exception $e) { $oTrigger->LogException($e, $this); utils::EnrichRaisedException($oTrigger, $e); - } - finally { + } finally { $oKPI->ComputeStatsForExtension($this, 'TriggerOnObjectDelete'); } } @@ -847,18 +819,18 @@ abstract class DBObject implements iDisplay } /** - * Get the label of an attribute. - * - * Shortcut to the field's AttributeDefinition->GetLabel() - * - * @api - * - * @param string $sAttCode - * - * @return string - * - * @throws Exception - */ + * Get the label of an attribute. + * + * Shortcut to the field's AttributeDefinition->GetLabel() + * + * @api + * + * @param string $sAttCode + * + * @return string + * + * @throws Exception + */ public function GetLabel($sAttCode) { $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode); @@ -883,55 +855,45 @@ abstract class DBObject implements iDisplay */ public function Get($sAttCode) { - if (($iPos = strpos($sAttCode, '->')) === false) - { + if (($iPos = strpos($sAttCode, '->')) === false) { return $this->GetStrict($sAttCode); - } - else - { + } else { $sExtKeyAttCode = substr($sAttCode, 0, $iPos); $sRemoteAttCode = substr($sAttCode, $iPos + 2); - if (!MetaModel::IsValidAttCode(get_class($this), $sExtKeyAttCode)) - { + if (!MetaModel::IsValidAttCode(get_class($this), $sExtKeyAttCode)) { throw new CoreException("Unknown external key '$sExtKeyAttCode' for the class ".get_class($this)); } $oExtFieldAtt = MetaModel::FindExternalField(get_class($this), $sExtKeyAttCode, $sRemoteAttCode); - if (!is_null($oExtFieldAtt)) - { + if (!is_null($oExtFieldAtt)) { /** @var \AttributeExternalField $oExtFieldAtt */ return $this->GetStrict($oExtFieldAtt->GetCode()); - } - else - { + } else { $oKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode); /** @var \AttributeExternalKey $oKeyAttDef */ $sRemoteClass = $oKeyAttDef->GetTargetClass(); $oRemoteObj = MetaModel::GetObject($sRemoteClass, $this->GetStrict($sExtKeyAttCode), false); - if (is_null($oRemoteObj)) - { + if (is_null($oRemoteObj)) { return ''; - } - else - { + } else { return $oRemoteObj->Get($sRemoteAttCode); } } } } - /** - * Getter : get values from the current object - * - * @internal - * @see Get - * - * @param string $sAttCode - * - * @return int|mixed|null - * @throws ArchivedObjectException - * @throws CoreException - */ + /** + * Getter : get values from the current object + * + * @internal + * @see Get + * + * @param string $sAttCode + * + * @return int|mixed|null + * @throws ArchivedObjectException + * @throws CoreException + */ public function GetStrict($sAttCode) { if ($sAttCode == 'id') { @@ -961,8 +923,7 @@ abstract class DBObject implements iDisplay /** @var \AttributeExternalField $oAttDef */ $sExtKeyAttCode = $oAttDef->GetKeyAttCode(); - if (($iRemote = $this->Get($sExtKeyAttCode)) && ($iRemote > 0)) // Objects in memory have negative IDs - { + if (($iRemote = $this->Get($sExtKeyAttCode)) && ($iRemote > 0)) { // Objects in memory have negative IDs $oExtKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode); // Note: "allow all data" must be enabled because the external fields are always visible // to the current user even if this is not the case for the remote object @@ -990,7 +951,6 @@ abstract class DBObject implements iDisplay $value = $this->m_aCurrValues[$sAttCode]; } - if ($value instanceof ormLinkSet) { $value->Rewind(); } @@ -998,23 +958,22 @@ abstract class DBObject implements iDisplay return $value; } - /** - * @see \DBObject::ListPreviousValuesForUpdatedAttributes() to get previous values anywhere in the CRUD stack - * @see https://www.itophub.io/wiki/page?id=latest%3Acustomization%3Asequence_crud iTop CRUD stack documentation - * - * @param string $sAttCode - * - * @return mixed|null the value as it was before changed with {@see DBObject::Set()}. - * Returns null if the attribute wasn't changed. - * Values are reset during {@see DBObject::DBUpdate()} - * - * @throws CoreException if the attribute is unknown for the current object - * @uses DBObject::$m_aOrigValues - */ + /** + * @see \DBObject::ListPreviousValuesForUpdatedAttributes() to get previous values anywhere in the CRUD stack + * @see https://www.itophub.io/wiki/page?id=latest%3Acustomization%3Asequence_crud iTop CRUD stack documentation + * + * @param string $sAttCode + * + * @return mixed|null the value as it was before changed with {@see DBObject::Set()}. + * Returns null if the attribute wasn't changed. + * Values are reset during {@see DBObject::DBUpdate()} + * + * @throws CoreException if the attribute is unknown for the current object + * @uses DBObject::$m_aOrigValues + */ public function GetOriginal($sAttCode) { - if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this)))) - { + if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this)))) { throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this)); } $aOrigValues = $this->m_aOrigValues; @@ -1026,31 +985,31 @@ abstract class DBObject implements iDisplay return $this->m_aCurrValues; } - /** - * Returns the default value of the $sAttCode. - * - * Returns the default value of the given attribute. - * - * @internal - * - * @param string $sAttCode - * - * @return mixed - * - * @throws Exception - */ + /** + * Returns the default value of the $sAttCode. + * + * Returns the default value of the given attribute. + * + * @internal + * + * @param string $sAttCode + * + * @return mixed + * + * @throws Exception + */ public function GetDefaultValue($sAttCode) - { - $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode); - return $oAttDef->GetDefaultValue($this); - } + { + $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode); + return $oAttDef->GetDefaultValue($this); + } /** * Returns data loaded by the mean of a dynamic and explicit JOIN - * - * @internal - * - * @return array|null + * + * @internal + * + * @return array|null */ public function GetExtendedData() { @@ -1058,14 +1017,14 @@ abstract class DBObject implements iDisplay } /** - * Set the HighlightCode - * - * Switch to $sCode if it has a greater rank than the current code - * - * @internal - * @used-by DBObject::ComputeHighlightCode() - * @see m_sHighlightCode - * + * Set the HighlightCode + * + * Switch to $sCode if it has a greater rank than the current code + * + * @internal + * @used-by DBObject::ComputeHighlightCode() + * @see m_sHighlightCode + * * @param string $sCode * * @return void @@ -1074,16 +1033,13 @@ abstract class DBObject implements iDisplay { $aHighlightScale = MetaModel::GetHighlightScale(get_class($this)); $fCurrentRank = 0.0; - if (($this->m_sHighlightCode !== null) && array_key_exists($this->m_sHighlightCode, $aHighlightScale)) - { + if (($this->m_sHighlightCode !== null) && array_key_exists($this->m_sHighlightCode, $aHighlightScale)) { $fCurrentRank = $aHighlightScale[$this->m_sHighlightCode]['rank']; } - if (array_key_exists($sCode, $aHighlightScale)) - { + if (array_key_exists($sCode, $aHighlightScale)) { $fRank = $aHighlightScale[$sCode]['rank']; - if ($fRank > $fCurrentRank) - { + if ($fRank > $fCurrentRank) { $this->m_sHighlightCode = $sCode; } } @@ -1091,10 +1047,10 @@ abstract class DBObject implements iDisplay /** * Get the current HighlightCode - * - * @internal - * @used-by DBObject::ComputeHighlightCode() - * + * + * @internal + * @used-by DBObject::ComputeHighlightCode() + * * @return string|null The Hightlight code (null if none set, meaning rank = 0) */ protected function GetHighlightCode() @@ -1102,35 +1058,31 @@ abstract class DBObject implements iDisplay return $this->m_sHighlightCode; } - /** - * Compute the highlightCode - * - * @internal - * - * @example When TTR, then TTR of a UserRequest is greater thant a defined scale, the item is highlighted in the listings - * - * @return string|null The Hightlight code (null if none set, meaning rank = 0) - * - * @throws ArchivedObjectException - * @throws CoreException - */ + /** + * Compute the highlightCode + * + * @internal + * + * @example When TTR, then TTR of a UserRequest is greater thant a defined scale, the item is highlighted in the listings + * + * @return string|null The Hightlight code (null if none set, meaning rank = 0) + * + * @throws ArchivedObjectException + * @throws CoreException + */ protected function ComputeHighlightCode() { - if (MetaModel::HasLifecycle(get_class($this))) - { + if (MetaModel::HasLifecycle(get_class($this))) { $sState = $this->GetState(); $sCode = MetaModel::GetHighlightCode(get_class($this), $sState); $this->SetHighlightCode($sCode); } // The check for each StopWatch if a HighlightCode is effective - foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) - { - if ($oAttDef instanceof AttributeStopWatch) - { + foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) { + if ($oAttDef instanceof AttributeStopWatch) { $oStopWatch = $this->Get($sAttCode); $sCode = $oStopWatch->GetHighlightCode(); - if ($sCode !== '') - { + if ($sCode !== '') { $this->SetHighlightCode($sCode); } } @@ -1138,28 +1090,27 @@ abstract class DBObject implements iDisplay return $this->GetHighlightCode(); } - /** - * Updates the value of an external field by (re)loading the object - * corresponding to the external key and getting the value from it - * - * UNUSED ? - * - * @internal - * @todo: check if this is dead code. - * - * @param string $sAttCode Attribute code of the external field to update - * - * @return void - * - * @throws ArchivedObjectException - * @throws CoreException - * @throws CoreUnexpectedValue - */ + /** + * Updates the value of an external field by (re)loading the object + * corresponding to the external key and getting the value from it + * + * UNUSED ? + * + * @internal + * @todo: check if this is dead code. + * + * @param string $sAttCode Attribute code of the external field to update + * + * @return void + * + * @throws ArchivedObjectException + * @throws CoreException + * @throws CoreUnexpectedValue + */ protected function UpdateExternalField($sAttCode) { $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode); - if ($oAttDef->IsExternalField()) - { + if ($oAttDef->IsExternalField()) { /** @var \AttributeExternalField $oAttDef */ $sTargetClass = $oAttDef->GetTargetClass(); $objkey = $this->Get($oAttDef->GetKeyAttCode()); @@ -1167,8 +1118,7 @@ abstract class DBObject implements iDisplay // to the current user even if this is not the case for the remote object // This is consistent with the behavior of the lists $oObj = MetaModel::GetObject($sTargetClass, $objkey, true, true); - if (is_object($oObj)) - { + if (is_object($oObj)) { $value = $oObj->Get($oAttDef->GetExtAttCode()); $this->Set($sAttCode, $value); } @@ -1177,9 +1127,9 @@ abstract class DBObject implements iDisplay /** * Overridable callback - * + * * @internal this method is elligible to the "overwritable-hook" tag. But it is willingly excluded. - * @used-by DoComputeValues() + * @used-by DoComputeValues() */ public function ComputeValues() { @@ -1199,11 +1149,16 @@ abstract class DBObject implements iDisplay // First check that we are not currently computing the fields // (yes, we need to do some things like Set/Get to compute the fields which will in turn trigger the update...) - foreach (debug_backtrace() as $aCallInfo) - { - if (!array_key_exists("class", $aCallInfo)) continue; - if ($aCallInfo["class"] != get_class($this)) continue; - if ($aCallInfo["function"] != "ComputeValues") continue; + foreach (debug_backtrace() as $aCallInfo) { + if (!array_key_exists("class", $aCallInfo)) { + continue; + } + if ($aCallInfo["class"] != get_class($this)) { + continue; + } + if ($aCallInfo["function"] != "ComputeValues") { + continue; + } return; //skip! } $this->FireEventComputeValues($this->sStimulusBeingApplied); @@ -1212,40 +1167,36 @@ abstract class DBObject implements iDisplay $oKPI->ComputeStatsForExtension($this, 'ComputeValues'); } - /** - * @api - * - * @param string $sAttCode - * @param bool $bLocalize - * - * @return string $sAttCode formatted as HTML for the console details forms (when viewing, not when editing !) - * The returned string is already escaped, and as such is protected against XSS - * The markup relies on a few assumptions (CSS) that could change without notice - * - * @throws ArchivedObjectException - * @throws CoreException - * @throws DictExceptionMissingString - * - * @see \Combodo\iTop\Form\Field\Field for rendering in portal forms - */ + /** + * @api + * + * @param string $sAttCode + * @param bool $bLocalize + * + * @return string $sAttCode formatted as HTML for the console details forms (when viewing, not when editing !) + * The returned string is already escaped, and as such is protected against XSS + * The markup relies on a few assumptions (CSS) that could change without notice + * + * @throws ArchivedObjectException + * @throws CoreException + * @throws DictExceptionMissingString + * + * @see \Combodo\iTop\Form\Field\Field for rendering in portal forms + */ public function GetAsHTML($sAttCode, $bLocalize = true) { $sClass = get_class($this); $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode); - if ($oAtt->IsExternalKey(EXTKEY_ABSOLUTE)) - { + if ($oAtt->IsExternalKey(EXTKEY_ABSOLUTE)) { //return $this->Get($sAttCode.'_friendlyname'); /** @var \AttributeExternalKey $oAtt */ $sTargetClass = $oAtt->GetTargetClass(EXTKEY_ABSOLUTE); $iTargetKey = $this->Get($sAttCode); - if ($iTargetKey < 0) - { + if ($iTargetKey < 0) { // the key points to an object that exists only in memory... no hyperlink points to it yet return ''; - } - else - { + } else { $sHtmlLabel = utils::EscapeHtml($this->Get($sAttCode.'_friendlyname')); $bArchived = $this->IsArchived($sAttCode); $bObsolete = $this->IsObsolete($sAttCode); @@ -1258,183 +1209,175 @@ abstract class DBObject implements iDisplay return $oAtt->GetAsHTML($this->Get($sAttCode), $this, $bLocalize); } - /** - * Get the value as it must be in the edit areas (forms) - * - * Makes a raw text representation of the value. - * - * @internal - * - * @param string $sAttCode - * - * @return int|mixed|string - * - * @throws ArchivedObjectException - * @throws CoreException - */ + /** + * Get the value as it must be in the edit areas (forms) + * + * Makes a raw text representation of the value. + * + * @internal + * + * @param string $sAttCode + * + * @return int|mixed|string + * + * @throws ArchivedObjectException + * @throws CoreException + */ public function GetEditValue($sAttCode) { $sClass = get_class($this); $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode); - if ($oAtt->IsExternalKey()) - { + if ($oAtt->IsExternalKey()) { /** @var \AttributeExternalKey $oAtt */ $sTargetClass = $oAtt->GetTargetClass(); - if ($this->IsNew()) - { + if ($this->IsNew()) { // The current object exists only in memory, don't try to query it in the DB ! // instead let's query for the object pointed by the external key, and get its name $targetObjId = $this->Get($sAttCode); $oTargetObj = MetaModel::GetObject($sTargetClass, $targetObjId, false); // false => not sure it exists - if (is_object($oTargetObj)) - { + if (is_object($oTargetObj)) { $sEditValue = $oTargetObj->GetName(); - } - else - { + } else { $sEditValue = 0; } - } - else - { + } else { $sEditValue = $this->Get($sAttCode.'_friendlyname'); } - } - else - { + } else { $sEditValue = $oAtt->GetEditValue($this->Get($sAttCode), $this); } return $sEditValue; } - /** - * Get $sAttCode formatted as XML - * - * The returned value is a text that is suitable for insertion into an XML node. - * Depending on the type of attribute, the returned text is either: - * * A literal, with XML entities already escaped, - * * XML - * - * @api - * - * @param string $sAttCode - * @param bool $bLocalize - * - * @return mixed - * - * @throws ArchivedObjectException - * @throws CoreException - */ + /** + * Get $sAttCode formatted as XML + * + * The returned value is a text that is suitable for insertion into an XML node. + * Depending on the type of attribute, the returned text is either: + * * A literal, with XML entities already escaped, + * * XML + * + * @api + * + * @param string $sAttCode + * @param bool $bLocalize + * + * @return mixed + * + * @throws ArchivedObjectException + * @throws CoreException + */ public function GetAsXML($sAttCode, $bLocalize = true) { $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode); return $oAtt->GetAsXML($this->Get($sAttCode), $this, $bLocalize); } - /** - * Get $sAttCode formatted as CSV - * - * @api - * - * @param string $sAttCode - * @param string $sSeparator - * @param string $sTextQualifier - * @param bool $bLocalize - * @param bool $bConvertToPlainText - * - * @return string - * - * @throws ArchivedObjectException - * @throws CoreException - */ + /** + * Get $sAttCode formatted as CSV + * + * @api + * + * @param string $sAttCode + * @param string $sSeparator + * @param string $sTextQualifier + * @param bool $bLocalize + * @param bool $bConvertToPlainText + * + * @return string + * + * @throws ArchivedObjectException + * @throws CoreException + */ public function GetAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"', $bLocalize = true, $bConvertToPlainText = false) { $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode); return $oAtt->GetAsCSV($this->Get($sAttCode), $sSeparator, $sTextQualifier, $this, $bLocalize, $bConvertToPlainText); } - /** - * - * @see GetAsHTML() - * @see GetOriginal() - * - * @param string $sAttCode - * @param bool $bLocalize - * - * @return string - * @throws CoreException - */ + /** + * + * @see GetAsHTML() + * @see GetOriginal() + * + * @param string $sAttCode + * @param bool $bLocalize + * + * @return string + * @throws CoreException + */ public function GetOriginalAsHTML($sAttCode, $bLocalize = true) { $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode); return $oAtt->GetAsHTML($this->GetOriginal($sAttCode), $this, $bLocalize); } - /** - * - * @see GetAsXML() - * @see GetOriginal() - * - * @param string $sAttCode - * @param bool $bLocalize - * - * @return mixed - * @throws CoreException - */ + /** + * + * @see GetAsXML() + * @see GetOriginal() + * + * @param string $sAttCode + * @param bool $bLocalize + * + * @return mixed + * @throws CoreException + */ public function GetOriginalAsXML($sAttCode, $bLocalize = true) { $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode); return $oAtt->GetAsXML($this->GetOriginal($sAttCode), $this, $bLocalize); } - /** - * - * @see GetAsCSV() - * @see GetOriginal() - * - * @param string $sAttCode - * @param string $sSeparator - * @param string $sTextQualifier - * @param bool $bLocalize - * @param bool $bConvertToPlainText - * - * @return string - * @throws CoreException - */ + /** + * + * @see GetAsCSV() + * @see GetOriginal() + * + * @param string $sAttCode + * @param string $sSeparator + * @param string $sTextQualifier + * @param bool $bLocalize + * @param bool $bConvertToPlainText + * + * @return string + * @throws CoreException + */ public function GetOriginalAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"', $bLocalize = true, $bConvertToPlainText = false) { $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode); return $oAtt->GetAsCSV($this->GetOriginal($sAttCode), $sSeparator, $sTextQualifier, $this, $bLocalize, $bConvertToPlainText); } - /** - * Return an hyperlink pointing to <$sObjClass, $sObjKey> - * - * @internal - * - * @param string $sObjClass - * @param string $sObjKey - * @param string $sHtmlLabel Label with HTML entities escaped (< escaped as <) - * @param null|string $sUrlMakerClass if not null, the class must expose a public method ''MakeObjectUrl(string $sObjClass, string $sObjKey)'' - * @param bool $bWithNavigationContext - * @param bool $bArchived - * @param bool $bObsolete - * - * @return string the HTML markup pointing to <$sObjClass, $sObjKey> - * - * @throws \ArchivedObjectException - * @throws \CoreException - * @throws \DictExceptionMissingString - */ + /** + * Return an hyperlink pointing to <$sObjClass, $sObjKey> + * + * @internal + * + * @param string $sObjClass + * @param string $sObjKey + * @param string $sHtmlLabel Label with HTML entities escaped (< escaped as <) + * @param null|string $sUrlMakerClass if not null, the class must expose a public method ''MakeObjectUrl(string $sObjClass, string $sObjKey)'' + * @param bool $bWithNavigationContext + * @param bool $bArchived + * @param bool $bObsolete + * + * @return string the HTML markup pointing to <$sObjClass, $sObjKey> + * + * @throws \ArchivedObjectException + * @throws \CoreException + * @throws \DictExceptionMissingString + */ public static function MakeHyperLink($sObjClass, $sObjKey, $sHtmlLabel = '', $sUrlMakerClass = null, $bWithNavigationContext = true, $bArchived = false, $bObsolete = false, $bIgnorePreview = false) { - if ($sObjKey <= 0) return ''.Dict::S('UI:UndefinedObject').''; // Objects built in memory have negative IDs + if ($sObjKey <= 0) { + return ''.Dict::S('UI:UndefinedObject').''; + } // Objects built in memory have negative IDs // Safety net // - if (empty($sHtmlLabel)) - { + if (empty($sHtmlLabel)) { // If the object if not issued from a query but constructed programmatically // the label may be empty. In this case run a query to get the object's friendly name $sObjOql = 'SELECT '.$sObjClass.' WHERE id='.$sObjKey; @@ -1459,29 +1402,21 @@ abstract class DBObject implements iDisplay $sUrl = ApplicationContext::MakeObjectUrl($sObjClass, $sObjKey, $sUrlMakerClass, $bWithNavigationContext); $bClickable = !$bArchived || utils::IsArchiveMode(); - if ($bArchived) - { + if ($bArchived) { $sSpanClass = 'archived'; $sFA = 'fa-archive object-archived'; $sHint = Dict::S('ObjectRef:Archived'); - } - elseif ($bObsolete) - { + } elseif ($bObsolete) { $sSpanClass = 'obsolete'; $sFA = 'fa-eye-slash object-obsolete'; $sHint = Dict::S('ObjectRef:Obsolete'); - } - else - { + } else { $sSpanClass = ''; $sFA = ''; } - if ($sFA == '') - { + if ($sFA == '') { $sIcon = ''; - } - else - { + } else { if ($bClickable) { $sIcon = ""; } else { @@ -1489,63 +1424,57 @@ abstract class DBObject implements iDisplay } } - if ($bClickable && (strlen($sUrl) > 0)) - { + if ($bClickable && (strlen($sUrl) > 0)) { $sHLink = "$sIcon$sHtmlLabel"; - } - else - { + } else { $sHLink = $sIcon.$sHtmlLabel; } $sPreview = ''; - if(SummaryCardService::IsAllowedForClass($sObjClass) && $bIgnorePreview === false){ + if (SummaryCardService::IsAllowedForClass($sObjClass) && $bIgnorePreview === false) { $sPreview = SummaryCardService::GetHyperlinkMarkup($sObjClass, $sObjKey); } $sRet = "$sHLink"; return $sRet; } - /** - * Return an hyperlink pointing to the current DBObject - * - * @api - * - * @param string $sUrlMakerClass - * @param bool $bWithNavigationContext - * @param string $sLabel - * - * @return string - * - * @throws ArchivedObjectException - * @throws CoreException - * @throws DictExceptionMissingString - */ + /** + * Return an hyperlink pointing to the current DBObject + * + * @api + * + * @param string $sUrlMakerClass + * @param bool $bWithNavigationContext + * @param string $sLabel + * + * @return string + * + * @throws ArchivedObjectException + * @throws CoreException + * @throws DictExceptionMissingString + */ public function GetHyperlink($sUrlMakerClass = null, $bWithNavigationContext = true, $sLabel = null, $bIgnorePreview = false) { - if($sLabel === null) - { - $sLabel = $this->GetName(); - } + if ($sLabel === null) { + $sLabel = $this->GetName(); + } $bArchived = $this->IsArchived(); $bObsolete = $this->IsObsolete(); return self::MakeHyperLink(get_class($this), $this->GetKey(), $sLabel, $sUrlMakerClass, $bWithNavigationContext, $bArchived, $bObsolete, $bIgnorePreview); } - /** - * @internal - * - * @param string $sClass - * - * @return mixed - */ + /** + * @internal + * + * @param string $sClass + * + * @return mixed + */ public static function ComputeStandardUIPage($sClass) { - static $aUIPagesCache = array(); // Cache to store the php page used to display each class of object - if (!isset($aUIPagesCache[$sClass])) - { + static $aUIPagesCache = []; // Cache to store the php page used to display each class of object + if (!isset($aUIPagesCache[$sClass])) { $UIPage = false; - if (is_callable("$sClass::GetUIPage")) - { + if (is_callable("$sClass::GetUIPage")) { $UIPage = eval("return $sClass::GetUIPage();"); // May return false in case of error } $aUIPagesCache[$sClass] = $UIPage === false ? './UI.php' : $UIPage; @@ -1554,93 +1483,87 @@ abstract class DBObject implements iDisplay return $sPage; } - /** - * @internal - * - * @return string - */ + /** + * @internal + * + * @return string + */ public static function GetUIPage() { return 'UI.php'; } - - - - /** - * Whether $value is valid as a primary key - * - * @internal - * - * @param string $value - * - * @return bool - */ + /** + * Whether $value is valid as a primary key + * + * @internal + * + * @param string $value + * + * @return bool + */ public static function IsValidPKey($value) { - // this function could be in the metamodel ? + // this function could be in the metamodel ? return ((string)$value === (string)(int)$value); } - /** - * Primary key Getter - * - * Get the id - * - * @api - * - * @return string|null - */ + /** + * Primary key Getter + * + * Get the id + * + * @api + * + * @return string|null + */ public function GetKey() { return $this->m_iKey; } - /** - * Primary key Setter - * Usable only for not yet persisted DBObjects - * - * @internal - * - * @param int $iNewKey the desired identifier - * - * @throws CoreException - */ + /** + * Primary key Setter + * Usable only for not yet persisted DBObjects + * + * @internal + * + * @param int $iNewKey the desired identifier + * + * @throws CoreException + */ public function SetKey($iNewKey) { - if (!self::IsValidPKey($iNewKey)) - { + if (!self::IsValidPKey($iNewKey)) { throw new CoreException("An object id must be an integer value ($iNewKey)"); } - if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey)) - { + if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey)) { throw new CoreException("Changing the key ({$this->m_iKey} to $iNewKey) on an object (class {".get_class($this).") wich already exists in the Database"); } $this->m_iKey = $iNewKey; } - /** - * Get the icon representing this object - * - * @api - * - * @param boolean $bImgTag If true the result is a full IMG tag (or an empty string if no icon is defined) - * - * @return string Either the full IMG tag ($bImgTag == true) or just the URL to the icon file - * @throws ArchivedObjectException - * @throws CoreException - */ + /** + * Get the icon representing this object + * + * @api + * + * @param boolean $bImgTag If true the result is a full IMG tag (or an empty string if no icon is defined) + * + * @return string Either the full IMG tag ($bImgTag == true) or just the URL to the icon file + * @throws ArchivedObjectException + * @throws CoreException + */ public function GetIcon($bImgTag = true) { $sClass = get_class($this); - if($this->HasHighlightIcon()) { + if ($this->HasHighlightIcon()) { $sIconUrl = MetaModel::GetHighlightScale($sClass)[$this->ComputeHighlightCode()]['icon']; - if($bImgTag) { + if ($bImgTag) { return ""; - } - else { + } else { return $sIconUrl; } } @@ -1649,10 +1572,9 @@ abstract class DBObject implements iDisplay $sImageAttCode = MetaModel::GetImageAttributeCode($sClass); $sIconUrl = $this->HasInstanceIcon() ? $this->Get($sImageAttCode)->GetDisplayURL($sClass, $this->GetKey(), $sImageAttCode) : ''; if (strlen($sIconUrl) > 0) { - if($bImgTag) { + if ($bImgTag) { return ""; - } - else { + } else { return $sIconUrl; } } @@ -1695,11 +1617,9 @@ abstract class DBObject implements iDisplay $sCode = $this->ComputeHighlightCode(); $sClass = get_class($this); - if($sCode != '') - { + if ($sCode != '') { $aHighlightScale = MetaModel::GetHighlightScale($sClass); - if (array_key_exists($sCode, $aHighlightScale)) - { + if (array_key_exists($sCode, $aHighlightScale)) { $bHasHighlightIcon = true; } } @@ -1711,9 +1631,9 @@ abstract class DBObject implements iDisplay * Get the label of a class * * Returns the label as defined in the dictionary for the language of the current user - * - * @api - * + * + * @api + * * @return string (empty for default name scheme) */ public static function GetClassName($sClass) @@ -1726,14 +1646,14 @@ abstract class DBObject implements iDisplay * Get the description of a class * * Returns the label as defined in the dictionary for the language of the current user - * - * @internal - * + * + * @internal + * * @param string $sClass * * @return string */ - final static public function GetClassDescription($sClass) + final public static function GetClassDescription($sClass) { $sStringCode = 'Class:'.$sClass.'+'; return Dict::S($sStringCode, ''); @@ -1748,7 +1668,7 @@ abstract class DBObject implements iDisplay * @since 3.0.0 N°580 New $sType parameter * @since 3.3.0 N°4107 Should never be overriden */ - public final function GetName($sType = FriendlyNameType::SHORT) + final public function GetName($sType = FriendlyNameType::SHORT) { return utils::EscapeHtml($this->GetRawName($sType)); } @@ -1778,69 +1698,60 @@ abstract class DBObject implements iDisplay } /** - * Helper to get the state - * - * @api - * + * Helper to get the state + * + * @api + * * @return mixed|string '' if no state attribute, object representing its value otherwise * @throws \CoreException */ public function GetState() { $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this)); - if (empty($sStateAttCode)) - { + if (empty($sStateAttCode)) { return ''; - } - else - { + } else { return $this->Get($sStateAttCode); } } - /** - * Get the label (raw text) of the current state - * helper for MetaModel::GetStateLabel() - * - * @api - * - * @return mixed|string - * - * @throws ArchivedObjectException - * @throws CoreException - */ + /** + * Get the label (raw text) of the current state + * helper for MetaModel::GetStateLabel() + * + * @api + * + * @return mixed|string + * + * @throws ArchivedObjectException + * @throws CoreException + */ public function GetStateLabel() { $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this)); - if (empty($sStateAttCode)) - { + if (empty($sStateAttCode)) { return ''; - } - else - { + } else { $sStateValue = $this->Get($sStateAttCode); return MetaModel::GetStateLabel(get_class($this), $sStateValue); } } - /** - * Get the description of the state - * - * @api - * - * @return mixed|string - * @throws ArchivedObjectException - * @throws CoreException - */ + /** + * Get the description of the state + * + * @api + * + * @return mixed|string + * @throws ArchivedObjectException + * @throws CoreException + */ public function GetStateDescription() { $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this)); - if (empty($sStateAttCode)) - { + if (empty($sStateAttCode)) { return ''; - } - else - { + } else { $sStateValue = $this->Get($sStateAttCode); return MetaModel::GetStateDescription(get_class($this), $sStateValue); } @@ -1856,15 +1767,14 @@ abstract class DBObject implements iDisplay return null; } - /** * Get predefined objects - * + * * The predefined objects will be synchronized with the DB at each install/upgrade - * As soon as a class has predefined objects, then nobody can create nor delete objects - * - * @internal - * + * As soon as a class has predefined objects, then nobody can create nor delete objects + * + * @internal + * * @return array An array of id => array of attcode => php value(so-called "real value": integer, string, ormDocument, DBObjectSet, etc.) */ public static function GetPredefinedObjects() @@ -1873,10 +1783,10 @@ abstract class DBObject implements iDisplay } /** - * Get the flags for the given state - * - * @overwritable-hook You can extend this method in order to provide your own logic. If you do so, rely on the parent as a fallback if you have uncovered $sAttCode - * + * Get the flags for the given state + * + * @overwritable-hook You can extend this method in order to provide your own logic. If you do so, rely on the parent as a fallback if you have uncovered $sAttCode + * * @param string $sAttCode $sAttCode The code of the attribute * @param array $aReasons To store the reasons why the attribute is read-only (info about the synchro replicas) * @param string $sTargetState The target state in which to evaluate the flags, if empty the current state will be used @@ -1884,41 +1794,34 @@ abstract class DBObject implements iDisplay * @return integer the binary combination of flags for the given attribute in the given state of the object. * Values can be one of the OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY, ... (see define in metamodel.class.php) * Combine multiple values using the "|" operator, for example `OPT_ATT_READONLY | OPT_ATT_HIDDEN`. - * + * * @throws \CoreException * * @see GetInitialStateAttributeFlags for creation */ - public function GetAttributeFlags($sAttCode, &$aReasons = array(), $sTargetState = '') + public function GetAttributeFlags($sAttCode, &$aReasons = [], $sTargetState = '') { $iFlags = 0; // By default (if no life cycle) no flag at all $sClass = get_class($this); $aReadOnlyAtts = $this->GetReadOnlyAttributes(); - if (($aReadOnlyAtts != null) && (in_array($sAttCode, $aReadOnlyAtts))) - { + if (($aReadOnlyAtts != null) && (in_array($sAttCode, $aReadOnlyAtts))) { return OPT_ATT_READONLY; } - if (MetaModel::HasLifecycle($sClass)) - { - if ($sTargetState != '') - { + if (MetaModel::HasLifecycle($sClass)) { + if ($sTargetState != '') { $iFlags = MetaModel::GetAttributeFlags($sClass, $sTargetState, $sAttCode); - } - else - { + } else { $sStateAttCode = MetaModel::GetStateAttributeCode($sClass); $iFlags = MetaModel::GetAttributeFlags($sClass, $this->Get($sStateAttCode), $sAttCode); } } - $aReasons = array(); + $aReasons = []; $iSynchroFlags = 0; - if ($this->InSyncScope()) - { + if ($this->InSyncScope()) { $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons); - if ($iSynchroFlags & OPT_ATT_SLAVE) - { + if ($iSynchroFlags & OPT_ATT_SLAVE) { $iSynchroFlags |= OPT_ATT_READONLY; } } @@ -1926,117 +1829,113 @@ abstract class DBObject implements iDisplay return $iFlags | $iSynchroFlags | $iExtensionsFlags; // Combine both sets of flags } - /** - * Whether the attribute is read-only - * - * @internal - * - * @param string $sAttCode - * @param array $aReasons To store the reasons why the attribute is read-only (info about the synchro replicas) - * - * @return int Values can be one of the OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY, ... (see define in metamodel.class.php) - * - * @throws \CoreException - */ - public function IsAttributeReadOnlyForCurrentState($sAttCode, &$aReasons = array()) + /** + * Whether the attribute is read-only + * + * @internal + * + * @param string $sAttCode + * @param array $aReasons To store the reasons why the attribute is read-only (info about the synchro replicas) + * + * @return int Values can be one of the OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY, ... (see define in metamodel.class.php) + * + * @throws \CoreException + */ + public function IsAttributeReadOnlyForCurrentState($sAttCode, &$aReasons = []) { $iAttFlags = $this->GetAttributeFlags($sAttCode, $aReasons); return ($iAttFlags & OPT_ATT_READONLY); } - /** - * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...) - * for the given attribute in a transition - * - * @internal - * - * @param string $sAttCode $sAttCode The code of the attribute - * @param string $sStimulus The stimulus code to apply - * @param array|null $aReasons To store the reasons why the attribute is read-only (info about the synchro replicas) - * @param string $sOriginState The state from which to apply $sStimulus, if empty current state will be used - * - * @return integer Flags: the binary combination of the flags applicable to this attribute - * @throws ArchivedObjectException - * @throws CoreException - */ - public function GetTransitionFlags($sAttCode, $sStimulus, &$aReasons = array(), $sOriginState = '') - { - $iFlags = 0; // By default (if no lifecycle) no flag at all - $sClass = get_class($this); + /** + * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...) + * for the given attribute in a transition + * + * @internal + * + * @param string $sAttCode $sAttCode The code of the attribute + * @param string $sStimulus The stimulus code to apply + * @param array|null $aReasons To store the reasons why the attribute is read-only (info about the synchro replicas) + * @param string $sOriginState The state from which to apply $sStimulus, if empty current state will be used + * + * @return integer Flags: the binary combination of the flags applicable to this attribute + * @throws ArchivedObjectException + * @throws CoreException + */ + public function GetTransitionFlags($sAttCode, $sStimulus, &$aReasons = [], $sOriginState = '') + { + $iFlags = 0; // By default (if no lifecycle) no flag at all + $sClass = get_class($this); - // If no state attribute, there is no lifecycle - if (!MetaModel::HasLifecycle($sClass)) - { - return $iFlags; - } + // If no state attribute, there is no lifecycle + if (!MetaModel::HasLifecycle($sClass)) { + return $iFlags; + } - // Retrieving current state if necessary - if ($sOriginState === '') - { - $sStateAttCode = MetaModel::GetStateAttributeCode($sClass); - $sOriginState = $this->Get($sStateAttCode); - } + // Retrieving current state if necessary + if ($sOriginState === '') { + $sStateAttCode = MetaModel::GetStateAttributeCode($sClass); + $sOriginState = $this->Get($sStateAttCode); + } - // Retrieving attribute flags - $iAttributeFlags = $this->GetAttributeFlags($sAttCode, $aReasons, $sOriginState); + // Retrieving attribute flags + $iAttributeFlags = $this->GetAttributeFlags($sAttCode, $aReasons, $sOriginState); - // Retrieving transition flags - $iTransitionFlags = MetaModel::GetTransitionFlags($sClass, $sOriginState, $sStimulus, $sAttCode); + // Retrieving transition flags + $iTransitionFlags = MetaModel::GetTransitionFlags($sClass, $sOriginState, $sStimulus, $sAttCode); - // Merging transition flags with attribute flags - $iFlags = $iTransitionFlags | $iAttributeFlags; + // Merging transition flags with attribute flags + $iFlags = $iTransitionFlags | $iAttributeFlags; - return $iFlags; - } + return $iFlags; + } - /** - * Returns an array of attribute codes (with their flags) when $sStimulus is applied on the object in the $sOriginState state. - * Note: Attributes (and flags) from the target state and the transition are combined. - * - * @internal - * - * @param string $sStimulus - * @param string $sOriginState Default is current state - * - * @return array - * @throws CoreException - */ - public function GetTransitionAttributes($sStimulus, $sOriginState = null) - { - $sObjClass = get_class($this); + /** + * Returns an array of attribute codes (with their flags) when $sStimulus is applied on the object in the $sOriginState state. + * Note: Attributes (and flags) from the target state and the transition are combined. + * + * @internal + * + * @param string $sStimulus + * @param string $sOriginState Default is current state + * + * @return array + * @throws CoreException + */ + public function GetTransitionAttributes($sStimulus, $sOriginState = null) + { + $sObjClass = get_class($this); - // Defining current state as origin state if not specified - if($sOriginState === null) - { - $sOriginState = $this->GetState(); - } + // Defining current state as origin state if not specified + if ($sOriginState === null) { + $sOriginState = $this->GetState(); + } - $aAttributes = MetaModel::GetTransitionAttributes($sObjClass, $sStimulus, $sOriginState); + $aAttributes = MetaModel::GetTransitionAttributes($sObjClass, $sStimulus, $sOriginState); - return $aAttributes; - } + return $aAttributes; + } /** * @param string $sAttCode The code of the attribute * @param array $aReasons * - * @overwritable-hook You can extend this method in order to provide your own logic - * + * @overwritable-hook You can extend this method in order to provide your own logic + * * @return integer The binary combination of the flags for the given attribute for the current state of the object considered as an INITIAL state. * Values can be one of the OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY, ... (see define in metamodel.class.php) - * + * * @throws \CoreException * * @see GetAttributeFlags when modifying the object */ - public function GetInitialStateAttributeFlags($sAttCode, &$aReasons = array()) + public function GetInitialStateAttributeFlags($sAttCode, &$aReasons = []) { $iFlags = 0; $sClass = get_class($this); - if (MetaModel::HasLifecycle($sClass)) - { + if (MetaModel::HasLifecycle($sClass)) { $sStateAttCode = MetaModel::GetStateAttributeCode($sClass); $iFlags = MetaModel::GetInitialStateAttributeFlags($sClass, $this->Get($sStateAttCode), $sAttCode); } @@ -2062,89 +1961,63 @@ abstract class DBObject implements iDisplay */ public function CheckValue($sAttCode, $value = null) { - if (!is_null($value)) - { + if (!is_null($value)) { $toCheck = $value; - } - else - { + } else { $toCheck = $this->Get($sAttCode); } $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode); - if (!$oAtt->IsWritable()) - { + if (!$oAtt->IsWritable()) { return true; - } - elseif ($oAtt->IsNull($toCheck)) - { - if ($oAtt->IsNullAllowed()) - { + } elseif ($oAtt->IsNull($toCheck)) { + if ($oAtt->IsNullAllowed()) { return true; - } - else - { + } else { return "Null not allowed"; } - } - elseif ($oAtt->IsExternalKey()) - { - if (!MetaModel::SkipCheckExtKeys()) - { + } elseif ($oAtt->IsExternalKey()) { + if (!MetaModel::SkipCheckExtKeys()) { /** @var \AttributeExternalKey $oAtt */ $sTargetClass = $oAtt->GetTargetClass(); if (false === MetaModel::IsObjectInDB($sTargetClass, $toCheck)) { return "Target object not found ({$sTargetClass}::{$toCheck})"; } } - if ($oAtt->IsHierarchicalKey()) - { + if ($oAtt->IsHierarchicalKey()) { // This check cannot be deactivated since otherwise the user may break things by a CSV import of a bulk modify - $aValues = $oAtt->GetAllowedValues(array('this' => $this)); - if (!array_key_exists($toCheck, $aValues)) - { + $aValues = $oAtt->GetAllowedValues(['this' => $this]); + if (!array_key_exists($toCheck, $aValues)) { return "Value not allowed [$toCheck]"; } } - } - elseif ($oAtt instanceof AttributeTagSet) - { - if (is_string($toCheck)) - { + } elseif ($oAtt instanceof AttributeTagSet) { + if (is_string($toCheck)) { $oTag = new ormTagSet(get_class($this), $sAttCode, $oAtt->GetMaxItems()); - try - { + try { $oTag->SetValues(explode(' ', $toCheck)); - } catch (Exception $e) - { + } catch (Exception $e) { return "Tag value '$toCheck' is not a valid tag list"; } return true; } - if ($toCheck instanceof ormTagSet) - { + if ($toCheck instanceof ormTagSet) { return true; } return "Bad type"; - } - elseif ($oAtt instanceof AttributeSet) - { - if (is_string($toCheck)) - { + } elseif ($oAtt instanceof AttributeSet) { + if (is_string($toCheck)) { $oTag = new ormSet(get_class($this), $sAttCode, $oAtt->GetMaxItems()); - try - { - $aValues = array(); - foreach(explode(',', $toCheck) as $sValue) - { + try { + $aValues = []; + foreach (explode(',', $toCheck) as $sValue) { $aValues[] = trim($sValue); } $oTag->SetValues($aValues); - } catch (Exception $e) - { + } catch (Exception $e) { return "Set value '$toCheck' is not a valid set"; } @@ -2173,9 +2046,7 @@ abstract class DBObject implements iDisplay if (!$oAtt->CheckFormat($toCheck)) { return "Wrong format [$toCheck]"; } - } - else - { + } else { return $oAtt->CheckValue($this, $toCheck); } return true; @@ -2194,11 +2065,11 @@ abstract class DBObject implements iDisplay } /** - * @internal - * + * @internal + * * @throws \CoreException * @throws \OQLException - * + * * @since 2.6.0 N°659 uniqueness constraint * @api */ @@ -2207,28 +2078,23 @@ abstract class DBObject implements iDisplay $sCurrentClass = get_class($this); $aUniquenessRules = MetaModel::GetUniquenessRules($sCurrentClass); - foreach ($aUniquenessRules as $sUniquenessRuleId => $aUniquenessRuleProperties) - { - if ($aUniquenessRuleProperties['disabled'] === true) - { + foreach ($aUniquenessRules as $sUniquenessRuleId => $aUniquenessRuleProperties) { + if ($aUniquenessRuleProperties['disabled'] === true) { continue; } // No iTopMutex so there might be concurrent access ! // But the necessary lock would have a high performance cost :( $bHasDuplicates = $this->HasObjectsInDbForUniquenessRule($sUniquenessRuleId, $aUniquenessRuleProperties); - if ($bHasDuplicates) - { + if ($bHasDuplicates) { $bIsBlockingRule = $aUniquenessRuleProperties['is_blocking']; - if (is_null($bIsBlockingRule)) - { + if (is_null($bIsBlockingRule)) { $bIsBlockingRule = true; } $sErrorMessage = $this->GetUniquenessRuleMessage($sUniquenessRuleId); - if ($bIsBlockingRule) - { + if ($bIsBlockingRule) { $this->m_aCheckIssues[] = $sErrorMessage; continue; } @@ -2239,9 +2105,9 @@ abstract class DBObject implements iDisplay } /** - * - * @internal - * + * + * @internal + * * @param string $sUniquenessRuleId * * @return string dict key : Class:$sClassName/UniquenessRule:$sUniquenessRuleId if none then will use Core:UniquenessDefaultError @@ -2270,7 +2136,7 @@ abstract class DBObject implements iDisplay $oString = new TemplateString($sTemplate); - return $oString->Render(array('this' => $this)); + return $oString->Render(['this' => $this]); } /** @@ -2323,8 +2189,7 @@ abstract class DBObject implements iDisplay } return Dict::Format($sMessageKey, ...$aPlaceholdersData); - } - catch (Exception $e) { + } catch (Exception $e) { ExceptionLog::LogException($e); return null; @@ -2355,36 +2220,33 @@ abstract class DBObject implements iDisplay } /** - * @param array $aUniquenessRuleProperties uniqueness rule properties + * @param array $aUniquenessRuleProperties uniqueness rule properties * - * @param string $sUniquenessRuleId uniqueness rule ID + * @param string $sUniquenessRuleId uniqueness rule ID * @return \DBSearch * @throws \OQLException - * @throws \CoreException - * - * @internal - * - * @since 2.6.0 N°659 uniqueness constraint - * @since 2.7.11 3.1.2 3.2.0 N°4314 Fix Uniqueness rules not working with Silo + * @throws \CoreException + * + * @internal + * + * @since 2.6.0 N°659 uniqueness constraint + * @since 2.7.11 3.1.2 3.2.0 N°4314 Fix Uniqueness rules not working with Silo */ protected function GetSearchForUniquenessRule($sUniquenessRuleId, $aUniquenessRuleProperties) { $sRuleRootClass = $aUniquenessRuleProperties['root_class']; $sOqlUniquenessQuery = "SELECT $sRuleRootClass"; - if (!(empty($sUniquenessFilter = $aUniquenessRuleProperties['filter']))) - { + if (!(empty($sUniquenessFilter = $aUniquenessRuleProperties['filter']))) { $sOqlUniquenessQuery .= ' WHERE '.$sUniquenessFilter; } /** @var \DBObjectSearch $oUniquenessQuery */ $oUniquenessQuery = DBObjectSearch::FromOQL($sOqlUniquenessQuery); - if (!$this->IsNew()) - { + if (!$this->IsNew()) { $oUniquenessQuery->AddCondition('id', $this->GetKey(), '<>'); } - foreach ($aUniquenessRuleProperties['attributes'] as $sAttributeCode) - { + foreach ($aUniquenessRuleProperties['attributes'] as $sAttributeCode) { $attributeValue = $this->Get($sAttributeCode); $oUniquenessQuery->AddCondition($sAttributeCode, $attributeValue, '='); } @@ -2441,9 +2303,11 @@ abstract class DBObject implements iDisplay } if (!empty($aDuplicatesFields)) { - $this->m_aCheckWarnings[] = Dict::Format('Core:AttributeLinkedSetDuplicatesFound', + $this->m_aCheckWarnings[] = Dict::Format( + 'Core:AttributeLinkedSetDuplicatesFound', $oAttDef->GetLabel(), - implode(', ', $aDuplicatesFields)); + implode(', ', $aDuplicatesFields) + ); } } @@ -2456,8 +2320,8 @@ abstract class DBObject implements iDisplay * @overwritable-hook You can extend this method in order to provide your own logic. * @see CheckToWrite() * @see $m_aCheckIssues - * @see $m_aCheckWarnings - * + * @see $m_aCheckWarnings + * * @throws \ArchivedObjectException * @throws \CoreException * @throws \OQLException @@ -2468,7 +2332,7 @@ abstract class DBObject implements iDisplay $aChanges = $this->ListChanges(); - foreach($aChanges as $sAttCode => $value) { + foreach ($aChanges as $sAttCode => $value) { $res = $this->CheckValue($sAttCode); if ($res !== true) { $sAttLabel = $this->GetLabel($sAttCode); @@ -2478,31 +2342,25 @@ abstract class DBObject implements iDisplay $this->DoCheckLinkedSetDuplicates($sAttCode, $value); } - if (count($this->m_aCheckIssues) > 0) - { + if (count($this->m_aCheckIssues) > 0) { // No need to check consistency between attributes if any of them has // an unexpected value return; } $res = $this->CheckConsistency(); - if ($res !== true) - { + if ($res !== true) { // $res contains the error description $this->m_aCheckIssues[] = Dict::Format('Core:CheckConsistencyError', $res); } // Synchronization: are we attempting to modify an attribute for which an external source is master? // - if ($this->m_bIsInDB && $this->InSyncScope() && (count($aChanges) > 0)) - { - foreach($aChanges as $sAttCode => $value) - { + if ($this->m_bIsInDB && $this->InSyncScope() && (count($aChanges) > 0)) { + foreach ($aChanges as $sAttCode => $value) { $iFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons); - if ($iFlags & OPT_ATT_SLAVE) - { + if ($iFlags & OPT_ATT_SLAVE) { // Note: $aReasonInfo['name'] could be reported (the task owning the attribute) - if (!empty($aReasons)) - { + if (!empty($aReasons)) { $sAttLabel = $this->GetLabel($sAttCode); $this->m_aCheckIssues[] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $sAttLabel, $sAttCode); } @@ -2547,7 +2405,7 @@ abstract class DBObject implements iDisplay } } - final static protected function GetObjectIfNotInCRUDStack($sClass, $sKey) + final protected static function GetObjectIfNotInCRUDStack($sClass, $sKey) { if (DBObject::IsObjectCurrentlyInCrud($sClass, $sKey)) { return null; @@ -2581,7 +2439,7 @@ abstract class DBObject implements iDisplay if ($this->IsNew()) { $this->CheckToWriteForSingleTargetObject_Internal('add', $oTargetObject, $sAttCodeMirrorLink, false); - } else if ($bIsCheckToDelete) { + } elseif ($bIsCheckToDelete) { $this->CheckToWriteForSingleTargetObject_Internal('remove', $oTargetObject, $sAttCodeMirrorLink, true); } else { if (array_key_exists($sExtKeyWithMirrorLinkAttCode, $aChanges)) { @@ -2636,32 +2494,30 @@ abstract class DBObject implements iDisplay } /** - * @api - * @api-advanced - * + * @api + * @api-advanced + * * @return array containing : * * $m_bCheckStatus * * $m_aCheckIssues * * $m_bSecurityIssue * - * @see $m_bCheckStatus - * @see $m_aCheckIssues - * @see $m_bSecurityIssue - * + * @see $m_bCheckStatus + * @see $m_aCheckIssues + * @see $m_bSecurityIssue + * * @throws \ArchivedObjectException * @throws \CoreException * @throws \OQLException */ final public function CheckToWrite($bDoComputeValues = true) { - if (MetaModel::SkipCheckToWrite()) - { - return array(true, array()); + if (MetaModel::SkipCheckToWrite()) { + return [true, []]; } - if (is_null($this->m_bCheckStatus)) - { - $this->m_aCheckIssues = array(); + if (is_null($this->m_bCheckStatus)) { + $this->m_aCheckIssues = []; if ($bDoComputeValues) { $this->DoComputeValues(); @@ -2674,21 +2530,18 @@ abstract class DBObject implements iDisplay $oKPI = new ExecutionKPI(); $this->DoCheckToWrite(); - $oKPI->ComputeStatsForExtension($this, 'DoCheckToWrite'); + $oKPI->ComputeStatsForExtension($this, 'DoCheckToWrite'); $this->CheckToWriteForTargetObjects(); - if (count($this->m_aCheckIssues) == 0) - { + if (count($this->m_aCheckIssues) == 0) { $this->m_bCheckStatus = true; - } - else - { + } else { $this->m_bCheckStatus = false; } } - return array($this->m_bCheckStatus, $this->m_aCheckIssues, $this->m_bSecurityIssue); + return [$this->m_bCheckStatus, $this->m_aCheckIssues, $this->m_bSecurityIssue]; } /** @@ -2745,7 +2598,7 @@ abstract class DBObject implements iDisplay if (($oAttDef instanceof AttributeHierarchicalKey) || ($oAttDef instanceof AttributeExternalKey)) { $sRemoteObjectClass = $oAttDef->GetTargetClass(); $sRemoteObjectKey = $this->Get($sAttDefCode); - } else if ($oAttDef instanceof AttributeObjectKey) { + } elseif ($oAttDef instanceof AttributeObjectKey) { $sRemoteObjectClassAttCode = $oAttDef->Get('class_attcode'); $sRemoteObjectClass = $this->Get($sRemoteObjectClassAttCode); $sRemoteObjectKey = $this->Get($sAttDefCode); @@ -2761,7 +2614,7 @@ abstract class DBObject implements iDisplay // 0 : Undefined ext. key (EG. non-mandatory and no value provided) // < 0 : Non yet persisted object - /** @noinspection TypeUnsafeComparisonInspection Non-strict comparison as object ID can be string */ + /** @noinspection TypeUnsafeComparisonInspection Non-strict comparison as object ID can be string */ if ($sRemoteObjectKey <= 0) { continue; } @@ -2777,94 +2630,86 @@ abstract class DBObject implements iDisplay * * an array of displayable error is added in {@see DBObject::$m_aDeleteIssues} * - * @internal - * + * @internal + * * @param \DeletionPlan $oDeletionPlan * * @throws \CoreException */ protected function DoCheckToDelete(&$oDeletionPlan) { - if ($this->InSyncScope()) - { + if ($this->InSyncScope()) { - foreach ($this->GetSynchroData() as $iSourceId => $aSourceData) - { - foreach ($aSourceData['replica'] as $oReplica) - { + foreach ($this->GetSynchroData() as $iSourceId => $aSourceData) { + foreach ($aSourceData['replica'] as $oReplica) { $oDeletionPlan->AddToDelete($oReplica, DEL_SILENT); } /** @var \SynchroDataSource $oDataSource */ $oDataSource = $aSourceData['source']; - if ($oDataSource->GetKey() == SynchroExecution::GetCurrentTaskId()) - { + if ($oDataSource->GetKey() == SynchroExecution::GetCurrentTaskId()) { // The current task has the right to delete the object continue; } $oReplica = reset($aSourceData['replica']); // Take the first one - if ($oReplica->Get('status_dest_creator') != 1) - { + if ($oReplica->Get('status_dest_creator') != 1) { // The object is not owned by the task continue; } $sLink = $oDataSource->GetName(); $sUserDeletePolicy = $oDataSource->Get('user_delete_policy'); - switch($sUserDeletePolicy) - { - case 'nobody': - $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink); - break; - - case 'administrators': - if (!UserRights::IsAdministrator()) - { + switch ($sUserDeletePolicy) { + case 'nobody': $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink); - } - break; + break; - case 'everybody': - default: - // Ok - break; + case 'administrators': + if (!UserRights::IsAdministrator()) { + $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink); + } + break; + + case 'everybody': + default: + // Ok + break; } } } } - /** - * @internal - * - * @param \DeletionPlan $oDeletionPlan - * - * @return bool - * @throws CoreException - */ + /** + * @internal + * + * @param \DeletionPlan $oDeletionPlan + * + * @return bool + * @throws CoreException + */ public function CheckToDelete(&$oDeletionPlan) - { + { $this->AddCurrentObjectInCrudStack('DELETE'); try { $this->MakeDeletionPlan($oDeletionPlan); $oDeletionPlan->ComputeResults(); - } - finally { + } finally { $this->RemoveCurrentObjectInCrudStack(); } return (!$oDeletionPlan->FoundStopper()); } - /** - * @internal - * - * @param array $aProposal - * - * @return array - * @throws Exception - */ + /** + * @internal + * + * @param array $aProposal + * + * @return array + * @throws Exception + */ protected function ListChangedValues(array $aProposal) { - $aDelta = array(); + $aDelta = []; $sClass = get_class($this); if (MetaModel::HasLifecycle($sClass) && utils::IsNotNullOrEmptyString($this->sStimulusBeingApplied)) { $sStateAttCode = MetaModel::GetStateAttributeCode($sClass); @@ -2873,52 +2718,36 @@ abstract class DBObject implements iDisplay $aDelta[$sStateAttCode] = $this->m_aCurrValues[$sStateAttCode]; } } - foreach ($aProposal as $sAtt => $proposedValue) - { - if (!array_key_exists($sAtt, $this->m_aOrigValues)) - { + foreach ($aProposal as $sAtt => $proposedValue) { + if (!array_key_exists($sAtt, $this->m_aOrigValues)) { // The value was not set $aDelta[$sAtt] = $proposedValue; - } - elseif(!array_key_exists($sAtt, $this->m_aTouchedAtt) || (array_key_exists($sAtt, $this->m_aModifiedAtt) && $this->m_aModifiedAtt[$sAtt] == false)) - { + } elseif (!array_key_exists($sAtt, $this->m_aTouchedAtt) || (array_key_exists($sAtt, $this->m_aModifiedAtt) && $this->m_aModifiedAtt[$sAtt] == false)) { // This attCode was never set, cannot be modified // or the same value - as the original value - was set, and has been verified as equivalent to the original value continue; - } - else if (array_key_exists($sAtt, $this->m_aModifiedAtt) && $this->m_aModifiedAtt[$sAtt] == true) - { + } elseif (array_key_exists($sAtt, $this->m_aModifiedAtt) && $this->m_aModifiedAtt[$sAtt] == true) { // We already know that the value is really modified $aDelta[$sAtt] = $proposedValue; - } - elseif(is_object($proposedValue)) - { + } elseif (is_object($proposedValue)) { $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAtt); // The value is an object, the comparison is not strict - if (!$oAttDef->Equals($this->m_aOrigValues[$sAtt], $proposedValue)) - { + if (!$oAttDef->Equals($this->m_aOrigValues[$sAtt], $proposedValue)) { $aDelta[$sAtt] = $proposedValue; $this->m_aModifiedAtt[$sAtt] = true; // Really modified - } - else - { + } else { $this->m_aModifiedAtt[$sAtt] = false; // Not really modified } - } - else - { + } else { // The value is a scalar, the comparison must be 100% strict - if($this->m_aOrigValues[$sAtt] !== $proposedValue) - { + if ($this->m_aOrigValues[$sAtt] !== $proposedValue) { //echo "$sAtt:
\n";
 					//var_dump($this->m_aOrigValues[$sAtt]);
 					//var_dump($proposedValue);
 					//echo "
\n"; $aDelta[$sAtt] = $proposedValue; $this->m_aModifiedAtt[$sAtt] = true; // Really modified - } - else - { + } else { $this->m_aModifiedAtt[$sAtt] = false; // Not really modified } } @@ -2962,15 +2791,13 @@ abstract class DBObject implements iDisplay */ public function ListPreviousValuesForUpdatedAttributes() { - if (empty($this->m_aPreviousValuesForUpdatedAttributes)) - { - return array(); + if (empty($this->m_aPreviousValuesForUpdatedAttributes)) { + return []; } return $this->m_aPreviousValuesForUpdatedAttributes; } - /** * Whether an object was modified since last read from the DB or not * (ie: does it differ from the DB ?) @@ -2996,33 +2823,27 @@ abstract class DBObject implements iDisplay */ public function Equals($oSibling) { - if (get_class($oSibling) != get_class($this)) - { + if (get_class($oSibling) != get_class($this)) { return false; } - if ($this->GetKey() != $oSibling->GetKey()) - { + if ($this->GetKey() != $oSibling->GetKey()) { return false; } - if ($this->m_bIsInDB) - { + if ($this->m_bIsInDB) { // If one has changed, then consider them as being different - if ($this->IsModified() || $oSibling->IsModified()) - { + if ($this->IsModified() || $oSibling->IsModified()) { return false; } - } - else - { + } else { // Todo - implement this case (loop on every attribute) //foreach(MetaModel::ListAttributeDefs(get_class($this) as $sAttCode => $oAttDef) //{ - //if (!isset($this->m_CurrentValues[$sAttCode])) continue; - //if (!isset($this->m_CurrentValues[$sAttCode])) continue; - //if (!$oAttDef->Equals($this->m_CurrentValues[$sAttCode], $oSibling->m_CurrentValues[$sAttCode])) - //{ - //return false; - //} + //if (!isset($this->m_CurrentValues[$sAttCode])) continue; + //if (!isset($this->m_CurrentValues[$sAttCode])) continue; + //if (!$oAttDef->Equals($this->m_CurrentValues[$sAttCode], $oSibling->m_CurrentValues[$sAttCode])) + //{ + //return false; + //} //} return false; } @@ -3031,27 +2852,32 @@ abstract class DBObject implements iDisplay /** * Used only by insert, Meant to be overloaded - * - * @overwritable-hook You can extend this method in order to provide your own logic. + * + * @overwritable-hook You can extend this method in order to provide your own logic. */ protected function OnObjectKeyReady() - { - } + { + } /** * used both by insert/update * - * @internal - * + * @internal + * * @throws \CoreException */ private function DBWriteLinks() { - foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) - { - if (!$oAttDef->IsLinkSet()) continue; - if (!array_key_exists($sAttCode, $this->m_aTouchedAtt)) continue; - if (array_key_exists($sAttCode, $this->m_aModifiedAtt) && ($this->m_aModifiedAtt[$sAttCode] == false)) continue; + foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) { + if (!$oAttDef->IsLinkSet()) { + continue; + } + if (!array_key_exists($sAttCode, $this->m_aTouchedAtt)) { + continue; + } + if (array_key_exists($sAttCode, $this->m_aModifiedAtt) && ($this->m_aModifiedAtt[$sAttCode] == false)) { + continue; + } /** @var \ormLinkSet $oLinkSet */ $oLinkSet = $this->m_aCurrValues[$sAttCode]; @@ -3062,49 +2888,53 @@ abstract class DBObject implements iDisplay /** * Used both by insert/update * - * @internal - * + * @internal + * * @throws \CoreException */ private function WriteExternalAttributes() { - foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) - { - if (!$oAttDef->LoadInObject()) continue; - if (!array_key_exists($sAttCode, $this->m_aTouchedAtt)) continue; - if (array_key_exists($sAttCode, $this->m_aModifiedAtt) && ($this->m_aModifiedAtt[$sAttCode] === false)) continue; + foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) { + if (!$oAttDef->LoadInObject()) { + continue; + } + if (!array_key_exists($sAttCode, $this->m_aTouchedAtt)) { + continue; + } + if (array_key_exists($sAttCode, $this->m_aModifiedAtt) && ($this->m_aModifiedAtt[$sAttCode] === false)) { + continue; + } $oAttDef->WriteExternalValues($this); } } - - /** - * Note: this is experimental - it was designed to speed up the setup of iTop - * Known limitations: - * - does not work with multi-table classes (issue with the unique id to maintain in several tables) - * - the id of the object is not updated - * - * @internal - * @experimental - */ - static public final function BulkInsertStart() + /** + * Note: this is experimental - it was designed to speed up the setup of iTop + * Known limitations: + * - does not work with multi-table classes (issue with the unique id to maintain in several tables) + * - the id of the object is not updated + * + * @internal + * @experimental + */ + final public static function BulkInsertStart() { self::$m_bBulkInsert = true; } - /** - * - * @internal - * @experimental - */ - static public final function BulkInsertFlush() + /** + * + * @internal + * @experimental + */ + final public static function BulkInsertFlush() { - if (!self::$m_bBulkInsert) return; + if (!self::$m_bBulkInsert) { + return; + } - foreach(self::$m_aBulkInsertCols as $sClass => $aTables) - { - foreach ($aTables as $sTable => $sColumns) - { + foreach (self::$m_aBulkInsertCols as $sClass => $aTables) { + foreach ($aTables as $sTable => $sColumns) { $sValues = implode(', ', self::$m_aBulkInsertItems[$sClass][$sTable]); $sInsertSQL = "INSERT INTO `$sTable` ($sColumns) VALUES $sValues"; CMDBSource::InsertInto($sInsertSQL); @@ -3112,15 +2942,15 @@ abstract class DBObject implements iDisplay } // Reset - self::$m_aBulkInsertItems = array(); - self::$m_aBulkInsertCols = array(); + self::$m_aBulkInsertItems = []; + self::$m_aBulkInsertCols = []; self::$m_bBulkInsert = false; } /** * Persists new object in the DB - * - * @internal + * + * @internal * * @param string $sTableClass * @@ -3132,65 +2962,57 @@ abstract class DBObject implements iDisplay { $sTable = MetaModel::DBGetTable($sTableClass); // Abstract classes or classes having no specific attribute do not have an associated table - if ($sTable == '') { return false; } + if ($sTable == '') { + return false; + } $sClass = get_class($this); // fields in first array, values in the second - $aFieldsToWrite = array(); - $aValuesToWrite = array(); + $aFieldsToWrite = []; + $aValuesToWrite = []; - if (!empty($this->m_iKey) && ($this->m_iKey >= 0)) - { + if (!empty($this->m_iKey) && ($this->m_iKey >= 0)) { // Add it to the list of fields to write $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`'; $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey); } - $aHierarchicalKeys = array(); + $aHierarchicalKeys = []; - foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef) { + foreach (MetaModel::ListAttributeDefs($sTableClass) as $sAttCode => $oAttDef) { // Skip this attribute if not defined in this table if ((!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode) && !$oAttDef->CopyOnAllTables()) || $oAttDef->IsExternalField()) { continue; } $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]); - foreach($aAttColumns as $sColumn => $sValue) - { + foreach ($aAttColumns as $sColumn => $sValue) { $aFieldsToWrite[] = "`$sColumn`"; $aValuesToWrite[] = CMDBSource::Quote($sValue); } - if ($oAttDef->IsHierarchicalKey()) - { + if ($oAttDef->IsHierarchicalKey()) { $aHierarchicalKeys[$sAttCode] = $oAttDef; } } - if (count($aValuesToWrite) == 0) { return false; } - - if (MetaModel::DBIsReadOnly()) - { - $iNewKey = -1; + if (count($aValuesToWrite) == 0) { + return false; } - else - { - if (self::$m_bBulkInsert) - { - if (!isset(self::$m_aBulkInsertCols[$sClass][$sTable])) - { + + if (MetaModel::DBIsReadOnly()) { + $iNewKey = -1; + } else { + if (self::$m_bBulkInsert) { + if (!isset(self::$m_aBulkInsertCols[$sClass][$sTable])) { self::$m_aBulkInsertCols[$sClass][$sTable] = implode(', ', $aFieldsToWrite); } - self::$m_aBulkInsertItems[$sClass][$sTable][] = '('.implode (', ', $aValuesToWrite).')'; + self::$m_aBulkInsertItems[$sClass][$sTable][] = '('.implode(', ', $aValuesToWrite).')'; $iNewKey = 999999; // TODO - compute next id.... - } - else - { - if (count($aHierarchicalKeys) > 0) - { - foreach($aHierarchicalKeys as $sAttCode => $oAttDef) - { + } else { + if (count($aHierarchicalKeys) > 0) { + foreach ($aHierarchicalKeys as $sAttCode => $oAttDef) { $aValues = MetaModel::HKInsertChildUnder($this->m_aCurrValues[$sAttCode], $oAttDef, $sTable); $aFieldsToWrite[] = '`'.$oAttDef->GetSQLRight().'`'; $aValuesToWrite[] = $aValues[$oAttDef->GetSQLRight()]; @@ -3203,8 +3025,7 @@ abstract class DBObject implements iDisplay } } // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class - if (empty($this->m_iKey)) - { + if (empty($this->m_iKey)) { // Take the autonumber $this->m_iKey = "$iNewKey"; } @@ -3248,75 +3069,72 @@ abstract class DBObject implements iDisplay return $this->m_iKey; } - /** - * @internal - * - * @param array $aAuthorizedExtKeys - * @param array $aStatements - * @param string $sTableClass - * - * @throws CoreException - * @throws MySQLException - */ + /** + * @internal + * + * @param array $aAuthorizedExtKeys + * @param array $aStatements + * @param string $sTableClass + * + * @throws CoreException + * @throws MySQLException + */ protected function MakeInsertStatementSingleTable($aAuthorizedExtKeys, &$aStatements, $sTableClass) { $sTable = MetaModel::DBGetTable($sTableClass); // Abstract classes or classes having no specific attribute do not have an associated table - if ($sTable == '') return; + if ($sTable == '') { + return; + } // fields in first array, values in the second - $aFieldsToWrite = array(); - $aValuesToWrite = array(); + $aFieldsToWrite = []; + $aValuesToWrite = []; - if (!empty($this->m_iKey) && ($this->m_iKey >= 0)) - { + if (!empty($this->m_iKey) && ($this->m_iKey >= 0)) { // Add it to the list of fields to write $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`'; $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey); } - $aHierarchicalKeys = array(); - foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode => $oAttDef) - { + $aHierarchicalKeys = []; + foreach (MetaModel::ListAttributeDefs($sTableClass) as $sAttCode => $oAttDef) { // Skip this attribute if not defined in this table if ((!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) || $oAttDef->IsExternalField()) { continue; }; // Skip link set that can still be undefined though the object is 100% loaded - if ($oAttDef->IsLinkSet()) continue; + if ($oAttDef->IsLinkSet()) { + continue; + } $value = $this->m_aCurrValues[$sAttCode]; - if ($oAttDef->IsExternalKey()) - { + if ($oAttDef->IsExternalKey()) { /** @var \AttributeExternalKey $oAttDef */ $sTargetClass = $oAttDef->GetTargetClass(); - if (is_array($aAuthorizedExtKeys)) - { - if (!array_key_exists($sTargetClass, $aAuthorizedExtKeys) || !array_key_exists($value, $aAuthorizedExtKeys[$sTargetClass])) - { + if (is_array($aAuthorizedExtKeys)) { + if (!array_key_exists($sTargetClass, $aAuthorizedExtKeys) || !array_key_exists($value, $aAuthorizedExtKeys[$sTargetClass])) { $value = 0; } } } $aAttColumns = $oAttDef->GetSQLValues($value); - foreach($aAttColumns as $sColumn => $sValue) - { + foreach ($aAttColumns as $sColumn => $sValue) { $aFieldsToWrite[] = "`$sColumn`"; $aValuesToWrite[] = CMDBSource::Quote($sValue); } - if ($oAttDef->IsHierarchicalKey()) - { + if ($oAttDef->IsHierarchicalKey()) { $aHierarchicalKeys[$sAttCode] = $oAttDef; } } - if (count($aValuesToWrite) == 0) return; + if (count($aValuesToWrite) == 0) { + return; + } - if (count($aHierarchicalKeys) > 0) - { - foreach($aHierarchicalKeys as $sAttCode => $oAttDef) - { + if (count($aHierarchicalKeys) > 0) { + foreach ($aHierarchicalKeys as $sAttCode => $oAttDef) { $aValues = MetaModel::HKInsertChildUnder($this->m_aCurrValues[$sAttCode], $oAttDef, $sTable); $aFieldsToWrite[] = '`'.$oAttDef->GetSQLRight().'`'; $aValuesToWrite[] = $aValues[$oAttDef->GetSQLRight()]; @@ -3327,15 +3145,15 @@ abstract class DBObject implements iDisplay $aStatements[] = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).");"; } - /** - * @internal - * - * @param array $aAuthorizedExtKeys - * @param array $aStatements - * - * @throws CoreException - * @throws MySQLException - */ + /** + * @internal + * + * @param array $aAuthorizedExtKeys + * @param array $aStatements + * + * @throws CoreException + * @throws MySQLException + */ public function MakeInsertStatements($aAuthorizedExtKeys, &$aStatements) { $sClass = get_class($this); @@ -3345,15 +3163,15 @@ abstract class DBObject implements iDisplay $this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sRootClass); // Then do the leaf class, if different from the root class - if ($sClass != $sRootClass) - { + if ($sClass != $sRootClass) { $this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sClass); } // Then do the other classes - foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass) - { - if ($sParentClass == $sRootClass) continue; + foreach (MetaModel::EnumParentClasses($sClass) as $sParentClass) { + if ($sParentClass == $sRootClass) { + continue; + } $this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sParentClass); } } @@ -3361,11 +3179,11 @@ abstract class DBObject implements iDisplay /** * Persist an object to the DB, for the first time * - * @api - * @see DBWrite - * + * @api + * @see DBWrite + * * @return string|null inserted object key - * + * * @throws \ArchivedObjectException * @throws \CoreCannotSaveObjectException * @throws \CoreException @@ -3411,13 +3229,13 @@ abstract class DBObject implements iDisplay // If not automatically computed, then check that the key is given by the caller if (!MetaModel::IsAutoIncrementKey($sRootClass)) { if (empty($this->m_iKey)) { - throw new CoreWarning('Missing key for the object to write - This class is supposed to have a user defined key, not an autonumber', array('class' => $sRootClass)); + throw new CoreWarning('Missing key for the object to write - This class is supposed to have a user defined key, not an autonumber', ['class' => $sRootClass]); } } [$bRes, $aIssues] = $this->CheckToWrite(false); if (!$bRes) { - throw new CoreCannotSaveObjectException(array('issues' => $aIssues, 'class' => get_class($this), 'id' => $this->GetKey())); + throw new CoreCannotSaveObjectException(['issues' => $aIssues, 'class' => get_class($this), 'id' => $this->GetKey()]); } if ($this->m_iKey < 0) { @@ -3479,8 +3297,7 @@ abstract class DBObject implements iDisplay CMDBSource::Query('COMMIT'); } break; - } - catch (Exception $e) { + } catch (Exception $e) { IssueLog::Error($e->getMessage()); if ($bIsTransactionEnabled) { CMDBSource::Query('ROLLBACK'); @@ -3515,16 +3332,14 @@ abstract class DBObject implements iDisplay try { $this->PostInsertActions(); - } - finally { + } finally { MetaModel::StopReentranceProtection($this); } if ((count($this->ListChanges()) !== 0)) { $this->DBUpdate(); } - } - finally { + } finally { $this->RemoveCurrentObjectInCrudStack(); } @@ -3548,14 +3363,13 @@ abstract class DBObject implements iDisplay // Activate any existing trigger $sClass = get_class($this); - $aParams = array('class_list' => MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL)); - $oSet = new DBObjectSet(DBObjectSearch::FromOQL('SELECT TriggerOnObjectCreate AS t WHERE t.target_class IN (:class_list)'), array(), $aParams); + $aParams = ['class_list' => MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL)]; + $oSet = new DBObjectSet(DBObjectSearch::FromOQL('SELECT TriggerOnObjectCreate AS t WHERE t.target_class IN (:class_list)'), [], $aParams); while ($oTrigger = $oSet->Fetch()) { /** @var \TriggerOnObjectCreate $oTrigger */ try { $oTrigger->DoActivate($this->ToArgs('this')); - } - catch (Exception $e) { + } catch (Exception $e) { $oTrigger->LogException($e, $this); utils::EnrichRaisedException($oTrigger, $e); } @@ -3568,23 +3382,23 @@ abstract class DBObject implements iDisplay $this->ActivateOnObjectUpdateTriggersForTargetObjects(); } - /** - * Creates a copy of the current object into the database - * - * @internal - * - * @param null $iNewKey - * - * @return int|null the id of the newly created object - * - * @throws ArchivedObjectException - * @throws CoreCannotSaveObjectException - * @throws CoreException - * @throws CoreUnexpectedValue - * @throws CoreWarning - * @throws MySQLException - * @throws OQLException - */ + /** + * Creates a copy of the current object into the database + * + * @internal + * + * @param null $iNewKey + * + * @return int|null the id of the newly created object + * + * @throws ArchivedObjectException + * @throws CoreCannotSaveObjectException + * @throws CoreException + * @throws CoreUnexpectedValue + * @throws CoreWarning + * @throws MySQLException + * @throws OQLException + */ public function DBClone($iNewKey = null) { $this->m_bIsInDB = false; @@ -3629,8 +3443,7 @@ abstract class DBObject implements iDisplay return false; } - if (!$this->m_bIsInDB) - { + if (!$this->m_bIsInDB) { throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead"); } $sClass = get_class($this); @@ -3641,7 +3454,6 @@ abstract class DBObject implements iDisplay // Protect against infinite loop $this->iUpdateLoopCount++; - try { $this->DoComputeValues(); $this->ComputeStopWatchesDeadline(false); @@ -3672,8 +3484,8 @@ abstract class DBObject implements iDisplay // Activate any existing trigger $sClass = get_class($this); - $aHierarchicalKeys = array(); - $aDBChanges = array(); + $aHierarchicalKeys = []; + $aDBChanges = []; foreach ($aChanges as $sAttCode => $currentValue) { $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode); if ($oAttDef->IsBasedOnDBColumns()) { @@ -3748,7 +3560,7 @@ abstract class DBObject implements iDisplay $this->DBWriteLinks(); $this->WriteExternalAttributes(); - $this->HandleTemporaryDescriptor(); + $this->HandleTemporaryDescriptor(); if (count($aChanges) != 0) { $this->RecordAttChanges($aChanges, $aOriginalValues); @@ -3758,8 +3570,7 @@ abstract class DBObject implements iDisplay CMDBSource::Query('COMMIT'); } break; - } - catch (MySQLException $e) { + } catch (MySQLException $e) { IssueLog::Error($e->getMessage()); if ($bIsTransactionEnabled) { CMDBSource::Query('ROLLBACK'); @@ -3775,17 +3586,15 @@ abstract class DBObject implements iDisplay } } } - $aErrors = array($e->getMessage()); + $aErrors = [$e->getMessage()]; throw new CoreCannotSaveObjectException(['id' => $this->GetKey(), 'class' => $sClass, 'issues' => $aErrors], $e); - } - catch (CoreCannotSaveObjectException $e) { + } catch (CoreCannotSaveObjectException $e) { IssueLog::Error($e->getMessage()); if ($bIsTransactionEnabled) { CMDBSource::Query('ROLLBACK'); } throw $e; - } - catch (Exception $e) { + } catch (Exception $e) { IssueLog::Error($e->getMessage()); if ($bIsTransactionEnabled) { CMDBSource::Query('ROLLBACK'); @@ -3799,8 +3608,8 @@ abstract class DBObject implements iDisplay // new values are already in the object (call {@see DBObject::Get()} to get them) // call {@see DBObject::ListPreviousValuesForUpdatedAttributes()} to get changed fields and previous values $this->m_bDirty = false; - $this->m_aTouchedAtt = array(); - $this->m_aModifiedAtt = array(); + $this->m_aTouchedAtt = []; + $this->m_aModifiedAtt = []; // Reset original values although the object has not been reloaded foreach ($this->m_aLoadedAtt as $sAttCode => $bLoaded) { if ($bLoaded) { @@ -3818,14 +3627,12 @@ abstract class DBObject implements iDisplay try { $this->PostUpdateActions($this->m_aPreviousValuesForUpdatedAttributes, $sClass); - } - catch (Exception $e) { + } catch (Exception $e) { $this->LogCRUDExit(__METHOD__, 'Error: '.$e->getMessage()); $aErrors = [$e->getMessage()]; throw new CoreException($e->getMessage(), ['id' => $this->GetKey(), 'class' => $sClass, 'issues' => $aErrors]); } - } - finally { + } finally { MetaModel::StopReentranceProtection($this); } @@ -3837,8 +3644,7 @@ abstract class DBObject implements iDisplay } $this->DBUpdate(); } - } - finally { + } finally { $this->RemoveCurrentObjectInCrudStack(); $this->iUpdateLoopCount--; } @@ -3874,35 +3680,32 @@ abstract class DBObject implements iDisplay $this->ActivateOnObjectUpdateTriggersForTargetObjects(); $sClass = get_class($this); - if (utils::IsNotNullOrEmptyString($sStimulusBeingApplied)) - { + if (utils::IsNotNullOrEmptyString($sStimulusBeingApplied)) { $sStateAttCode = MetaModel::GetStateAttributeCode($sClass); $sPreviousState = $this->m_aPreviousValuesForUpdatedAttributes[$sStateAttCode]; // Change state triggers... - $aParams = array( + $aParams = [ 'class_list' => MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL), 'previous_state' => $sPreviousState, 'new_state' => $this->Get($sStateAttCode), - ); - $oSet = new DBObjectSet(DBObjectSearch::FromOQL('SELECT TriggerOnStateLeave AS t WHERE t.target_class IN (:class_list) AND t.state=:previous_state'), array(), $aParams); + ]; + $oSet = new DBObjectSet(DBObjectSearch::FromOQL('SELECT TriggerOnStateLeave AS t WHERE t.target_class IN (:class_list) AND t.state=:previous_state'), [], $aParams); while ($oTrigger = $oSet->Fetch()) { /** @var \TriggerOnStateLeave $oTrigger */ try { $oTrigger->DoActivate($this->ToArgs('this')); - } - catch (Exception $e) { + } catch (Exception $e) { $oTrigger->LogException($e, $this); utils::EnrichRaisedException($oTrigger, $e); } } - $oSet = new DBObjectSet(DBObjectSearch::FromOQL('SELECT TriggerOnStateEnter AS t WHERE t.target_class IN (:class_list) AND t.state=:new_state'), array(), $aParams); + $oSet = new DBObjectSet(DBObjectSearch::FromOQL('SELECT TriggerOnStateEnter AS t WHERE t.target_class IN (:class_list) AND t.state=:new_state'), [], $aParams); while ($oTrigger = $oSet->Fetch()) { /** @var \TriggerOnStateEnter $oTrigger */ try { $oTrigger->DoActivate($this->ToArgs('this')); - } - catch (Exception $e) { + } catch (Exception $e) { $oTrigger->LogException($e, $this); utils::EnrichRaisedException($oTrigger, $e); } @@ -3932,15 +3735,17 @@ abstract class DBObject implements iDisplay // - TriggerOnObjectUpdate $aClassList = MetaModel::EnumParentClasses(get_class($oObject), ENUM_PARENT_CLASSES_ALL); - $aParams = array('class_list' => $aClassList); - $oSet = new DBObjectSet(DBObjectSearch::FromOQL('SELECT TriggerOnObjectUpdate AS t WHERE t.target_class IN (:class_list)'), - array(), $aParams); + $aParams = ['class_list' => $aClassList]; + $oSet = new DBObjectSet( + DBObjectSearch::FromOQL('SELECT TriggerOnObjectUpdate AS t WHERE t.target_class IN (:class_list)'), + [], + $aParams + ); while ($oTrigger = $oSet->Fetch()) { /** @var \TriggerOnObjectUpdate $oTrigger */ try { $oTrigger->DoActivateForSpecificAttributes($oObject->ToArgs(), $aAttributes); - } - catch (Exception $e) { + } catch (Exception $e) { $oTrigger->LogException($e, $oObject); utils::EnrichRaisedException($oTrigger, $e); } @@ -3969,13 +3774,13 @@ abstract class DBObject implements iDisplay $sClass = get_class($this); // dirty object not allowed - if($this->m_bDirty){ + if ($this->m_bDirty) { throw new CoreException("Invalid DBIncrement usage, dirty objects are not allowed. Call DBUpdate before calling DBIncrement."); } // ensure attribute type is AttributeInteger $oAttr = MetaModel::GetAttributeDef($sClass, $sAttCode); - if(!$oAttr instanceof AttributeInteger){ + if (!$oAttr instanceof AttributeInteger) { throw new CoreException(sprintf("Invalid DBIncrement usage, attribute type of {$sAttCode} is %s. Only AttributeInteger are compatibles with DBIncrement.", get_class($oAttr))); } @@ -4045,8 +3850,7 @@ abstract class DBObject implements iDisplay $aParams = ['class_list' => MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL)]; $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnObjectMention AS t WHERE t.target_class IN (:class_list)"), [], $aParams); - while ($oTrigger = $oSet->Fetch()) - { + while ($oTrigger = $oSet->Fetch()) { /** @var \TriggerOnObjectMention $oTrigger */ try { // Ensure to handle only mentioned object in the trigger's scope @@ -4055,8 +3859,7 @@ abstract class DBObject implements iDisplay } $oTrigger->DoActivate($aTriggerArgs); - } - catch (Exception $e) { + } catch (Exception $e) { utils::EnrichRaisedException($oTrigger, $e); } } @@ -4075,12 +3878,11 @@ abstract class DBObject implements iDisplay * @since 3.1.0 N°6299 - change visibility * @throws \Exception */ - protected final function InitPreviousValuesForUpdatedAttributes() + final protected function InitPreviousValuesForUpdatedAttributes() { - $aChanges= $this->ListChanges(); - if (empty($aChanges)) - { - $this->m_aPreviousValuesForUpdatedAttributes = array(); + $aChanges = $this->ListChanges(); + if (empty($aChanges)) { + $this->m_aPreviousValuesForUpdatedAttributes = []; return; } @@ -4106,29 +3908,28 @@ abstract class DBObject implements iDisplay */ public function DBWrite() { - if ($this->m_bIsInDB) - { + if ($this->m_bIsInDB) { return $this->DBUpdate(); - } - else - { + } else { return $this->DBInsert(); } } - /** - * @internal - * - * @param string $sTableClass - * - * @throws CoreException - * @throws MySQLException - */ + /** + * @internal + * + * @param string $sTableClass + * + * @throws CoreException + * @throws MySQLException + */ private function DBDeleteSingleTable($sTableClass) { $sTable = MetaModel::DBGetTable($sTableClass); // Abstract classes or classes having no specific attribute do not have an associated table - if ($sTable == '') return; + if ($sTable == '') { + return; + } $sPKField = '`'.MetaModel::DBGetKey($sTableClass).'`'; $sKey = CMDBSource::Quote($this->m_iKey); @@ -4152,8 +3953,7 @@ abstract class DBObject implements iDisplay { $this->LogCRUDEnter(__METHOD__); - if (MetaModel::DBIsReadOnly()) - { + if (MetaModel::DBIsReadOnly()) { $this->LogCRUDExit(__METHOD__, 'DB is read-only'); return; } @@ -4162,10 +3962,8 @@ abstract class DBObject implements iDisplay $this->RecordObjDeletion($this->m_iKey); // May cause a reload for storing history information - foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) - { - if ($oAttDef->IsHierarchicalKey()) - { + foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) { + if ($oAttDef->IsHierarchicalKey()) { // Update the left & right indexes for each hierarchical key $sTable = $sTable = MetaModel::DBGetTable(get_class($this), $sAttCode); /** @var \AttributeHierarchicalKey $oAttDef */ @@ -4179,12 +3977,9 @@ abstract class DBObject implements iDisplay // No new parent for now, insert completely at the right of the tree $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`"; $aRes = CMDBSource::QueryToArray($sSQL); - if (count($aRes) == 0) - { + if (count($aRes) == 0) { $iNewLeft = 1; - } - else - { + } else { $iNewLeft = $aRes[0]['max'] + 1; } MetaModel::HKReplugBranch($iNewLeft, $iNewLeft + $iDelta - 1, $oAttDef, $sTable); @@ -4193,51 +3988,38 @@ abstract class DBObject implements iDisplay } $iTransactionRetry = 1; $bIsTransactionEnabled = MetaModel::GetConfig()->Get('db_core_transactions_enabled'); - if ($bIsTransactionEnabled) - { + if ($bIsTransactionEnabled) { // TODO Deep clone this object before the transaction (to use it in case of rollback) // $iTransactionRetryCount = MetaModel::GetConfig()->Get('db_core_transactions_retry_count'); $iTransactionRetryCount = 1; $iTransactionRetryDelay = MetaModel::GetConfig()->Get('db_core_transactions_retry_delay_ms'); $iTransactionRetry = $iTransactionRetryCount; } - while ($iTransactionRetry > 0) - { - try - { + while ($iTransactionRetry > 0) { + try { $iTransactionRetry--; - if ($bIsTransactionEnabled) - { + if ($bIsTransactionEnabled) { CMDBSource::Query('START TRANSACTION'); } - foreach (MetaModel::EnumParentClasses(get_class($this), ENUM_PARENT_CLASSES_ALL) as $sParentClass) - { + foreach (MetaModel::EnumParentClasses(get_class($this), ENUM_PARENT_CLASSES_ALL) as $sParentClass) { $this->DBDeleteSingleTable($sParentClass); } - if ($bIsTransactionEnabled) - { + if ($bIsTransactionEnabled) { CMDBSource::Query('COMMIT'); } break; - } - catch (MySQLException $e) - { + } catch (MySQLException $e) { IssueLog::Error($e->getMessage()); - if ($bIsTransactionEnabled) - { + if ($bIsTransactionEnabled) { CMDBSource::Query('ROLLBACK'); - if (!CMDBSource::IsInsideTransaction() && CMDBSource::IsDeadlockException($e)) - { + if (!CMDBSource::IsInsideTransaction() && CMDBSource::IsDeadlockException($e)) { // Deadlock found when trying to get lock; try restarting transaction - if ($iTransactionRetry > 0) - { + if ($iTransactionRetry > 0) { // wait and retry IssueLog::Error("Delete TRANSACTION Retrying..."); usleep(random_int(1, 5) * 1000 * $iTransactionRetryDelay * ($iTransactionRetryCount - $iTransactionRetry)); continue; - } - else - { + } else { IssueLog::Error("Delete Deadlock TRANSACTION prevention failed."); } } @@ -4260,28 +4042,28 @@ abstract class DBObject implements iDisplay // Thought the key is not reset, using DBInsert or DBWrite will create an object having the same characteristics and a new ID. DBUpdate is protected } - /** - * Delete an object - * - * First, checks if the object can be deleted regarding database integrity. - * If the answer is yes, it performs any required cleanup (delete other objects or reset external keys) in addition to the object - * deletion. - * - * @api - * - * @param \DeletionPlan $oDeletionPlan Do not use: aims at dealing with recursion - * - * @return DeletionPlan The detailed description of cleanup operation that have been performed - * - * @throws ArchivedObjectException - * @throws CoreCannotSaveObjectException - * @throws CoreException - * @throws CoreUnexpectedValue - * @throws DeleteException - * @throws MySQLException - * @throws MySQLHasGoneAwayException - * @throws OQLException - */ + /** + * Delete an object + * + * First, checks if the object can be deleted regarding database integrity. + * If the answer is yes, it performs any required cleanup (delete other objects or reset external keys) in addition to the object + * deletion. + * + * @api + * + * @param \DeletionPlan $oDeletionPlan Do not use: aims at dealing with recursion + * + * @return DeletionPlan The detailed description of cleanup operation that have been performed + * + * @throws ArchivedObjectException + * @throws CoreCannotSaveObjectException + * @throws CoreException + * @throws CoreUnexpectedValue + * @throws DeleteException + * @throws MySQLException + * @throws MySQLHasGoneAwayException + * @throws OQLException + */ public function DBDelete(&$oDeletionPlan = null) { $this->LogCRUDEnter(__METHOD__); @@ -4297,10 +4079,9 @@ abstract class DBObject implements iDisplay if (false === $this->CheckToDelete($oDeletionPlan)) { $aIssues = $oDeletionPlan->GetIssues(); $this->LogCRUDError(__METHOD__, ' Errors: '.implode(', ', $aIssues)); - throw new DeleteException('Found issue(s)', array('target_class' => get_class($this), 'target_id' => $this->GetKey(), 'issues' => implode(', ', $aIssues))); + throw new DeleteException('Found issue(s)', ['target_class' => get_class($this), 'target_id' => $this->GetKey(), 'issues' => implode(', ', $aIssues)]); } - // Getting and setting time limit are not symmetric: // www.php.net/manual/fr/function.set-time-limit.php#72305 $iPreviousTimeLimit = ini_get('max_execution_time'); @@ -4320,8 +4101,7 @@ abstract class DBObject implements iDisplay $oToDelete->AddCurrentObjectInCrudStack('DELETE'); try { $oToDelete->DBDeleteSingleObject(); - } - finally { + } finally { $oToDelete->RemoveCurrentObjectInCrudStack(); } } @@ -4348,14 +4128,14 @@ abstract class DBObject implements iDisplay return $oDeletionPlan; } - /** - * @overwritable-hook You can extend this method in order to provide your own logic. - * - * @return array - * - * @throws ArchivedObjectException - * @throws CoreException - */ + /** + * @overwritable-hook You can extend this method in order to provide your own logic. + * + * @return array + * + * @throws ArchivedObjectException + * @throws CoreException + */ public function EnumTransitions() { $sClass = get_class($this); @@ -4383,7 +4163,7 @@ abstract class DBObject implements iDisplay $aStimuli = MetaModel::EnumStimuli($sClass); // Sort $aSortedTransitions based on labels from $aStimuli - uksort($aSortedTransitions, function($sKey1, $sKey2) use ($aStimuli) { + uksort($aSortedTransitions, function ($sKey1, $sKey2) use ($aStimuli) { // If any transition is not in $aStimuli, put it at the end even though it's a weird situation if ((false === isset($aStimuli[$sKey1])) || (false === isset($aStimuli[$sKey2]))) { return 1; @@ -4403,7 +4183,7 @@ abstract class DBObject implements iDisplay $aStatesSortFromDatamodel = array_keys($aAllowedValues); // Sort $aSortedTransitions based on the states sort from the datamodel - uksort($aSortedTransitions, function($sKey1, $sKey2) use ($aSortedTransitions, $aStatesSortFromDatamodel) { + uksort($aSortedTransitions, function ($sKey1, $sKey2) use ($aSortedTransitions, $aStatesSortFromDatamodel) { $sTargetState1 = $aSortedTransitions[$sKey1]['target_state']; $sTargetState2 = $aSortedTransitions[$sKey2]['target_state']; @@ -4461,25 +4241,24 @@ abstract class DBObject implements iDisplay } } - /** - * Helper to reset a stop-watch - * Suitable for use as a lifecycle action - * - * @api - * - * @param string $sAttCode - * - * @return bool - * - * @throws ArchivedObjectException - * @throws CoreException - * @throws CoreUnexpectedValue - */ + /** + * Helper to reset a stop-watch + * Suitable for use as a lifecycle action + * + * @api + * + * @param string $sAttCode + * + * @return bool + * + * @throws ArchivedObjectException + * @throws CoreException + * @throws CoreUnexpectedValue + */ public function ResetStopWatch($sAttCode) { $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode); - if (!$oAttDef instanceof AttributeStopWatch) - { + if (!$oAttDef instanceof AttributeStopWatch) { throw new CoreException("Invalid stop watch id: '$sAttCode'"); } $oSW = $this->Get($sAttCode); @@ -4512,8 +4291,7 @@ abstract class DBObject implements iDisplay $this->LogCRUDEnter(__METHOD__, "Code: $sStimulusCode"); $sClass = get_class($this); - if (!MetaModel::HasLifecycle($sClass)) - { + if (!MetaModel::HasLifecycle($sClass)) { throw new CoreException('No lifecycle for the class '.$sClass); } @@ -4521,15 +4299,14 @@ abstract class DBObject implements iDisplay $sStateAttCode = MetaModel::GetStateAttributeCode($sClass); $aStateTransitions = $this->EnumTransitions(); - if (!array_key_exists($sStimulusCode, $aStateTransitions)) - { + if (!array_key_exists($sStimulusCode, $aStateTransitions)) { // This stimulus has no effect in the current state... do nothing IssueLog::Error("$sClass: Transition $sStimulusCode is not allowed in ".$this->Get($sStateAttCode)); return false; } // save current object values in case of an action failure (in memory rollback) - $aBackupValues = array(); - foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) { + $aBackupValues = []; + foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) { if (isset($this->m_aCurrValues[$sAttCode])) { $value = $this->m_aCurrValues[$sAttCode]; if (is_object($value)) { @@ -4560,19 +4337,18 @@ abstract class DBObject implements iDisplay foreach ($aTransitionDef['actions'] as $actionHandler) { if (is_string($actionHandler)) { // Old (pre-2.1.0 modules) action definition without any parameter - $aActionCallSpec = array($this, $actionHandler); + $aActionCallSpec = [$this, $actionHandler]; $sActionDesc = $sClass.'::'.$actionHandler; if (!is_callable($aActionCallSpec)) { throw new CoreException("Unable to call action: $sClass::$actionHandler"); } $bRet = call_user_func($aActionCallSpec, $sStimulusCode); - } else // if (is_array($actionHandler)) - { + } else { // if (is_array($actionHandler)) // New syntax: 'verb' and typed parameters $sAction = $actionHandler['verb']; $sActionDesc = "$sClass::$sAction"; - $aParams = array(); + $aParams = []; foreach ($actionHandler['params'] as $aDefinition) { $sParamType = array_key_exists('type', $aDefinition) ? $aDefinition['type'] : 'string'; switch ($sParamType) { @@ -4598,7 +4374,7 @@ abstract class DBObject implements iDisplay } $aParams[] = $value; } - $aCallSpec = array($this, $sAction); + $aCallSpec = [$this, $sAction]; $bRet = call_user_func_array($aCallSpec, $aParams); } // if one call fails, the whole is considered as failed @@ -4615,17 +4391,13 @@ abstract class DBObject implements iDisplay } $this->RemoveCurrentObjectInCrudStack(); } - if ($bSuccess) - { + if ($bSuccess) { $this->sStimulusBeingApplied = $sStimulusCode; // Stop watches - foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) - { - if ($oAttDef instanceof AttributeStopWatch) - { + foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) { + if ($oAttDef instanceof AttributeStopWatch) { $oSW = $this->Get($sAttCode); - if (in_array($sNewState, $oAttDef->GetStates())) - { + if (in_array($sNewState, $oAttDef->GetStates())) { $oSW->Start($this, $oAttDef); } else { $oSW->Stop($this, $oAttDef); @@ -4637,12 +4409,9 @@ abstract class DBObject implements iDisplay if (!$bDoNotWrite) { $this->DBWrite(); } - } - else - { + } else { // At least one action failed, rollback the object value to its previous value - foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) - { + foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) { $this->m_aCurrValues[$sAttCode] = $aBackupValues[$sAttCode]; } } @@ -4666,10 +4435,10 @@ abstract class DBObject implements iDisplay /** * Helper to recover the default value (aka when an object is being created) - * Suitable for use as a lifecycle action - * - * @api - * + * Suitable for use as a lifecycle action + * + * @api + * */ public function Reset($sAttCode) { @@ -4678,35 +4447,26 @@ abstract class DBObject implements iDisplay } /** - * Helper to copy the value of an attribute to another one - * Suitable for use as a lifecycle action - * - * @api + * Helper to copy the value of an attribute to another one + * Suitable for use as a lifecycle action + * + * @api */ public function Copy($sDestAttCode, $sSourceAttCode) { $oTypeValueToCopy = MetaModel::GetAttributeDef(get_class($this), $sSourceAttCode); $oTypeValueDest = MetaModel::GetAttributeDef(get_class($this), $sDestAttCode); - if ($oTypeValueToCopy instanceof AttributeText && $oTypeValueDest instanceof AttributeText) - { - if ($oTypeValueToCopy->GetFormat() == $oTypeValueDest->GetFormat()) - { + if ($oTypeValueToCopy instanceof AttributeText && $oTypeValueDest instanceof AttributeText) { + if ($oTypeValueToCopy->GetFormat() == $oTypeValueDest->GetFormat()) { $sValueToCopy = $this->Get($sSourceAttCode); - } - else - { - if ($oTypeValueToCopy->GetFormat() == 'text')// and $oTypeValueDest->GetFormat()=='HTML' - { + } else { + if ($oTypeValueToCopy->GetFormat() == 'text') {// and $oTypeValueDest->GetFormat()=='HTML' $sValueToCopy = $this->GetAsHTML($sSourceAttCode); - } - else - {// $oTypeValueToCopy->GetFormat() == 'HTML' and $oTypeValueDest->GetFormat()=='Text' + } else {// $oTypeValueToCopy->GetFormat() == 'HTML' and $oTypeValueDest->GetFormat()=='Text' $sValueToCopy = utils::HtmlToText($this->Get($sSourceAttCode)); } } - } - else - { + } else { $sValueToCopy = $this->Get($sSourceAttCode); } $this->Set($sDestAttCode, $sValueToCopy); @@ -4714,19 +4474,19 @@ abstract class DBObject implements iDisplay return true; } - /** - * Helper to set the current date/time for the given attribute - * Suitable for use as a lifecycle action - * - * @api - * - * @param string $sAttCode - * - * @return bool - * - * @throws CoreException - * @throws CoreUnexpectedValue - */ + /** + * Helper to set the current date/time for the given attribute + * Suitable for use as a lifecycle action + * + * @api + * + * @param string $sAttCode + * + * @return bool + * + * @throws CoreException + * @throws CoreUnexpectedValue + */ public function SetCurrentDate($sAttCode) { $this->Set($sAttCode, time()); @@ -4832,7 +4592,6 @@ abstract class DBObject implements iDisplay } } - /** * Helper to set the current logged in user for the given attribute * Suitable for use as a lifecycle action @@ -4864,42 +4623,34 @@ abstract class DBObject implements iDisplay return true; } - /** - * Helper to set the current logged in CONTACT for the given attribute - * Suitable for use as a lifecycle action - * - * @api - * - * @param string $sAttCode - * - * @return bool - * @throws ArchivedObjectException - * @throws CoreException - * @throws CoreUnexpectedValue - */ + /** + * Helper to set the current logged in CONTACT for the given attribute + * Suitable for use as a lifecycle action + * + * @api + * + * @param string $sAttCode + * + * @return bool + * @throws ArchivedObjectException + * @throws CoreException + * @throws CoreUnexpectedValue + */ public function SetCurrentPerson($sAttCode) { $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode); - if ($oAttDef instanceof AttributeString) - { + if ($oAttDef instanceof AttributeString) { $iPerson = UserRights::GetContactId(); - if ($iPerson == 0) - { + if ($iPerson == 0) { $this->Set($sAttCode, ''); - } - else - { + } else { $oPerson = MetaModel::GetObject('Person', $iPerson); $this->Set($sAttCode, $oPerson->Get('friendlyname')); } - } - else - { - if ($oAttDef->IsExternalKey()) - { + } else { + if ($oAttDef->IsExternalKey()) { /** @var \AttributeExternalKey $oAttDef */ - if (!MetaModel::IsParentClass($oAttDef->GetTargetClass(), 'Person')) - { + if (!MetaModel::IsParentClass($oAttDef->GetTargetClass(), 'Person')) { throw new Exception("SetCurrentContact: the attribute $sAttCode must be an external key to 'Person' or any other class above 'Person', found '".$oAttDef->GetTargetClass()."'"); } } @@ -4908,31 +4659,29 @@ abstract class DBObject implements iDisplay return true; } - /** - * Helper to set the time elapsed since a reference point - * Suitable for use as a lifecycle action - * - * @api - * - * @param string $sAttCode - * @param string $sRefAttCode - * @param string|null $sWorkingTimeComputer - * - * @return bool - * @throws ArchivedObjectException - * @throws CoreException - * @throws CoreUnexpectedValue - */ + /** + * Helper to set the time elapsed since a reference point + * Suitable for use as a lifecycle action + * + * @api + * + * @param string $sAttCode + * @param string $sRefAttCode + * @param string|null $sWorkingTimeComputer + * + * @return bool + * @throws ArchivedObjectException + * @throws CoreException + * @throws CoreUnexpectedValue + */ public function SetElapsedTime($sAttCode, $sRefAttCode, $sWorkingTimeComputer = null) { - if (is_null($sWorkingTimeComputer)) - { + if (is_null($sWorkingTimeComputer)) { $sWorkingTimeComputer = MetaModel::GetWorkingTime(get_class($this)); } $oComputer = new $sWorkingTimeComputer(); - $aCallSpec = array($oComputer, 'GetOpenDuration'); - if (!is_callable($aCallSpec)) - { + $aCallSpec = [$oComputer, 'GetOpenDuration']; + if (!is_callable($aCallSpec)) { throw new CoreException("Unknown class/verb '$sWorkingTimeComputer/GetOpenDuration'"); } @@ -4940,14 +4689,12 @@ abstract class DBObject implements iDisplay $oStartDate = new DateTime('@'.$iStartTime); // setTimestamp not available in PHP 5.2 $oEndDate = new DateTime(); // now - if (class_exists('WorkingTimeRecorder')) - { + if (class_exists('WorkingTimeRecorder')) { $sClass = get_class($this); - WorkingTimeRecorder::Start($this, time(), "DBObject-SetElapsedTime-$sAttCode-$sRefAttCode", 'Core:ExplainWTC:ElapsedTime', array("Class:$sClass/Attribute:$sAttCode")); + WorkingTimeRecorder::Start($this, time(), "DBObject-SetElapsedTime-$sAttCode-$sRefAttCode", 'Core:ExplainWTC:ElapsedTime', ["Class:$sClass/Attribute:$sAttCode"]); } $iElapsed = call_user_func($aCallSpec, $this, $oStartDate, $oEndDate); - if (class_exists('WorkingTimeRecorder')) - { + if (class_exists('WorkingTimeRecorder')) { WorkingTimeRecorder::End(); } @@ -4955,219 +4702,197 @@ abstract class DBObject implements iDisplay return true; } - - /** - * Create query parameters (SELECT ... WHERE service = :this->service_id) - * to be used with the APIs DBObjectSearch/DBObjectSet - * - * Starting 2.0.2 the parameters are computed on demand, at the lowest level, - * in VariableExpression::Render() - * - * @internal - * - * @param string $sArgName - * - * @return array - */ + /** + * Create query parameters (SELECT ... WHERE service = :this->service_id) + * to be used with the APIs DBObjectSearch/DBObjectSet + * + * Starting 2.0.2 the parameters are computed on demand, at the lowest level, + * in VariableExpression::Render() + * + * @internal + * + * @param string $sArgName + * + * @return array + */ public function ToArgsForQuery($sArgName = 'this') { - return array($sArgName.'->object()' => $this); + return [$sArgName.'->object()' => $this]; } - /** - * Create template placeholders: now equivalent to ToArgsForQuery since the actual - * template placeholders are computed on demand. - * - * @internal - * - * @param string $sArgName - * - * @return array - */ + /** + * Create template placeholders: now equivalent to ToArgsForQuery since the actual + * template placeholders are computed on demand. + * + * @internal + * + * @param string $sArgName + * + * @return array + */ public function ToArgs($sArgName = 'this') { return $this->ToArgsForQuery($sArgName); } - /** - * Get various representations of the value, for insertion into a template (e.g. in Notifications) - * - * @internal - * - * @param string $sPlaceholderAttCode - * - * @return int|mixed|string|null - * @throws ArchivedObjectException - * @throws CoreException - * @throws DictExceptionMissingString - */ + /** + * Get various representations of the value, for insertion into a template (e.g. in Notifications) + * + * @internal + * + * @param string $sPlaceholderAttCode + * + * @return int|mixed|string|null + * @throws ArchivedObjectException + * @throws CoreException + * @throws DictExceptionMissingString + */ public function GetForTemplate($sPlaceholderAttCode) { $ret = null; - if (preg_match('/^([^-]+)-(>|>)(.+)$/', $sPlaceholderAttCode, $aMatches)) // Support both syntaxes: this->xxx or this->xxx for HTML compatibility - { + if (preg_match('/^([^-]+)-(>|>)(.+)$/', $sPlaceholderAttCode, $aMatches)) { // Support both syntaxes: this->xxx or this->xxx for HTML compatibility $sExtKeyAttCode = $aMatches[1]; $sRemoteAttCode = $aMatches[3]; - if (!MetaModel::IsValidAttCode(get_class($this), $sExtKeyAttCode)) - { + if (!MetaModel::IsValidAttCode(get_class($this), $sExtKeyAttCode)) { throw new CoreException("Unknown attribute '$sExtKeyAttCode' for the class ".get_class($this)); } $oKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode); - if (!$oKeyAttDef instanceof AttributeExternalKey) - { + if (!$oKeyAttDef instanceof AttributeExternalKey) { throw new CoreException("'$sExtKeyAttCode' is not an external key of the class ".get_class($this)); } $sRemoteClass = $oKeyAttDef->GetTargetClass(); $oRemoteObj = MetaModel::GetObject($sRemoteClass, $this->GetStrict($sExtKeyAttCode), false); - if (is_null($oRemoteObj)) - { + if (is_null($oRemoteObj)) { $ret = Dict::S('UI:UndefinedObject'); - } - else - { + } else { // Recurse $ret = $oRemoteObj->GetForTemplate($sRemoteAttCode); } - } - else - { - switch($sPlaceholderAttCode) - { + } else { + switch ($sPlaceholderAttCode) { case 'id': - $ret = $this->GetKey(); - break; + $ret = $this->GetKey(); + break; case 'name()': - $ret = $this->GetName(); - break; + $ret = $this->GetName(); + break; default: - if (preg_match('/^([^(]+)\\((.*)\\)$/', $sPlaceholderAttCode, $aMatches)) - { - $sVerb = $aMatches[1]; - $sAttCode = $aMatches[2]; - } - else - { - $sVerb = ''; - $sAttCode = $sPlaceholderAttCode; - } - - if (in_array($sVerb, ['hyperlink', 'url'])) - { - $sPortalId = ($sAttCode === '') ? 'console' : $sAttCode; - if (!array_key_exists($sPortalId, self::$aPortalToURLMaker)) - { - throw new Exception("Unknown portal id '$sPortalId' in placeholder '$sPlaceholderAttCode''"); + if (preg_match('/^([^(]+)\\((.*)\\)$/', $sPlaceholderAttCode, $aMatches)) { + $sVerb = $aMatches[1]; + $sAttCode = $aMatches[2]; + } else { + $sVerb = ''; + $sAttCode = $sPlaceholderAttCode; } - if($sVerb == 'hyperlink') - { - $ret = $this->GetHyperlink(self::$aPortalToURLMaker[$sPortalId], false); + if (in_array($sVerb, ['hyperlink', 'url'])) { + $sPortalId = ($sAttCode === '') ? 'console' : $sAttCode; + if (!array_key_exists($sPortalId, self::$aPortalToURLMaker)) { + throw new Exception("Unknown portal id '$sPortalId' in placeholder '$sPlaceholderAttCode''"); + } + + if ($sVerb == 'hyperlink') { + $ret = $this->GetHyperlink(self::$aPortalToURLMaker[$sPortalId], false); + } else { + $ret = ApplicationContext::MakeObjectUrl(get_class($this), $this->GetKey(), self::$aPortalToURLMaker[$sPortalId], false); + } + } else { + $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode); + $ret = $oAttDef->GetForTemplate($this->Get($sAttCode), $sVerb, $this); } - else - { - $ret = ApplicationContext::MakeObjectUrl(get_class($this), $this->GetKey(), self::$aPortalToURLMaker[$sPortalId], false); - } - } - else - { - $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode); - $ret = $oAttDef->GetForTemplate($this->Get($sAttCode), $sVerb, $this); - } } - if ($ret === null) - { + if ($ret === null) { $ret = ''; } } return $ret; } - static protected $aPortalToURLMaker = array('console' => 'iTopStandardURLMaker', 'portal' => 'PortalURLMaker'); + protected static $aPortalToURLMaker = ['console' => 'iTopStandardURLMaker', 'portal' => 'PortalURLMaker']; /** * Associate a portal to a class that implements iDBObjectURLMaker, * and which will be invoked with placeholders like $this->org_id->hyperlink(portal)$ * - * @internal - * + * @internal + * * @param string $sPortalId Identifies the portal. Conventions: the main portal is 'console', The user requests portal is 'portal'. * @param string $sUrlMakerClass */ - static public function RegisterURLMakerClass($sPortalId, $sUrlMakerClass) + public static function RegisterURLMakerClass($sPortalId, $sUrlMakerClass) { self::$aPortalToURLMaker[$sPortalId] = $sUrlMakerClass; } /** * this method is called before the object is inserted into DB. - * - * + * + * * @overwritable-hook You can extend this method in order to provide your own logic. */ protected function OnInsert() { } - /** - * this method is called after the object is inserted into DB. - * - * @overwritable-hook You can extend this method in order to provide your own logic. - */ + /** + * this method is called after the object is inserted into DB. + * + * @overwritable-hook You can extend this method in order to provide your own logic. + */ protected function AfterInsert() { } - /** - * this method is called before the object is updated into DB. - * - * @overwritable-hook You can extend this method in order to provide your own logic. - */ + /** + * this method is called before the object is updated into DB. + * + * @overwritable-hook You can extend this method in order to provide your own logic. + */ protected function OnUpdate() { } - /** - * @overwritable-hook You can extend this method in order to provide your own logic. - * - * This method is called after the object is updated into DB, and just before the {@see DBObject::Reload()} call. - * - * Warning : do not use {@see DBObject::ListChanges()} as it will return an empty array ! - * Use instead {@see DBObject::ListPreviousValuesForUpdatedAttributes()} to get modified fields and their previous values, - * and {@see DBObject::Get()} to get the persisted value for a given attribute. - * - * @since 2.7.0 N°2293 can access object changes by calling {@see DBObject::ListPreviousValuesForUpdatedAttributes()} - */ + /** + * @overwritable-hook You can extend this method in order to provide your own logic. + * + * This method is called after the object is updated into DB, and just before the {@see DBObject::Reload()} call. + * + * Warning : do not use {@see DBObject::ListChanges()} as it will return an empty array ! + * Use instead {@see DBObject::ListPreviousValuesForUpdatedAttributes()} to get modified fields and their previous values, + * and {@see DBObject::Get()} to get the persisted value for a given attribute. + * + * @since 2.7.0 N°2293 can access object changes by calling {@see DBObject::ListPreviousValuesForUpdatedAttributes()} + */ protected function AfterUpdate() { } - /** - * this method is called before the object is deleted into DB. - * - * @overwritable-hook You can extend this method in order to provide your own logic. - */ + /** + * this method is called before the object is deleted into DB. + * + * @overwritable-hook You can extend this method in order to provide your own logic. + */ protected function OnDelete() { } - /** - * this method is called after the object is deleted into DB. - * - * @overwritable-hook You can extend this method in order to provide your own logic. - */ + /** + * this method is called after the object is deleted into DB. + * + * @overwritable-hook You can extend this method in order to provide your own logic. + */ protected function AfterDelete() { } - /** * Common to the recording of link set changes (add/remove/modify) * - * @internal - * + * @internal + * * @param $iLinkSetOwnerId * @param \AttributeLinkedSet $oLinkSet * @param $sChangeOpClass @@ -5180,39 +4905,31 @@ abstract class DBObject implements iDisplay */ private function PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, $sChangeOpClass, $aOriginalValues = null) { - if ($iLinkSetOwnerId <= 0) - { + if ($iLinkSetOwnerId <= 0) { return null; } - if (!is_subclass_of($oLinkSet->GetHostClass(), 'CMDBObject')) - { + if (!is_subclass_of($oLinkSet->GetHostClass(), 'CMDBObject')) { // The link set owner class does not keep track of its history return null; } // Determine the linked item class and id // - if ($oLinkSet->IsIndirect()) - { + if ($oLinkSet->IsIndirect()) { // The "item" is on the other end (N-N links) /** @var \AttributeLinkedSetIndirect $oLinkSet */ $sExtKeyToRemote = $oLinkSet->GetExtKeyToRemote(); $oExtKeyToRemote = MetaModel::GetAttributeDef(get_class($this), $sExtKeyToRemote); /** @var \AttributeExternalKey $oExtKeyToRemote */ $sItemClass = $oExtKeyToRemote->GetTargetClass(); - if ($aOriginalValues) - { + if ($aOriginalValues) { // Get the value from the original values $iItemId = $aOriginalValues[$sExtKeyToRemote]; - } - else - { + } else { $iItemId = $this->Get($sExtKeyToRemote); } - } - else - { + } else { // I am the "item" (1-N links) $sItemClass = get_class($this); $iItemId = $this->GetKey(); @@ -5221,8 +4938,7 @@ abstract class DBObject implements iDisplay // Get the remote object, to determine its exact class // Possible optimization: implement a tool in MetaModel, to get the final class of an object (not always querying + query reduced to a select on the root table! $oOwner = MetaModel::GetObject($oLinkSet->GetHostClass(), $iLinkSetOwnerId, false); - if ($oOwner) - { + if ($oOwner) { $sLinkSetOwnerClass = get_class($oOwner); $oMyChangeOp = MetaModel::NewObject($sChangeOpClass); @@ -5232,9 +4948,7 @@ abstract class DBObject implements iDisplay $oMyChangeOp->Set("item_class", $sItemClass); $oMyChangeOp->Set("item_id", $iItemId); return $oMyChangeOp; - } - else - { + } else { // Depending on the deletion order, it may happen that the id is already invalid... ignore return null; } @@ -5247,21 +4961,18 @@ abstract class DBObject implements iDisplay */ private function RecordLinkSetListChange($bAdd = true) { - foreach(MetaModel::GetTrackForwardExternalKeys(get_class($this)) as $sExtKeyAttCode => $oLinkSet) - { + foreach (MetaModel::GetTrackForwardExternalKeys(get_class($this)) as $sExtKeyAttCode => $oLinkSet) { /** @var \AttributeLinkedSet $oLinkSet */ - if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_LIST) == 0) continue; + if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_LIST) == 0) { + continue; + } $iLinkSetOwnerId = $this->Get($sExtKeyAttCode); $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove'); - if ($oMyChangeOp) - { - if ($bAdd) - { + if ($oMyChangeOp) { + if ($bAdd) { $oMyChangeOp->Set("type", "added"); - } - else - { + } else { $oMyChangeOp->Set("type", "removed"); } $oMyChangeOp->DBInsertNoReload(); @@ -5277,55 +4988,52 @@ abstract class DBObject implements iDisplay $this->RecordLinkSetListChange(true); } - /** - * @internal - */ + /** + * @internal + */ protected function RecordObjDeletion($objkey) { $this->RecordLinkSetListChange(false); } - /** - * @internal - */ + /** + * @internal + */ protected function RecordAttChanges(array $aValues, array $aOrigValues) { - foreach(MetaModel::GetTrackForwardExternalKeys(get_class($this)) as $sExtKeyAttCode => $oLinkSet) - { + foreach (MetaModel::GetTrackForwardExternalKeys(get_class($this)) as $sExtKeyAttCode => $oLinkSet) { - if (array_key_exists($sExtKeyAttCode, $aValues)) - { + if (array_key_exists($sExtKeyAttCode, $aValues)) { /** @var \AttributeLinkedSet $oLinkSet */ - if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_LIST) == 0) continue; + if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_LIST) == 0) { + continue; + } // Keep track of link added/removed // $iLinkSetOwnerNext = $aValues[$sExtKeyAttCode]; $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerNext, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove'); - if ($oMyChangeOp) - { + if ($oMyChangeOp) { $oMyChangeOp->Set("type", "added"); $oMyChangeOp->DBInsertNoReload(); } $iLinkSetOwnerPrevious = $aOrigValues[$sExtKeyAttCode]; $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerPrevious, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove', $aOrigValues); - if ($oMyChangeOp) - { + if ($oMyChangeOp) { $oMyChangeOp->Set("type", "removed"); $oMyChangeOp->DBInsertNoReload(); } - } - else - { + } else { // Keep track of link changes // - if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_DETAILS) == 0) continue; + if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_DETAILS) == 0) { + continue; + } $iLinkSetOwnerId = $this->Get($sExtKeyAttCode); $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, 'CMDBChangeOpSetAttributeLinksTune'); - if ($oMyChangeOp) - { + if ($oMyChangeOp) { $oMyChangeOp->Set("link_id", $this->GetKey()); $oMyChangeOp->DBInsertNoReload(); } @@ -5333,31 +5041,29 @@ abstract class DBObject implements iDisplay } } - - - /** - * Reserved: do not overload - * - * @internal - */ + /** + * Reserved: do not overload + * + * @internal + */ public static function GetRelationQueriesEx($sRelCode) { - return array(); + return []; } - /** - * Compute the "RelatedObjects" (forward or "down" direction) for the object - * for the specified relation - * - * @internal - * - * @param string $sRelCode The code of the relation to use for the computation - * @param int $iMaxDepth Maximum recursion depth - * @param bool $bEnableRedundancy - * - * @return RelationGraph The graph of all the related objects - * @throws CoreException - */ + /** + * Compute the "RelatedObjects" (forward or "down" direction) for the object + * for the specified relation + * + * @internal + * + * @param string $sRelCode The code of the relation to use for the computation + * @param int $iMaxDepth Maximum recursion depth + * @param bool $bEnableRedundancy + * + * @return RelationGraph The graph of all the related objects + * @throws CoreException + */ public function GetRelatedObjectsDown($sRelCode, $iMaxDepth = 99, $bEnableRedundancy = true) { $oGraph = new RelationGraph(); @@ -5366,19 +5072,19 @@ abstract class DBObject implements iDisplay return $oGraph; } - /** - * Compute the "RelatedObjects" (reverse or "up" direction) for the object - * for the specified relation - * - * @internal - * - * @param string $sRelCode The code of the relation to use for the computation - * @param int $iMaxDepth Maximum recursion depth - * @param bool $bEnableRedundancy - * - * @return RelationGraph The graph of all the related objects - * @throws CoreException - */ + /** + * Compute the "RelatedObjects" (reverse or "up" direction) for the object + * for the specified relation + * + * @internal + * + * @param string $sRelCode The code of the relation to use for the computation + * @param int $iMaxDepth Maximum recursion depth + * @param bool $bEnableRedundancy + * + * @return RelationGraph The graph of all the related objects + * @throws CoreException + */ public function GetRelatedObjectsUp($sRelCode, $iMaxDepth = 99, $bEnableRedundancy = true) { $oGraph = new RelationGraph(); @@ -5401,32 +5107,32 @@ abstract class DBObject implements iDisplay */ protected function GetReferencingObjectsForDeletion($bAllowAllData = false) { - $aDependentObjects = array(); + $aDependentObjects = []; $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this)); - foreach($aRererencingMe as $sRemoteClass => $aExtKeys) - { + foreach ($aRererencingMe as $sRemoteClass => $aExtKeys) { /** @var \AttributeExternalKey $oExtKeyAttDef */ - foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef) - { + foreach ($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef) { // skip if external key doesn't require the deletion cascading - if($oExtKeyAttDef->GetDeletionPropagationOption() === DEL_NONE) continue; + if ($oExtKeyAttDef->GetDeletionPropagationOption() === DEL_NONE) { + continue; + } // skip if this external key is behind an external field - if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue; + if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) { + continue; + } $oSearch = new DBObjectSearch($sRemoteClass); $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey(), '='); - if ($bAllowAllData) - { + if ($bAllowAllData) { $oSearch->AllowAllData(); } $oSet = new CMDBObjectSet($oSearch); - if ($oSet->CountExceeds(0)) - { - $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array( + if ($oSet->CountExceeds(0)) { + $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = [ 'attribute' => $oExtKeyAttDef, 'objects' => $oSet, - ); + ]; } } } @@ -5434,19 +5140,18 @@ abstract class DBObject implements iDisplay } /** - * @internal - * + * @internal + * * @param \DeletionPlan $oDeletionPlan * @param array $aVisited * @param int $iDeleteOption * * @throws \CoreException */ - private function MakeDeletionPlan(&$oDeletionPlan, $aVisited = array(), $iDeleteOption = null) + private function MakeDeletionPlan(&$oDeletionPlan, $aVisited = [], $iDeleteOption = null) { static $iLoopTimeLimit = null; - if ($iLoopTimeLimit == null) - { + if ($iLoopTimeLimit == null) { $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop'); } $sClass = get_class($this); @@ -5454,22 +5159,19 @@ abstract class DBObject implements iDisplay $oDeletionPlan->AddToDelete($this, $iDeleteOption); - if (array_key_exists($sClass, $aVisited)) - { - if (in_array($iThisId, $aVisited[$sClass])) - { + if (array_key_exists($sClass, $aVisited)) { + if (in_array($iThisId, $aVisited[$sClass])) { return; } } $aVisited[$sClass] = $iThisId; - if ($iDeleteOption == DEL_MANUAL) - { + if ($iDeleteOption == DEL_MANUAL) { // Stop the recursion here return; } // Check the node itself - $this->m_aDeleteIssues = array(); // Ok + $this->m_aDeleteIssues = []; // Ok $this->FireEventCheckToDelete($oDeletionPlan); $this->DoCheckToDelete($oDeletionPlan); $this->CheckToWriteForTargetObjects(true); @@ -5479,10 +5181,8 @@ abstract class DBObject implements iDisplay // www.php.net/manual/fr/function.set-time-limit.php#72305 $iPreviousTimeLimit = ini_get('max_execution_time'); - foreach ($this->GetReferencingObjectsForDeletion(true /* allow all data */) as $aPotentialDeletes) - { - foreach ($aPotentialDeletes as $aData) - { + foreach ($this->GetReferencingObjectsForDeletion(true /* allow all data */) as $aPotentialDeletes) { + foreach ($aPotentialDeletes as $aData) { set_time_limit(intval($iLoopTimeLimit)); /** @var \AttributeExternalKey $oAttDef */ @@ -5491,24 +5191,17 @@ abstract class DBObject implements iDisplay /** @var \DBObjectSet $oDepSet */ $oDepSet = $aData['objects']; $oDepSet->Rewind(); - while ($oDependentObj = $oDepSet->fetch()) - { - if ($oAttDef->IsNullAllowed()) - { + while ($oDependentObj = $oDepSet->fetch()) { + if ($oAttDef->IsNullAllowed()) { // Optional external key, list to reset - if (($iDeletePropagationOption == DEL_MOVEUP) && ($oAttDef->IsHierarchicalKey())) - { + if (($iDeletePropagationOption == DEL_MOVEUP) && ($oAttDef->IsHierarchicalKey())) { // Move the child up one level i.e. set the same parent as the current object $iParentId = $this->Get($oAttDef->GetCode()); $oDeletionPlan->AddToUpdate($oDependentObj, $oAttDef, $iParentId); - } - else - { + } else { $oDeletionPlan->AddToUpdate($oDependentObj, $oAttDef); } - } - else - { + } else { // Mandatory external key, list to delete $oDependentObj->MakeDeletionPlan($oDeletionPlan, $aVisited, $iDeletePropagationOption); } @@ -5520,8 +5213,8 @@ abstract class DBObject implements iDisplay /** * Get all the synchro data related to this object - * - * @internal + * + * @internal * * @return array of data_source_id => array * * 'source' => $oSource, @@ -5539,23 +5232,23 @@ abstract class DBObject implements iDisplay if (!$bIncludeObsolete) { $sOQL .= " AND replica.status != 'obsolete'"; } - $oReplicaSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array('dest_class' => get_class($this), 'dest_id' => $this->GetKey())); - $this->m_aSynchroData = array(); + $oReplicaSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), [] /* order by*/, ['dest_class' => get_class($this), 'dest_id' => $this->GetKey()]); + $this->m_aSynchroData = []; while ($aData = $oReplicaSet->FetchAssoc()) { /** @var \DBObject[] $aData */ $iSourceId = $aData['datasource']->GetKey(); if (!array_key_exists($iSourceId, $this->m_aSynchroData)) { - $aAttributes = array(); + $aAttributes = []; $oAttrSet = $aData['datasource']->Get('attribute_list'); while ($oSyncAttr = $oAttrSet->Fetch()) { /** @var \DBObject $oSyncAttr */ $aAttributes[$oSyncAttr->Get('attcode')] = $oSyncAttr; } - $this->m_aSynchroData[$iSourceId] = array( + $this->m_aSynchroData[$iSourceId] = [ 'source' => $aData['datasource'], 'attributes' => $aAttributes, - 'replica' => array() - ); + 'replica' => [], + ]; } // Assumption: $aData['datasource'] will not be null because the data source id is always set... $this->m_aSynchroData[$iSourceId]['replica'][] = $aData['replica']; @@ -5564,20 +5257,20 @@ abstract class DBObject implements iDisplay return $this->m_aSynchroData; } - /** - * - * @internal - * - * @param string $sAttCode - * @param array $aReason - * - * @return int - * @throws ArchivedObjectException - * @throws CoreException - * @throws CoreUnexpectedValue - * @throws MySQLException - * @throws OQLException - */ + /** + * + * @internal + * + * @param string $sAttCode + * @param array $aReason + * + * @return int + * @throws ArchivedObjectException + * @throws CoreException + * @throws CoreUnexpectedValue + * @throws MySQLException + * @throws OQLException + */ public function GetSynchroReplicaFlags($sAttCode, &$aReason) { $iFlags = OPT_ATT_NORMAL; @@ -5592,12 +5285,11 @@ abstract class DBObject implements iDisplay if (array_key_exists($sAttCode, $aSourceData['attributes'])) { /** @var \DBObject $oSyncAttr */ $oSyncAttr = $aSourceData['attributes'][$sAttCode]; - if (($oSyncAttr->Get('update') == 1) && ($oSyncAttr->Get('update_policy') == 'master_locked')) - { + if (($oSyncAttr->Get('update') == 1) && ($oSyncAttr->Get('update_policy') == 'master_locked')) { $iFlags |= OPT_ATT_SLAVE; /** @var \SynchroDataSource $oSource */ $sUrl = $oSource->GetApplicationUrl($this, $oReplica); - $aReason[] = array('name' => $oSource->GetName(), 'description' => $oSource->Get('description'), 'url_application' => $sUrl); + $aReason[] = ['name' => $oSource->GetName(), 'description' => $oSource->Get('description'), 'url_application' => $sUrl]; } } } @@ -5605,9 +5297,9 @@ abstract class DBObject implements iDisplay } /** - * - * @internal - * + * + * @internal + * * @return bool true if this object is used in a data synchro * @throws \CoreException * @throws \CoreUnexpectedValue @@ -5622,22 +5314,18 @@ abstract class DBObject implements iDisplay // Optimization: cache the list of Data Sources and classes candidates for synchro // static $aSynchroClasses = null; - if (is_null($aSynchroClasses)) - { - $aSynchroClasses = array(); + if (is_null($aSynchroClasses)) { + $aSynchroClasses = []; $sOQL = "SELECT SynchroDataSource AS datasource"; - $oSourceSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array()); - while($oSource = $oSourceSet->Fetch()) - { + $oSourceSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), [] /* order by*/, []); + while ($oSource = $oSourceSet->Fetch()) { $sTarget = $oSource->Get('scope_class'); $aSynchroClasses[] = $sTarget; } } - foreach($aSynchroClasses as $sClass) - { - if ($this instanceof $sClass) - { + foreach ($aSynchroClasses as $sClass) { + if ($this instanceof $sClass) { return true; } } @@ -5649,86 +5337,79 @@ abstract class DBObject implements iDisplay // ///////////////////////////////////////////////////////////////////////// - /** - * @internal - * - * @param string $sContextParam - * - * @return string|null - */ + /** + * @internal + * + * @param string $sContextParam + * + * @return string|null + */ public static function MapContextParam($sContextParam) { return null; } - /** - * @internal - * - * @return String - * @throws ArchivedObjectException - * @throws CoreException - */ + /** + * @internal + * + * @return String + * @throws ArchivedObjectException + * @throws CoreException + */ public function GetHilightClass() { $sCode = $this->ComputeHighlightCode(); - if($sCode != '') - { + if ($sCode != '') { $aHighlightScale = MetaModel::GetHighlightScale(get_class($this)); - if (array_key_exists($sCode, $aHighlightScale)) - { + if (array_key_exists($sCode, $aHighlightScale)) { return $aHighlightScale[$sCode]['color']; } } return HILIGHT_CLASS_NONE; } - /** - * @internal - * - * @param WebPage $oPage - * @param bool $bEditMode - * - * @throws ArchivedObjectException - * @throws CoreException - * @throws DictExceptionMissingString - */ + /** + * @internal + * + * @param WebPage $oPage + * @param bool $bEditMode + * + * @throws ArchivedObjectException + * @throws CoreException + * @throws DictExceptionMissingString + */ public function DisplayDetails(WebPage $oPage, $bEditMode = false) { $oPage->add('

'.MetaModel::GetName(get_class($this)).': '.$this->GetName().'

'); - $aValues = array(); + $aValues = []; $aList = MetaModel::FlattenZList(MetaModel::GetZListItems(get_class($this), 'details')); - if (empty($aList)) - { + if (empty($aList)) { $aList = array_keys(MetaModel::ListAttributeDefs(get_class($this))); } - foreach($aList as $sAttCode) - { - $aValues[$sAttCode] = array('label' => MetaModel::GetLabel(get_class($this), $sAttCode), 'value' => $this->GetAsHTML($sAttCode)); + foreach ($aList as $sAttCode) { + $aValues[$sAttCode] = ['label' => MetaModel::GetLabel(get_class($this), $sAttCode), 'value' => $this->GetAsHTML($sAttCode)]; } $oPage->details($aValues); } - /** - * Computes a text-like fingerprint identifying the content of the object - * but excluding the specified columns - * - * @internal - * - * @param $aExcludedColumns array The list of columns to exclude - * - * @return string - * @throws ArchivedObjectException - * @throws CoreException - */ - public function Fingerprint($aExcludedColumns = array()) + /** + * Computes a text-like fingerprint identifying the content of the object + * but excluding the specified columns + * + * @internal + * + * @param $aExcludedColumns array The list of columns to exclude + * + * @return string + * @throws ArchivedObjectException + * @throws CoreException + */ + public function Fingerprint($aExcludedColumns = []) { $sFingerprint = ''; - foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) - { - if (!in_array($sAttCode, $aExcludedColumns)) - { - if ($oAttDef->IsPartOfFingerprint()) - { + foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) { + if (!in_array($sAttCode, $aExcludedColumns)) { + if ($oAttDef->IsPartOfFingerprint()) { $sFingerprint .= chr(0).$oAttDef->Fingerprint($this->Get($sAttCode)); } } @@ -5739,8 +5420,8 @@ abstract class DBObject implements iDisplay /** * Execute a set of scripted actions onto the current object * See ExecAction for the syntax and features of the scripted actions - * - * @internal + * + * @internal * * @param $aActions array of statements (e.g. "set(name, Made after $source->name$)") * @param $aSourceObjects array of Alias => Context objects (Convention: some statements require the 'source' element @@ -5748,42 +5429,31 @@ abstract class DBObject implements iDisplay */ public function ExecActions($aActions, $aSourceObjects) { - foreach($aActions as $sAction) - { - try - { - if (preg_match('/^(\S*)\s*\((.*)\)$/ms', $sAction, $aMatches)) // multiline and newline matched by a dot - { + foreach ($aActions as $sAction) { + try { + if (preg_match('/^(\S*)\s*\((.*)\)$/ms', $sAction, $aMatches)) { // multiline and newline matched by a dot $sVerb = trim($aMatches[1]); $sParams = $aMatches[2]; // the coma is the separator for the parameters // comas can be escaped: \, - $sParams = str_replace(array("\\\\", "\\,"), array("__backslash__", "__coma__"), $sParams); + $sParams = str_replace(["\\\\", "\\,"], ["__backslash__", "__coma__"], $sParams); $sParams = trim($sParams); - if (strlen($sParams) == 0) - { - $aParams = array(); - } - else - { + if (strlen($sParams) == 0) { + $aParams = []; + } else { $aParams = explode(',', $sParams); - foreach ($aParams as &$sParam) - { - $sParam = str_replace(array("__backslash__", "__coma__"), array("\\", ","), $sParam); + foreach ($aParams as &$sParam) { + $sParam = str_replace(["__backslash__", "__coma__"], ["\\", ","], $sParam); $sParam = trim($sParam); } } $this->ExecAction($sVerb, $aParams, $aSourceObjects); - } - else - { + } else { throw new Exception("Invalid syntax"); } - } - catch(Exception $e) - { + } catch (Exception $e) { throw new Exception('Action: '.$sAction.' - '.$e->getMessage()); } } @@ -5792,8 +5462,8 @@ abstract class DBObject implements iDisplay /** * Helper to copy an attribute between two objects (in memory) * Originally designed for ExecAction() - * - * @internal + * + * @internal * * @param \DBObject $oSourceObject * @param $sSourceAttCode @@ -5805,8 +5475,7 @@ abstract class DBObject implements iDisplay */ public function CopyAttribute($oSourceObject, $sSourceAttCode, $sDestAttCode) { - if ($sSourceAttCode == 'id') - { + if ($sSourceAttCode == 'id') { $oSourceAttDef = null; } else { if (!MetaModel::IsValidAttCode(get_class($this), $sDestAttCode)) { @@ -5838,9 +5507,7 @@ abstract class DBObject implements iDisplay $oDestSet->AddItem($oLinkClone); } $this->Set($sDestAttCode, $oDestSet); - } - else - { + } else { $this->Set($sDestAttCode, $oSourceObject->Get($sSourceAttCode)); } } @@ -5858,9 +5525,9 @@ abstract class DBObject implements iDisplay * - add_to_list (source_key_att, dest_att, lnk_att, lnk_att_value) * - apply_stimulus (stimulus) * - call_method (method_name) - * - * - * @internal + * + * + * @internal * * @param $sVerb string Any of the verb listed above (e.g. "set") * @param $aParams array of strings (e.g. array('name', 'copied from $source->name$') @@ -5871,48 +5538,39 @@ abstract class DBObject implements iDisplay */ public function ExecAction($sVerb, $aParams, $aSourceObjects) { - switch($sVerb) - { + switch ($sVerb) { case 'clone': - if (!array_key_exists('source', $aSourceObjects)) - { + if (!array_key_exists('source', $aSourceObjects)) { throw new Exception('Missing conventional "source" object'); } $oObjectToRead = $aSourceObjects['source']; - foreach($aParams as $sAttCode) - { + foreach ($aParams as $sAttCode) { $this->CopyAttribute($oObjectToRead, $sAttCode, $sAttCode); } break; case 'clone_scalars': - if (!array_key_exists('source', $aSourceObjects)) - { + if (!array_key_exists('source', $aSourceObjects)) { throw new Exception('Missing conventional "source" object'); } $oObjectToRead = $aSourceObjects['source']; - foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) - { - if ($oAttDef->IsScalar() && $oAttDef->IsWritable()) - { + foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) { + if ($oAttDef->IsScalar() && $oAttDef->IsWritable()) { $this->CopyAttribute($oObjectToRead, $sAttCode, $sAttCode); } } break; case 'copy': - if (!array_key_exists('source', $aSourceObjects)) - { + if (!array_key_exists('source', $aSourceObjects)) { throw new Exception('Missing conventional "source" object'); } $oObjectToRead = $aSourceObjects['source']; - if (!array_key_exists(0, $aParams)) - { + if (!array_key_exists(0, $aParams)) { throw new Exception('Missing argument #1: source attribute'); } $sSourceAttCode = $aParams[0]; - if (!array_key_exists(1, $aParams)) - { + if (!array_key_exists(1, $aParams)) { throw new Exception('Missing argument #2: target attribute'); } $sDestAttCode = $aParams[1]; @@ -5920,26 +5578,22 @@ abstract class DBObject implements iDisplay break; case 'reset': - if (!array_key_exists(0, $aParams)) - { + if (!array_key_exists(0, $aParams)) { throw new Exception('Missing argument #1: target attribute'); } $sAttCode = $aParams[0]; - if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode)) - { + if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode)) { throw new Exception("Unknown attribute ".get_class($this)."::".$sAttCode); } $this->Set($sAttCode, $this->GetDefaultValue($sAttCode)); break; case 'nullify': - if (!array_key_exists(0, $aParams)) - { + if (!array_key_exists(0, $aParams)) { throw new Exception('Missing argument #1: target attribute'); } $sAttCode = $aParams[0]; - if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode)) - { + if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode)) { throw new Exception("Unknown attribute ".get_class($this)."::".$sAttCode); } $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode); @@ -5947,23 +5601,19 @@ abstract class DBObject implements iDisplay break; case 'set': - if (!array_key_exists(0, $aParams)) - { + if (!array_key_exists(0, $aParams)) { throw new Exception('Missing argument #1: target attribute'); } $sAttCode = $aParams[0]; - if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode)) - { + if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode)) { throw new Exception("Unknown attribute ".get_class($this)."::".$sAttCode); } - if (!array_key_exists(1, $aParams)) - { + if (!array_key_exists(1, $aParams)) { throw new Exception('Missing argument #2: value to set'); } $sRawValue = $aParams[1]; - $aContext = array(); - foreach ($aSourceObjects as $sAlias => $oObject) - { + $aContext = []; + foreach ($aSourceObjects as $sAlias => $oObject) { $aContext = array_merge($aContext, $oObject->ToArgs($sAlias)); } $aContext['current_contact_id'] = UserRights::GetContactId(); @@ -5975,23 +5625,19 @@ abstract class DBObject implements iDisplay break; case 'append': - if (!array_key_exists(0, $aParams)) - { + if (!array_key_exists(0, $aParams)) { throw new Exception('Missing argument #1: target attribute'); } $sAttCode = $aParams[0]; - if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode)) - { + if (!MetaModel::IsValidAttCode(get_class($this), $sAttCode)) { throw new Exception("Unknown attribute ".get_class($this)."::".$sAttCode); } - if (!array_key_exists(1, $aParams)) - { + if (!array_key_exists(1, $aParams)) { throw new Exception('Missing argument #2: value to append'); } $sRawAddendum = $aParams[1]; - $aContext = array(); - foreach ($aSourceObjects as $sAlias => $oObject) - { + $aContext = []; + foreach ($aSourceObjects as $sAlias => $oObject) { $aContext = array_merge($aContext, $oObject->ToArgs($sAlias)); } $aContext['current_contact_id'] = UserRights::GetContactId(); @@ -6003,38 +5649,31 @@ abstract class DBObject implements iDisplay break; case 'add_to_list': - if (!array_key_exists('source', $aSourceObjects)) - { + if (!array_key_exists('source', $aSourceObjects)) { throw new Exception('Missing conventional "source" object'); } $oObjectToRead = $aSourceObjects['source']; - if (!array_key_exists(0, $aParams)) - { + if (!array_key_exists(0, $aParams)) { throw new Exception('Missing argument #1: source attribute'); } $sSourceKeyAttCode = $aParams[0]; - if (($sSourceKeyAttCode != 'id') && !MetaModel::IsValidAttCode(get_class($oObjectToRead), $sSourceKeyAttCode)) - { + if (($sSourceKeyAttCode != 'id') && !MetaModel::IsValidAttCode(get_class($oObjectToRead), $sSourceKeyAttCode)) { throw new Exception("Unknown attribute ".get_class($oObjectToRead)."::".$sSourceKeyAttCode); } - if (!array_key_exists(1, $aParams)) - { + if (!array_key_exists(1, $aParams)) { throw new Exception('Missing argument #2: target attribute (link set)'); } $sTargetListAttCode = $aParams[1]; // indirect !!! - if (!MetaModel::IsValidAttCode(get_class($this), $sTargetListAttCode)) - { + if (!MetaModel::IsValidAttCode(get_class($this), $sTargetListAttCode)) { throw new Exception("Unknown attribute ".get_class($this)."::".$sTargetListAttCode); } - if (isset($aParams[2]) && isset($aParams[3])) - { + if (isset($aParams[2]) && isset($aParams[3])) { $sRoleAttCode = $aParams[2]; $sRoleValue = $aParams[3]; } $iObjKey = $oObjectToRead->Get($sSourceKeyAttCode); - if ($iObjKey > 0) - { + if ($iObjKey > 0) { $oLinkSet = $this->Get($sTargetListAttCode); /** @var \AttributeLinkedSetIndirect $oListAttDef */ @@ -6042,10 +5681,8 @@ abstract class DBObject implements iDisplay /** @var \AttributeLinkedSet $oListAttDef */ $oLnk = MetaModel::NewObject($oListAttDef->GetLinkedClass()); $oLnk->Set($oListAttDef->GetExtKeyToRemote(), $iObjKey); - if (isset($sRoleAttCode)) - { - if (!MetaModel::IsValidAttCode(get_class($oLnk), $sRoleAttCode)) - { + if (isset($sRoleAttCode)) { + if (!MetaModel::IsValidAttCode(get_class($oLnk), $sRoleAttCode)) { throw new Exception("Unknown attribute ".get_class($oLnk)."::".$sRoleAttCode); } $oLnk->Set($sRoleAttCode, $sRoleValue); @@ -6056,8 +5693,7 @@ abstract class DBObject implements iDisplay break; case 'apply_stimulus': - if (!array_key_exists(0, $aParams)) - { + if (!array_key_exists(0, $aParams)) { throw new Exception('Missing argument #1: stimulus'); } $sStimulus = $aParams[0]; @@ -6065,19 +5701,16 @@ abstract class DBObject implements iDisplay break; case 'call_method': - if (!array_key_exists('source', $aSourceObjects)) - { + if (!array_key_exists('source', $aSourceObjects)) { throw new Exception('Missing conventional "source" object'); } $oObjectToRead = $aSourceObjects['source']; - if (!array_key_exists(0, $aParams)) - { + if (!array_key_exists(0, $aParams)) { throw new Exception('Missing argument #1: method name'); } $sMethod = $aParams[0]; - $aCallSpec = array($this, $sMethod); - if (!is_callable($aCallSpec)) - { + $aCallSpec = [$this, $sMethod]; + if (!is_callable($aCallSpec)) { throw new Exception("Unknown method ".get_class($this)."::".$sMethod.'()'); } // Note: $oObjectToRead has been preserved when adding $aSourceObjects, so as to remain backward compatible with methods having only 1 parameter ($oObjectToRead� @@ -6089,51 +5722,49 @@ abstract class DBObject implements iDisplay } } - /** - * Is the object archived - * - * @api - * - * @param string|null $sKeyAttCode - * - * @return bool - * @throws ArchivedObjectException - * @throws CoreException - */ + /** + * Is the object archived + * + * @api + * + * @param string|null $sKeyAttCode + * + * @return bool + * @throws ArchivedObjectException + * @throws CoreException + */ public function IsArchived($sKeyAttCode = null) { $bRet = false; $sFlagAttCode = is_null($sKeyAttCode) ? 'archive_flag' : $sKeyAttCode.'_archive_flag'; - if (MetaModel::IsValidAttCode(get_class($this), $sFlagAttCode) && $this->Get($sFlagAttCode)) - { - $bRet = true; - } - return $bRet; - } - - /** - * Is the object obsolete - * - * @param string|null $sKeyAttCode - * - * @return bool - * @throws ArchivedObjectException - * @throws CoreException - */ - public function IsObsolete($sKeyAttCode = null) - { - $bRet = false; - $sFlagAttCode = is_null($sKeyAttCode) ? 'obsolescence_flag' : $sKeyAttCode.'_obsolescence_flag'; - if (MetaModel::IsValidAttCode(get_class($this), $sFlagAttCode) && $this->Get($sFlagAttCode)) - { + if (MetaModel::IsValidAttCode(get_class($this), $sFlagAttCode) && $this->Get($sFlagAttCode)) { $bRet = true; } return $bRet; } /** - * @internal - * + * Is the object obsolete + * + * @param string|null $sKeyAttCode + * + * @return bool + * @throws ArchivedObjectException + * @throws CoreException + */ + public function IsObsolete($sKeyAttCode = null) + { + $bRet = false; + $sFlagAttCode = is_null($sKeyAttCode) ? 'obsolescence_flag' : $sKeyAttCode.'_obsolescence_flag'; + if (MetaModel::IsValidAttCode(get_class($this), $sFlagAttCode) && $this->Get($sFlagAttCode)) { + $bRet = true; + } + return $bRet; + } + + /** + * @internal + * *

Sets the archive_flag For all of the class hierarchy
* Also update the archive_date : *

    @@ -6151,8 +5782,7 @@ abstract class DBObject implements iDisplay */ protected function DBWriteArchiveFlag($bArchive) { - if (!MetaModel::IsArchivable(get_class($this))) - { + if (!MetaModel::IsArchivable(get_class($this))) { throw new Exception(get_class($this).' is not an archivable class'); } @@ -6163,24 +5793,21 @@ abstract class DBObject implements iDisplay $sArchiveRoot = MetaModel::GetAttributeOrigin($sClass, 'archive_flag'); $sRootTable = MetaModel::DBGetTable($sArchiveRoot); $sRootKey = MetaModel::DBGetKey($sArchiveRoot); - $aJoins = array("`$sRootTable`"); - $aUpdates = array(); - foreach (MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL) as $sParentClass) - { - if (!MetaModel::IsValidAttCode($sParentClass, 'archive_flag')) continue; + $aJoins = ["`$sRootTable`"]; + $aUpdates = []; + foreach (MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL) as $sParentClass) { + if (!MetaModel::IsValidAttCode($sParentClass, 'archive_flag')) { + continue; + } $sTable = MetaModel::DBGetTable($sParentClass); $aUpdates[] = "`$sTable`.`archive_flag` = $iFlag"; - if ($sParentClass == $sArchiveRoot) - { - if (!$bArchive || $this->Get('archive_date') == '') - { + if ($sParentClass == $sArchiveRoot) { + if (!$bArchive || $this->Get('archive_date') == '') { // Erase or set the date (do not change it) $aUpdates[] = "`$sTable`.`archive_date` = $sDate"; } - } - else - { + } else { $sKey = MetaModel::DBGetKey($sParentClass); $aJoins[] = "`$sTable` ON `$sTable`.`$sKey` = `$sRootTable`.`$sRootKey`"; } @@ -6203,10 +5830,10 @@ abstract class DBObject implements iDisplay $this->FireEventArchive(); } - /** - * @throws Exception - * @uses DBWriteArchiveFlag - */ + /** + * @throws Exception + * @uses DBWriteArchiveFlag + */ public function DBUnarchive() { $this->DBWriteArchiveFlag(false); @@ -6217,21 +5844,19 @@ abstract class DBObject implements iDisplay $this->FireEventUnArchive(); } - - /** - * @internal - * - * @param string $sClass Needs to be an instanciable class - * - * @return DBObject - * @throws CoreException - * @throws CoreUnexpectedValue - */ + /** + * @internal + * + * @param string $sClass Needs to be an instanciable class + * + * @return DBObject + * @throws CoreException + * @throws CoreUnexpectedValue + */ public static function MakeDefaultInstance($sClass) { $oObj = MetaModel::NewObject($sClass); - if (MetaModel::HasLifecycle($sClass)) - { + if (MetaModel::HasLifecycle($sClass)) { $sStateAttCode = MetaModel::GetStateAttributeCode($sClass); $sTargetState = MetaModel::GetDefaultState($sClass); $oObj->Set($sStateAttCode, $sTargetState); @@ -6241,7 +5866,7 @@ abstract class DBObject implements iDisplay /** * Complete a new object with data from context - * + * * @overwritable-hook You can extend this method in order to provide your own logic. * * @see https://www.itophub.io/wiki/page?id=latest%3Acustomization%3Aform_prefill wiki tutorial @@ -6263,7 +5888,7 @@ abstract class DBObject implements iDisplay * Complete an object after a state transition with data from context * * @overwritable-hook You can extend this method in order to provide your own logic. - * + * * @see https://www.itophub.io/wiki/page?id=latest%3Acustomization%3Aform_prefill wiki tutorial * * @param array $aContextParam Context used for creation form prefilling. Contains those keys : @@ -6313,7 +5938,7 @@ abstract class DBObject implements iDisplay */ public function PrefillForm($sOperation, &$aContextParam) { - switch($sOperation){ + switch ($sOperation) { case 'creation_from_0': case 'creation_from_extkey': case 'creation_from_editinplace': @@ -6333,7 +5958,7 @@ abstract class DBObject implements iDisplay public function EvaluateExpression(Expression $oExpression) { $aFields = $oExpression->ListRequiredFields(); - $aArgs = array(); + $aArgs = []; foreach ($aFields as $sFieldDesc) { $aFieldParts = explode('.', $sFieldDesc); if (count($aFieldParts) == 2) { @@ -6496,7 +6121,7 @@ abstract class DBObject implements iDisplay return OPT_ATT_NORMAL; } - public final function GetListeners(): array + final public function GetListeners(): array { $aListeners = []; foreach ($this->aEventListeners as $aEventListener) { @@ -6522,12 +6147,12 @@ abstract class DBObject implements iDisplay { $aEventCallbacks = $this->aEventListeners[$sEvent] ?? []; - $aEventCallbacks[] = array( + $aEventCallbacks[] = [ 'event' => $sEvent, 'callback' => $callback, 'priority' => $fPriority, 'module' => $sModuleId, - ); + ]; usort($aEventCallbacks, function ($a, $b) { $fPriorityA = $a['priority']; $fPriorityB = $b['priority']; @@ -6550,7 +6175,7 @@ abstract class DBObject implements iDisplay * @throws \Exception * @since 3.1.0 */ - public function FireEvent(string $sEvent, array $aEventData = array()): void + public function FireEvent(string $sEvent, array $aEventData = []): void { $aEventData['debug_info'] = 'from: '.get_class($this).':'.$this->GetKey(); $aEventData['object'] = $this; @@ -6569,20 +6194,17 @@ abstract class DBObject implements iDisplay EventServiceLog::Debug("Fire event '$sEvent' calling '".get_class($this).":$sCallback'"); try { call_user_func([$this, $sCallback], new EventData($sEvent, null, $aEventData)); - } - catch (EventException $e) { + } catch (EventException $e) { EventServiceLog::Error("Event '$sEvent' for '$sCallback'} failed with blocking error: ".$e->getMessage()); throw $e; - } - catch (Exception $e) { + } catch (Exception $e) { $sMessage = "Event '$sEvent' for '$sCallback'} failed with non-blocking error: ".$e->getMessage(); EventServiceLog::Error($sMessage); if (is_null($oFirstException)) { $sFirstExceptionMessage = $sMessage; $oFirstException = $e; } - } - finally { + } finally { if (!$oKPI->ComputeStatsForExtension($this, $sCallback, "Event: $sEvent")) { $sSignature = ModuleService::GetInstance()->GetModuleMethodSignature($this, $sCallback); $oKPI->ComputeStats('FireEvent', "$sEvent callback: $sSignature"); @@ -6952,4 +6574,3 @@ abstract class DBObject implements iDisplay return array_key_exists($sSection, $this->aContext); } } - diff --git a/core/dbobjectsearch.class.php b/core/dbobjectsearch.class.php index 5f3ca1047..7e1ae9d8f 100644 --- a/core/dbobjectsearch.class.php +++ b/core/dbobjectsearch.class.php @@ -1,4 +1,5 @@ m_aSelectedClasses = array($sClassAlias => $sClass); - $this->m_aClasses = array($sClassAlias => $sClass); - $this->m_oSearchCondition = new TrueExpression; - $this->m_aParams = array(); - $this->m_aPointingTo = array(); - $this->m_aReferencedBy = array(); + $this->m_aSelectedClasses = [$sClassAlias => $sClass]; + $this->m_aClasses = [$sClassAlias => $sClass]; + $this->m_oSearchCondition = new TrueExpression(); + $this->m_aParams = []; + $this->m_aPointingTo = []; + $this->m_aReferencedBy = []; } - public function AllowAllData($bAllowAllData = true) { + public function AllowAllData($bAllowAllData = true) + { $this->m_bAllowAllData = $bAllowAllData; $this->m_oSearchCondition->Browse(function ($oThisExpression) use ($bAllowAllData) { @@ -76,32 +78,37 @@ class DBObjectSearch extends DBSearch }); } - public function IsAllDataAllowed() { + public function IsAllDataAllowed() + { return $this->m_bAllowAllData; } - protected function IsDataFiltered() { + protected function IsDataFiltered() + { return $this->m_bDataFiltered; } - protected function SetDataFiltered() { + protected function SetDataFiltered() + { $this->m_bDataFiltered = true; } // Create a search definition that leads to 0 result, still a valid search object - public static function FromEmptySet($sClass) { + public static function FromEmptySet($sClass) + { $oResultFilter = new DBObjectSearch($sClass); - $oResultFilter->m_oSearchCondition = new FalseExpression; + $oResultFilter->m_oSearchCondition = new FalseExpression(); return $oResultFilter; } - - public function GetJoinedClasses() { + public function GetJoinedClasses() + { return $this->m_aClasses; } - public function GetClassName($sAlias) { + public function GetClassName($sAlias) + { if (array_key_exists($sAlias, $this->m_aSelectedClasses)) { return $this->m_aSelectedClasses[$sAlias]; } else { @@ -140,26 +147,20 @@ class DBObjectSearch extends DBSearch */ public function ChangeClass($sNewClass, $sAlias = null) { - if (is_null($sAlias)) - { + if (is_null($sAlias)) { $sAlias = $this->GetClassAlias(); - } - else - { - if (!array_key_exists($sAlias, $this->m_aSelectedClasses)) - { + } else { + if (!array_key_exists($sAlias, $this->m_aSelectedClasses)) { // discard silently - necessary when recursing on the related nodes (see code below) return; } } $sCurrClass = $this->GetClassName($sAlias); - if ($sNewClass == $sCurrClass) - { + if ($sNewClass == $sCurrClass) { // Skip silently return; } - if (!MetaModel::IsParentClass($sCurrClass, $sNewClass)) - { + if (!MetaModel::IsParentClass($sCurrClass, $sNewClass)) { throw new Exception("Could not change the search class from '$sCurrClass' to '$sNewClass'. Only child classes are permitted."); } @@ -170,24 +171,17 @@ class DBObjectSearch extends DBSearch // Change for all the related node (yes, this was necessary with some queries - strange effects otherwise) // - foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo) - { - foreach($aPointingTo as $iOperatorCode => $aFilter) - { - foreach($aFilter as $oExtFilter) - { + foreach ($this->m_aPointingTo as $sExtKeyAttCode => $aPointingTo) { + foreach ($aPointingTo as $iOperatorCode => $aFilter) { + foreach ($aFilter as $oExtFilter) { $oExtFilter->ChangeClass($sNewClass, $sAlias); } } } - foreach($this->m_aReferencedBy as $sForeignClass => $aReferences) - { - foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) - { - foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) - { - foreach ($aFilters as $oForeignFilter) - { + foreach ($this->m_aReferencedBy as $sForeignClass => $aReferences) { + foreach ($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) { + foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) { + foreach ($aFilters as $oForeignFilter) { $oForeignFilter->ChangeClass($sNewClass, $sAlias); } } @@ -206,11 +200,9 @@ class DBObjectSearch extends DBSearch */ public function SetSelectedClasses($aSelectedClasses) { - $this->m_aSelectedClasses = array(); - foreach ($aSelectedClasses as $sAlias) - { - if (!array_key_exists($sAlias, $this->m_aClasses)) - { + $this->m_aSelectedClasses = []; + foreach ($aSelectedClasses as $sAlias) { + if (!array_key_exists($sAlias, $this->m_aClasses)) { throw new CoreException("SetSelectedClasses: Invalid class alias $sAlias"); } $this->m_aSelectedClasses[$sAlias] = $this->m_aClasses[$sAlias]; @@ -229,38 +221,28 @@ class DBObjectSearch extends DBSearch public function RenameAlias($sOldName, $sNewName) { $bFound = false; - if (!array_key_exists($sOldName, $this->m_aClasses)) - { + if (!array_key_exists($sOldName, $this->m_aClasses)) { return false; } - if (array_key_exists($sNewName, $this->m_aClasses)) - { + if (array_key_exists($sNewName, $this->m_aClasses)) { throw new Exception("RenameAlias: alias '$sNewName' already used"); } - $aClasses = array(); - foreach ($this->m_aClasses as $sAlias => $sClass) - { - if ($sAlias === $sOldName) - { + $aClasses = []; + foreach ($this->m_aClasses as $sAlias => $sClass) { + if ($sAlias === $sOldName) { $aClasses[$sNewName] = $sClass; - } - else - { + } else { $aClasses[$sAlias] = $sClass; } } $this->m_aClasses = $aClasses; - $aSelectedClasses = array(); - foreach ($this->m_aSelectedClasses as $sAlias => $sClass) - { - if ($sAlias === $sOldName) - { + $aSelectedClasses = []; + foreach ($this->m_aSelectedClasses as $sAlias => $sClass) { + if ($sAlias === $sOldName) { $aSelectedClasses[$sNewName] = $sClass; - } - else - { + } else { $aSelectedClasses[$sAlias] = $sClass; } } @@ -268,24 +250,17 @@ class DBObjectSearch extends DBSearch $this->m_oSearchCondition->RenameAlias($sOldName, $sNewName); - foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo) - { - foreach($aPointingTo as $iOperatorCode => $aFilter) - { - foreach($aFilter as $oExtFilter) - { + foreach ($this->m_aPointingTo as $sExtKeyAttCode => $aPointingTo) { + foreach ($aPointingTo as $iOperatorCode => $aFilter) { + foreach ($aFilter as $oExtFilter) { $bFound = $oExtFilter->RenameAlias($sOldName, $sNewName) || $bFound; } } } - foreach($this->m_aReferencedBy as $sForeignClass => $aReferences) - { - foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) - { - foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) - { - foreach ($aFilters as $oForeignFilter) - { + foreach ($this->m_aReferencedBy as $sForeignClass => $aReferences) { + foreach ($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) { + foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) { + foreach ($aFilters as $oForeignFilter) { $bFound = $oForeignFilter->RenameAlias($sOldName, $sNewName) || $bFound; } } @@ -301,21 +276,24 @@ class DBObjectSearch extends DBSearch public function GetModifierProperties($sPluginClass) { - if (array_key_exists($sPluginClass, $this->m_aModifierProperties)) - { + if (array_key_exists($sPluginClass, $this->m_aModifierProperties)) { return $this->m_aModifierProperties[$sPluginClass]; - } - else - { - return array(); + } else { + return []; } } public function IsAny() { - if (!$this->m_oSearchCondition->IsTrue()) return false; - if (count($this->m_aPointingTo) > 0) return false; - if (count($this->m_aReferencedBy) > 0) return false; + if (!$this->m_oSearchCondition->IsTrue()) { + return false; + } + if (count($this->m_aPointingTo) > 0) { + return false; + } + if (count($this->m_aReferencedBy) > 0) { + return false; + } return true; } @@ -327,14 +305,11 @@ class DBObjectSearch extends DBSearch protected function TransferConditionExpression($oFilter, $aTranslation) { // Prevent collisions in the parameter names by renaming them if needed - foreach($this->m_aParams as $sParam => $value) - { - if (array_key_exists($sParam, $oFilter->m_aParams) && ($value != $oFilter->m_aParams[$sParam])) - { + foreach ($this->m_aParams as $sParam => $value) { + if (array_key_exists($sParam, $oFilter->m_aParams) && ($value != $oFilter->m_aParams[$sParam])) { // Generate a new and unique name for the collinding parameter $index = 1; - while(array_key_exists($sParam.$index, $oFilter->m_aParams)) - { + while (array_key_exists($sParam.$index, $oFilter->m_aParams)) { $index++; } $secondValue = $oFilter->m_aParams[$sParam]; @@ -352,19 +327,15 @@ class DBObjectSearch extends DBSearch public function RenameParam($sOldName, $sNewName) { $this->m_oSearchCondition->RenameParam($sOldName, $sNewName); - foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo) - { - foreach($aPointingTo as $iOperatorCode => $aFilter) - { - foreach($aFilter as $oExtFilter) - { + foreach ($this->m_aPointingTo as $sExtKeyAttCode => $aPointingTo) { + foreach ($aPointingTo as $iOperatorCode => $aFilter) { + foreach ($aFilter as $oExtFilter) { $oExtFilter->RenameParam($sOldName, $sNewName); } } } - foreach($this->m_aReferencedBy as $sForeignClass => $aReferences) - { - foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) { + foreach ($this->m_aReferencedBy as $sForeignClass => $aReferences) { + foreach ($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) { foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) { foreach ($aFilters as $oForeignFilter) { $oForeignFilter->RenameParam($sOldName, $sNewName); @@ -374,16 +345,19 @@ class DBObjectSearch extends DBSearch } } - public function ResetCondition() { + public function ResetCondition() + { $this->m_oSearchCondition = new TrueExpression(); // ? is that usefull/enough, do I need to rebuild the list after the subqueries ? } - public function MergeConditionExpression($oExpression) { + public function MergeConditionExpression($oExpression) + { $this->m_oSearchCondition = $this->m_oSearchCondition->LogOr($oExpression); } - public function AddConditionExpression($oExpression) { + public function AddConditionExpression($oExpression) + { $this->m_oSearchCondition = $this->m_oSearchCondition->LogAnd($oExpression); $bRootSearchAllowAllData = $this->IsAllDataAllowed(); @@ -392,7 +366,8 @@ class DBObjectSearch extends DBSearch }); } - public function AddNameCondition($sName) { + public function AddNameCondition($sName) + { $oValueExpr = new ScalarExpression($sName); $oNameExpr = new FieldExpression('friendlyname', $this->GetClassAlias()); $oNewCondition = new BinaryExpression($oNameExpr, '=', $oValueExpr); @@ -417,15 +392,15 @@ class DBObjectSearch extends DBSearch */ public function AddCondition($sFilterCode, $value, $sOpCode = null, $bParseSearchString = false) { - if (MetaModel::IsValidFilterCode($this->GetClass(),$sFilterCode) == false){ - /* $sArrayDesc = if (count($aData) == 0) - { - $sArrayDesc = "{}"; - } - else - { - $sArrayDesc = "{".implode(", ", $aData)."}"; - }*/ + if (MetaModel::IsValidFilterCode($this->GetClass(), $sFilterCode) == false) { + /* $sArrayDesc = if (count($aData) == 0) + { + $sArrayDesc = "{}"; + } + else + { + $sArrayDesc = "{".implode(", ", $aData)."}"; + }*/ throw new CoreException("Wrong value for '".$this->GetClass()."', found '$sFilterCode'");// while expecting a value in $sArrayDesc"); } $oField = new FieldExpression($sFilterCode, $this->GetClassAlias()); @@ -440,81 +415,82 @@ class DBObjectSearch extends DBSearch } } // Parse search strings if needed and if the filter code corresponds to a valid attcode - if($bParseSearchString && MetaModel::IsValidAttCode($this->GetClass(), $sFilterCode)) - { + if ($bParseSearchString && MetaModel::IsValidAttCode($this->GetClass(), $sFilterCode)) { $oAttDef = MetaModel::GetAttributeDef($this->GetClass(), $sFilterCode); $value = $oAttDef->ParseSearchString($value); } // Preserve backward compatibility - quick n'dirty way to change that API semantic // - switch($sOpCode) - { - case 'SameDay': - case 'SameMonth': - case 'SameYear': - case 'Today': - case '>|': - case '<|': - case '=|': - throw new CoreException('Deprecated operator, please consider using OQL (SQL) expressions like "(TO_DAYS(NOW()) - TO_DAYS(x)) AS AgeDays"', array('operator' => $sOpCode)); + switch ($sOpCode) { + case 'SameDay': + case 'SameMonth': + case 'SameYear': + case 'Today': + case '>|': + case '<|': + case '=|': + throw new CoreException('Deprecated operator, please consider using OQL (SQL) expressions like "(TO_DAYS(NOW()) - TO_DAYS(x)) AS AgeDays"', ['operator' => $sOpCode]); - case 'IN': - if (!is_array($value)) $value = array($value); - if (count($value) === 0) throw new Exception('AddCondition '.$sOpCode.': Value cannot be an empty array.'); - $sListExpr = '('.implode(', ', CMDBSource::Quote($value)).')'; - $sOQLCondition = $oField->RenderExpression()." IN $sListExpr"; - break; - - case 'NOTIN': - if (!is_array($value)) $value = array($value); - if (count($value) === 0) throw new Exception('AddCondition '.$sOpCode.': Value cannot be an empty array.'); - $sListExpr = '('.implode(', ', CMDBSource::Quote($value)).')'; - $sOQLCondition = $oField->RenderExpression()." NOT IN $sListExpr"; - break; - - case 'Contains': - $this->m_aParams[$sFilterCode] = "%$value%"; - $sOperator = 'LIKE'; - break; - - case 'Begins with': - $this->m_aParams[$sFilterCode] = "$value%"; - $sOperator = 'LIKE'; - break; - - case 'Finishes with': - $this->m_aParams[$sFilterCode] = "%$value"; - $sOperator = 'LIKE'; - break; - - default: - if ($value === null) - { - switch ($sOpCode) - { - case '=': - $sOpCode = '*Expression*'; - $oExpression = new FunctionExpression('ISNULL', array($oField)); - break; - case '!=': - $sOpCode = '*Expression*'; - $oExpression = new FunctionExpression('ISNULL', array($oField)); - $oExpression = new BinaryExpression($oExpression, '=', new ScalarExpression(0)); - break; - default: - throw new Exception("AddCondition on null value: unsupported operator '$sOpCode''"); + case 'IN': + if (!is_array($value)) { + $value = [$value]; + } + if (count($value) === 0) { + throw new Exception('AddCondition '.$sOpCode.': Value cannot be an empty array.'); + } + $sListExpr = '('.implode(', ', CMDBSource::Quote($value)).')'; + $sOQLCondition = $oField->RenderExpression()." IN $sListExpr"; + break; + + case 'NOTIN': + if (!is_array($value)) { + $value = [$value]; + } + if (count($value) === 0) { + throw new Exception('AddCondition '.$sOpCode.': Value cannot be an empty array.'); + } + $sListExpr = '('.implode(', ', CMDBSource::Quote($value)).')'; + $sOQLCondition = $oField->RenderExpression()." NOT IN $sListExpr"; + break; + + case 'Contains': + $this->m_aParams[$sFilterCode] = "%$value%"; + $sOperator = 'LIKE'; + break; + + case 'Begins with': + $this->m_aParams[$sFilterCode] = "$value%"; + $sOperator = 'LIKE'; + break; + + case 'Finishes with': + $this->m_aParams[$sFilterCode] = "%$value"; + $sOperator = 'LIKE'; + break; + + default: + if ($value === null) { + switch ($sOpCode) { + case '=': + $sOpCode = '*Expression*'; + $oExpression = new FunctionExpression('ISNULL', [$oField]); + break; + case '!=': + $sOpCode = '*Expression*'; + $oExpression = new FunctionExpression('ISNULL', [$oField]); + $oExpression = new BinaryExpression($oExpression, '=', new ScalarExpression(0)); + break; + default: + throw new Exception("AddCondition on null value: unsupported operator '$sOpCode''"); + } + } else { + $this->m_aParams[$sFilterCode] = $value; + $sOperator = $sOpCode; } - } - else - { - $this->m_aParams[$sFilterCode] = $value; - $sOperator = $sOpCode; - } } - switch($sOpCode) - { + switch ($sOpCode) { case '*Expression*': $oNewCondition = $oExpression; break; @@ -562,7 +538,7 @@ class DBObjectSearch extends DBSearch $oParamExpression = new VariableExpression($sInParamName); $this->GetInternalParamsByRef()[$sInParamName] = $aValues; - $oListExpression = new ListExpression(array($oParamExpression)); + $oListExpression = new ListExpression([$oParamExpression]); $oInCondition = new BinaryExpression($oFieldExpression, $sOperator, $oListExpression); $this->AddConditionExpression($oInCondition); @@ -582,19 +558,16 @@ class DBObjectSearch extends DBSearch $sClass = $this->GetClass(); $iPos = strpos($sAttSpec, '->'); - if ($iPos !== false) - { + if ($iPos !== false) { $sAttCode = substr($sAttSpec, 0, $iPos); $sSubSpec = substr($sAttSpec, $iPos + 2); - if (!MetaModel::IsValidAttCode($sClass, $sAttCode)) - { + if (!MetaModel::IsValidAttCode($sClass, $sAttCode)) { throw new Exception("Invalid attribute code '$sClass/$sAttCode' in condition specification '$sAttSpec'"); } $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode); - if ($oAttDef->IsLinkSet()) - { + if ($oAttDef->IsLinkSet()) { $sTargetClass = $oAttDef->GetLinkedClass(); $sExtKeyToMe = $oAttDef->GetExtKeyToMe(); @@ -602,35 +575,26 @@ class DBObjectSearch extends DBSearch $oNewFilter->AddConditionAdvanced($sSubSpec, $value); $this->AddCondition_ReferencedBy($oNewFilter, $sExtKeyToMe); - } - elseif ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) - { + } elseif ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) { $sTargetClass = $oAttDef->GetTargetClass(EXTKEY_ABSOLUTE); $oNewFilter = new DBObjectSearch($sTargetClass); $oNewFilter->AddConditionAdvanced($sSubSpec, $value); $this->AddCondition_PointingTo($oNewFilter, $sAttCode); - } - else - { + } else { throw new Exception("Attribute specification '$sAttSpec', '$sAttCode' should be either a link set or an external key"); } - } - else - { + } else { // $sAttSpec is an attribute code // - if (is_array($value)) - { + if (is_array($value)) { $oField = new FieldExpression($sAttSpec, $this->GetClass()); $oListExpr = ListExpression::FromScalars($value); $oInValues = new BinaryExpression($oField, 'IN', $oListExpr); $this->AddConditionExpression($oInValues); - } - else - { + } else { $this->AddCondition($sAttSpec, $value); } } @@ -641,9 +605,15 @@ class DBObjectSearch extends DBSearch // Transform the full text condition into additional condition expression $aAttCodes = []; foreach (MetaModel::ListAttributeDefs($this->GetClass()) as $sAttCode => $oAttDef) { - if (!$oAttDef->IsScalar()) continue; - if ($oAttDef->IsExternalKey()) continue; - if (!$oAttDef->IsSearchable()) continue; + if (!$oAttDef->IsScalar()) { + continue; + } + if ($oAttDef->IsExternalKey()) { + continue; + } + if (!$oAttDef->IsSearchable()) { + continue; + } $aAttCodes[] = $sAttCode; } $this->AddCondition_FullTextOnAttributes($aAttCodes, $sNeedle); @@ -665,7 +635,7 @@ class DBObjectSearch extends DBSearch $oTextFields = new CharConcatWSExpression(' ', $aFullTextFields); $sQueryParam = str_replace('.', '', uniqid('needle_', true)); - $oFlexNeedle = new CharConcatExpression(array(new ScalarExpression('%'), new VariableExpression($sQueryParam), new ScalarExpression('%'))); + $oFlexNeedle = new CharConcatExpression([new ScalarExpression('%'), new VariableExpression($sQueryParam), new ScalarExpression('%')]); $oNewCond = new BinaryExpression($oTextFields, 'LIKE', $oFlexNeedle); $this->AddConditionExpression($oNewCond); @@ -677,14 +647,11 @@ class DBObjectSearch extends DBSearch protected function AddToNameSpace(&$aClassAliases, &$aAliasTranslation, $bTranslateMainAlias = true) { - if ($bTranslateMainAlias) - { + if ($bTranslateMainAlias) { $sOrigAlias = $this->GetFirstJoinedClassAlias(); - if (array_key_exists($sOrigAlias, $aClassAliases)) - { + if (array_key_exists($sOrigAlias, $aClassAliases)) { $sNewAlias = MetaModel::GenerateUniqueAlias($aClassAliases, $sOrigAlias, $this->GetFirstJoinedClass()); - if (isset($this->m_aSelectedClasses[$sOrigAlias])) - { + if (isset($this->m_aSelectedClasses[$sOrigAlias])) { $this->m_aSelectedClasses[$sNewAlias] = $this->GetFirstJoinedClass(); unset($this->m_aSelectedClasses[$sOrigAlias]); } @@ -692,46 +659,35 @@ class DBObjectSearch extends DBSearch // TEMPORARY ALGORITHM (m_aClasses is not correctly updated, it is not possible to add a subtree onto a subnode) // Replace the element at the same position (unset + set is not enough because the hash array is ordered) $aPrevList = $this->m_aClasses; - $this->m_aClasses = array(); - foreach ($aPrevList as $sSomeAlias => $sSomeClass) - { - if ($sSomeAlias == $sOrigAlias) - { + $this->m_aClasses = []; + foreach ($aPrevList as $sSomeAlias => $sSomeClass) { + if ($sSomeAlias == $sOrigAlias) { $this->m_aClasses[$sNewAlias] = $sSomeClass; // note: GetFirstJoinedClass now returns '' !!! - } - else - { + } else { $this->m_aClasses[$sSomeAlias] = $sSomeClass; } } - + // Translate the condition expression with the new alias $aAliasTranslation[$sOrigAlias]['*'] = $sNewAlias; } - + // add the alias into the filter aliases list $aClassAliases[$this->GetFirstJoinedClassAlias()] = $this->GetFirstJoinedClass(); } - - foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo) - { - foreach($aPointingTo as $iOperatorCode => $aFilter) - { - foreach($aFilter as $oFilter) - { + + foreach ($this->m_aPointingTo as $sExtKeyAttCode => $aPointingTo) { + foreach ($aPointingTo as $iOperatorCode => $aFilter) { + foreach ($aFilter as $oFilter) { $oFilter->AddToNameSpace($aClassAliases, $aAliasTranslation); } } } - foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences) - { - foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) - { - foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) - { - foreach ($aFilters as $oForeignFilter) - { + foreach ($this->m_aReferencedBy as $sForeignClass => $aReferences) { + foreach ($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) { + foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) { + foreach ($aFilters as $oForeignFilter) { $oForeignFilter->AddToNameSpace($aClassAliases, $aAliasTranslation); } } @@ -745,18 +701,17 @@ class DBObjectSearch extends DBSearch * @param array $aClassAliases array of alias => class for the main query * @param array $aAliasTranslation translation table of main query to apply to nested queries */ - public function RenameNestedQueriesAliasesInNameSpace($aClassAliases, $aAliasTranslation = array()) + public function RenameNestedQueriesAliasesInNameSpace($aClassAliases, $aAliasTranslation = []) { $this->GetCriteria()->Browse(function ($oNode) use ($aClassAliases, $aAliasTranslation) { - if ($oNode instanceof NestedQueryExpression) - { + if ($oNode instanceof NestedQueryExpression) { $oNestedQuery = $oNode->GetNestedQuery(); $oNestedQuery->RenameAliasesInNameSpace($aClassAliases, $aAliasTranslation); } }); } - public function RenameAliasesInNameSpace($aClassAliases, $aAliasTranslation = array()) + public function RenameAliasesInNameSpace($aClassAliases, $aAliasTranslation = []) { // Recurse in nested queries $this->RenameNestedQueriesAliasesInNameSpace($aClassAliases, $aAliasTranslation); @@ -775,37 +730,25 @@ class DBObjectSearch extends DBSearch // protected function GetNode($sAlias) { - if ($this->GetFirstJoinedClassAlias() == $sAlias) - { + if ($this->GetFirstJoinedClassAlias() == $sAlias) { return $this; - } - else - { - foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo) - { - foreach($aPointingTo as $iOperatorCode => $aFilter) - { - foreach($aFilter as $oFilter) - { + } else { + foreach ($this->m_aPointingTo as $sExtKeyAttCode => $aPointingTo) { + foreach ($aPointingTo as $iOperatorCode => $aFilter) { + foreach ($aFilter as $oFilter) { $ret = $oFilter->GetNode($sAlias); - if (is_object($ret)) - { + if (is_object($ret)) { return $ret; } } } } - foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences) - { - foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) - { - foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) - { - foreach ($aFilters as $oForeignFilter) - { + foreach ($this->m_aReferencedBy as $sForeignClass => $aReferences) { + foreach ($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) { + foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) { + foreach ($aFilters as $oForeignFilter) { $ret = $oForeignFilter->GetNode($sAlias); - if (is_object($ret)) - { + if (is_object($ret)) { return $ret; } } @@ -829,36 +772,27 @@ class DBObjectSearch extends DBSearch */ protected function UpdateRealiasingMap(&$aRealiasingMap, $aAliasTranslation) { - if ($aRealiasingMap !== null) - { - foreach ($aAliasTranslation as $sPrevAlias => $aRules) - { - if (!isset($aRules['*'])) - { + if ($aRealiasingMap !== null) { + foreach ($aAliasTranslation as $sPrevAlias => $aRules) { + if (!isset($aRules['*'])) { continue; } $sNewAlias = $aRules['*']; $bOriginalFound = false; $iIndex = 0; - foreach ($aRealiasingMap as $sOriginalAlias => $aAliases) - { + foreach ($aRealiasingMap as $sOriginalAlias => $aAliases) { $iIndex = array_search($sPrevAlias, $aAliases); - if ($iIndex !== false) - { + if ($iIndex !== false) { $bOriginalFound = true; break; } } - if ($bOriginalFound) - { + if ($bOriginalFound) { $aRealiasingMap[$sOriginalAlias][$iIndex] = $sNewAlias; - } - else - { - if (!isset($aRealiasingMap[$sPrevAlias]) || !in_array($sNewAlias, $aRealiasingMap[$sPrevAlias])) - { + } else { + if (!isset($aRealiasingMap[$sPrevAlias]) || !in_array($sNewAlias, $aRealiasingMap[$sPrevAlias])) { $aRealiasingMap[$sPrevAlias][] = $sNewAlias; } } @@ -878,25 +812,18 @@ class DBObjectSearch extends DBSearch $aClasses[$this->GetFirstJoinedClassAlias()] = $this->GetFirstJoinedClass(); // Recurse in the query tree - foreach($this->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo) - { - foreach($aPointingTo as $iOperatorCode => $aFilter) - { - foreach($aFilter as $oFilter) - { + foreach ($this->m_aPointingTo as $sExtKeyAttCode => $aPointingTo) { + foreach ($aPointingTo as $iOperatorCode => $aFilter) { + foreach ($aFilter as $oFilter) { $oFilter->RecomputeClassList($aClasses); } } } - foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences) - { - foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) - { - foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) - { - foreach ($aFilters as $oForeignFilter) - { + foreach ($this->m_aReferencedBy as $sForeignClass => $aReferences) { + foreach ($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) { + foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) { + foreach ($aFilters as $oForeignFilter) { $oForeignFilter->RecomputeClassList($aClasses); } } @@ -918,40 +845,33 @@ class DBObjectSearch extends DBSearch */ public function AddCondition_PointingTo(DBObjectSearch $oFilter, $sExtKeyAttCode, $iOperatorCode = TREE_OPERATOR_EQUALS, &$aRealiasingMap = null) { - if (!MetaModel::IsValidKeyAttCode($this->GetClass(), $sExtKeyAttCode)) - { + if (!MetaModel::IsValidKeyAttCode($this->GetClass(), $sExtKeyAttCode)) { throw new CoreWarning("The attribute code '$sExtKeyAttCode' is not an external key of the class '{$this->GetClass()}'"); } $oAttExtKey = MetaModel::GetAttributeDef($this->GetClass(), $sExtKeyAttCode); - if(!MetaModel::IsSameFamilyBranch($oFilter->GetClass(), $oAttExtKey->GetTargetClass())) - { + if (!MetaModel::IsSameFamilyBranch($oFilter->GetClass(), $oAttExtKey->GetTargetClass())) { throw new CoreException("The specified filter (pointing to {$oFilter->GetClass()}) is not compatible with the key '{$this->GetClass()}::$sExtKeyAttCode', which is pointing to {$oAttExtKey->GetTargetClass()}"); } - if(($iOperatorCode != TREE_OPERATOR_EQUALS) && !($oAttExtKey instanceof AttributeHierarchicalKey)) - { + if (($iOperatorCode != TREE_OPERATOR_EQUALS) && !($oAttExtKey instanceof AttributeHierarchicalKey)) { throw new CoreException("The specified tree operator $iOperatorCode is not applicable to the key '{$this->GetClass()}::$sExtKeyAttCode', which is not a HierarchicalKey"); } // Note: though it seems to be a good practice to clone the given source filter // (as it was done and fixed an issue in Intersect()) // this was not implemented here because it was causing a regression (login as admin, select an org, click on any badge) - // root cause: FromOQL relies on the fact that the passed filter can be modified later + // root cause: FromOQL relies on the fact that the passed filter can be modified later // NO: $oFilter = $oFilter->DeepClone(); // See also: Trac #639, and self::AddCondition_ReferencedBy() - $aAliasTranslation = array(); + $aAliasTranslation = []; $res = $this->AddCondition_PointingTo_InNameSpace($oFilter, $sExtKeyAttCode, $this->m_aClasses, $aAliasTranslation, $iOperatorCode); $this->TransferConditionExpression($oFilter, $aAliasTranslation); $this->UpdateRealiasingMap($aRealiasingMap, $aAliasTranslation); - if (ENABLE_OPT && ($oFilter->GetClass() == $oFilter->GetFirstJoinedClass())) - { - if (isset($oFilter->m_aReferencedBy[$this->GetClass()][$sExtKeyAttCode][$iOperatorCode])) - { - foreach ($oFilter->m_aReferencedBy[$this->GetClass()][$sExtKeyAttCode][$iOperatorCode] as $oRemoteFilter) - { - if ($this->GetClass() == $oRemoteFilter->GetClass()) - { + if (ENABLE_OPT && ($oFilter->GetClass() == $oFilter->GetFirstJoinedClass())) { + if (isset($oFilter->m_aReferencedBy[$this->GetClass()][$sExtKeyAttCode][$iOperatorCode])) { + foreach ($oFilter->m_aReferencedBy[$this->GetClass()][$sExtKeyAttCode][$iOperatorCode] as $oRemoteFilter) { + if ($this->GetClass() == $oRemoteFilter->GetClass()) { // Optimization - fold sibling query - $aAliasTranslation = array(); + $aAliasTranslation = []; $this->MergeWith_InNamespace($oRemoteFilter, $this->m_aClasses, $aAliasTranslation); unset($oFilter->m_aReferencedBy[$this->GetClass()][$sExtKeyAttCode][$iOperatorCode]); $this->m_oSearchCondition = $this->m_oSearchCondition->Translate($aAliasTranslation, false, false); @@ -980,21 +900,17 @@ class DBObjectSearch extends DBSearch $oReceivingFilter = $this->GetNode($this->GetClassAlias()); $bMerged = false; - if (ENABLE_OPT && isset($oReceivingFilter->m_aPointingTo[$sExtKeyAttCode][$iOperatorCode])) - { - foreach ($oReceivingFilter->m_aPointingTo[$sExtKeyAttCode][$iOperatorCode] as $oExisting) - { + if (ENABLE_OPT && isset($oReceivingFilter->m_aPointingTo[$sExtKeyAttCode][$iOperatorCode])) { + foreach ($oReceivingFilter->m_aPointingTo[$sExtKeyAttCode][$iOperatorCode] as $oExisting) { /** @var DBObjectSearch $oExisting */ - if ($oExisting->GetClass() == $oFilter->GetClass()) - { + if ($oExisting->GetClass() == $oFilter->GetClass()) { $oExisting->MergeWith_InNamespace($oFilter, $aClassAliases, $aAliasTranslation); $bMerged = true; break; } } } - if (!$bMerged) - { + if (!$bMerged) { $oFilter->AddToNamespace($aClassAliases, $aAliasTranslation); $oReceivingFilter->m_aPointingTo[$sExtKeyAttCode][$iOperatorCode][] = $oFilter; } @@ -1011,13 +927,11 @@ class DBObjectSearch extends DBSearch public function AddCondition_ReferencedBy(DBObjectSearch $oFilter, $sForeignExtKeyAttCode, $iOperatorCode = TREE_OPERATOR_EQUALS, &$aRealiasingMap = null) { $sForeignClass = $oFilter->GetClass(); - if (!MetaModel::IsValidKeyAttCode($sForeignClass, $sForeignExtKeyAttCode)) - { + if (!MetaModel::IsValidKeyAttCode($sForeignClass, $sForeignExtKeyAttCode)) { throw new CoreException("The attribute code '$sForeignExtKeyAttCode' is not an external key of the class '{$sForeignClass}'"); } $oAttExtKey = MetaModel::GetAttributeDef($sForeignClass, $sForeignExtKeyAttCode); - if(!MetaModel::IsSameFamilyBranch($this->GetClass(), $oAttExtKey->GetTargetClass())) - { + if (!MetaModel::IsSameFamilyBranch($this->GetClass(), $oAttExtKey->GetTargetClass())) { // à refaire en spécifique dans FromOQL throw new CoreException("The specified filter (objects referencing an object of class {$this->GetClass()}) is not compatible with the key '{$sForeignClass}::$sForeignExtKeyAttCode', which is pointing to {$oAttExtKey->GetTargetClass()}"); } @@ -1025,24 +939,20 @@ class DBObjectSearch extends DBSearch // Note: though it seems to be a good practice to clone the given source filter // (as it was done and fixed an issue in Intersect()) // this was not implemented here because it was causing a regression (login as admin, select an org, click on any badge) - // root cause: FromOQL relies on the fact that the passed filter can be modified later + // root cause: FromOQL relies on the fact that the passed filter can be modified later // NO: $oFilter = $oFilter->DeepClone(); // See also: Trac #639, and self::AddCondition_PointingTo() - $aAliasTranslation = array(); + $aAliasTranslation = []; $this->AddCondition_ReferencedBy_InNameSpace($oFilter, $sForeignExtKeyAttCode, $this->m_aClasses, $aAliasTranslation, $iOperatorCode); $this->TransferConditionExpression($oFilter, $aAliasTranslation); $this->UpdateRealiasingMap($aRealiasingMap, $aAliasTranslation); - if (ENABLE_OPT && ($oFilter->GetClass() == $oFilter->GetFirstJoinedClass())) - { - if (isset($oFilter->m_aPointingTo[$sForeignExtKeyAttCode][$iOperatorCode])) - { - foreach ($oFilter->m_aPointingTo[$sForeignExtKeyAttCode][$iOperatorCode] as $oRemoteFilter) - { - if ($this->GetClass() == $oRemoteFilter->GetClass()) - { + if (ENABLE_OPT && ($oFilter->GetClass() == $oFilter->GetFirstJoinedClass())) { + if (isset($oFilter->m_aPointingTo[$sForeignExtKeyAttCode][$iOperatorCode])) { + foreach ($oFilter->m_aPointingTo[$sForeignExtKeyAttCode][$iOperatorCode] as $oRemoteFilter) { + if ($this->GetClass() == $oRemoteFilter->GetClass()) { // Optimization - fold sibling query - $aAliasTranslation = array(); + $aAliasTranslation = []; $this->MergeWith_InNamespace($oRemoteFilter, $this->m_aClasses, $aAliasTranslation); unset($oFilter->m_aPointingTo[$sForeignExtKeyAttCode][$iOperatorCode]); $this->m_oSearchCondition = $this->m_oSearchCondition->Translate($aAliasTranslation, false, false); @@ -1063,20 +973,16 @@ class DBObjectSearch extends DBSearch $oReceivingFilter = $this->GetNode($this->GetClassAlias()); $bMerged = false; - if (ENABLE_OPT && isset($oReceivingFilter->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode][$iOperatorCode])) - { - foreach ($oReceivingFilter->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode][$iOperatorCode] as $oExisting) - { - if ($oExisting->GetClass() == $oFilter->GetClass()) - { + if (ENABLE_OPT && isset($oReceivingFilter->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode][$iOperatorCode])) { + foreach ($oReceivingFilter->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode][$iOperatorCode] as $oExisting) { + if ($oExisting->GetClass() == $oFilter->GetClass()) { $oExisting->MergeWith_InNamespace($oFilter, $aClassAliases, $aAliasTranslation); $bMerged = true; break; } } } - if (!$bMerged) - { + if (!$bMerged) { $oFilter->AddToNamespace($aClassAliases, $aAliasTranslation); $oReceivingFilter->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode][$iOperatorCode][] = $oFilter; } @@ -1144,23 +1050,18 @@ class DBObjectSearch extends DBSearch */ private static function FilterSubClass(DBObjectSearch &$oSearch, $sClassAlias, DBSearch $oFilter, $aRootClasses) { - if (($oSearch->GetFirstJoinedClassAlias() == $sClassAlias)) - { + if (($oSearch->GetFirstJoinedClassAlias() == $sClassAlias)) { $oSearch = $oSearch->IntersectSubClass($oFilter, $aRootClasses); return $oSearch->GetCriteria(); } /** @var Expression $oFilterExpression */ // Search in the filter tree where is the correct DBSearch - foreach ($oSearch->m_aPointingTo as $sExtKey => $aPointingTo) - { - foreach ($aPointingTo as $iOperatorCode => $aFilters) - { - foreach ($aFilters as $index => $oExtFilter) - { + foreach ($oSearch->m_aPointingTo as $sExtKey => $aPointingTo) { + foreach ($aPointingTo as $iOperatorCode => $aFilters) { + foreach ($aFilters as $index => $oExtFilter) { $oFilterExpression = self::FilterSubClass($oExtFilter, $sClassAlias, $oFilter, $aRootClasses); - if ($oFilterExpression !== false) - { + if ($oFilterExpression !== false) { $oSearch->m_aPointingTo[$sExtKey][$iOperatorCode][$index] = $oExtFilter; return $oFilterExpression; } @@ -1168,17 +1069,12 @@ class DBObjectSearch extends DBSearch } } - foreach($oSearch->m_aReferencedBy as $sForeignClass => $aReferences) - { - foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) - { - foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) - { - foreach ($aFilters as $index => $oForeignFilter) - { + foreach ($oSearch->m_aReferencedBy as $sForeignClass => $aReferences) { + foreach ($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) { + foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) { + foreach ($aFilters as $index => $oForeignFilter) { $oFilterExpression = self::FilterSubClass($oForeignFilter, $sClassAlias, $oFilter, $aRootClasses); - if ($oFilterExpression !== false) - { + if ($oFilterExpression !== false) { $oSearch->m_aReferencedBy[$sForeignClass][$sForeignExtKeyAttCode][$iOperatorCode][$index] = $oForeignFilter; return $oFilterExpression; } @@ -1196,24 +1092,19 @@ class DBObjectSearch extends DBSearch */ public function Intersect(DBSearch $oFilter) { - if ($oFilter instanceof DBUnionSearch) - { + if ($oFilter instanceof DBUnionSearch) { // Develop! $aFilters = $oFilter->GetSearches(); - } - else - { - $aFilters = array($oFilter); + } else { + $aFilters = [$oFilter]; } - $aSearches = array(); - foreach ($aFilters as $oRightFilter) - { + $aSearches = []; + foreach ($aFilters as $oRightFilter) { $aSearches[] = $this->IntersectSubClass($oRightFilter, $this->m_aClasses); } - if (count($aSearches) == 1) - { + if (count($aSearches) == 1) { // return a DBObjectSearch return $aSearches[0]; } @@ -1257,7 +1148,7 @@ class DBObjectSearch extends DBSearch } } - $aAliasTranslation = array(); + $aAliasTranslation = []; $oLeftFilter->RenameNestedQueriesAliasesInNameSpace($aRootClasses, $aAliasTranslation); $oLeftFilter->MergeWith_InNamespace($oRightFilter, $aRootClasses, $aAliasTranslation); $oRightFilter->RenameNestedQueriesAliasesInNameSpace($aRootClasses, $aAliasTranslation); @@ -1275,32 +1166,24 @@ class DBObjectSearch extends DBSearch */ protected function MergeWith_InNamespace($oFilter, &$aClassAliases, &$aAliasTranslation) { - if ($this->GetFirstJoinedClass() != $oFilter->GetClass()) - { + if ($this->GetFirstJoinedClass() != $oFilter->GetClass()) { throw new CoreException("Attempting to merge a filter of class '{$this->GetFirstJoinedClass()}' with a filter of class '{$oFilter->GetClass()}'"); } // Translate search condition into our aliasing scheme $aAliasTranslation[$oFilter->GetClassAlias()]['*'] = $this->GetFirstJoinedClassAlias(); - foreach($oFilter->m_aPointingTo as $sExtKeyAttCode=>$aPointingTo) - { - foreach($aPointingTo as $iOperatorCode => $aFilter) - { - foreach($aFilter as $oExtFilter) - { + foreach ($oFilter->m_aPointingTo as $sExtKeyAttCode => $aPointingTo) { + foreach ($aPointingTo as $iOperatorCode => $aFilter) { + foreach ($aFilter as $oExtFilter) { $this->AddCondition_PointingTo_InNamespace($oExtFilter, $sExtKeyAttCode, $aClassAliases, $aAliasTranslation, $iOperatorCode); } } } - foreach($oFilter->m_aReferencedBy as $sForeignClass => $aReferences) - { - foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) - { - foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) - { - foreach ($aFilters as $oForeignFilter) - { + foreach ($oFilter->m_aReferencedBy as $sForeignClass => $aReferences) { + foreach ($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) { + foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) { + foreach ($aFilters as $oForeignFilter) { $this->AddCondition_ReferencedBy_InNamespace($oForeignFilter, $sForeignExtKeyAttCode, $aClassAliases, $aAliasTranslation, $iOperatorCode); } } @@ -1308,15 +1191,22 @@ class DBObjectSearch extends DBSearch } } - public function GetCriteria() {return $this->m_oSearchCondition;} - public function GetCriteria_FullText() {throw new Exception("Removed GetCriteria_FullText");} + public function GetCriteria() + { + return $this->m_oSearchCondition; + } + public function GetCriteria_FullText() + { + throw new Exception("Removed GetCriteria_FullText"); + } public function GetCriteria_PointingTo($sKeyAttCode = "") { - if (empty($sKeyAttCode)) - { + if (empty($sKeyAttCode)) { return $this->m_aPointingTo; } - if (!array_key_exists($sKeyAttCode, $this->m_aPointingTo)) return array(); + if (!array_key_exists($sKeyAttCode, $this->m_aPointingTo)) { + return []; + } return $this->m_aPointingTo[$sKeyAttCode]; } @@ -1362,10 +1252,8 @@ class DBObjectSearch extends DBSearch */ public function AddInternalParam($sKey, $value, $bDoNotOverride = false) { - if ($bDoNotOverride) - { - if (array_key_exists($sKey, $this->m_aParams)) - { + if ($bDoNotOverride) { + if (array_key_exists($sKey, $this->m_aParams)) { throw new CoreUnexpectedValue("The key $sKey already exists with value : ".$this->m_aParams[$sKey]); } } @@ -1375,38 +1263,29 @@ class DBObjectSearch extends DBSearch public function GetQueryParams() { - $aParams = array(); + $aParams = []; $this->m_oSearchCondition->RenderExpression(false, $aParams, true); - $aRet = array(); + $aRet = []; // Make the list of acceptable arguments... could be factorized with run_query, into oSearch->GetQueryParams() - $aNakedMagicArguments = array(); - foreach (MetaModel::PrepareQueryArguments(array(),array(), $this->GetExpectedArguments()) as $sArgName => $value) - { + $aNakedMagicArguments = []; + foreach (MetaModel::PrepareQueryArguments([], [], $this->GetExpectedArguments()) as $sArgName => $value) { $iPos = strpos($sArgName, '->object()'); - if ($iPos === false) - { + if ($iPos === false) { $aNakedMagicArguments[$sArgName] = $value; - } - else - { + } else { $aNakedMagicArguments[substr($sArgName, 0, $iPos)] = true; } } - foreach ($aParams as $sParam => $foo) - { + foreach ($aParams as $sParam => $foo) { $iPos = strpos($sParam, '->'); - if ($iPos === false) - { + if ($iPos === false) { $sRefName = $sParam; - } - else - { + } else { $sRefName = substr($sParam, 0, $iPos); } - if (!array_key_exists($sRefName, $aNakedMagicArguments)) - { + if (!array_key_exists($sRefName, $aNakedMagicArguments)) { $aRet[$sParam] = $foo; } } @@ -1428,44 +1307,36 @@ class DBObjectSearch extends DBSearch { $this->m_oSearchCondition->ApplyParameters(array_merge($this->m_aParams, $aArgs)); } - + public function ToOQL($bDevelopParams = false, $aContextParams = null, $bWithAllowAllFlag = false) { // Currently unused, but could be useful later $bRetrofitParams = false; - if ($bDevelopParams) - { - if (is_null($aContextParams)) - { + if ($bDevelopParams) { + if (is_null($aContextParams)) { $aParams = array_merge($this->m_aParams); - } - else - { + } else { $aParams = array_merge($aContextParams, $this->m_aParams); } - $aParams = MetaModel::PrepareQueryArguments($aParams,array(), $this->GetExpectedArguments()); - } - else - { + $aParams = MetaModel::PrepareQueryArguments($aParams, [], $this->GetExpectedArguments()); + } else { // Leave it as is, the rendering will be made with parameters in clear $aParams = null; } - $aSelectedAliases = array(); - foreach ($this->m_aSelectedClasses as $sAlias => $sClass) - { - $aSelectedAliases[] = '`' . $sAlias . '`'; + $aSelectedAliases = []; + foreach ($this->m_aSelectedClasses as $sAlias => $sClass) { + $aSelectedAliases[] = '`'.$sAlias.'`'; } $sSelectedClasses = implode(', ', $aSelectedAliases); $sRes = 'SELECT '.$sSelectedClasses.' FROM'; - $sRes .= ' ' . $this->GetFirstJoinedClass() . ' AS `' . $this->GetFirstJoinedClassAlias() . '`'; + $sRes .= ' '.$this->GetFirstJoinedClass().' AS `'.$this->GetFirstJoinedClassAlias().'`'; $sRes .= $this->ToOQL_Joins(); $sRes .= " WHERE ".$this->m_oSearchCondition->RenderExpression(false, $aParams, $bRetrofitParams); - if ($bWithAllowAllFlag && $this->m_bAllowAllData) - { + if ($bWithAllowAllFlag && $this->m_bAllowAllData) { $sRes .= " ALLOW ALL DATA"; } return $sRes; @@ -1473,8 +1344,7 @@ class DBObjectSearch extends DBSearch protected function OperatorCodeToOQL($iOperatorCode) { - switch($iOperatorCode) - { + switch ($iOperatorCode) { case TREE_OPERATOR_EQUALS: $sOperator = ' = '; break; @@ -1518,28 +1388,21 @@ class DBObjectSearch extends DBSearch protected function ToOQL_Joins() { $sRes = ''; - foreach($this->m_aPointingTo as $sExtKey => $aPointingTo) - { - foreach($aPointingTo as $iOperatorCode => $aFilter) - { + foreach ($this->m_aPointingTo as $sExtKey => $aPointingTo) { + foreach ($aPointingTo as $iOperatorCode => $aFilter) { $sOperator = $this->OperatorCodeToOQL($iOperatorCode); - foreach($aFilter as $oFilter) - { - $sRes .= ' JOIN ' . $oFilter->GetFirstJoinedClass() . ' AS `' . $oFilter->GetFirstJoinedClassAlias() . '` ON `' . $this->GetFirstJoinedClassAlias() . '`.' . $sExtKey . $sOperator . '`' . $oFilter->GetFirstJoinedClassAlias() . '`.id'; - $sRes .= $oFilter->ToOQL_Joins(); + foreach ($aFilter as $oFilter) { + $sRes .= ' JOIN '.$oFilter->GetFirstJoinedClass().' AS `'.$oFilter->GetFirstJoinedClassAlias().'` ON `'.$this->GetFirstJoinedClassAlias().'`.'.$sExtKey.$sOperator.'`'.$oFilter->GetFirstJoinedClassAlias().'`.id'; + $sRes .= $oFilter->ToOQL_Joins(); } } } - foreach($this->m_aReferencedBy as $sForeignClass=>$aReferences) - { - foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) - { - foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) - { + foreach ($this->m_aReferencedBy as $sForeignClass => $aReferences) { + foreach ($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) { + foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) { $sOperator = $this->OperatorCodeToOQL($iOperatorCode); - foreach ($aFilters as $oForeignFilter) - { - $sRes .= ' JOIN ' . $oForeignFilter->GetFirstJoinedClass() . ' AS `' . $oForeignFilter->GetFirstJoinedClassAlias() . '` ON `' . $oForeignFilter->GetFirstJoinedClassAlias() . '`.' . $sForeignExtKeyAttCode . $sOperator . '`' . $this->GetFirstJoinedClassAlias() . '`.id'; + foreach ($aFilters as $oForeignFilter) { + $sRes .= ' JOIN '.$oForeignFilter->GetFirstJoinedClass().' AS `'.$oForeignFilter->GetFirstJoinedClassAlias().'` ON `'.$oForeignFilter->GetFirstJoinedClassAlias().'`.'.$sForeignExtKeyAttCode.$sOperator.'`'.$this->GetFirstJoinedClassAlias().'`.id'; $sRes .= $oForeignFilter->ToOQL_Joins(); } } @@ -1550,81 +1413,55 @@ class DBObjectSearch extends DBSearch protected function OQLExpressionToCondition($sQuery, $oExpression, $aClassAliases) { - if ($oExpression instanceof BinaryOqlExpression) - { + if ($oExpression instanceof BinaryOqlExpression) { $sOperator = $oExpression->GetOperator(); $oLeft = $this->OQLExpressionToCondition($sQuery, $oExpression->GetLeftExpr(), $aClassAliases); $oRight = $this->OQLExpressionToCondition($sQuery, $oExpression->GetRightExpr(), $aClassAliases); return new BinaryExpression($oLeft, $sOperator, $oRight); - } - elseif ($oExpression instanceof MatchOqlExpression) - { + } elseif ($oExpression instanceof MatchOqlExpression) { $oLeft = $this->OQLExpressionToCondition($sQuery, $oExpression->GetLeftExpr(), $aClassAliases); $oRight = $this->OQLExpressionToCondition($sQuery, $oExpression->GetRightExpr(), $aClassAliases); return new MatchExpression($oLeft, $oRight); - } - elseif ($oExpression instanceof FieldOqlExpression) - { + } elseif ($oExpression instanceof FieldOqlExpression) { $sClassAlias = $oExpression->GetParent(); $sFltCode = $oExpression->GetName(); - if (empty($sClassAlias)) - { + if (empty($sClassAlias)) { // Need to find the right alias // Build an array of field => array of aliases - $aFieldClasses = array(); - foreach($aClassAliases as $sAlias => $sReal) - { - foreach(MetaModel::GetFiltersList($sReal) as $sAnFltCode) - { + $aFieldClasses = []; + foreach ($aClassAliases as $sAlias => $sReal) { + foreach (MetaModel::GetFiltersList($sReal) as $sAnFltCode) { $aFieldClasses[$sAnFltCode][] = $sAlias; } } $sClassAlias = $aFieldClasses[$sFltCode][0]; } return new FieldExpression($sFltCode, $sClassAlias); - } - elseif ($oExpression instanceof VariableOqlExpression) - { + } elseif ($oExpression instanceof VariableOqlExpression) { return new VariableExpression($oExpression->GetName()); - } - elseif ($oExpression instanceof TrueOqlExpression) - { - return new TrueExpression; - } - elseif ($oExpression instanceof ScalarOqlExpression) - { + } elseif ($oExpression instanceof TrueOqlExpression) { + return new TrueExpression(); + } elseif ($oExpression instanceof ScalarOqlExpression) { return new ScalarExpression($oExpression->GetValue()); - } - elseif ($oExpression instanceof ListOqlExpression) - { - $aItems = array(); - foreach ($oExpression->GetItems() as $oItemExpression) - { + } elseif ($oExpression instanceof ListOqlExpression) { + $aItems = []; + foreach ($oExpression->GetItems() as $oItemExpression) { $aItems[] = $this->OQLExpressionToCondition($sQuery, $oItemExpression, $aClassAliases); } return new ListExpression($aItems); - } - elseif ($oExpression instanceof FunctionOqlExpression) - { - $aArgs = array(); - foreach ($oExpression->GetArgs() as $oArgExpression) - { + } elseif ($oExpression instanceof FunctionOqlExpression) { + $aArgs = []; + foreach ($oExpression->GetArgs() as $oArgExpression) { $aArgs[] = $this->OQLExpressionToCondition($sQuery, $oArgExpression, $aClassAliases); } return new FunctionExpression($oExpression->GetVerb(), $aArgs); - } - elseif ($oExpression instanceof IntervalOqlExpression) - { + } elseif ($oExpression instanceof IntervalOqlExpression) { return new IntervalExpression($oExpression->GetValue(), $oExpression->GetUnit()); - } - elseif ($oExpression instanceof NestedQueryOqlExpression) - { + } elseif ($oExpression instanceof NestedQueryOqlExpression) { return NestedQueryExpression::FromOQLObjectQuery($oExpression->GetOQLObjectQuery()); - } - else - { - throw new CoreException('Unknown expression type', array('class'=>get_class($oExpression), 'query'=>$sQuery)); + } else { + throw new CoreException('Unknown expression type', ['class' => get_class($oExpression), 'query' => $sQuery]); } } @@ -1634,14 +1471,13 @@ class DBObjectSearch extends DBSearch */ public function ToJSON() { - $aRet = array('selects' => array(), 'joins' => array(), 'where' => array()); + $aRet = ['selects' => [], 'joins' => [], 'where' => []]; $aParams = array_merge($this->m_aParams); - $aParams = MetaModel::PrepareQueryArguments($aParams, array(), $this->GetExpectedArguments()); + $aParams = MetaModel::PrepareQueryArguments($aParams, [], $this->GetExpectedArguments()); - foreach ($this->m_aSelectedClasses as $sAlias => $sClass) - { - $aRet['selects'][] = array('class' => $sClass, 'alias' => $sAlias); + foreach ($this->m_aSelectedClasses as $sAlias => $sClass) { + $aRet['selects'][] = ['class' => $sClass, 'alias' => $sAlias]; } $this->JoinsToJSON($aRet); @@ -1659,42 +1495,35 @@ class DBObjectSearch extends DBSearch */ protected function JoinsToJSON(&$aRet) { - foreach($this->m_aPointingTo as $sExtKey => $aPointingTo) - { - foreach($aPointingTo as $iOperatorCode => $aFilter) - { + foreach ($this->m_aPointingTo as $sExtKey => $aPointingTo) { + foreach ($aPointingTo as $iOperatorCode => $aFilter) { $sOperator = $this->OperatorCodeToOQL($iOperatorCode); - foreach($aFilter as $oFilter) - { - $aRet['joins'][] = array( + foreach ($aFilter as $oFilter) { + $aRet['joins'][] = [ 'src' => $this->GetFirstJoinedClass(), 'src_alias' => $this->GetFirstJoinedClassAlias(), 'target' => $oFilter->GetFirstJoinedClass(), 'target_alias' => $oFilter->GetFirstJoinedClassAlias(), 'foreign_key' => $sExtKey, 'operator' => $sOperator, - ); + ]; $oFilter->JoinsToJSON($aRet); } } } - foreach($this->m_aReferencedBy as $aReferences) - { - foreach($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) - { - foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) - { + foreach ($this->m_aReferencedBy as $aReferences) { + foreach ($aReferences as $sForeignExtKeyAttCode => $aFiltersByOperator) { + foreach ($aFiltersByOperator as $iOperatorCode => $aFilters) { $sOperator = $this->OperatorCodeToOQL($iOperatorCode); - foreach ($aFilters as $oForeignFilter) - { - $aRet['joins'][] = array( + foreach ($aFilters as $oForeignFilter) { + $aRet['joins'][] = [ 'src' => $oForeignFilter->GetFirstJoinedClass(), 'src_alias' => $oForeignFilter->GetFirstJoinedClassAlias(), 'target' => $this->GetFirstJoinedClass(), 'target_alias' => $this->GetFirstJoinedClassAlias(), 'foreign_key' => $sForeignExtKeyAttCode, 'operator' => $sOperator, - ); + ]; $oForeignFilter->JoinsToJSON($aRet); } } @@ -1715,18 +1544,15 @@ class DBObjectSearch extends DBSearch $sClass = $oOqlQuery->GetClass($oModelReflection); $sClassAlias = $oOqlQuery->GetClassAlias(); - $aAliases = array($sClassAlias => $sClass); + $aAliases = [$sClassAlias => $sClass]; // Note: the condition must be built here, it may be altered later on when optimizing some joins $oConditionTree = $oOqlQuery->GetCondition(); - if ($oConditionTree instanceof Expression) - { - $aRawAliases = array($sClassAlias => $sClass); + if ($oConditionTree instanceof Expression) { + $aRawAliases = [$sClassAlias => $sClass]; $aJoinSpecs = $oOqlQuery->GetJoins(); - if (is_array($aJoinSpecs)) - { - foreach ($aJoinSpecs as $oJoinSpec) - { + if (is_array($aJoinSpecs)) { + foreach ($aJoinSpecs as $oJoinSpec) { $aRawAliases[$oJoinSpec->GetClassAlias()] = $oJoinSpec->GetClass(); } } @@ -1736,18 +1562,15 @@ class DBObjectSearch extends DBSearch // Maintain an array of filters, because the flat list is in fact referring to a tree // And this will be an easy way to dispatch the conditions // $this will be referenced by the other filters, or the other way around... - $aJoinItems = array($sClassAlias => $this); + $aJoinItems = [$sClassAlias => $this]; $aJoinSpecs = $oOqlQuery->GetJoins(); - if (is_array($aJoinSpecs)) - { - $aAliasTranslation = array(); - foreach ($aJoinSpecs as $oJoinSpec) - { + if (is_array($aJoinSpecs)) { + $aAliasTranslation = []; + foreach ($aJoinSpecs as $oJoinSpec) { $sJoinClass = $oJoinSpec->GetClass(); $sJoinClassAlias = $oJoinSpec->GetClassAlias(); - if (isset($aAliasTranslation[$sJoinClassAlias]['*'])) - { + if (isset($aAliasTranslation[$sJoinClassAlias]['*'])) { $sJoinClassAlias = $aAliasTranslation[$sJoinClassAlias]['*']; } @@ -1755,16 +1578,14 @@ class DBObjectSearch extends DBSearch // normalization should take care of this $oLeftField = $oJoinSpec->GetLeftField(); $sFromClass = $oLeftField->GetParent(); - if (isset($aAliasTranslation[$sFromClass]['*'])) - { + if (isset($aAliasTranslation[$sFromClass]['*'])) { $sFromClass = $aAliasTranslation[$sFromClass]['*']; } $sExtKeyAttCode = $oLeftField->GetName(); $oRightField = $oJoinSpec->GetRightField(); $sToClass = $oRightField->GetParent(); - if (isset($aAliasTranslation[$sToClass]['*'])) - { + if (isset($aAliasTranslation[$sToClass]['*'])) { $sToClass = $aAliasTranslation[$sToClass]['*']; } @@ -1772,8 +1593,7 @@ class DBObjectSearch extends DBSearch $aJoinItems[$sJoinClassAlias] = new DBObjectSearch($sJoinClass, $sJoinClassAlias); $sOperator = $oJoinSpec->GetOperator(); - switch($sOperator) - { + switch ($sOperator) { case '=': default: $iOperatorCode = TREE_OPERATOR_EQUALS; @@ -1804,14 +1624,11 @@ class DBObjectSearch extends DBSearch break; } - if ($sFromClass == $sJoinClassAlias) - { + if ($sFromClass == $sJoinClassAlias) { $oReceiver = $aJoinItems[$sToClass]; $oNewComer = $aJoinItems[$sFromClass]; $oReceiver->AddCondition_ReferencedBy_InNameSpace($oNewComer, $sExtKeyAttCode, $oReceiver->m_aClasses, $aAliasTranslation, $iOperatorCode); - } - else - { + } else { $oReceiver = $aJoinItems[$sFromClass]; $oNewComer = $aJoinItems[$sToClass]; $oReceiver->AddCondition_PointingTo_InNameSpace($oNewComer, $sExtKeyAttCode, $oReceiver->m_aClasses, $aAliasTranslation, $iOperatorCode); @@ -1821,12 +1638,10 @@ class DBObjectSearch extends DBSearch } // Check and prepare the select information - $this->m_aSelectedClasses = array(); - foreach ($oOqlQuery->GetSelectedClasses() as $oClassDetails) - { + $this->m_aSelectedClasses = []; + foreach ($oOqlQuery->GetSelectedClasses() as $oClassDetails) { $sClassToSelect = $oClassDetails->GetValue(); - if (!array_key_exists($sClassToSelect, $aAliases)) - { + if (!array_key_exists($sClassToSelect, $aAliases)) { throw new CoreException("$sClassToSelect is not a valid alias"); } $this->m_aSelectedClasses[$sClassToSelect] = $aAliases[$sClassToSelect]; @@ -1840,7 +1655,7 @@ class DBObjectSearch extends DBSearch // //////////////////////////////////////////////////////////////////////////// - public function MakeDeleteQuery($aArgs = array()) + public function MakeDeleteQuery($aArgs = []) { $oSQLObjectQueryBuilder = new SQLObjectQueryBuilder($this); $oSQLQuery = $oSQLObjectQueryBuilder->MakeSQLObjectDeleteQuery(); @@ -1856,7 +1671,7 @@ class DBObjectSearch extends DBSearch * @return string * @throws \CoreException */ - public function MakeUpdateQuery($aValues, $aArgs = array()) + public function MakeUpdateQuery($aValues, $aArgs = []) { $oSQLObjectQueryBuilder = new SQLObjectQueryBuilder($this); $oSQLQuery = $oSQLObjectQueryBuilder->MakeSQLObjectUpdateQuery($aValues); @@ -1875,7 +1690,7 @@ class DBObjectSearch extends DBSearch * @return string * @throws \CoreException */ - public function MakeInsertQuery($aValues, $aArgs = array()) + public function MakeInsertQuery($aValues, $aArgs = []) { $oSQLObjectQueryBuilder = new SQLObjectQueryBuilder($this); $oSQLQuery = $oSQLObjectQueryBuilder->MakeSQLObjectUpdateQuery($aValues); @@ -1920,14 +1735,12 @@ class DBObjectSearch extends DBSearch // Create a unique cache id // - $aContextData = array(); + $aContextData = []; $bCanCache = true; - if (self::$m_bQueryCacheEnabled || self::$m_bTraceQueries) - { - if (isset($_SERVER['REQUEST_URI'])) - { + if (self::$m_bQueryCacheEnabled || self::$m_bTraceQueries) { + if (isset($_SERVER['REQUEST_URI'])) { $aContextData['sRequestUri'] = $_SERVER['REQUEST_URI']; - } else if (isset($_SERVER['SCRIPT_NAME'])) { + } elseif (isset($_SERVER['SCRIPT_NAME'])) { $aContextData['sRequestUri'] = $_SERVER['SCRIPT_NAME']; } else { $aContextData['sRequestUri'] = ''; @@ -1980,19 +1793,15 @@ class DBObjectSearch extends DBSearch $aContextData['bIsArchiveMode'] = $bIsArchiveMode; $aContextData['bShowObsoleteData'] = $bShowObsoleteData; $sOqlId = md5($sRawId); - } - else - { + } else { $sOqlQuery = "SELECTING... ".$oSearch->GetClass(); $sOqlId = "query id ? n/a"; } - // Query caching // $sOqlAPCCacheId = null; - if (self::$m_bQueryCacheEnabled && $bCanCache) - { + if (self::$m_bQueryCacheEnabled && $bCanCache) { // Warning: using directly the query string as the key to the hash array can FAIL if the string // is long and the differences are only near the end... so it's safer (but not bullet proof?) // to use a hash (like md5) of the string as the key ! @@ -2003,15 +1812,12 @@ class DBObjectSearch extends DBSearch // SELECT SLT JOIN lnkSLTToSLA AS L1 ON L1.slt_id=SLT.id JOIN SLA ON L1.sla_id = SLA.id JOIN lnkContractToSLA AS L2 ON L2.sla_id = SLA.id JOIN CustomerContract ON L2.contract_id = CustomerContract.id WHERE SLT.ticket_priority = 1 AND SLA.service_id = 3 AND SLT.metric = 'TTR' AND CustomerContract.customer_id = 2 // the only difference is R instead or O at position 285 (TTR instead of TTO)... // - if (array_key_exists($sOqlId, self::$m_aQueryStructCache)) - { + if (array_key_exists($sOqlId, self::$m_aQueryStructCache)) { // hit! $oSQLQuery = unserialize(serialize(self::$m_aQueryStructCache[$sOqlId])); // Note: cloning is not enough because the subtree is made of objects - } - elseif (self::$m_bUseAPCCache) - { + } elseif (self::$m_bUseAPCCache) { // Note: For versions of APC older than 3.0.17, fetch() accepts only one parameter // $sOqlAPCCacheId = 'itop-'.MetaModel::GetEnvironmentId().'-query-cache-'.$sOqlId; @@ -2019,25 +1825,21 @@ class DBObjectSearch extends DBSearch $result = apc_fetch($sOqlAPCCacheId); $oKPI->ComputeStats('Query APC (fetch)', $sOqlQuery); - if (is_object($result)) - { + if (is_object($result)) { $oSQLQuery = $result; self::$m_aQueryStructCache[$sOqlId] = $oSQLQuery; } } } - if (!isset($oSQLQuery)) - { + if (!isset($oSQLQuery)) { $oKPI = new ExecutionKPI(); $oSQLObjectQueryBuilder = new SQLObjectQueryBuilder($oSearch); $oSQLQuery = $oSQLObjectQueryBuilder->BuildSQLQueryStruct($aAttToLoad, $bGetCount, $aModifierProperties, $aGroupByExpr, $aSelectedClasses, $aSelectExpr); $oKPI->ComputeStats('BuildSQLQueryStruct', $sOqlQuery); - if (self::$m_bQueryCacheEnabled) - { - if ($bCanCache && self::$m_bUseAPCCache) - { + if (self::$m_bQueryCacheEnabled) { + if ($bCanCache && self::$m_bUseAPCCache) { $oSQLQuery->m_aContextData = $aContextData; $oKPI = new ExecutionKPI(); apc_store($sOqlAPCCacheId, $oSQLQuery, self::$m_iQueryCacheTTL); @@ -2058,28 +1860,28 @@ class DBObjectSearch extends DBSearch * @return \FunctionExpression|mixed|null * @throws \CoreException */ - static public function GetPolymorphicExpression($sClass, $sAttCode) + public static function GetPolymorphicExpression($sClass, $sAttCode) { $oExpression = ExpressionCache::GetCachedExpression($sClass, $sAttCode); - if (!empty($oExpression)) - { + if (!empty($oExpression)) { return $oExpression; } // 1st step - get all of the required expressions (instantiable classes) // and group them using their OQL representation // - $aExpressions = array(); // signature => array('expression' => oExp, 'classes' => array of classes) - foreach (MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL) as $sSubClass) - { - if (($sSubClass != $sClass) && MetaModel::IsAbstract($sSubClass)) continue; + $aExpressions = []; // signature => array('expression' => oExp, 'classes' => array of classes) + foreach (MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL) as $sSubClass) { + if (($sSubClass != $sClass) && MetaModel::IsAbstract($sSubClass)) { + continue; + } $oAttDef = MetaModel::GetAttributeDef($sSubClass, $sAttCode); $oSubClassExp = $oAttDef->GetOQLExpression($sSubClass); // 3rd step - position the attributes in the hierarchy of classes // - $oSubClassExp->Browse(function($oNode) use ($sSubClass) { + $oSubClassExp->Browse(function ($oNode) use ($sSubClass) { if ($oNode instanceof FieldExpression) { $sAttCode = $oNode->GetName(); $oAttDef = MetaModel::GetAttributeDef($sSubClass, $sAttCode); @@ -2096,44 +1898,37 @@ class DBObjectSearch extends DBSearch $sSignature = $oSubClassExp->RenderExpression(); if (!array_key_exists($sSignature, $aExpressions)) { - $aExpressions[$sSignature] = array( + $aExpressions[$sSignature] = [ 'expression' => $oSubClassExp, - 'classes' => array(), - ); + 'classes' => [], + ]; } $aExpressions[$sSignature]['classes'][] = $sSubClass; } // 2nd step - build the final name expression depending on the finalclass // - if (count($aExpressions) == 1) - { + if (count($aExpressions) == 1) { $aExpData = reset($aExpressions); $oExpression = $aExpData['expression']; - } - else - { + } else { $oExpression = null; - foreach ($aExpressions as $sSignature => $aExpData) - { + foreach ($aExpressions as $sSignature => $aExpData) { $oClassListExpr = ListExpression::FromScalars($aExpData['classes']); $oClassExpr = new FieldExpression('finalclass', $sClass); $oClassInList = new BinaryExpression($oClassExpr, 'IN', $oClassListExpr); - if (is_null($oExpression)) - { + if (is_null($oExpression)) { $oExpression = $aExpData['expression']; - } - else - { - $oExpression = new FunctionExpression('IF', array($oClassInList, $aExpData['expression'], $oExpression)); + } else { + $oExpression = new FunctionExpression('IF', [$oClassInList, $aExpData['expression'], $oExpression]); } } } return $oExpression; } - function GetExpectedArguments(): array + public function GetExpectedArguments(): array { return $this->GetCriteria()->ListParameters(); } diff --git a/core/dbsearch.class.php b/core/dbsearch.class.php index 3aed95306..be26a5628 100644 --- a/core/dbsearch.class.php +++ b/core/dbsearch.class.php @@ -1,4 +1,5 @@ Init(); } - /** - * called by the constructor - * @internal Set the obsolete and archive modes to the default ones - */ + /** + * called by the constructor + * @internal Set the obsolete and archive modes to the default ones + */ protected function Init() { $this->m_bArchiveMode = utils::IsArchiveMode(); @@ -86,104 +87,104 @@ abstract class DBSearch $this->m_bArchiveMode = $bEnable; } - /** - * @internal - * @return bool - */ + /** + * @internal + * @return bool + */ public function GetArchiveMode() { return $this->m_bArchiveMode; } - /** - * Should the obsolete data be fetched - * - * @internal - * @param $bShow - */ + /** + * Should the obsolete data be fetched + * + * @internal + * @param $bShow + */ public function SetShowObsoleteData($bShow) { $this->m_bShowObsoleteData = $bShow; } - /** - * @internal - * @return bool - */ + /** + * @internal + * @return bool + */ public function GetShowObsoleteData() { - if ($this->m_bArchiveMode || $this->IsAllDataAllowed()) - { + if ($this->m_bArchiveMode || $this->IsAllDataAllowed()) { // Enable obsolete data too! $bRet = true; - } - else - { + } else { $bRet = $this->m_bShowObsoleteData; } return $bRet; } - /** - * @internal - */ - public function NoContextParameters() {$this->m_bNoContextParameters = true;} + /** + * @internal + */ + public function NoContextParameters() + { + $this->m_bNoContextParameters = true; + } - /** - * @internal - * @return bool - */ - public function HasContextParameters() {return $this->m_bNoContextParameters;} + /** + * @internal + * @return bool + */ + public function HasContextParameters() + { + return $this->m_bNoContextParameters; + } - /** - * @internal - * - * @param $sPluginClass - * @param $sProperty - * @param $value - */ + /** + * @internal + * + * @param $sPluginClass + * @param $sProperty + * @param $value + */ public function SetModifierProperty($sPluginClass, $sProperty, $value) { $this->m_aModifierProperties[$sPluginClass][$sProperty] = $value; } - /** - * @internal - * - * @param $sPluginClass - * - * @return array|mixed - */ + /** + * @internal + * + * @param $sPluginClass + * + * @return array|mixed + */ public function GetModifierProperties($sPluginClass) { - if (array_key_exists($sPluginClass, $this->m_aModifierProperties)) - { + if (array_key_exists($sPluginClass, $this->m_aModifierProperties)) { return $this->m_aModifierProperties[$sPluginClass]; - } - else - { - return array(); + } else { + return []; } } - /** - * @internal - * @param $sAlias - * - * @return mixed - */ + /** + * @internal + * @param $sAlias + * + * @return mixed + */ abstract public function GetClassName($sAlias); - /** - * @internal - * @return mixed - */ + /** + * @internal + * @return mixed + */ abstract public function GetClass(); - /** - * @internal - * @return mixed - */ + /** + * @internal + * @return mixed + */ abstract public function GetClassAlias(); /** @@ -193,23 +194,23 @@ abstract class DBSearch abstract public function GetFirstJoinedClass(); /** - * Change the class - * - * Defaults to the first selected class (most of the time it is also the first joined class - * only subclasses are supported as of now, because the conditions must fit the new class - * - * @internal - */ + * Change the class + * + * Defaults to the first selected class (most of the time it is also the first joined class + * only subclasses are supported as of now, because the conditions must fit the new class + * + * @internal + */ abstract public function ChangeClass($sNewClass, $sAlias = null); - /** - * @internal - * @return mixed - */ + /** + * @internal + * @return mixed + */ abstract public function GetSelectedClasses(); /** - * @internal + * @internal * @param array $aSelectedClasses array of aliases * @throws CoreException */ @@ -218,15 +219,15 @@ abstract class DBSearch /** * Change any alias of the query tree * - * @internal - * + * @internal + * * @param $sOldName * @param $sNewName * @return bool True if the alias has been found and changed */ abstract public function RenameAlias($sOldName, $sNewName); - abstract public function RenameAliasesInNameSpace($aClassAliases, $aAliasTranslation = array()); + abstract public function RenameAliasesInNameSpace($aClassAliases, $aAliasTranslation = []); abstract public function TranslateConditions($aTranslationData, $bMatchAll = true, $bMarkFieldsAsResolved = true); @@ -249,56 +250,56 @@ abstract class DBSearch * @see DBSearch::AddConditionExpression() * * @param Expression $oExpression - * - * @return mixed - */ + * + * @return mixed + */ abstract public function MergeConditionExpression($oExpression); - /** - * add $oExpression as a AND - * - * @api - * @see DBSearch::MergeConditionExpression() - * - * @param Expression $oExpression - * - * @return mixed - */ + /** + * add $oExpression as a AND + * + * @api + * @see DBSearch::MergeConditionExpression() + * + * @param Expression $oExpression + * + * @return mixed + */ abstract public function AddConditionExpression($oExpression); - /** - * Condition on the friendlyname - * - * Restrict the query to only the corresponding selected class' friendlyname - * - * @internal - * - * @param string $sName the desired friendlyname - * - * @return mixed - */ - abstract public function AddNameCondition($sName); + /** + * Condition on the friendlyname + * + * Restrict the query to only the corresponding selected class' friendlyname + * + * @internal + * + * @param string $sName the desired friendlyname + * + * @return mixed + */ + abstract public function AddNameCondition($sName); - /** - * Add a condition - * - * This is the simplest way to express a AND condition. For complex use cases, use MergeConditionExpression or AddConditionExpression instead - * - * @api - * - * @param string $sFilterCode - * @param mixed $value - * @param string $sOpCode operator to use : '=' (default), '!=', 'IN', 'NOT IN' - * - * @throws \CoreException - * - */ + /** + * Add a condition + * + * This is the simplest way to express a AND condition. For complex use cases, use MergeConditionExpression or AddConditionExpression instead + * + * @api + * + * @param string $sFilterCode + * @param mixed $value + * @param string $sOpCode operator to use : '=' (default), '!=', 'IN', 'NOT IN' + * + * @throws \CoreException + * + */ abstract public function AddCondition($sFilterCode, $value, $sOpCode = null); /** * Specify a condition on external keys or link sets - * - * @internal - * + * + * @internal + * * @param string $sAttSpec Can be either an attribute code or extkey->[sAttSpec] or linkset->[sAttSpec] and so on, recursively * Example: infra_list->ci_id->location_id->country * @param mixed $value The value to match (can be an array => IN(val1, val2...) @@ -306,50 +307,50 @@ abstract class DBSearch */ abstract public function AddConditionAdvanced($sAttSpec, $value); - /** - * @internal - * - * @param string $sFullText - * - * @return mixed - */ + /** + * @internal + * + * @param string $sFullText + * + * @return mixed + */ abstract public function AddCondition_FullText($sFullText); abstract public function AddCondition_FullTextOnAttributes(array $aAttCodes, $sNeedle); - /** - * Perform a join, the remote class being matched by the mean of its primary key - * - * The join is performed - * * from the searched class, based on the $sExtKeyAttCode attribute - * * against the oFilter searched class, based on its primary key - * Note : if several classes have already being joined (SELECT a join b ON...), the first joined class (a in the example) is considered as being the searched class. - * - * @api - * @see AddCondition_ReferencedBy() - * + /** + * Perform a join, the remote class being matched by the mean of its primary key + * + * The join is performed + * * from the searched class, based on the $sExtKeyAttCode attribute + * * against the oFilter searched class, based on its primary key + * Note : if several classes have already being joined (SELECT a join b ON...), the first joined class (a in the example) is considered as being the searched class. + * + * @api + * @see AddCondition_ReferencedBy() + * * @param DBObjectSearch $oFilter * @param string $sExtKeyAttCode * @param int $iOperatorCode the comparison operator to use. For the list of all possible values, see the constant defined in core/oql/oqlquery.class.inc.php * @param array|null $aRealiasingMap array of => , for each alias that has changed in the newly attached oFilter (in case of collisions between the two filters) - * + * * @throws CoreException * @throws CoreWarning */ abstract public function AddCondition_PointingTo(DBObjectSearch $oFilter, $sExtKeyAttCode, $iOperatorCode = TREE_OPERATOR_EQUALS, &$aRealiasingMap = null); /** - * Inverse operation of AddCondition_PointingTo - * - * The join is performed - * * from the olFilter searched class, based on the $sExtKeyAttCode attribute - * * against the searched class, based on its primary key - * Note : if several classes have already being joined (SELECT a join b ON...), the first joined class (a in the example) is considered as being the searched class. - * - * - * @api - * @see AddCondition_PointingTo() - * + * Inverse operation of AddCondition_PointingTo + * + * The join is performed + * * from the olFilter searched class, based on the $sExtKeyAttCode attribute + * * against the searched class, based on its primary key + * Note : if several classes have already being joined (SELECT a join b ON...), the first joined class (a in the example) is considered as being the searched class. + * + * + * @api + * @see AddCondition_PointingTo() + * * @param DBObjectSearch $oFilter * @param $sForeignExtKeyAttCode * @param int $iOperatorCode @@ -373,62 +374,54 @@ abstract class DBSearch abstract public function Filter($sClassAlias, DBSearch $oFilter); /** - * Filter the result - * - * The filter is performed by returning only the values in common with the given $oFilter - * The impact on the resulting query performance/viability can be significant. - * Only the first joined class can be filtered. - * - * @internal - * - * @param DBSearch $oFilter - * - * @return mixed - */ + * Filter the result + * + * The filter is performed by returning only the values in common with the given $oFilter + * The impact on the resulting query performance/viability can be significant. + * Only the first joined class can be filtered. + * + * @internal + * + * @param DBSearch $oFilter + * + * @return mixed + */ abstract public function Intersect(DBSearch $oFilter); - /** - * Perform a join - * - * The join is performed against $oFilter selected class using $sExtKeyAttCode of the current selected class - * - * @internal - * - * @param DBSearch $oFilter The join is performed against $oFilter selected class - * @param integer $iDirection can be either DBSearch::JOIN_POINTING_TO or DBSearch::JOIN_REFERENCED_BY - * @param string $sExtKeyAttCode The join is performed against $sExtKeyAttCode whether it is compared against the current DBSearch or $oFilter depend of $iDirection - * @param integer $iOperatorCode See DBSearch::AddCondition_PointingTo() - * @param array|null $aRealiasingMap Map of aliases from the attached query, that could have been renamed by the optimization process - * - * @return DBSearch - * @throws CoreException - * @throws CoreWarning - */ + /** + * Perform a join + * + * The join is performed against $oFilter selected class using $sExtKeyAttCode of the current selected class + * + * @internal + * + * @param DBSearch $oFilter The join is performed against $oFilter selected class + * @param integer $iDirection can be either DBSearch::JOIN_POINTING_TO or DBSearch::JOIN_REFERENCED_BY + * @param string $sExtKeyAttCode The join is performed against $sExtKeyAttCode whether it is compared against the current DBSearch or $oFilter depend of $iDirection + * @param integer $iOperatorCode See DBSearch::AddCondition_PointingTo() + * @param array|null $aRealiasingMap Map of aliases from the attached query, that could have been renamed by the optimization process + * + * @return DBSearch + * @throws CoreException + * @throws CoreWarning + */ public function Join(DBSearch $oFilter, $iDirection, $sExtKeyAttCode, $iOperatorCode = TREE_OPERATOR_EQUALS, &$aRealiasingMap = null) { $oSourceFilter = $this->DeepClone(); $oRet = null; - if ($oFilter instanceof DBUnionSearch) - { - $aSearches = array(); - foreach ($oFilter->GetSearches() as $oSearch) - { + if ($oFilter instanceof DBUnionSearch) { + $aSearches = []; + foreach ($oFilter->GetSearches() as $oSearch) { $aSearches[] = $oSourceFilter->Join($oSearch, $iDirection, $sExtKeyAttCode, $iOperatorCode, $aRealiasingMap); } $oRet = new DBUnionSearch($aSearches); - } - else - { + } else { /** @var \DBObjectSearch $oFilter */ - if ($iDirection === static::JOIN_POINTING_TO) - { + if ($iDirection === static::JOIN_POINTING_TO) { $oSourceFilter->AddCondition_PointingTo($oFilter, $sExtKeyAttCode, $iOperatorCode, $aRealiasingMap); - } - else - { - if ($iOperatorCode !== TREE_OPERATOR_EQUALS) - { + } else { + if ($iOperatorCode !== TREE_OPERATOR_EQUALS) { throw new Exception('Only TREE_OPERATOR_EQUALS operator code is supported yet for AddCondition_ReferencedBy.'); } $oSourceFilter->AddCondition_ReferencedBy($oFilter, $sExtKeyAttCode, TREE_OPERATOR_EQUALS, $aRealiasingMap); @@ -439,99 +432,88 @@ abstract class DBSearch return $oRet; } - /** - * Set the internal params. - * - * If any params pre-existed, they are lost. - * - * @internal - * - * @param mixed[string] $aParams array of mixed params index by string name - * - * @return mixed - */ + /** + * Set the internal params. + * + * If any params pre-existed, they are lost. + * + * @internal + * + * @param mixed[string] $aParams array of mixed params index by string name + * + * @return mixed + */ abstract public function SetInternalParams($aParams); - /** - * @internal - * @return mixed - */ + /** + * @internal + * @return mixed + */ abstract public function GetInternalParams(); - /** - * @internal - * - * @return mixed - */ + /** + * @internal + * + * @return mixed + */ abstract public function GetQueryParams(); - /** - * @internal - * @return mixed - */ + /** + * @internal + * @return mixed + */ abstract public function ListConstantFields(); /** - * Turn the parameters (:xxx) into scalar values - * - * The goal is to easily serialize a search + * Turn the parameters (:xxx) into scalar values + * + * The goal is to easily serialize a search + * + * @internal * - * @internal - * * @param array $aArgs * * @return string */ abstract public function ApplyParameters($aArgs); - /** - * Convert a query to a string representation - * - * This operation can be revert back to a DBSearch using DBSearch::unserialize() - * - * @api - * @see DBSearch::unserialize() - * - * @param bool $bDevelopParams - * @param array $aContextParams - * - * @return false|string - * @throws ArchivedObjectException - * @throws CoreException - */ - public function serialize($bDevelopParams = false, $aContextParams = array()) + /** + * Convert a query to a string representation + * + * This operation can be revert back to a DBSearch using DBSearch::unserialize() + * + * @api + * @see DBSearch::unserialize() + * + * @param bool $bDevelopParams + * @param array $aContextParams + * + * @return false|string + * @throws ArchivedObjectException + * @throws CoreException + */ + public function serialize($bDevelopParams = false, $aContextParams = []) { $aQueryParams = $this->GetQueryParams(); $aContextParams = array_merge($this->GetInternalParams(), $aContextParams); - foreach($aQueryParams as $sParam => $sValue) - { - if (isset($aContextParams[$sParam])) - { + foreach ($aQueryParams as $sParam => $sValue) { + if (isset($aContextParams[$sParam])) { $aQueryParams[$sParam] = $aContextParams[$sParam]; - } - elseif (($iPos = strpos($sParam, '->')) !== false) - { + } elseif (($iPos = strpos($sParam, '->')) !== false) { $sParamName = substr($sParam, 0, $iPos); - if (isset($aContextParams[$sParamName.'->object()']) || isset($aContextParams[$sParamName])) - { + if (isset($aContextParams[$sParamName.'->object()']) || isset($aContextParams[$sParamName])) { $sAttCode = substr($sParam, $iPos + 2); /** @var \DBObject $oObj */ $oObj = isset($aContextParams[$sParamName.'->object()']) ? $aContextParams[$sParamName.'->object()'] : $aContextParams[$sParamName]; - if ($oObj->IsModified()) - { - if ($sAttCode == 'id') - { + if ($oObj->IsModified()) { + if ($sAttCode == 'id') { $aQueryParams[$sParam] = $oObj->GetKey(); - } - else - { + } else { $aQueryParams[$sParam] = $oObj->Get($sAttCode); } - } - else - { + } else { unset($aQueryParams[$sParam]); // For database objects, serialize only class, key $aQueryParams[$sParamName.'->id'] = $oObj->GetKey(); @@ -542,14 +524,14 @@ abstract class DBSearch } $sOql = $this->ToOql($bDevelopParams, $aContextParams); - return urlencode(json_encode(array($sOql, $aQueryParams, $this->m_aModifierProperties))); + return urlencode(json_encode([$sOql, $aQueryParams, $this->m_aModifierProperties])); } /** - * Convert a serialized query back to an instance of DBSearch - * - * @api - * + * Convert a serialized query back to an instance of DBSearch + * + * @api + * * @param string $sValue Serialized OQL query * * @return \DBSearch @@ -557,23 +539,19 @@ abstract class DBSearch * @throws \CoreException * @throws \OQLException */ - static public function unserialize($sValue) + public static function unserialize($sValue) { $aData = json_decode(urldecode($sValue), true); - if (is_null($aData)) - { + if (is_null($aData)) { throw new CoreException("Invalid filter parameter"); } $sOql = $aData[0]; $aParams = $aData[1]; - $aExtraParams = array(); - foreach($aParams as $sParam => $sValue) - { - if (($iPos = strpos($sParam, '->class')) !== false) - { + $aExtraParams = []; + foreach ($aParams as $sParam => $sValue) { + if (($iPos = strpos($sParam, '->class')) !== false) { $sParamName = substr($sParam, 0, $iPos); - if (isset($aParams[$sParamName.'->id'])) - { + if (isset($aParams[$sParamName.'->id'])) { $sClass = $aParams[$sParamName.'->class']; $iKey = $aParams[$sParamName.'->id']; $oObj = MetaModel::GetObject($sClass, $iKey); @@ -590,65 +568,65 @@ abstract class DBSearch return $oRetFilter; } - /** - * Create a new DBObjectSearch from $oSearch with a new alias $sAlias - * - * @internal Note : This has not be tested with UNION queries. - * - * @param DBSearch $oSearch - * @param string $sAlias - * - * @return DBObjectSearch - * @throws CoreException - */ - static public function CloneWithAlias(DBSearch $oSearch, $sAlias) - { - $oSearchWithAlias = new DBObjectSearch($oSearch->GetClass(), $sAlias); - $oSearchWithAlias = $oSearchWithAlias->Intersect($oSearch); - return $oSearchWithAlias; - } + /** + * Create a new DBObjectSearch from $oSearch with a new alias $sAlias + * + * @internal Note : This has not be tested with UNION queries. + * + * @param DBSearch $oSearch + * @param string $sAlias + * + * @return DBObjectSearch + * @throws CoreException + */ + public static function CloneWithAlias(DBSearch $oSearch, $sAlias) + { + $oSearchWithAlias = new DBObjectSearch($oSearch->GetClass(), $sAlias); + $oSearchWithAlias = $oSearchWithAlias->Intersect($oSearch); + return $oSearchWithAlias; + } - /** - * Convert the DBSearch to an OQL representation - * - * @api - * @see DBSearch::FromOQL() - * - * @param bool $bDevelopParams - * @param null $aContextParams - * @param bool $bWithAllowAllFlag - * - * @return mixed - */ - abstract public function ToOQL($bDevelopParams = false, $aContextParams = null, $bWithAllowAllFlag = false); + /** + * Convert the DBSearch to an OQL representation + * + * @api + * @see DBSearch::FromOQL() + * + * @param bool $bDevelopParams + * @param null $aContextParams + * @param bool $bWithAllowAllFlag + * + * @return mixed + */ + abstract public function ToOQL($bDevelopParams = false, $aContextParams = null, $bWithAllowAllFlag = false); - /** - * Export the DBSearch as a structure (array of arrays...) suitable for a conversion to JSON - * - * @internal - * - * @return mixed[string] - */ - abstract public function ToJSON(); + /** + * Export the DBSearch as a structure (array of arrays...) suitable for a conversion to JSON + * + * @internal + * + * @return mixed[string] + */ + abstract public function ToJSON(); - static protected $m_aOQLQueries = array(); + protected static $m_aOQLQueries = []; - /** - * FromOQL with AllowAllData enabled - * - * The goal is to not filter out depending on user rights. - * In particular when we are currently in the process of evaluating the user rights... - * - * @internal - * @see DBSearch::FromOQL() - * - * @param string $sQuery - * @param null $aParams - * - * @return DBSearch - * @throws OQLException - */ - static public function FromOQL_AllData($sQuery, $aParams = null) + /** + * FromOQL with AllowAllData enabled + * + * The goal is to not filter out depending on user rights. + * In particular when we are currently in the process of evaluating the user rights... + * + * @internal + * @see DBSearch::FromOQL() + * + * @param string $sQuery + * @param null $aParams + * + * @return DBSearch + * @throws OQLException + */ + public static function FromOQL_AllData($sQuery, $aParams = null) { $oRes = self::FromOQL($sQuery, $aParams); $oRes->AllowAllData(); @@ -656,41 +634,36 @@ abstract class DBSearch } /** - * Create a new DBSearch from the given OQL. - * - * This is the simplest way to create a DBSearch. - * For almost every cases, this is the easiest way. - * - * @api - * @see DBSearch::ToOQL() - * + * Create a new DBSearch from the given OQL. + * + * This is the simplest way to create a DBSearch. + * For almost every cases, this is the easiest way. + * + * @api + * @see DBSearch::ToOQL() + * * @param string $sQuery The OQL to convert to a DBSearch * @param array $aParams array of params index by name * @param ModelReflection|null $oMetaModel The MetaModel to use when checking the consistency of the OQL - * + * * @return DBObjectSearch|DBUnionSearch - * + * * @throws OQLException */ - public static function FromOQL($sQuery, $aParams = null, ModelReflection $oMetaModel=null) + public static function FromOQL($sQuery, $aParams = null, ModelReflection $oMetaModel = null) { - if (empty($sQuery)) - { + if (empty($sQuery)) { return null; } // Query caching $sQueryId = md5($sQuery); $bOQLCacheEnabled = true; - if ($bOQLCacheEnabled) - { - if (array_key_exists($sQueryId, self::$m_aOQLQueries)) - { + if ($bOQLCacheEnabled) { + if (array_key_exists($sQueryId, self::$m_aOQLQueries)) { // hit! $oResultFilter = self::$m_aOQLQueries[$sQueryId]->DeepClone(); - } - elseif (self::$m_bUseAPCCache) - { + } elseif (self::$m_bUseAPCCache) { // Note: For versions of APC older than 3.0.17, fetch() accepts only one parameter // $sAPCCacheId = 'itop-'.MetaModel::GetEnvironmentId().'-dbsearch-cache-'.$sQueryId; @@ -698,8 +671,7 @@ abstract class DBSearch $result = apc_fetch($sAPCCacheId); $oKPI->ComputeStats('Search APC (fetch)', $sQuery); - if (is_object($result)) - { + if (is_object($result)) { $oResultFilter = $result; self::$m_aOQLQueries[$sQueryId] = $oResultFilter->DeepClone(); } @@ -707,15 +679,13 @@ abstract class DBSearch } /** @var DBObjectSearch | null $oResultFilter */ - if (!isset($oResultFilter)) - { + if (!isset($oResultFilter)) { $oKPI = new ExecutionKPI(); $oOql = new OqlInterpreter($sQuery); $oOqlQuery = $oOql->ParseQuery(); - if ($oMetaModel === null) - { + if ($oMetaModel === null) { $oMetaModel = new ModelReflectionRuntime(); } $oOqlQuery->Check($oMetaModel, $sQuery); // Exceptions thrown in case of issue @@ -724,12 +694,10 @@ abstract class DBSearch $oKPI->ComputeStats('Parse OQL', $sQuery); - if ($bOQLCacheEnabled) - { + if ($bOQLCacheEnabled) { self::$m_aOQLQueries[$sQueryId] = $oResultFilter->DeepClone(); - if (self::$m_bUseAPCCache) - { + if (self::$m_bUseAPCCache) { $oKPI = new ExecutionKPI(); apc_store($sAPCCacheId, $oResultFilter, self::$m_iQueryCacheTTL); $oKPI->ComputeStats('Search APC (store)', $sQueryId); @@ -737,8 +705,7 @@ abstract class DBSearch } } - if (!is_null($aParams)) - { + if (!is_null($aParams)) { $oResultFilter->SetInternalParams($aParams); } @@ -749,60 +716,54 @@ abstract class DBSearch } /** - * Fetch the result has an array structure. - * + * Fetch the result has an array structure. + * * Alternative to object mapping: the data are transfered directly into an array * This is 10 times faster than creating a set of objects, and makes sense when optimization is required - * But this speed comes at the cost of not obtaining the easy to manipulates DBObject instances but simple array structure. - * - * @internal + * But this speed comes at the cost of not obtaining the easy to manipulates DBObject instances but simple array structure. + * + * @internal * * @param array $aColumns The columns you'd like to fetch. * @param array $aOrderBy Array of '[.]attcode' => bAscending * @param array $aArgs * * @return array|void - * + * * @throws \CoreException * @throws \MissingQueryArgument * @throws \MySQLException * @throws \MySQLHasGoneAwayException */ - public function ToDataArray($aColumns = array(), $aOrderBy = array(), $aArgs = array()) + public function ToDataArray($aColumns = [], $aOrderBy = [], $aArgs = []) { $sSQL = $this->MakeSelectQuery($aOrderBy, $aArgs); $resQuery = CMDBSource::Query($sSQL); - if (!$resQuery) - { + if (!$resQuery) { return; } - if (count($aColumns) == 0) - { - $aColumns = array_keys(MetaModel::ListAttributeDefs($this->GetClass())); - // Add the standard id (as first column) - array_unshift($aColumns, 'id'); + if (count($aColumns) == 0) { + $aColumns = array_keys(MetaModel::ListAttributeDefs($this->GetClass())); + // Add the standard id (as first column) + array_unshift($aColumns, 'id'); } $aQueryCols = CMDBSource::GetColumns($resQuery, $sSQL); $sClassAlias = $this->GetClassAlias(); - $aColMap = array(); - foreach ($aColumns as $sAttCode) - { + $aColMap = []; + foreach ($aColumns as $sAttCode) { $sColName = $sClassAlias.$sAttCode; - if (in_array($sColName, $aQueryCols)) - { + if (in_array($sColName, $aQueryCols)) { $aColMap[$sAttCode] = $sColName; } } - $aRes = array(); - while ($aRow = CMDBSource::FetchArray($resQuery)) - { - $aMappedRow = array(); - foreach ($aColMap as $sAttCode => $sColName) - { + $aRes = []; + while ($aRow = CMDBSource::FetchArray($resQuery)) { + $aMappedRow = []; + foreach ($aColMap as $sAttCode => $sColName) { $aMappedRow[$sAttCode] = $aRow[$sColName]; } $aRes[] = $aMappedRow; @@ -811,68 +772,65 @@ abstract class DBSearch return $aRes; } - /** - * Selects a column ($sAttCode) from the specified class ($sClassAlias - default main class) of the DBsearch object and gives the result as an array - * @param string $sAttCode - * @param string|null $sClassAlias - * - * @return array - * @throws ConfigException - * @throws CoreException - * @throws MissingQueryArgument - * @throws MySQLException - * @throws MySQLHasGoneAwayException - */ - public function SelectAttributeToArray(string $sAttCode, ?string $sClassAlias = null):array - { - if(is_null($sClassAlias)) { - $sClassAlias = $this->GetClassAlias(); - } + /** + * Selects a column ($sAttCode) from the specified class ($sClassAlias - default main class) of the DBsearch object and gives the result as an array + * @param string $sAttCode + * @param string|null $sClassAlias + * + * @return array + * @throws ConfigException + * @throws CoreException + * @throws MissingQueryArgument + * @throws MySQLException + * @throws MySQLHasGoneAwayException + */ + public function SelectAttributeToArray(string $sAttCode, ?string $sClassAlias = null): array + { + if (is_null($sClassAlias)) { + $sClassAlias = $this->GetClassAlias(); + } - $sClass = $this->GetClass(); - if($sAttCode === 'id'){ - $aAttToLoad[$sClassAlias]=[]; - } else { - $aAttToLoad[$sClassAlias][$sAttCode] = MetaModel::GetAttributeDef($sClass, $sAttCode); - } + $sClass = $this->GetClass(); + if ($sAttCode === 'id') { + $aAttToLoad[$sClassAlias] = []; + } else { + $aAttToLoad[$sClassAlias][$sAttCode] = MetaModel::GetAttributeDef($sClass, $sAttCode); + } - $sSQL = $this->MakeSelectQuery([], [], $aAttToLoad); - $resQuery = CMDBSource::Query($sSQL); - if (!$resQuery) - { - return []; - } + $sSQL = $this->MakeSelectQuery([], [], $aAttToLoad); + $resQuery = CMDBSource::Query($sSQL); + if (!$resQuery) { + return []; + } - $sColName = $sClassAlias.$sAttCode; + $sColName = $sClassAlias.$sAttCode; - $aRes = []; - while ($aRow = CMDBSource::FetchArray($resQuery)) - { - $aMappedRow = array(); - if($sAttCode === 'id') { - $aMappedRow[$sAttCode] = $aRow[$sColName]; - } else { - $aMappedRow[$sAttCode] = $aAttToLoad[$sClassAlias][$sAttCode]->FromSQLToValue($aRow, $sColName); - } - $aRes[] = $aMappedRow; - } - CMDBSource::FreeResult($resQuery); - return $aRes; - } + $aRes = []; + while ($aRow = CMDBSource::FetchArray($resQuery)) { + $aMappedRow = []; + if ($sAttCode === 'id') { + $aMappedRow[$sAttCode] = $aRow[$sColName]; + } else { + $aMappedRow[$sAttCode] = $aAttToLoad[$sClassAlias][$sAttCode]->FromSQLToValue($aRow, $sColName); + } + $aRes[] = $aMappedRow; + } + CMDBSource::FreeResult($resQuery); + return $aRes; + } //////////////////////////////////////////////////////////////////////////// // // Construction of the SQL queries // //////////////////////////////////////////////////////////////////////////// - protected static $m_aQueryStructCache = array(); + protected static $m_aQueryStructCache = []; - - /** - * Generate a Group By SQL query from the current search - * - * @internal - * + /** + * Generate a Group By SQL query from the current search + * + * @internal + * * @param array $aArgs * @param array $aGroupByExpr array('alias' => Expression) * @param bool $bExcludeNullValues @@ -880,76 +838,62 @@ abstract class DBSearch * @param array $aOrderBy array('alias' => bool) true = ASC false = DESC * @param int $iLimitCount * @param int $iLimitStart - * + * * @return string SQL query generated - * + * * @throws Exception */ - public function MakeGroupByQuery($aArgs, $aGroupByExpr, $bExcludeNullValues = false, $aSelectExpr = array(), $aOrderBy = array(), $iLimitCount = 0, $iLimitStart = 0) + public function MakeGroupByQuery($aArgs, $aGroupByExpr, $bExcludeNullValues = false, $aSelectExpr = [], $aOrderBy = [], $iLimitCount = 0, $iLimitStart = 0) { // Sanity check - foreach($aGroupByExpr as $sAlias => $oExpr) - { - if (!($oExpr instanceof Expression)) - { + foreach ($aGroupByExpr as $sAlias => $oExpr) { + if (!($oExpr instanceof Expression)) { throw new CoreException("Wrong parameter for 'Group By' for [$sAlias] (an array('alias' => Expression) is awaited)"); } } - foreach($aSelectExpr as $sAlias => $oExpr) - { - if (array_key_exists($sAlias, $aGroupByExpr)) - { + foreach ($aSelectExpr as $sAlias => $oExpr) { + if (array_key_exists($sAlias, $aGroupByExpr)) { throw new CoreException("Alias collision between 'Group By' and 'Select Expressions' [$sAlias]"); } - if (!($oExpr instanceof Expression)) - { + if (!($oExpr instanceof Expression)) { throw new CoreException("Wrong parameter for 'Select Expressions' for [$sAlias] (an array('alias' => Expression) is awaited)"); } } - foreach($aOrderBy as $sAlias => $bAscending) - { - if (!array_key_exists($sAlias, $aGroupByExpr) && !array_key_exists($sAlias, $aSelectExpr) && ($sAlias != '_itop_count_')) - { + foreach ($aOrderBy as $sAlias => $bAscending) { + if (!array_key_exists($sAlias, $aGroupByExpr) && !array_key_exists($sAlias, $aSelectExpr) && ($sAlias != '_itop_count_')) { $aAllowedAliases = array_keys($aSelectExpr); - $aAllowedAliases = array_merge($aAllowedAliases, array_keys($aGroupByExpr)); + $aAllowedAliases = array_merge($aAllowedAliases, array_keys($aGroupByExpr)); $aAllowedAliases[] = '_itop_count_'; throw new CoreException("Wrong alias [$sAlias] for 'Order By'. Allowed values are: ", null, implode(", ", $aAllowedAliases)); } - if (!is_bool($bAscending)) - { + if (!is_bool($bAscending)) { throw new CoreException("Wrong direction in ORDER BY spec, found '$bAscending' and expecting a boolean value for '$sAlias''"); } } - if ($bExcludeNullValues) - { + if ($bExcludeNullValues) { // Null values are not handled (though external keys set to 0 are allowed) $oQueryFilter = $this->DeepClone(); - foreach ($aGroupByExpr as $oGroupByExp) - { - $oNull = new FunctionExpression('ISNULL', array($oGroupByExp)); + foreach ($aGroupByExpr as $oGroupByExp) { + $oNull = new FunctionExpression('ISNULL', [$oGroupByExp]); $oNotNull = new BinaryExpression($oNull, '!=', new TrueExpression()); $oQueryFilter->AddConditionExpression($oNotNull); } - } - else - { + } else { $oQueryFilter = $this; } - $aAttToLoad = array(); - $oSQLQuery = $oQueryFilter->GetSQLQuery(array(), $aArgs, $aAttToLoad, null, 0, 0, false, $aGroupByExpr, $aSelectExpr); + $aAttToLoad = []; + $oSQLQuery = $oQueryFilter->GetSQLQuery([], $aArgs, $aAttToLoad, null, 0, 0, false, $aGroupByExpr, $aSelectExpr); $aScalarArgs = MetaModel::PrepareQueryArguments($aArgs, $this->GetInternalParams(), $this->GetExpectedArguments()); - try - { + try { $bBeautifulSQL = self::$m_bTraceQueries || self::$m_bDebugQuery || self::$m_bIndentQueries; $sRes = $oSQLQuery->RenderGroupBy($aScalarArgs, $bBeautifulSQL, $aOrderBy, $iLimitCount, $iLimitStart); } // Catch CoreException to add info before throwing again // Other exceptions will be thrown directly - catch (CoreException $e) - { + catch (CoreException $e) { // Add some information... $e->addInfo('OQL', $this->ToOQL()); throw $e; @@ -977,79 +921,62 @@ abstract class DBSearch * @internal * */ - public function MakeSelectQuery($aOrderBy = array(), $aArgs = array(), $aAttToLoad = null, $aExtendedDataSpec = null, $iLimitCount = 0, $iLimitStart = 0, $bGetCount = false, $bBeautifulSQL = true) + public function MakeSelectQuery($aOrderBy = [], $aArgs = [], $aAttToLoad = null, $aExtendedDataSpec = null, $iLimitCount = 0, $iLimitStart = 0, $bGetCount = false, $bBeautifulSQL = true) { // Check the order by specification, and prefix with the class alias // and make sure that the ordering columns are going to be selected // $sClass = $this->GetClass(); $sClassAlias = $this->GetClassAlias(); - $aOrderSpec = array(); - foreach ($aOrderBy as $sFieldAlias => $bAscending) - { - if (!is_bool($bAscending)) - { + $aOrderSpec = []; + foreach ($aOrderBy as $sFieldAlias => $bAscending) { + if (!is_bool($bAscending)) { throw new CoreException("Wrong direction in ORDER BY spec, found '$bAscending' and expecting a boolean value"); } $iDotPos = strpos($sFieldAlias, '.'); - if ($iDotPos === false) - { + if ($iDotPos === false) { $sAttClass = $sClass; $sAttClassAlias = $sClassAlias; $sAttCode = $sFieldAlias; - } - else - { + } else { $sAttClassAlias = substr($sFieldAlias, 0, $iDotPos); $sAttClass = $this->GetClassName($sAttClassAlias); $sAttCode = substr($sFieldAlias, $iDotPos + 1); } - if ($sAttCode != 'id') - { + if ($sAttCode != 'id') { MyHelpers::CheckValueInArray('field name in ORDER BY spec', $sAttCode, MetaModel::GetAttributesList($sAttClass)); $oAttDef = MetaModel::GetAttributeDef($sAttClass, $sAttCode); - foreach($oAttDef->GetOrderBySQLExpressions($sAttClassAlias) as $sSQLExpression) - { + foreach ($oAttDef->GetOrderBySQLExpressions($sAttClassAlias) as $sSQLExpression) { $aOrderSpec[$sSQLExpression] = $bAscending; } - // Make sure that the columns used for sorting are present in the loaded columns - if (!is_null($aAttToLoad) && !isset($aAttToLoad[$sAttClassAlias][$sAttCode])) - { - $aAttToLoad[$sAttClassAlias][$sAttCode] = MetaModel::GetAttributeDef($sAttClass, $sAttCode); - } - } - else - { + // Make sure that the columns used for sorting are present in the loaded columns + if (!is_null($aAttToLoad) && !isset($aAttToLoad[$sAttClassAlias][$sAttCode])) { + $aAttToLoad[$sAttClassAlias][$sAttCode] = MetaModel::GetAttributeDef($sAttClass, $sAttCode); + } + } else { $aOrderSpec['`'.$sAttClassAlias.$sAttCode.'`'] = $bAscending; } } $oSQLQuery = $this->GetSQLQuery($aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount); - if ($this->m_bNoContextParameters) - { + if ($this->m_bNoContextParameters) { // Only internal parameters $aScalarArgs = $this->GetInternalParams(); - } - else - { + } else { // The complete list of arguments will include magic arguments (e.g. current_user->attcode) $aScalarArgs = MetaModel::PrepareQueryArguments($aArgs, $this->GetInternalParams(), $this->GetExpectedArguments()); } - try - { + try { $sRes = $oSQLQuery->RenderSelect($aOrderSpec, $aScalarArgs, $iLimitCount, $iLimitStart, $bGetCount, $bBeautifulSQL); - if ($sClassAlias == '_itop_') - { + if ($sClassAlias == '_itop_') { IssueLog::Info('SQL Query (_itop_): '.$sRes); } - } - catch (MissingQueryArgument $e) - { + } catch (MissingQueryArgument $e) { // Add some information... $e->addInfo('OQL', $this->ToOQL()); throw $e; @@ -1071,39 +998,37 @@ abstract class DBSearch * * @since 2.7.0 N°2555 */ - public function GetFirstResult($bMustHaveOneResultMax = true, $aOrderBy = array(), $aSearchParams = array()) + public function GetFirstResult($bMustHaveOneResultMax = true, $aOrderBy = [], $aSearchParams = []) { - $oSet = new DBObjectSet($this, array(), $aSearchParams, null, 2); + $oSet = new DBObjectSet($this, [], $aSearchParams, null, 2); $oFirstResult = $oSet->Fetch(); - if ($oFirstResult === null) // useless but here for readability ;) - { + if ($oFirstResult === null) { // useless but here for readability ;) return null; } - if ($bMustHaveOneResultMax) - { + if ($bMustHaveOneResultMax) { $oSecondResult = $oSet->Fetch(); - if ($oSecondResult !== null) - { + if ($oSecondResult !== null) { throw new CoreOqlMultipleResultsForbiddenException( - 'Search returned multiple results, this is forbidden. Query was: '.$this->ToOQL()); + 'Search returned multiple results, this is forbidden. Query was: '.$this->ToOQL() + ); } } return $oFirstResult; } - /** - * @internal - * @return mixed - */ - protected abstract function IsDataFiltered(); + /** + * @internal + * @return mixed + */ + abstract protected function IsDataFiltered(); - /** - * @internal - * @return mixed - */ - protected abstract function SetDataFiltered(); + /** + * @internal + * @return mixed + */ + abstract protected function SetDataFiltered(); /** * @param $aOrderBy @@ -1124,18 +1049,14 @@ abstract class DBSearch protected function GetSQLQuery($aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount, $aGroupByExpr = null, $aSelectExpr = null) { $oSearch = $this; - if (!$this->IsAllDataAllowed() && !$this->IsDataFiltered()) - { - foreach ($this->GetSelectedClasses() as $sClassAlias => $sClass) - { + if (!$this->IsAllDataAllowed() && !$this->IsDataFiltered()) { + foreach ($this->GetSelectedClasses() as $sClassAlias => $sClass) { $oVisibleObjects = UserRights::GetSelectFilter($sClass, $this->GetModifierProperties('UserRightsGetSelectFilter')); - if ($oVisibleObjects === false) - { + if ($oVisibleObjects === false) { // Make sure this is a valid search object, saying NO for all $oVisibleObjects = DBObjectSearch::FromEmptySet($sClass); } - if (is_object($oVisibleObjects)) - { + if (is_object($oVisibleObjects)) { $oVisibleObjects->AllowAllData(); $oSearch = $oSearch->Filter($sClassAlias, $oVisibleObjects); $oSearch->SetDataFiltered(); @@ -1143,22 +1064,17 @@ abstract class DBSearch } } - if (is_array($aGroupByExpr)) - { - foreach($aGroupByExpr as $sAlias => $oGroupByExp) - { + if (is_array($aGroupByExpr)) { + foreach ($aGroupByExpr as $sAlias => $oGroupByExp) { /** @var \Expression $oGroupByExp */ $aFields = $oGroupByExp->ListRequiredFields(); - foreach($aFields as $sFieldAlias) - { - $aMatches = array(); - if (preg_match('/^([^.]+)\\.([^.]+)$/', $sFieldAlias, $aMatches)) - { + foreach ($aFields as $sFieldAlias) { + $aMatches = []; + if (preg_match('/^([^.]+)\\.([^.]+)$/', $sFieldAlias, $aMatches)) { $sFieldClass = $this->GetClassName($aMatches[1]); $oAttDef = MetaModel::GetAttributeDef($sFieldClass, $aMatches[2]); - if ( $oAttDef instanceof iAttributeNoGroupBy) - { + if ($oAttDef instanceof iAttributeNoGroupBy) { throw new Exception("Grouping on '$sFieldClass' fields is not supported."); } } @@ -1171,12 +1087,10 @@ abstract class DBSearch // Join to an additional table, if required... // - if ($aExtendedDataSpec != null) - { + if ($aExtendedDataSpec != null) { $sTableAlias = '_extended_data_'; - $aExtendedFields = array(); - foreach($aExtendedDataSpec['fields'] as $sColumn) - { + $aExtendedFields = []; + foreach ($aExtendedDataSpec['fields'] as $sColumn) { $sColRef = $this->GetClassAlias().'_extdata_'.$sColumn; $aExtendedFields[$sColRef] = new FieldExpressionResolved($sColumn, $sTableAlias); } @@ -1187,40 +1101,45 @@ abstract class DBSearch return $oSQLQuery; } - /** - * @internal - * - * @param $aAttToLoad - * @param $bGetCount - * @param null $aGroupByExpr - * @param null $aSelectedClasses - * @param null $aSelectExpr - * - * @return mixed - */ - public abstract function GetSQLQueryStructure( - $aAttToLoad, $bGetCount, $aGroupByExpr = null, $aSelectedClasses = null, $aSelectExpr = null + /** + * @internal + * + * @param $aAttToLoad + * @param $bGetCount + * @param null $aGroupByExpr + * @param null $aSelectedClasses + * @param null $aSelectExpr + * + * @return mixed + */ + abstract public function GetSQLQueryStructure( + $aAttToLoad, + $bGetCount, + $aGroupByExpr = null, + $aSelectedClasses = null, + $aSelectExpr = null ); - /** - * Shortcut to add efficient IN condition - * - * @internal - * - * @param $sFilterCode - * @param $aValues - * @param bool $bPositiveMatch if true a `IN` is performed, if false, a `NOT IN` is performed - * - * @return mixed - */ - public abstract function AddConditionForInOperatorUsingParam($sFilterCode, $aValues, $bPositiveMatch = true); + /** + * Shortcut to add efficient IN condition + * + * @internal + * + * @param $sFilterCode + * @param $aValues + * @param bool $bPositiveMatch if true a `IN` is performed, if false, a `NOT IN` is performed + * + * @return mixed + */ + abstract public function AddConditionForInOperatorUsingParam($sFilterCode, $aValues, $bPositiveMatch = true); /** - * @internal + * @internal * @return string a unique param name */ - protected function GenerateUniqueParamName() { - return str_replace('.', '', 'param_'.microtime(true).rand(0,100)); + protected function GenerateUniqueParamName() + { + return str_replace('.', '', 'param_'.microtime(true).rand(0, 100)); } //////////////////////////////////////////////////////////////////////////// @@ -1229,7 +1148,7 @@ abstract class DBSearch // //////////////////////////////////////////////////////////////////////////// protected static $m_bDebugQuery = false; - protected static $m_aQueriesLog = array(); + protected static $m_aQueriesLog = []; protected static $m_bQueryCacheEnabled = false; protected static $m_bUseAPCCache = false; protected static $m_iQueryCacheTTL = 3600; @@ -1237,30 +1156,30 @@ abstract class DBSearch protected static $m_bIndentQueries = false; protected static $m_bOptimizeQueries = false; - /** - * @internal - */ + /** + * @internal + */ public static function StartDebugQuery() { $aBacktrace = debug_backtrace(); self::$m_bDebugQuery = true; } - /** - * @internal - */ + /** + * @internal + */ public static function StopDebugQuery() { self::$m_bDebugQuery = false; } - /** - * @internal - * - * @param bool $bEnabled - * @param bool $bUseAPC - * @param int $iTimeToLive - */ + /** + * @internal + * + * @param bool $bEnabled + * @param bool $bUseAPC + * @param int $iTimeToLive + */ public static function EnableQueryCache($bEnabled, $bUseAPC, $iTimeToLive = 3600) { self::$m_bQueryCacheEnabled = $bEnabled; @@ -1268,28 +1187,28 @@ abstract class DBSearch self::$m_iQueryCacheTTL = $iTimeToLive; } - /** - * @internal - * @param $bEnabled - */ + /** + * @internal + * @param $bEnabled + */ public static function EnableQueryTrace($bEnabled) { self::$m_bTraceQueries = $bEnabled; } - /** - * @internal - * @param $bEnabled - */ + /** + * @internal + * @param $bEnabled + */ public static function EnableQueryIndentation($bEnabled) { self::$m_bIndentQueries = $bEnabled; } - /** - * @internal - * @param $bEnabled - */ + /** + * @internal + * @param $bEnabled + */ public static function EnableOptimizeQuery($bEnabled) { self::$m_bOptimizeQueries = $bEnabled; @@ -1313,46 +1232,39 @@ abstract class DBSearch */ protected function AddQueryTraceSelect($sOql, $aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount, $sSql) { - if (self::$m_bTraceQueries) - { - $aQueryData = array( + if (self::$m_bTraceQueries) { + $aQueryData = [ 'type' => 'select', 'order_by' => $aOrderBy, 'att_to_load' => $aAttToLoad, 'limit_count' => $iLimitCount, 'limit_start' => $iLimitStart, - 'is_count' => $bGetCount - ); + 'is_count' => $bGetCount, + ]; DBSearch::EnableQueryTrace(false); $aQueryData['oql'] = $this->ToOQL(true, $aArgs); DBSearch::EnableQueryTrace(true); - if (!empty($aAttToLoad)) - { - $aAttToLoadNames = array(); - foreach ($aAttToLoad as $sClass => $aAttributes) - { - $aAttToLoadNames[$sClass] = array(); - foreach ($aAttributes as $sAttCode => $oAttDef) - { + if (!empty($aAttToLoad)) { + $aAttToLoadNames = []; + foreach ($aAttToLoad as $sClass => $aAttributes) { + $aAttToLoadNames[$sClass] = []; + foreach ($aAttributes as $sAttCode => $oAttDef) { $aAttToLoadNames[$sClass][] = $sAttCode; } } - } - else - { + } else { $aAttToLoadNames = null; } $aQueryData['att_to_load'] = $aAttToLoadNames; $hLogFile = @fopen(APPROOT.'log/oql_records.txt', 'a'); - if ($hLogFile !== false) - { - flock($hLogFile,LOCK_EX); - fwrite($hLogFile,serialize($aQueryData)."\n"); + if ($hLogFile !== false) { + flock($hLogFile, LOCK_EX); + fwrite($hLogFile, serialize($aQueryData)."\n"); fflush($hLogFile); - flock($hLogFile,LOCK_UN); + flock($hLogFile, LOCK_UN); fclose($hLogFile); } } @@ -1376,9 +1288,8 @@ abstract class DBSearch */ protected function AddQueryTraceGroupBy($aArgs, $aGroupByExpr, $bExcludeNullValues, $aSelectExpr, $aOrderBy, $iLimitCount, $iLimitStart, $sSql) { - if (self::$m_bTraceQueries) - { - $aQueryData = array( + if (self::$m_bTraceQueries) { + $aQueryData = [ 'type' => 'group_by', 'order_by' => $aOrderBy, 'group_by_expr' => $aGroupByExpr, @@ -1386,89 +1297,77 @@ abstract class DBSearch 'select_expr' => $aSelectExpr, 'limit_count' => $iLimitCount, 'limit_start' => $iLimitStart, - ); + ]; $aQueryData['oql'] = $this->ToOQL(true, $aArgs); $aQueryData['group_by_expr'] = Expression::ConvertArrayToOQL($aQueryData['group_by_expr'], $aArgs); $aQueryData['select_expr'] = Expression::ConvertArrayToOQL($aQueryData['select_expr'], $aArgs); $hLogFile = @fopen(APPROOT.'log/oql_group_by_records.txt', 'a'); - if ($hLogFile !== false) - { - flock($hLogFile,LOCK_EX); - fwrite($hLogFile,serialize($aQueryData)."\n"); + if ($hLogFile !== false) { + flock($hLogFile, LOCK_EX); + fwrite($hLogFile, serialize($aQueryData)."\n"); fflush($hLogFile); - flock($hLogFile,LOCK_UN); + flock($hLogFile, LOCK_UN); fclose($hLogFile); } } } - /** - * @internal - * - * @param $aQueryData - * @param $sOql - * @param $sSql - * - * @throws MySQLException - */ + /** + * @internal + * + * @param $aQueryData + * @param $sOql + * @param $sSql + * + * @throws MySQLException + */ protected static function AddQueryTrace($aQueryData, $sOql, $sSql) { - if (self::$m_bTraceQueries) - { + if (self::$m_bTraceQueries) { $sQueryId = md5(serialize($aQueryData)); $sMySQLQueryId = md5($sSql); - if(!isset(self::$m_aQueriesLog[$sQueryId])) - { + if (!isset(self::$m_aQueriesLog[$sQueryId])) { self::$m_aQueriesLog[$sQueryId]['data'] = serialize($aQueryData); self::$m_aQueriesLog[$sQueryId]['oql'] = $sOql; self::$m_aQueriesLog[$sQueryId]['hits'] = 1; - } - else - { + } else { self::$m_aQueriesLog[$sQueryId]['hits']++; } - if(!isset(self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId])) - { + if (!isset(self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId])) { self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['sql'] = $sSql; self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['count'] = 1; $iTableCount = count(CMDBSource::ExplainQuery($sSql)); self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['table_count'] = $iTableCount; - } - else - { + } else { self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['count']++; } } } - /** - * @internal - */ + /** + * @internal + */ public static function RecordQueryTrace() { - if (!self::$m_bTraceQueries) - { + if (!self::$m_bTraceQueries) { return; } $iOqlCount = count(self::$m_aQueriesLog); $iSqlCount = 0; - foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData) - { + foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData) { $iSqlCount += $aOqlData['hits']; } $sHtml = "

    Stats on SELECT queries: OQL=$iOqlCount, SQL=$iSqlCount

    \n"; - foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData) - { + foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData) { $sOql = $aOqlData['oql']; $sHits = $aOqlData['hits']; $sHtml .= "

    $sHits hits for OQL query: $sOql

    \n"; $sHtml .= "
      \n"; - foreach($aOqlData['queries'] as $aSqlData) - { + foreach ($aOqlData['queries'] as $aSqlData) { $sQuery = $aSqlData['sql']; $sSqlHits = $aSqlData['count']; $iTableCount = $aSqlData['table_count']; @@ -1485,60 +1384,49 @@ abstract class DBSearch // Cumulate the queries $sAllQueries = utils::GetDataPath().'queries.log'; - if (file_exists($sAllQueries)) - { + if (file_exists($sAllQueries)) { // Merge the new queries into the existing log include($sAllQueries); - $aQueriesLog = array(); - foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData) - { - if (!array_key_exists($sQueryId, $aQueriesLog)) - { + $aQueriesLog = []; + foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData) { + if (!array_key_exists($sQueryId, $aQueriesLog)) { $aQueriesLog[$sQueryId] = $aOqlData; } } - } - else - { + } else { $aQueriesLog = self::$m_aQueriesLog; } $sLog = "".$aBacktrace[1]["function"].""; - if (is_object($value)) - { + if (is_object($value)) { echo "$sIndent$sFunction:\n
      \n";
       			print_r($value);
       			echo "
      \n"; - } - else - { + } else { echo "$sIndent$sFunction: $value
      \n"; } } @@ -1556,63 +1444,49 @@ abstract class DBSearch public function DBBulkWriteArchiveFlag($bArchive) { $sClass = $this->GetClass(); - if (!MetaModel::IsArchivable($sClass)) - { + if (!MetaModel::IsArchivable($sClass)) { throw new Exception($sClass.' is not an archivable class'); } $iFlag = $bArchive ? 1 : 0; $oSet = new DBObjectSet($this); - if (MetaModel::IsStandaloneClass($sClass)) - { - $oSet->OptimizeColumnLoad(array($this->GetClassAlias() => array())); - $aIds = array($sClass => $oSet->GetColumnAsArray('id')); - } - else - { - $oSet->OptimizeColumnLoad(array($this->GetClassAlias() => array('finalclass'))); + if (MetaModel::IsStandaloneClass($sClass)) { + $oSet->OptimizeColumnLoad([$this->GetClassAlias() => []]); + $aIds = [$sClass => $oSet->GetColumnAsArray('id')]; + } else { + $oSet->OptimizeColumnLoad([$this->GetClassAlias() => ['finalclass']]); $aTemp = $oSet->GetColumnAsArray('finalclass'); - $aIds = array(); - foreach ($aTemp as $iObjectId => $sObjectClass) - { + $aIds = []; + foreach ($aTemp as $iObjectId => $sObjectClass) { $aIds[$sObjectClass][$iObjectId] = $iObjectId; } } - foreach ($aIds as $sFinalClass => $aObjectIds) - { + foreach ($aIds as $sFinalClass => $aObjectIds) { $sIds = implode(', ', $aObjectIds); $sArchiveRoot = MetaModel::GetAttributeOrigin($sFinalClass, 'archive_flag'); $sRootTable = MetaModel::DBGetTable($sArchiveRoot); $sRootKey = MetaModel::DBGetKey($sArchiveRoot); - $aJoins = array("`$sRootTable`"); - $aUpdates = array(); - foreach (MetaModel::EnumParentClasses($sFinalClass, ENUM_PARENT_CLASSES_ALL) as $sParentClass) - { - if (!MetaModel::IsValidAttCode($sParentClass, 'archive_flag')) - { + $aJoins = ["`$sRootTable`"]; + $aUpdates = []; + foreach (MetaModel::EnumParentClasses($sFinalClass, ENUM_PARENT_CLASSES_ALL) as $sParentClass) { + if (!MetaModel::IsValidAttCode($sParentClass, 'archive_flag')) { continue; } $sTable = MetaModel::DBGetTable($sParentClass); $aUpdates[] = "`$sTable`.`archive_flag` = $iFlag"; - if ($sParentClass == $sArchiveRoot) - { - if ($bArchive) - { + if ($sParentClass == $sArchiveRoot) { + if ($bArchive) { // Set the date (do not change it) $sDate = '"'.date(AttributeDate::GetSQLFormat()).'"'; $aUpdates[] = "`$sTable`.`archive_date` = coalesce(`$sTable`.`archive_date`, $sDate)"; - } - else - { + } else { // Reset the date $aUpdates[] = "`$sTable`.`archive_date` = null"; } - } - else - { + } else { $sKey = MetaModel::DBGetKey($sParentClass); $aJoins[] = "`$sTable` ON `$sTable`.`$sKey` = `$sRootTable`.`$sRootKey`"; } @@ -1624,9 +1498,9 @@ abstract class DBSearch } } - /** - * @internal - */ + /** + * @internal + */ public function UpdateContextFromUser() { $this->SetShowObsoleteData(utils::ShowObsoleteData()); @@ -1649,5 +1523,5 @@ abstract class DBSearch * * @return array{\VariableExpression} */ - abstract function GetExpectedArguments(): array; + abstract public function GetExpectedArguments(): array; } diff --git a/core/dbunionsearch.class.php b/core/dbunionsearch.class.php index bd2336936..9d3836f0e 100644 --- a/core/dbunionsearch.class.php +++ b/core/dbunionsearch.class.php @@ -1,4 +1,5 @@ classes (lowest common ancestors) computed at construction protected $aColumnToAliases; - /** - * DBUnionSearch constructor. - * - * @api - * - * @param $aSearches - * - * @throws CoreException - */ + /** + * DBUnionSearch constructor. + * + * @api + * + * @param $aSearches + * + * @throws CoreException + */ public function __construct($aSearches) { - if (count ($aSearches) == 0) - { + if (count($aSearches) == 0) { throw new CoreException('A DBUnionSearch must be made of at least one search'); } - $this->aSearches = array(); - foreach ($aSearches as $oSearch) - { - if ($oSearch instanceof DBUnionSearch) - { - foreach ($oSearch->aSearches as $oSubSearch) - { + $this->aSearches = []; + foreach ($aSearches as $oSearch) { + if ($oSearch instanceof DBUnionSearch) { + foreach ($oSearch->aSearches as $oSubSearch) { $this->aSearches[] = $oSubSearch->DeepClone(); } } else { @@ -69,15 +66,16 @@ class DBUnionSearch extends DBSearch public function IsAllDataAllowed() { foreach ($this->aSearches as $oSearch) { - if ($oSearch->IsAllDataAllowed() === false) return false; + if ($oSearch->IsAllDataAllowed() === false) { + return false; + } } return true; } public function SetArchiveMode($bEnable) { - foreach ($this->aSearches as $oSearch) - { + foreach ($this->aSearches as $oSearch) { $oSearch->SetArchiveMode($bEnable); } parent::SetArchiveMode($bEnable); @@ -85,8 +83,7 @@ class DBUnionSearch extends DBSearch public function SetShowObsoleteData($bShow) { - foreach ($this->aSearches as $oSearch) - { + foreach ($this->aSearches as $oSearch) { $oSearch->SetShowObsoleteData($bShow); } parent::SetShowObsoleteData($bShow); @@ -102,31 +99,25 @@ class DBUnionSearch extends DBSearch // 1 - Collect all the column/classes $aColumnToClasses = []; $this->aColumnToAliases = []; - foreach ($this->aSearches as $iPos => $oSearch) - { + foreach ($this->aSearches as $iPos => $oSearch) { $aSelected = array_values($oSearch->GetSelectedClasses()); - if ($iPos != 0) - { - if (count($aSelected) < count($aColumnToClasses)) - { - throw new Exception('Too few selected classes in the subquery #'.($iPos+1)); + if ($iPos != 0) { + if (count($aSelected) < count($aColumnToClasses)) { + throw new Exception('Too few selected classes in the subquery #'.($iPos + 1)); } - if (count($aSelected) > count($aColumnToClasses)) - { - throw new Exception('Too many selected classes in the subquery #'.($iPos+1)); + if (count($aSelected) > count($aColumnToClasses)) { + throw new Exception('Too many selected classes in the subquery #'.($iPos + 1)); } } - foreach ($aSelected as $iColumn => $sClass) - { + foreach ($aSelected as $iColumn => $sClass) { $aColumnToClasses[$iColumn][$iPos] = $sClass; } // Store the aliases by column to map them later (the first query impose the aliases) $aAliases = array_keys($oSearch->GetSelectedClasses()); - foreach ($aAliases as $iColumn => $sAlias) - { + foreach ($aAliases as $iColumn => $sAlias) { $this->aColumnToAliases[$iColumn][$iPos] = $sAlias; } } @@ -137,13 +128,11 @@ class DBUnionSearch extends DBSearch // 3 - Compute alias => lowest common ancestor $this->aSelectedClasses = []; - foreach ($aColumnToClasses as $iColumn => $aClasses) - { + foreach ($aColumnToClasses as $iColumn => $aClasses) { $sAlias = $aColumnToAlias[$iColumn]; $sAncestor = MetaModel::GetLowestCommonAncestor($aClasses); - if (is_null($sAncestor)) - { - throw new Exception('Could not find a common ancestor for the column '.($iColumn+1).' (Classes: '.implode(', ', $aClasses).')'); + if (is_null($sAncestor)) { + throw new Exception('Could not find a common ancestor for the column '.($iColumn + 1).' (Classes: '.implode(', ', $aClasses).')'); } $this->aSelectedClasses[$sAlias] = $sAncestor; } @@ -164,12 +153,9 @@ class DBUnionSearch extends DBSearch */ public function GetClassName($sAlias) { - if (array_key_exists($sAlias, $this->aSelectedClasses)) - { + if (array_key_exists($sAlias, $this->aSelectedClasses)) { return $this->aSelectedClasses[$sAlias]; - } - else - { + } else { throw new CoreException("Invalid class alias '$sAlias'"); } } @@ -185,20 +171,16 @@ class DBUnionSearch extends DBSearch return key($this->aSelectedClasses); } - /** * Change the class (only subclasses are supported as of now, because the conditions must fit the new class) * Defaults to the first selected class * Only the selected classes can be changed - */ + */ public function ChangeClass($sNewClass, $sAlias = null) { - if (is_null($sAlias)) - { + if (is_null($sAlias)) { $sAlias = $this->GetClassAlias(); - } - elseif (!array_key_exists($sAlias, $this->aSelectedClasses)) - { + } elseif (!array_key_exists($sAlias, $this->aSelectedClasses)) { // discard silently - necessary when recursing (??? copied from DBObjectSearch) return; } @@ -207,8 +189,7 @@ class DBUnionSearch extends DBSearch $iColumn = array_search($sAlias, array_keys($this->aSelectedClasses)); // 2 - change for each search - foreach ($this->aSearches as $oSearch) - { + foreach ($this->aSearches as $oSearch) { $aSearchAliases = array_keys($oSearch->GetSelectedClasses()); $sSearchAlias = $aSearchAliases[$iColumn]; $oSearch->ChangeClass($sNewClass, $sSearchAlias); @@ -279,38 +260,31 @@ class DBUnionSearch extends DBSearch public function RenameAlias($sOldName, $sNewName) { $bRet = false; - foreach ($this->aSearches as $oSearch) - { + foreach ($this->aSearches as $oSearch) { $bRet = $oSearch->RenameAlias($sOldName, $sNewName) || $bRet; } return $bRet; } - public function RenameAliasesInNameSpace($aClassAliases, $aAliasTranslation = array()) + public function RenameAliasesInNameSpace($aClassAliases, $aAliasTranslation = []) { - foreach ($this->aSearches as $oSearch) - { + foreach ($this->aSearches as $oSearch) { $oSearch->RenameAliasesInNameSpace($aClassAliases, $aAliasTranslation); } } public function TranslateConditions($aTranslationData, $bMatchAll = true, $bMarkFieldsAsResolved = true) { - foreach ($this->aSearches as $oSearch) - { + foreach ($this->aSearches as $oSearch) { $oSearch->TranslateConditions($aTranslationData, $bMatchAll, $bMarkFieldsAsResolved); } } - - public function IsAny() { $bIsAny = true; - foreach ($this->aSearches as $oSearch) - { - if (!$oSearch->IsAny()) - { + foreach ($this->aSearches as $oSearch) { + if (!$oSearch->IsAny()) { $bIsAny = false; break; } @@ -320,8 +294,7 @@ class DBUnionSearch extends DBSearch public function ResetCondition() { - foreach ($this->aSearches as $oSearch) - { + foreach ($this->aSearches as $oSearch) { $oSearch->ResetCondition(); } } @@ -329,13 +302,10 @@ class DBUnionSearch extends DBSearch public function MergeConditionExpression($oExpression) { $aAliases = array_keys($this->aSelectedClasses); - foreach ($this->aSearches as $iSearchIndex => $oSearch) - { + foreach ($this->aSearches as $iSearchIndex => $oSearch) { $oClonedExpression = $oExpression->DeepClone(); - if ($iSearchIndex != 0) - { - foreach (array_keys($oSearch->GetSelectedClasses()) as $iColumn => $sSearchAlias) - { + if ($iSearchIndex != 0) { + foreach (array_keys($oSearch->GetSelectedClasses()) as $iColumn => $sSearchAlias) { $oClonedExpression->RenameAlias($aAliases[$iColumn], $sSearchAlias); } } @@ -346,13 +316,10 @@ class DBUnionSearch extends DBSearch public function AddConditionExpression($oExpression) { $aAliases = array_keys($this->aSelectedClasses); - foreach ($this->aSearches as $iSearchIndex => $oSearch) - { + foreach ($this->aSearches as $iSearchIndex => $oSearch) { $oClonedExpression = $oExpression->DeepClone(); - if ($iSearchIndex != 0) - { - foreach (array_keys($oSearch->GetSelectedClasses()) as $iColumn => $sSearchAlias) - { + if ($iSearchIndex != 0) { + foreach (array_keys($oSearch->GetSelectedClasses()) as $iColumn => $sSearchAlias) { $oClonedExpression->RenameAlias($aAliases[$iColumn], $sSearchAlias); } } @@ -360,18 +327,16 @@ class DBUnionSearch extends DBSearch } } - public function AddNameCondition($sName) + public function AddNameCondition($sName) { - foreach ($this->aSearches as $oSearch) - { + foreach ($this->aSearches as $oSearch) { $oSearch->AddNameCondition($sName); } } public function AddCondition($sFilterCode, $value, $sOpCode = null) { - foreach ($this->aSearches as $oSearch) - { + foreach ($this->aSearches as $oSearch) { $oSearch->AddCondition($sFilterCode, $value, $sOpCode); } } @@ -379,35 +344,32 @@ class DBUnionSearch extends DBSearch /** * Specify a condition on external keys or link sets * @param String sAttSpec Can be either an attribute code or extkey->[sAttSpec] or linkset->[sAttSpec] and so on, recursively - * Example: infra_list->ci_id->location_id->country + * Example: infra_list->ci_id->location_id->country * @param Object value The value to match (can be an array => IN(val1, val2...) * @return void */ public function AddConditionAdvanced($sAttSpec, $value) { - foreach ($this->aSearches as $oSearch) - { + foreach ($this->aSearches as $oSearch) { $oSearch->AddConditionAdvanced($sAttSpec, $value); } } public function AddCondition_FullText($sFullText) { - foreach ($this->aSearches as $oSearch) - { + foreach ($this->aSearches as $oSearch) { $oSearch->AddCondition_FullText($sFullText); } } public function AddCondition_FullTextOnAttributes(array $aAttCodes, $sNeedle) { - foreach ($this->aSearches as $oSearch) - { + foreach ($this->aSearches as $oSearch) { $oSearch->AddCondition_FullTextOnAttributes($aAttCodes, $sNeedle); } } - /** + /** * @param DBObjectSearch $oFilter * @param $sExtKeyAttCode * @param int $iOperatorCode @@ -415,8 +377,7 @@ class DBUnionSearch extends DBSearch */ public function AddCondition_PointingTo(DBObjectSearch $oFilter, $sExtKeyAttCode, $iOperatorCode = TREE_OPERATOR_EQUALS, &$aRealiasingMap = null) { - foreach ($this->aSearches as $oSearch) - { + foreach ($this->aSearches as $oSearch) { $oConditionFilter = $oFilter->DeepClone(); $oSearch->AddCondition_PointingTo($oConditionFilter, $sExtKeyAttCode, $iOperatorCode, $aRealiasingMap); } @@ -430,8 +391,7 @@ class DBUnionSearch extends DBSearch */ public function AddCondition_ReferencedBy(DBObjectSearch $oFilter, $sForeignExtKeyAttCode, $iOperatorCode = TREE_OPERATOR_EQUALS, &$aRealiasingMap = null) { - foreach ($this->aSearches as $oSearch) - { + foreach ($this->aSearches as $oSearch) { $oConditionFilter = $oFilter->DeepClone(); $oSearch->AddCondition_ReferencedBy($oConditionFilter, $sForeignExtKeyAttCode, $iOperatorCode, $aRealiasingMap); } @@ -439,9 +399,8 @@ class DBUnionSearch extends DBSearch public function Filter($sClassAlias, DBSearch $oFilter) { - $aSearches = array(); - foreach ($this->aSearches as $oSearch) - { + $aSearches = []; + foreach ($this->aSearches as $oSearch) { if (!$oSearch->IsAllDataAllowed()) { $aSearches[] = $oSearch->Filter($sClassAlias, $oFilter); } else { @@ -453,9 +412,8 @@ class DBUnionSearch extends DBSearch public function Intersect(DBSearch $oFilter) { - $aSearches = array(); - foreach ($this->aSearches as $oSearch) - { + $aSearches = []; + foreach ($this->aSearches as $oSearch) { $aSearches[] = $oSearch->Intersect($oFilter); } return new DBUnionSearch($aSearches); @@ -463,17 +421,15 @@ class DBUnionSearch extends DBSearch public function SetInternalParams($aParams) { - foreach ($this->aSearches as $oSearch) - { + foreach ($this->aSearches as $oSearch) { $oSearch->SetInternalParams($aParams); } } public function GetInternalParams() { - $aParams = array(); - foreach ($this->aSearches as $oSearch) - { + $aParams = []; + foreach ($this->aSearches as $oSearch) { $aParams = array_merge($oSearch->GetInternalParams(), $aParams); } return $aParams; @@ -481,9 +437,8 @@ class DBUnionSearch extends DBSearch public function GetQueryParams() { - $aParams = array(); - foreach ($this->aSearches as $oSearch) - { + $aParams = []; + foreach ($this->aSearches as $oSearch) { $aParams = array_merge($oSearch->GetQueryParams(), $aParams); } return $aParams; @@ -492,7 +447,7 @@ class DBUnionSearch extends DBSearch public function ListConstantFields() { // Somewhat complex to implement for unions, for a poor benefit - return array(); + return []; } /** @@ -501,20 +456,18 @@ class DBUnionSearch extends DBSearch */ public function ApplyParameters($aArgs) { - foreach ($this->aSearches as $oSearch) - { + foreach ($this->aSearches as $oSearch) { $oSearch->ApplyParameters($aArgs); } } /** * Overloads for query building - */ + */ public function ToOQL($bDevelopParams = false, $aContextParams = null, $bWithAllowAllFlag = false) { - $aSubQueries = array(); - foreach ($this->aSearches as $oSearch) - { + $aSubQueries = []; + foreach ($this->aSearches as $oSearch) { $aSubQueries[] = $oSearch->ToOQL($bDevelopParams, $aContextParams, $bWithAllowAllFlag); } $sRet = implode(' UNION ', $aSubQueries); @@ -527,9 +480,8 @@ class DBUnionSearch extends DBSearch */ public function ToJSON() { - $sRet = array('unions' => array()); - foreach ($this->aSearches as $oSearch) - { + $sRet = ['unions' => []]; + foreach ($this->aSearches as $oSearch) { $sRet['unions'][] = $oSearch->ToJSON(); } return $sRet; @@ -543,21 +495,19 @@ class DBUnionSearch extends DBSearch */ public function RemoveDuplicateQueries() { - $aQueries = array(); - $aSearches = array(); + $aQueries = []; + $aSearches = []; - foreach ($this->GetSearches() as $oTmpSearch) - { + foreach ($this->GetSearches() as $oTmpSearch) { $sQuery = $oTmpSearch->ToOQL(true); - if (!in_array($sQuery, $aQueries)) - { + if (!in_array($sQuery, $aQueries)) { $aQueries[] = $sQuery; $aSearches[] = $oTmpSearch; } } $oNewSearch = new DBUnionSearch($aSearches); - + return $oNewSearch; } @@ -567,60 +517,49 @@ class DBUnionSearch extends DBSearch // //////////////////////////////////////////////////////////////////////////// - public function MakeDeleteQuery($aArgs = array()) + public function MakeDeleteQuery($aArgs = []) { throw new Exception('MakeDeleteQuery is not implemented for the unions!'); } - public function MakeUpdateQuery($aValues, $aArgs = array()) + public function MakeUpdateQuery($aValues, $aArgs = []) { throw new Exception('MakeUpdateQuery is not implemented for the unions!'); } public function GetSQLQueryStructure($aAttToLoad, $bGetCount, $aGroupByExpr = null, $aSelectedClasses = null, $aSelectExpr = null) { - if (count($this->aSearches) == 1) - { + if (count($this->aSearches) == 1) { return $this->aSearches[0]->GetSQLQueryStructure($aAttToLoad, $bGetCount, $aGroupByExpr, $aSelectedClasses, $aSelectExpr); } - $aSQLQueries = array(); + $aSQLQueries = []; $aAliases = array_keys($this->aSelectedClasses); $aQueryAttToLoad = null; - $aUnionQuerySelectExpr = array(); - foreach ($this->aSearches as $iSearch => $oSearch) - { + $aUnionQuerySelectExpr = []; + foreach ($this->aSearches as $iSearch => $oSearch) { $aSearchAliases = array_keys($oSearch->GetSelectedClasses()); // The selected classes from the query build perspective are the lowest common ancestors amongst the various queries // (used when it comes to determine which attributes must be selected) - $aSearchSelectedClasses = array(); - foreach ($aSearchAliases as $iColumn => $sSearchAlias) - { + $aSearchSelectedClasses = []; + foreach ($aSearchAliases as $iColumn => $sSearchAlias) { $sAlias = $aAliases[$iColumn]; $aSearchSelectedClasses[$sSearchAlias] = $this->aSelectedClasses[$sAlias]; } - if ($bGetCount) - { + if ($bGetCount) { // Select only ids for the count to allow optimization of joins - foreach($aSearchAliases as $sSearchAlias) - { - $aQueryAttToLoad[$sSearchAlias] = array(); + foreach ($aSearchAliases as $sSearchAlias) { + $aQueryAttToLoad[$sSearchAlias] = []; } - } - else - { - if (is_null($aAttToLoad)) - { + } else { + if (is_null($aAttToLoad)) { $aQueryAttToLoad = null; - } - else - { + } else { // (Eventually) Transform the aliases - $aQueryAttToLoad = array(); - foreach($aAttToLoad as $sAlias => $aAttributes) - { + $aQueryAttToLoad = []; + foreach ($aAttToLoad as $sAlias => $aAttributes) { $iColumn = array_search($sAlias, $aAliases); $sQueryAlias = ($iColumn === false) ? $sAlias : $aSearchAliases[$iColumn]; $aQueryAttToLoad[$sQueryAlias] = $aAttributes; @@ -628,66 +567,51 @@ class DBUnionSearch extends DBSearch } } - if (is_null($aGroupByExpr)) - { + if (is_null($aGroupByExpr)) { $aQueryGroupByExpr = null; - } - else - { + } else { // Clone (and eventually transform) the group by expressions - $aQueryGroupByExpr = array(); - $aTranslationData = array(); + $aQueryGroupByExpr = []; + $aTranslationData = []; $aQueryColumns = array_keys($oSearch->GetSelectedClasses()); - foreach ($aAliases as $iColumn => $sAlias) - { + foreach ($aAliases as $iColumn => $sAlias) { $sQueryAlias = $aQueryColumns[$iColumn]; $aTranslationData[$sAlias]['*'] = $sQueryAlias; $aQueryGroupByExpr[$sAlias.'id'] = new FieldExpression('id', $sQueryAlias); } - foreach ($aGroupByExpr as $sExpressionAlias => $oExpression) - { + foreach ($aGroupByExpr as $sExpressionAlias => $oExpression) { $aQueryGroupByExpr[$sExpressionAlias] = $oExpression->Translate($aTranslationData, false, false); } } - if (is_null($aSelectExpr)) - { + if (is_null($aSelectExpr)) { $aQuerySelectExpr = null; - } - else - { - $aQuerySelectExpr = array(); - $aTranslationData = array(); + } else { + $aQuerySelectExpr = []; + $aTranslationData = []; $aQueryColumns = array_keys($oSearch->GetSelectedClasses()); - foreach($aAliases as $iColumn => $sAlias) - { + foreach ($aAliases as $iColumn => $sAlias) { $sQueryAlias = $aQueryColumns[$iColumn]; $aTranslationData[$sAlias]['*'] = $sQueryAlias; } - foreach($aSelectExpr as $sExpressionAlias => $oExpression) - { - $oExpression->Browse(function ($oNode) use (&$aQuerySelectExpr, &$aTranslationData) - { - if ($oNode instanceof FieldExpression) - { + foreach ($aSelectExpr as $sExpressionAlias => $oExpression) { + $oExpression->Browse(function ($oNode) use (&$aQuerySelectExpr, &$aTranslationData) { + if ($oNode instanceof FieldExpression) { $sAlias = $oNode->GetParent()."__".$oNode->GetName(); - if (!key_exists($sAlias, $aQuerySelectExpr)) - { + if (!key_exists($sAlias, $aQuerySelectExpr)) { $aQuerySelectExpr[$sAlias] = $oNode->Translate($aTranslationData, false, false); } $aTranslationData[$oNode->GetParent()][$oNode->GetName()] = new FieldExpression($sAlias); } }); // Only done for the first select as aliases are named after the first query - if (!array_key_exists($sExpressionAlias, $aUnionQuerySelectExpr)) - { + if (!array_key_exists($sExpressionAlias, $aUnionQuerySelectExpr)) { $aUnionQuerySelectExpr[$sExpressionAlias] = $oExpression->Translate($aTranslationData, false, false); } } } $oSubQuery = $oSearch->GetSQLQueryStructure($aQueryAttToLoad, false, $aQueryGroupByExpr, $aSearchSelectedClasses, $aQuerySelectExpr); - if (count($aSearchAliases) > 1) - { + if (count($aSearchAliases) > 1) { // Necessary to make sure that selected columns will match throughout all the queries // (default order of selected fields depending on the order of JOINS) $oSubQuery->SortSelectedFields(); @@ -698,17 +622,17 @@ class DBUnionSearch extends DBSearch $oSQLQuery = new SQLUnionQuery($aSQLQueries, $aGroupByExpr, $aUnionQuerySelectExpr); //MyHelpers::var_dump_html($oSQLQuery, true); //MyHelpers::var_dump_html($oSQLQuery->RenderSelect(), true); - if (self::$m_bDebugQuery) $oSQLQuery->DisplayHtml(); + if (self::$m_bDebugQuery) { + $oSQLQuery->DisplayHtml(); + } return $oSQLQuery; } protected function IsDataFiltered() { $bIsAllDataFiltered = true; - foreach ($this->aSearches as $oSearch) - { - if (!$oSearch->IsDataFiltered()) - { + foreach ($this->aSearches as $oSearch) { + if (!$oSearch->IsDataFiltered()) { $bIsAllDataFiltered = false; break; } @@ -718,19 +642,15 @@ class DBUnionSearch extends DBSearch protected function SetDataFiltered() { - foreach ($this->aSearches as $oSearch) - { + foreach ($this->aSearches as $oSearch) { $oSearch->SetDataFiltered(); } } - - public function AddConditionForInOperatorUsingParam($sFilterCode, $aValues, $bPositiveMatch = true) { $sInParamName = $this->GenerateUniqueParamName(); - foreach ($this->aSearches as $iSearchIndex => $oSearch) - { + foreach ($this->aSearches as $iSearchIndex => $oSearch) { $oFieldExpression = new FieldExpression($sFilterCode, $oSearch->GetClassAlias()); $sOperator = $bPositiveMatch ? 'IN' : 'NOT IN'; @@ -738,17 +658,16 @@ class DBUnionSearch extends DBSearch $oParamExpression = new VariableExpression($sInParamName); $oSearch->GetInternalParamsByRef()[$sInParamName] = $aValues; - $oListExpression = new ListExpression(array($oParamExpression)); + $oListExpression = new ListExpression([$oParamExpression]); $oInCondition = new BinaryExpression($oFieldExpression, $sOperator, $oListExpression); $oSearch->AddConditionExpression($oInCondition); } } - function GetExpectedArguments(): array + public function GetExpectedArguments(): array { - $aVariableCriteria = array(); - foreach ($this->aSearches as $oSearch) - { + $aVariableCriteria = []; + foreach ($this->aSearches as $oSearch) { $aVariableCriteria = array_merge($aVariableCriteria, $oSearch->GetExpectedArguments()); } diff --git a/core/displayablegraph.class.inc.php b/core/displayablegraph.class.inc.php index f454c030e..f1e378cdf 100644 --- a/core/displayablegraph.class.inc.php +++ b/core/displayablegraph.class.inc.php @@ -1,4 +1,5 @@ x - $oNode->x; $dy = $this->y - $oNode->y; - $d2 = $dx*$dx + $dy*$dy - $this->GetHeight()*$this->GetHeight(); - if ($d2 < 40) - { + $d2 = $dx * $dx + $dy * $dy - $this->GetHeight() * $this->GetHeight(); + if ($d2 < 40) { $d2 = 40; } return $d2; @@ -94,7 +94,7 @@ class DisplayableNode extends GraphNode public function GetForRaphael($aContextDefs) { - $aNode = array(); + $aNode = []; $aNode['shape'] = 'icon'; $aNode['icon_url'] = $this->GetIconURL(); $aNode['width'] = 32; @@ -103,19 +103,17 @@ class DisplayableNode extends GraphNode $aNode['obj_key'] = $this->GetProperty('object')->GetKey(); $aNode['sink'] = ($this->GetProperty('sink') == true); $aNode['x'] = $this->x; - $aNode['y']= $this->y; + $aNode['y'] = $this->y; $aNode['label'] = $this->GetLabel(); $aNode['id'] = $this->GetId(); $fOpacity = ($this->GetProperty('is_reached') ? 1 : 0.4); - $aNode['icon_attr'] = array('opacity' => $fOpacity); - $aNode['text_attr'] = array('opacity' => $fOpacity); + $aNode['icon_attr'] = ['opacity' => $fOpacity]; + $aNode['text_attr'] = ['opacity' => $fOpacity]; $aNode['tooltip'] = $this->GetTooltip($aContextDefs); - $aNode['context_icons'] = array(); + $aNode['context_icons'] = []; $aContextRootCauses = $this->GetProperty('context_root_causes'); - if (!is_null($aContextRootCauses)) - { - foreach($aContextRootCauses as $key => $aObjects) - { + if (!is_null($aContextRootCauses)) { + foreach ($aContextRootCauses as $key => $aObjects) { $aNode['context_icons'][] = utils::GetAbsoluteUrlModulesRoot().$aContextDefs[$key]['icon']; } } @@ -132,10 +130,10 @@ class DisplayableNode extends GraphNode $sIconPath = str_replace(utils::GetAbsoluteUrlModulesRoot(), APPROOT.'env-'.utils::GetCurrentEnvironment().'/', $sIconUrl); if ($this->GetProperty('source')) { - $oPdf->SetLineStyle(array('width' => 2 * $fScale, 'cap' => 'round', 'join' => 'miter', 'dash' => 0, 'color' => array(204, 51, 51))); + $oPdf->SetLineStyle(['width' => 2 * $fScale, 'cap' => 'round', 'join' => 'miter', 'dash' => 0, 'color' => [204, 51, 51]]); $oPdf->Circle($this->x * $fScale, $this->y * $fScale, 16 * 1.25 * $fScale, 0, 360, 'D'); - } else if ($this->GetProperty('sink')) { - $oPdf->SetLineStyle(array('width' => 2 * $fScale, 'cap' => 'round', 'join' => 'miter', 'dash' => 0, 'color' => array(51, 51, 204))); + } elseif ($this->GetProperty('sink')) { + $oPdf->SetLineStyle(['width' => 2 * $fScale, 'cap' => 'round', 'join' => 'miter', 'dash' => 0, 'color' => [51, 51, 204]]); $oPdf->Circle($this->x * $fScale, $this->y * $fScale, 16 * 1.25 * $fScale, 0, 360, 'D'); } @@ -172,10 +170,10 @@ class DisplayableNode extends GraphNode $oPdf->setAlpha(0.6 * $Alpha); $oPdf->SetFillColor(255, 255, 255); $oPdf->SetDrawColor(255, 255, 255); - $oPdf->Rect($this->x*$fScale - $width/2, ($this->y + 18)*$fScale, $width, $height, 'DF'); + $oPdf->Rect($this->x * $fScale - $width / 2, ($this->y + 18) * $fScale, $width, $height, 'DF'); $oPdf->setAlpha($Alpha); $oPdf->SetTextColor(0, 0, 0); - $oPdf->Text($this->x*$fScale - $width/2, ($this->y + 18)*$fScale, $this->GetProperty('label')); + $oPdf->Text($this->x * $fScale - $width / 2, ($this->y + 18) * $fScale, $this->GetProperty('label')); } /** @@ -188,26 +186,22 @@ class DisplayableNode extends GraphNode $aInfo = getimagesize($sIconFile); $im = null; - switch($aInfo['mime']) - { + switch ($aInfo['mime']) { case 'image/png': - if (function_exists('imagecreatefrompng')) - { + if (function_exists('imagecreatefrompng')) { $im = imagecreatefrompng($sIconFile); } break; case 'image/gif': - if (function_exists('imagecreatefromgif')) - { + if (function_exists('imagecreatefromgif')) { $im = imagecreatefromgif($sIconFile); } break; case 'image/jpeg': case 'image/jpg': - if (function_exists('imagecreatefromjpeg')) - { + if (function_exists('imagecreatefromjpeg')) { $im = imagecreatefromjpeg($sIconFile); } break; @@ -216,16 +210,13 @@ class DisplayableNode extends GraphNode return null; } - if($im && imagefilter($im, IMG_FILTER_COLORIZE, 255, 255, 255)) - { + if ($im && imagefilter($im, IMG_FILTER_COLORIZE, 255, 255, 255)) { $sTempImageName = $oGraph->GetTempImageName(); imagesavealpha($im, true); imagepng($im, $sTempImageName); imagedestroy($im); return $sTempImageName; - } - else - { + } else { return null; } } @@ -243,24 +234,22 @@ class DisplayableNode extends GraphNode protected function AddToStats($oNode, &$aNodesPerClass) { $sClass = $oNode->GetObjectClass(); - if (!array_key_exists($sClass, $aNodesPerClass)) - { - $aNodesPerClass[$sClass] = array( - 'reached' => array( + if (!array_key_exists($sClass, $aNodesPerClass)) { + $aNodesPerClass[$sClass] = [ + 'reached' => [ 'count' => 0, - 'nodes' => array(), + 'nodes' => [], 'icon_url' => $oNode->GetProperty('icon_url'), - ), - 'not_reached' => array( + ], + 'not_reached' => [ 'count' => 0, - 'nodes' => array(), + 'nodes' => [], 'icon_url' => $oNode->GetProperty('icon_url'), - ) - ); + ], + ]; } $sKey = $oNode->GetProperty('is_reached') ? 'reached' : 'not_reached'; - if (!array_key_exists($oNode->GetId(), $aNodesPerClass[$sClass][$sKey]['nodes'])) - { + if (!array_key_exists($oNode->GetId(), $aNodesPerClass[$sClass][$sKey]['nodes'])) { $aNodesPerClass[$sClass][$sKey]['nodes'][$oNode->GetId()] = $oNode; $aNodesPerClass[$sClass][$sKey]['count'] += $oNode->GetObjectCount(); } @@ -273,18 +262,13 @@ class DisplayableNode extends GraphNode */ protected function GetNextNodes($bDirectionDown = true) { - $aNextNodes = array(); - if ($bDirectionDown) - { - foreach($this->GetOutgoingEdges() as $oEdge) - { + $aNextNodes = []; + if ($bDirectionDown) { + foreach ($this->GetOutgoingEdges() as $oEdge) { $aNextNodes[] = $oEdge->GetSinkNode(); } - } - else - { - foreach($this->GetIncomingEdges() as $oEdge) - { + } else { + foreach ($this->GetIncomingEdges() as $oEdge) { $aNextNodes[] = $oEdge->GetSourceNode(); } } @@ -302,76 +286,50 @@ class DisplayableNode extends GraphNode protected function ReplaceNextNodeBy(DisplayableGraph $oGraph, DisplayableNode $oNextNode, DisplayableGroupNode $oNewNode, $bDirectionDown = true) { $sClass = $oNewNode->GetProperty('class'); - if ($bDirectionDown) - { - foreach($oNextNode->GetIncomingEdges() as $oEdge) - { - if ($oEdge->GetSourceNode()->GetId() !== $this->GetId()) - { - try - { + if ($bDirectionDown) { + foreach ($oNextNode->GetIncomingEdges() as $oEdge) { + if ($oEdge->GetSourceNode()->GetId() !== $this->GetId()) { + try { $oNewEdge = new DisplayableEdge($oGraph, $oEdge->GetId().'::'.$sClass, $oEdge->GetSourceNode(), $oNewNode); - } - catch(Exception $e) - { + } catch (Exception $e) { // ignore this edge } } } - foreach($oNextNode->GetOutgoingEdges() as $oEdge) - { - try - { + foreach ($oNextNode->GetOutgoingEdges() as $oEdge) { + try { $oNewEdge = new DisplayableEdge($oGraph, $oEdge->GetId().'::'.$sClass, $oNewNode, $oEdge->GetSinkNode()); - } - catch(Exception $e) - { + } catch (Exception $e) { // ignore this edge } } - } - else - { - foreach($oNextNode->GetOutgoingEdges() as $oEdge) - { - if ($oEdge->GetSinkNode()->GetId() !== $this->GetId()) - { - try - { + } else { + foreach ($oNextNode->GetOutgoingEdges() as $oEdge) { + if ($oEdge->GetSinkNode()->GetId() !== $this->GetId()) { + try { $oNewEdge = new DisplayableEdge($oGraph, $oEdge->GetId().'::'.$sClass, $oNewNode, $oEdge->GetSinkNode()); - } - catch(Exception $e) - { + } catch (Exception $e) { // ignore this edge } } } - foreach($oNextNode->GetIncomingEdges() as $oEdge) - { - try - { + foreach ($oNextNode->GetIncomingEdges() as $oEdge) { + try { $oNewEdge = new DisplayableEdge($oGraph, $oEdge->GetId().'::'.$sClass, $oEdge->GetSourceNode(), $oNewNode); - } - catch(Exception $e) - { + } catch (Exception $e) { // ignore this edge } } } - if ($oGraph->GetNode($oNextNode->GetId())) - { + if ($oGraph->GetNode($oNextNode->GetId())) { $oGraph->_RemoveNode($oNextNode); - if ($oNextNode instanceof DisplayableGroupNode) - { + if ($oNextNode instanceof DisplayableGroupNode) { // Copy all the objects of the previous group into the new group - foreach($oNextNode->GetObjects() as $oObj) - { + foreach ($oNextNode->GetObjects() as $oObj) { $oNewNode->AddObject($oObj); } - } - else - { + } else { $oNewNode->AddObject($oNextNode->GetProperty('object')); } } @@ -386,32 +344,26 @@ class DisplayableNode extends GraphNode */ public function GroupSimilarNeighbours(DisplayableGraph $oGraph, $iThresholdCount, $bDirectionUp = false, $bDirectionDown = true) { - if ($this->GetProperty('grouped') === true) return; + if ($this->GetProperty('grouped') === true) { + return; + } $this->SetProperty('grouped', true); - $aNodesPerClass = array(); - foreach($this->GetNextNodes($bDirectionDown) as $oNode) - { + $aNodesPerClass = []; + foreach ($this->GetNextNodes($bDirectionDown) as $oNode) { $sClass = $oNode->GetObjectClass(); - if ($sClass !== null) - { + if ($sClass !== null) { $this->AddToStats($oNode, $aNodesPerClass); - } - else - { + } else { $oNode->GroupSimilarNeighbours($oGraph, $iThresholdCount, $bDirectionUp, $bDirectionDown); } } - foreach($aNodesPerClass as $sClass => $aDefs) - { - foreach($aDefs as $sStatus => $aGroupProps) - { - if (count($aGroupProps['nodes']) >= $iThresholdCount) - { - $sNewId = $this->GetId().'::'.$sClass.'/'.(($sStatus == 'reached') ? '_reached': ''); + foreach ($aNodesPerClass as $sClass => $aDefs) { + foreach ($aDefs as $sStatus => $aGroupProps) { + if (count($aGroupProps['nodes']) >= $iThresholdCount) { + $sNewId = $this->GetId().'::'.$sClass.'/'.(($sStatus == 'reached') ? '_reached' : ''); $oNewNode = $oGraph->GetNode($sNewId); - if ($oNewNode == null) - { + if ($oNewNode == null) { $oNewNode = new DisplayableGroupNode($oGraph, $sNewId); $oNewNode->SetProperty('label', 'x'.$aGroupProps['count']); $oNewNode->SetProperty('icon_url', MetaModel::GetClassIcon($sClass, false)); @@ -420,32 +372,22 @@ class DisplayableNode extends GraphNode $oNewNode->SetProperty('count', $aGroupProps['count']); } - try - { - if ($bDirectionDown) - { + try { + if ($bDirectionDown) { $oIncomingEdge = new DisplayableEdge($oGraph, $this->GetId().'-'.$oNewNode->GetId(), $this, $oNewNode); - } - else - { + } else { $oOutgoingEdge = new DisplayableEdge($oGraph, $this->GetId().'-'.$oNewNode->GetId(), $oNewNode, $this); } - } - catch(Exception $e) - { + } catch (Exception $e) { // Ignore this redundant egde } - foreach($aGroupProps['nodes'] as $oNextNode) - { + foreach ($aGroupProps['nodes'] as $oNextNode) { $this->ReplaceNextNodeBy($oGraph, $oNextNode, $oNewNode, $bDirectionDown); } $oNewNode->GroupSimilarNeighbours($oGraph, $iThresholdCount, $bDirectionUp, $bDirectionDown); - } - else - { - foreach($aGroupProps['nodes'] as $oNode) - { + } else { + foreach ($aGroupProps['nodes'] as $oNode) { $oNode->GroupSimilarNeighbours($oGraph, $iThresholdCount, $bDirectionUp, $bDirectionDown); } } @@ -460,12 +402,10 @@ class DisplayableNode extends GraphNode $sSubClass = get_class($oCurrObj); $sHtml .= $oCurrObj->GetHyperlink()."
      "; $aContextRootCauses = $this->GetProperty('context_root_causes'); - if (!is_null($aContextRootCauses)) - { - foreach($aContextRootCauses as $key => $aObjects) - { + if (!is_null($aContextRootCauses)) { + foreach ($aContextRootCauses as $key => $aObjects) { $aContext = $aContextDefs[$key]; - $aRootCauses = array(); + $aRootCauses = []; foreach ($aObjects as $oRootCause) { $aRootCauses[] = $oRootCause->GetHyperlink(); } @@ -474,8 +414,7 @@ class DisplayableNode extends GraphNode $sHtml .= '
      '; } $sHtml .= ''; - foreach(MetaModel::GetZListItems($sSubClass, 'list') as $sAttCode) - { + foreach (MetaModel::GetZListItems($sSubClass, 'list') as $sAttCode) { $oAttDef = MetaModel::GetAttributeDef($sSubClass, $sAttCode); $sHtml .= ''; } @@ -492,14 +431,11 @@ class DisplayableNode extends GraphNode public function GetDotAttributes($bNoLabel = false) { $sDot = ''; - if ($bNoLabel) - { + if ($bNoLabel) { // simulate a fake label with the approximate same size as the true label $sLabel = str_repeat('x', mb_strlen($this->GetProperty('label', $this->GetId()))); $sDot = 'label="'.$sLabel.'"'; - } - else - { + } else { // actual label $sLabel = addslashes($this->GetProperty('label', $this->GetId())); $sDot = 'label="'.$sLabel.'"'; @@ -517,20 +453,20 @@ class DisplayableRedundancyNode extends DisplayableNode public function GetForRaphael($aContextDefs) { - $aNode = array(); + $aNode = []; $aNode['shape'] = 'disc'; $aNode['icon_url'] = $this->GetIconURL(); $aNode['source'] = ($this->GetProperty('source') == true); $aNode['width'] = $this->GetWidth(); $aNode['x'] = $this->x; - $aNode['y']= $this->y; + $aNode['y'] = $this->y; $aNode['label'] = $this->GetLabel(); $aNode['id'] = $this->GetId(); $fDiscOpacity = ($this->GetProperty('is_reached') ? 1 : 0.2); $sColor = ($this->GetProperty('is_reached_count') > $this->GetProperty('threshold')) ? '#c33' : '#999'; - $aNode['disc_attr'] = array('stroke-width' => 2, 'stroke' => '#000', 'fill' => $sColor, 'opacity' => $fDiscOpacity); + $aNode['disc_attr'] = ['stroke-width' => 2, 'stroke' => '#000', 'fill' => $sColor, 'opacity' => $fDiscOpacity]; $fTextOpacity = ($this->GetProperty('is_reached') ? 1 : 0.4); - $aNode['text_attr'] = array('fill' => '#fff', 'opacity' => $fTextOpacity); + $aNode['text_attr'] = ['fill' => '#fff', 'opacity' => $fTextOpacity]; $aNode['tooltip'] = $this->GetTooltip($aContextDefs); return $aNode; } @@ -538,28 +474,25 @@ class DisplayableRedundancyNode extends DisplayableNode public function RenderAsPDF(iTopPDF $oPdf, DisplayableGraph $oGraph, $fScale, $aContextDefs) { $oPdf->SetAlpha(1); - if($this->GetProperty('is_reached_count') > $this->GetProperty('threshold')) - { + if ($this->GetProperty('is_reached_count') > $this->GetProperty('threshold')) { $oPdf->SetFillColor(200, 0, 0); - } - else - { + } else { $oPdf->SetFillColor(144, 144, 144); } $oPdf->SetDrawColor(0, 0, 0); - $oPdf->Circle($this->x*$fScale, $this->y*$fScale, 16*$fScale, 0, 360, 'DF'); + $oPdf->Circle($this->x * $fScale, $this->y * $fScale, 16 * $fScale, 0, 360, 'DF'); $oPdf->SetTextColor(255, 255, 255); $oPdf->SetFontParams('', 28 * $fScale, '', true); $sLabel = (string)$this->GetProperty('label'); $width = $oPdf->GetStringWidth($sLabel, iTopPDF::GetPdfFont(), 'B', 24 * $fScale); $height = $oPdf->GetStringHeight(1000, $sLabel); - $xPos = (float)$this->x*$fScale - $width/2; - $yPos = (float)$this->y*$fScale - $height/2; + $xPos = (float)$this->x * $fScale - $width / 2; + $yPos = (float)$this->y * $fScale - $height / 2; - $oPdf->SetXY(($this->x - 16)*$fScale, ($this->y - 16)*$fScale); + $oPdf->SetXY(($this->x - 16) * $fScale, ($this->y - 16) * $fScale); - $oPdf->Cell(32*$fScale, 32*$fScale, $sLabel, 0, 0, 'C', 0, '', 0, false, 'T', 'C'); + $oPdf->Cell(32 * $fScale, 32 * $fScale, $sLabel, 0, 0, 'C', 0, '', 0, false, 'T', 'C'); } /** @@ -569,28 +502,20 @@ class DisplayableRedundancyNode extends DisplayableNode { parent::GroupSimilarNeighbours($oGraph, $iThresholdCount, $bDirectionUp, $bDirectionDown); - if ($bDirectionUp) - { - $aNodesPerClass = array(); - foreach($this->GetIncomingEdges() as $oEdge) - { + if ($bDirectionUp) { + $aNodesPerClass = []; + foreach ($this->GetIncomingEdges() as $oEdge) { $oNode = $oEdge->GetSourceNode(); - if (($oNode->GetObjectClass() !== null) && (!$oNode->GetProperty('is_reached'))) - { + if (($oNode->GetObjectClass() !== null) && (!$oNode->GetProperty('is_reached'))) { $this->AddToStats($oNode, $aNodesPerClass); - } - else - { + } else { //$oNode->GroupSimilarNeighbours($oGraph, $iThresholdCount, $bDirectionUp, $bDirectionDown); } } - foreach($aNodesPerClass as $sClass => $aDefs) - { - foreach($aDefs as $sStatus => $aGroupProps) - { - if (count($aGroupProps['nodes']) >= $iThresholdCount) - { + foreach ($aNodesPerClass as $sClass => $aDefs) { + foreach ($aDefs as $sStatus => $aGroupProps) { + if (count($aGroupProps['nodes']) >= $iThresholdCount) { $oNewNode = new DisplayableGroupNode($oGraph, '-'.$this->GetId().'::'.$sClass.'/'.$sStatus); $oNewNode->SetProperty('label', 'x'.count($aGroupProps['nodes'])); $oNewNode->SetProperty('icon_url', MetaModel::GetClassIcon($sClass, false)); @@ -598,11 +523,9 @@ class DisplayableRedundancyNode extends DisplayableNode $oNewNode->SetProperty('class', $sClass); $oNewNode->SetProperty('count', count($aGroupProps['nodes'])); - - $sNewId = $this->GetId().'::'.$sClass.'/'.(($sStatus == 'reached') ? '_reached': ''); + $sNewId = $this->GetId().'::'.$sClass.'/'.(($sStatus == 'reached') ? '_reached' : ''); $oNewNode = $oGraph->GetNode($sNewId); - if ($oNewNode == null) - { + if ($oNewNode == null) { $oNewNode = new DisplayableGroupNode($oGraph, $sNewId); $oNewNode->SetProperty('label', 'x'.$aGroupProps['count']); $oNewNode->SetProperty('icon_url', $aGroupProps['icon_url']); @@ -611,25 +534,18 @@ class DisplayableRedundancyNode extends DisplayableNode $oNewNode->SetProperty('count', $aGroupProps['count']); } - try - { + try { $oOutgoingEdge = new DisplayableEdge($oGraph, '-'.$this->GetId().'-'.$oNewNode->GetId().'/'.$sStatus, $oNewNode, $this); - } - catch(Exception $e) - { + } catch (Exception $e) { // Ignore this redundant egde } - foreach($aGroupProps['nodes'] as $oNextNode) - { + foreach ($aGroupProps['nodes'] as $oNextNode) { $this->ReplaceNextNodeBy($oGraph, $oNextNode, $oNewNode, !$bDirectionUp); } //$oNewNode->GroupSimilarNeighbours($oGraph, $iThresholdCount, $bDirectionUp, $bDirectionDown); - } - else - { - foreach($aGroupProps['nodes'] as $oNode) - { + } else { + foreach ($aGroupProps['nodes'] as $oNode) { //$oNode->GroupSimilarNeighbours($oGraph, $iThresholdCount, $bDirectionUp, $bDirectionDown); } } @@ -643,13 +559,12 @@ class DisplayableRedundancyNode extends DisplayableNode $sHtml = ''; $sHtml .= Dict::S('UI:RelationTooltip:Redundancy')."
      "; $sHtml .= '
      '.$oAttDef->GetLabel().': '.$oCurrObj->GetAsHtml($sAttCode).'
      '; - $sHtml .= ""; - $sHtml .= ""; + $sHtml .= ""; + $sHtml .= ""; $sHtml .= '
      ".Dict::Format('UI:RelationTooltip:ImpactedItems_N_of_M' , $this->GetProperty('is_reached_count'), $this->GetProperty('min_up') + $this->GetProperty('threshold'))."
      ".Dict::Format('UI:RelationTooltip:CriticalThreshold_N_of_M' , $this->GetProperty('threshold'), $this->GetProperty('min_up') + $this->GetProperty('threshold'))."
      ".Dict::Format('UI:RelationTooltip:ImpactedItems_N_of_M', $this->GetProperty('is_reached_count'), $this->GetProperty('min_up') + $this->GetProperty('threshold'))."
      ".Dict::Format('UI:RelationTooltip:CriticalThreshold_N_of_M', $this->GetProperty('threshold'), $this->GetProperty('min_up') + $this->GetProperty('threshold'))."
      '; return $sHtml; } - public function GetObjectCount() { return 0; @@ -666,16 +581,14 @@ class DisplayableEdge extends GraphEdge public function RenderAsPDF(TCPDF $oPdf, DisplayableGraph $oGraph, $fScale, $aContextDefs) { $oSourceNode = $this->GetSourceNode(); - if (($oSourceNode->x == null) || ($oSourceNode->y == null)) - { + if (($oSourceNode->x == null) || ($oSourceNode->y == null)) { return; } $xStart = $oSourceNode->x * $fScale; $yStart = $oSourceNode->y * $fScale; $oSinkNode = $this->GetSinkNode(); - if (($oSinkNode->x == null) || ($oSinkNode->y == null)) - { + if (($oSinkNode->x == null) || ($oSinkNode->y == null)) { return; } $xEnd = $oSinkNode->x * $fScale; @@ -684,32 +597,28 @@ class DisplayableEdge extends GraphEdge $bReached = ($this->GetSourceNode()->GetProperty('is_reached') && $this->GetSinkNode()->GetProperty('is_reached')); $oPdf->setAlpha(1); - if ($bReached) - { - $aColor = array(100, 100, 100); + if ($bReached) { + $aColor = [100, 100, 100]; + } else { + $aColor = [200, 200, 200]; } - else - { - $aColor = array(200, 200, 200); - } - $oPdf->SetLineStyle(array('width' => 2*$fScale, 'cap' => 'round', 'join' => 'miter', 'dash' => 0, 'color' => $aColor)); + $oPdf->SetLineStyle(['width' => 2 * $fScale, 'cap' => 'round', 'join' => 'miter', 'dash' => 0, 'color' => $aColor]); $oPdf->Line($xStart, $yStart, $xEnd, $yEnd); - $vx = $xEnd - $xStart; $vy = $yEnd - $yStart; - $l = sqrt($vx*$vx + $vy*$vy); + $l = sqrt($vx * $vx + $vy * $vy); $vx = $vx / $l; $vy = $vy / $l; $ux = -$vy; $uy = $vx; - $lPos = max($l/2, $l - 40*$fScale); - $iArrowSize = 5*$fScale; + $lPos = max($l / 2, $l - 40 * $fScale); + $iArrowSize = 5 * $fScale; $x = $xStart + $lPos * $vx; $y = $yStart + $lPos * $vy; - $oPdf->Line($x, $y, $x + $iArrowSize * ($ux-$vx), $y + $iArrowSize * ($uy-$vy)); - $oPdf->Line($x, $y, $x - $iArrowSize * ($ux+$vx), $y - $iArrowSize * ($uy+$vy)); + $oPdf->Line($x, $y, $x + $iArrowSize * ($ux - $vx), $y + $iArrowSize * ($uy - $vy)); + $oPdf->Line($x, $y, $x - $iArrowSize * ($ux + $vx), $y - $iArrowSize * ($uy + $vy)); } } @@ -720,16 +629,14 @@ class DisplayableGroupNode extends DisplayableNode public function __construct(SimpleGraph $oGraph, $sId, $x = 0, $y = 0) { parent::__construct($oGraph, $sId, $x, $y); - $this->aObjects = array(); + $this->aObjects = []; } public function AddObject(DBObject $oObj = null) { - if (is_object($oObj)) - { + if (is_object($oObj)) { $sPrevClass = $this->GetObjectClass(); - if (($sPrevClass !== null) && (get_class($oObj) !== $sPrevClass)) - { + if (($sPrevClass !== null) && (get_class($oObj) !== $sPrevClass)) { throw new Exception("Error: adding an object of class '".get_class($oObj)."' to a group of '$sPrevClass' objects."); } $this->aObjects[$oObj->GetKey()] = $oObj; @@ -748,21 +655,21 @@ class DisplayableGroupNode extends DisplayableNode public function GetForRaphael($aContextDefs) { - $aNode = array(); + $aNode = []; $aNode['shape'] = 'group'; $aNode['icon_url'] = $this->GetIconURL(); $aNode['source'] = ($this->GetProperty('source') == true); $aNode['width'] = $this->GetWidth(); $aNode['x'] = $this->x; - $aNode['y']= $this->y; + $aNode['y'] = $this->y; $aNode['label'] = $this->GetLabel(); $aNode['id'] = $this->GetId(); $aNode['group_index'] = $this->GetProperty('group_index'); // if supplied $fDiscOpacity = ($this->GetProperty('is_reached') ? 1 : 0.2); $fTextOpacity = ($this->GetProperty('is_reached') ? 1 : 0.4); - $aNode['icon_attr'] = array('opacity' => $fTextOpacity); - $aNode['disc_attr'] = array('stroke-width' => 2, 'stroke' => '#000', 'fill' => '#fff', 'opacity' => $fDiscOpacity); - $aNode['text_attr'] = array('fill' => '#000', 'opacity' => $fTextOpacity); + $aNode['icon_attr'] = ['opacity' => $fTextOpacity]; + $aNode['disc_attr'] = ['stroke-width' => 2, 'stroke' => '#000', 'fill' => '#fff', 'opacity' => $fDiscOpacity]; + $aNode['text_attr'] = ['fill' => '#000', 'opacity' => $fTextOpacity]; $aNode['tooltip'] = $this->GetTooltip($aContextDefs); return $aNode; } @@ -772,11 +679,11 @@ class DisplayableGroupNode extends DisplayableNode $bReached = $this->GetProperty('is_reached'); $oPdf->SetFillColor(255, 255, 255); if ($bReached) { - $aBorderColor = array(100, 100, 100); + $aBorderColor = [100, 100, 100]; } else { - $aBorderColor = array(200, 200, 200); + $aBorderColor = [200, 200, 200]; } - $oPdf->SetLineStyle(array('width' => 2 * $fScale, 'cap' => 'round', 'join' => 'miter', 'dash' => 0, 'color' => $aBorderColor)); + $oPdf->SetLineStyle(['width' => 2 * $fScale, 'cap' => 'round', 'join' => 'miter', 'dash' => 0, 'color' => $aBorderColor]); $sIconUrl = $this->GetProperty('icon_url'); $sIconPath = str_replace(utils::GetAbsoluteUrlModulesRoot(), APPROOT.'env-'.utils::GetCurrentEnvironment().'/', $sIconUrl); @@ -800,7 +707,7 @@ class DisplayableGroupNode extends DisplayableNode public function GetTooltip($aContextDefs) { $iGroupIdx = $this->GetProperty('group_index'); - $sHtml = ''.Dict::Format('UI:RelationGroupNumber_N', (1+$iGroupIdx)).""; + $sHtml = ''.Dict::Format('UI:RelationGroupNumber_N', (1 + $iGroupIdx)).""; $sHtml .= '
      '; $sHtml .= ''; $sHtml .= '"; $sHtml .= " "; $sHtml .= ""; - foreach (self::$m_aExecData as $aOpStats) - { + foreach (self::$m_aExecData as $aOpStats) { $sOperation = $aOpStats['op']; $sBegin = round($aOpStats['time_begin'], 3); $sEnd = round($aOpStats['time_end'], 3); @@ -170,12 +172,10 @@ class ExecutionKPI $sMemBegin = 'n/a'; $sMemEnd = 'n/a'; $sMemPeak = 'n/a'; - if (isset($aOpStats['mem_begin'])) - { + if (isset($aOpStats['mem_begin'])) { $sMemBegin = self::MemStr($aOpStats['mem_begin']); $sMemEnd = self::MemStr($aOpStats['mem_end']); - if (isset($aOpStats['mem_peak'])) - { + if (isset($aOpStats['mem_peak'])) { $sMemPeak = self::MemStr($aOpStats['mem_peak']); } } @@ -187,38 +187,34 @@ class ExecutionKPI $sHtml .= "
      '.MetaModel::GetName($this->GetObjectClass()).'
      '; @@ -833,9 +740,9 @@ class DisplayableGraph extends SimpleGraph public function __construct() { parent::__construct(); - $this->aTempImages = array(); - $this->aSourceObjects = array(); - $this->aSinkObjects = array(); + $this->aTempImages = []; + $this->aSourceObjects = []; + $this->aSinkObjects = []; } public function GetTempImageName() @@ -847,8 +754,7 @@ class DisplayableGraph extends SimpleGraph public function __destruct() { - foreach($this->aTempImages as $sTempFile) - { + foreach ($this->aTempImages as $sTempFile) { @unlink($sTempFile); } } @@ -880,14 +786,14 @@ class DisplayableGraph extends SimpleGraph $sClass = get_class($oObj); if ($oNode->GetProperty('source')) { if (!array_key_exists($sClass, $oNewGraph->aSourceObjects)) { - $oNewGraph->aSourceObjects[$sClass] = array(); + $oNewGraph->aSourceObjects[$sClass] = []; } $oNewGraph->aSourceObjects[$sClass][] = $oObj->GetKey(); $oNewNode->SetProperty('source', true); } if ($oNode->GetProperty('sink')) { if (!array_key_exists($sClass, $oNewGraph->aSinkObjects)) { - $oNewGraph->aSinkObjects[$sClass] = array(); + $oNewGraph->aSinkObjects[$sClass] = []; } $oNewGraph->aSinkObjects[$sClass][] = $oObj->GetKey(); $oNewNode->SetProperty('sink', true); @@ -917,8 +823,7 @@ class DisplayableGraph extends SimpleGraph } } $oEdgesIter = new RelationTypeIterator($oGraph, 'Edge'); - foreach($oEdgesIter as $oEdge) - { + foreach ($oEdgesIter as $oEdge) { set_time_limit(intval($iLoopTimeLimit)); $oSourceNode = $oNewGraph->GetNode($oEdge->GetSourceNode()->GetId()); $oSinkNode = $oNewGraph->GetNode($oEdge->GetSinkNode()->GetId()); @@ -927,60 +832,44 @@ class DisplayableGraph extends SimpleGraph // Remove duplicate edges between two nodes $oEdgesIter = new RelationTypeIterator($oNewGraph, 'Edge'); - $aEdgeKeys = array(); - foreach($oEdgesIter as $oEdge) - { + $aEdgeKeys = []; + foreach ($oEdgesIter as $oEdge) { set_time_limit(intval($iLoopTimeLimit)); $sSourceId = $oEdge->GetSourceNode()->GetId(); $sSinkId = $oEdge->GetSinkNode()->GetId(); - if ($sSourceId == $sSinkId) - { + if ($sSourceId == $sSinkId) { // Remove self referring edges $oNewGraph->_RemoveEdge($oEdge); - } - else - { + } else { $sKey = $sSourceId.'//'.$sSinkId; - if (array_key_exists($sKey, $aEdgeKeys)) - { + if (array_key_exists($sKey, $aEdgeKeys)) { // Remove duplicate edges $oNewGraph->_RemoveEdge($oEdge); - } - else - { + } else { $aEdgeKeys[$sKey] = true; } } } $oNodesIter = new RelationTypeIterator($oNewGraph, 'Node'); - foreach($oNodesIter as $oNode) - { + foreach ($oNodesIter as $oNode) { set_time_limit(intval($iLoopTimeLimit)); - if ($bDirectionDown && $oNode->GetProperty('source')) - { + if ($bDirectionDown && $oNode->GetProperty('source')) { $oNode->GroupSimilarNeighbours($oNewGraph, $iGroupingThreshold, true, $bDirectionDown); - } - else if (!$bDirectionDown && $oNode->GetProperty('sink')) - { + } elseif (!$bDirectionDown && $oNode->GetProperty('sink')) { $oNode->GroupSimilarNeighbours($oNewGraph, $iGroupingThreshold, true, $bDirectionDown); } } // Groups numbering $oIterator = new RelationTypeIterator($oNewGraph, 'Node'); $iGroupIdx = 0; - foreach($oIterator as $oNode) - { + foreach ($oIterator as $oNode) { set_time_limit(intval($iLoopTimeLimit)); - if ($oNode instanceof DisplayableGroupNode) - { - if ($oNode->GetObjectCount() == 0) - { + if ($oNode instanceof DisplayableGroupNode) { + if ($oNode->GetObjectCount() == 0) { // Remove empty groups $oNewGraph->_RemoveNode($oNode); - } - else - { + } else { $aGroups[] = $oNode->GetObjects(); $oNode->SetProperty('group_index', $iGroupIdx); $iGroupIdx++; @@ -990,27 +879,20 @@ class DisplayableGraph extends SimpleGraph // Remove duplicate edges between two nodes $oEdgesIter = new RelationTypeIterator($oNewGraph, 'Edge'); - $aEdgeKeys = array(); - foreach($oEdgesIter as $oEdge) - { + $aEdgeKeys = []; + foreach ($oEdgesIter as $oEdge) { set_time_limit(intval($iLoopTimeLimit)); $sSourceId = $oEdge->GetSourceNode()->GetId(); $sSinkId = $oEdge->GetSinkNode()->GetId(); - if ($sSourceId == $sSinkId) - { + if ($sSourceId == $sSinkId) { // Remove self referring edges $oNewGraph->_RemoveEdge($oEdge); - } - else - { + } else { $sKey = $sSourceId.'//'.$sSinkId; - if (array_key_exists($sKey, $aEdgeKeys)) - { + if (array_key_exists($sKey, $aEdgeKeys)) { // Remove duplicate edges $oNewGraph->_RemoveEdge($oEdge); - } - else - { + } else { $aEdgeKeys[$sKey] = true; } } @@ -1028,28 +910,22 @@ class DisplayableGraph extends SimpleGraph public function InitFromGraphviz() { $sDot = $this->DumpAsXDot(); - if (strpos($sDot, 'digraph') === false) - { + if (strpos($sDot, 'digraph') === false) { throw new Exception($sDot); } $aChunks = explode(";", $sDot); - foreach($aChunks as $sChunk) - { - if(preg_match('/"([^"]+)".+pos="([0-9\\.]+),([0-9\\.]+)"/ms', $sChunk, $aMatches)) - { + foreach ($aChunks as $sChunk) { + if (preg_match('/"([^"]+)".+pos="([0-9\\.]+),([0-9\\.]+)"/ms', $sChunk, $aMatches)) { $sId = $aMatches[1]; $xPos = $aMatches[2]; $yPos = $aMatches[3]; $oNode = $this->GetNode($sId); - if ($oNode !== null) - { + if ($oNode !== null) { $oNode->x = (float)$xPos; $oNode->y = (float)$yPos; - } - else - { + } else { IssueLog::Warning("??? Position of the non-existing node '$sId', x=$xPos, y=$yPos"); } } @@ -1063,17 +939,13 @@ class DisplayableGraph extends SimpleGraph $yMin = null; $yMax = null; $oIterator = new RelationTypeIterator($this, 'Node'); - foreach($oIterator as $sId => $oNode) - { - if ($xMin === null) // First element in the loop - { + foreach ($oIterator as $sId => $oNode) { + if ($xMin === null) { // First element in the loop $xMin = $oNode->x - $oNode->GetWidth(); $xMax = $oNode->x + $oNode->GetWidth(); $yMin = $oNode->y - $oNode->GetHeight(); $yMax = $oNode->y + $oNode->GetHeight(); - } - else - { + } else { $xMin = min($xMin, $oNode->x - $oNode->GetWidth() / 2); $xMax = max($xMax, $oNode->x + $oNode->GetWidth() / 2); $yMin = min($yMin, $oNode->y - $oNode->GetHeight() / 2); @@ -1081,14 +953,13 @@ class DisplayableGraph extends SimpleGraph } } - return array('xmin' => $xMin, 'xmax' => $xMax, 'ymin' => $yMin, 'ymax' => $yMax); + return ['xmin' => $xMin, 'xmax' => $xMax, 'ymin' => $yMin, 'ymax' => $yMax]; } - function Translate($dx, $dy) + public function Translate($dx, $dy) { $oIterator = new RelationTypeIterator($this, 'Node'); - foreach($oIterator as $sId => $oNode) - { + foreach ($oIterator as $sId => $oNode) { $oNode->x += $dx; $oNode->y += $dy; } @@ -1096,11 +967,9 @@ class DisplayableGraph extends SimpleGraph public function UpdatePositions($aPositions) { - foreach($aPositions as $sNodeId => $aPos) - { + foreach ($aPositions as $sNodeId => $aPos) { $oNode = $this->GetNode($sNodeId); - if ($oNode != null) - { + if ($oNode != null) { $oNode->x = $aPos['x']; $oNode->y = $aPos['y']; } @@ -1110,17 +979,15 @@ class DisplayableGraph extends SimpleGraph /** * Renders as JSON string suitable for loading into the simple_graph widget */ - function GetAsJSON($sContextKey) + public function GetAsJSON($sContextKey) { $aContextDefs = static::GetContextDefinitions($sContextKey, false); - $aData = array('nodes' => array(), 'edges' => array(), 'groups' => array(), 'lists' => array()); + $aData = ['nodes' => [], 'edges' => [], 'groups' => [], 'lists' => []]; $iGroupIdx = 0; $oIterator = new RelationTypeIterator($this, 'Node'); - foreach($oIterator as $sId => $oNode) - { - if ($oNode instanceof DisplayableGroupNode) - { + foreach ($oIterator as $sId => $oNode) { + if ($oNode instanceof DisplayableGroupNode) { // The contents of the "Groups" tab will be rendered // using a separate ajax call, since the content of // the page is made of a mix of HTML / CSS / JS which @@ -1128,53 +995,45 @@ class DisplayableGraph extends SimpleGraph // So we just pass a list of groups, each being defined by a class and a list of keys // in order to avoid redoing the impact computation which is expensive $aObjects = $oNode->GetObjects(); - $aKeys = array(); - foreach($aObjects as $oObj) - { + $aKeys = []; + foreach ($aObjects as $oObj) { $sClass = get_class($oObj); $aKeys[] = $oObj->GetKey(); } - $aData['groups'][$iGroupIdx] = array('class' => $sClass, 'keys' => $aKeys); + $aData['groups'][$iGroupIdx] = ['class' => $sClass, 'keys' => $aKeys]; $oNode->SetProperty('group_index', $iGroupIdx); $iGroupIdx++; - if ($oNode->GetProperty('is_reached')) - { + if ($oNode->GetProperty('is_reached')) { // Also add the objects from this group into the 'list' tab - if (!array_key_exists($sClass, $aData['lists'])) - { + if (!array_key_exists($sClass, $aData['lists'])) { $aData['lists'][$sClass] = $aKeys; - } - else - { + } else { $aData['lists'][$sClass] = array_merge($aData['lists'][$sClass], $aKeys); } } } - if (($oNode instanceof DisplayableNode) && $oNode->GetProperty('is_reached') && is_object($oNode->GetProperty('object'))) - { + if (($oNode instanceof DisplayableNode) && $oNode->GetProperty('is_reached') && is_object($oNode->GetProperty('object'))) { $sObjClass = get_class($oNode->GetProperty('object')); - if (!array_key_exists($sObjClass, $aData['lists'])) - { - $aData['lists'][$sObjClass] = array(); + if (!array_key_exists($sObjClass, $aData['lists'])) { + $aData['lists'][$sObjClass] = []; } $aData['lists'][$sObjClass][] = $oNode->GetProperty('object')->GetKey(); } $aData['nodes'][] = $oNode->GetForRaphael($aContextDefs); } - uksort($aData['lists'], array(get_class($this), 'SortOnClassLabel')); // sort on the localized names of the classes to provide a consistent and stable order + uksort($aData['lists'], [get_class($this), 'SortOnClassLabel']); // sort on the localized names of the classes to provide a consistent and stable order $oIterator = new RelationTypeIterator($this, 'Edge'); - foreach($oIterator as $sId => $oEdge) - { - $aEdge = array(); + foreach ($oIterator as $sId => $oEdge) { + $aEdge = []; $aEdge['id'] = $oEdge->GetId(); $aEdge['source_node_id'] = $oEdge->GetSourceNode()->GetId(); $aEdge['sink_node_id'] = $oEdge->GetSinkNode()->GetId(); $fOpacity = ($oEdge->GetSinkNode()->GetProperty('is_reached') && $oEdge->GetSourceNode()->GetProperty('is_reached') ? 1 : 0.2); - $aEdge['attr'] = array('opacity' => $fOpacity, 'stroke' => '#000'); + $aEdge['attr'] = ['opacity' => $fOpacity, 'stroke' => '#000']; $aData['edges'][] = $aEdge; } @@ -1204,7 +1063,7 @@ class DisplayableGraph extends SimpleGraph * * @since 2.7.7 3.0.2 3.1.0 N°4985 $sComments param is no longer optional */ - function RenderAsPDF(PDFPage $oPage, $sComments, $sContextKey, $xMin = -1, $xMax = -1, $yMin = -1, $yMax = -1) + public function RenderAsPDF(PDFPage $oPage, $sComments, $sContextKey, $xMin = -1, $xMax = -1, $yMin = -1, $yMax = -1) { $aContextDefs = static::GetContextDefinitions($sContextKey, false); // No need to develop the parameters $oPdf = $oPage->get_tcpdf(); @@ -1214,20 +1073,16 @@ class DisplayableGraph extends SimpleGraph $aMargins = $oPdf->getMargins(); - if ($xMin == -1) - { + if ($xMin == -1) { $xMin = $aMargins['left']; } - if ($xMax == -1) - { + if ($xMax == -1) { $xMax = $oPdf->getPageWidth() - $aMargins['right']; } - if ($yMin == -1) - { + if ($yMin == -1) { $yMin = $aMargins['top']; } - if ($yMax == -1) - { + if ($yMax == -1) { $yMax = $oPdf->getPageHeight() - $aMargins['bottom']; } @@ -1251,19 +1106,17 @@ class DisplayableGraph extends SimpleGraph $dx = ($fPageW - $fScale * $w) / 2; $dy = ($fPageH - $fScale * $h) / 2; - $this->Translate(($xMin + $dx)/$fScale, ($yMin + $dy)/$fScale); + $this->Translate(($xMin + $dx) / $fScale, ($yMin + $dy) / $fScale); $oIterator = new RelationTypeIterator($this, 'Edge'); $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop'); - foreach($oIterator as $sId => $oEdge) - { + foreach ($oIterator as $sId => $oEdge) { set_time_limit(intval($iLoopTimeLimit)); $oEdge->RenderAsPDF($oPdf, $this, $fScale, $aContextDefs); } $oIterator = new RelationTypeIterator($this, 'Node'); - foreach($oIterator as $sId => $oNode) - { + foreach ($oIterator as $sId => $oNode) { set_time_limit(intval($iLoopTimeLimit)); $oNode->RenderAsPDF($oPdf, $this, $fScale, $aContextDefs); } @@ -1292,17 +1145,14 @@ class DisplayableGraph extends SimpleGraph $fPadding = 1; // in mm $oIterator = new RelationTypeIterator($this, 'Node'); $fMaxWidth = max($oPdf->GetStringWidth(Dict::S('UI:Relation:Key')) - $fIconSize, $oPdf->GetStringWidth(Dict::S('UI:Relation:Comments')) - $fIconSize); - $aClasses = array(); - $aIcons = array(); - $aContexts = array(); - $aContextIcons = array(); + $aClasses = []; + $aIcons = []; + $aContexts = []; + $aContextIcons = []; $oPdf->SetFontParams('', $fFontSize, '', true); - foreach($oIterator as $sId => $oNode) - { - if ($sClass = $oNode->GetObjectClass()) - { - if (!array_key_exists($sClass, $aClasses)) - { + foreach ($oIterator as $sId => $oNode) { + if ($sClass = $oNode->GetObjectClass()) { + if (!array_key_exists($sClass, $aClasses)) { $sClassLabel = MetaModel::GetName($sClass); $width = $oPdf->GetStringWidth($sClassLabel); $fMaxWidth = max($width, $fMaxWidth); @@ -1313,10 +1163,8 @@ class DisplayableGraph extends SimpleGraph } } $aContextRootCauses = $oNode->GetProperty('context_root_causes'); - if (!is_null($aContextRootCauses)) - { - foreach($aContextRootCauses as $key => $aObjects) - { + if (!is_null($aContextRootCauses)) { + foreach ($aContextRootCauses as $key => $aObjects) { $aContexts[$key] = Dict::S($aContextDefs[$key]['dict']); $aContextIcons[$key] = APPROOT.'env-'.utils::GetCurrentEnvironment().'/'.$aContextDefs[$key]['icon']; } @@ -1339,7 +1187,7 @@ class DisplayableGraph extends SimpleGraph $oPdf->AddImage($aContextIcons[$key], $xMin + 1 + $fIconSize * 0.125, $yPos + $fIconSize * 0.125, $fIconSize * 0.75, $fIconSize * 0.75); $yPos += $fIconSize + 2 * $fPadding; } - $oPdf->Rect($xMin, $yMin, $fMaxWidth + $fIconSize + 3*$fPadding, $yMax - $yMin, 'D'); + $oPdf->Rect($xMin, $yMin, $fMaxWidth + $fIconSize + 3 * $fPadding, $yMax - $yMin, 'D'); if ($sComments != '') { // Draw the comment text (surrounded by a rectangle) @@ -1355,7 +1203,7 @@ class DisplayableGraph extends SimpleGraph $yMax = $yPos - $fPadding; } - return array('xmin' => $xMin + $fMaxWidth + $fIconSize + 4*$fPadding, 'xmax' => $xMax, 'ymin' => $yMin, 'ymax' => $yMax); + return ['xmin' => $xMin + $fMaxWidth + $fIconSize + 4 * $fPadding, 'xmax' => $xMax, 'ymin' => $yMin, 'ymax' => $yMax]; } /** @@ -1368,45 +1216,33 @@ class DisplayableGraph extends SimpleGraph * @param array $aContextParams Arguments for the queries (via ToArgs()) if $bDevelopParams == true * @return multitype:multitype:string */ - public static function GetContextDefinitions($sContextKey, $bDevelopParams = true, $aContextParams = array()) + public static function GetContextDefinitions($sContextKey, $bDevelopParams = true, $aContextParams = []) { - $aContextDefs = array(); + $aContextDefs = []; $aLevels = explode('/', $sContextKey); - if (count($aLevels) < 5) - { + if (count($aLevels) < 5) { IssueLog::Warning("GetContextDefinitions: invalid 'sContextKey' = '$sContextKey'. 5 levels of / are expected !"); - } - else - { + } else { $sLeafClass = $aLevels[2]; - if (!MetaModel::IsValidClass($sLeafClass)) - { + if (!MetaModel::IsValidClass($sLeafClass)) { IssueLog::Warning("GetContextDefinitions: invalid 'sLeafClass' = '$sLeafClass'. A valid class name is expected in 3rd position inside '$sContextKey' !"); - } - else - { - $aRelationContext = MetaModel::GetConfig()->GetModuleSetting($aLevels[0], $aLevels[1], array()); - foreach(MetaModel::EnumParentClasses($sLeafClass, ENUM_PARENT_CLASSES_ALL) as $sClass) - { - if (isset($aRelationContext[$sClass][$aLevels[3]][$aLevels[4]]['items'])) - { + } else { + $aRelationContext = MetaModel::GetConfig()->GetModuleSetting($aLevels[0], $aLevels[1], []); + foreach (MetaModel::EnumParentClasses($sLeafClass, ENUM_PARENT_CLASSES_ALL) as $sClass) { + if (isset($aRelationContext[$sClass][$aLevels[3]][$aLevels[4]]['items'])) { $aContextDefs = array_merge($aContextDefs, $aRelationContext[$sClass][$aLevels[3]][$aLevels[4]]['items']); } } // Check if the queries are valid - foreach($aContextDefs as $sKey => $sDefs) - { + foreach ($aContextDefs as $sKey => $sDefs) { $sOQL = $aContextDefs[$sKey]['oql']; - try - { + try { // Expand the parameters. If anything goes wrong, then the query is considered as invalid and removed from the list $oSearch = DBObjectSearch::FromOQL($sOQL); $aContextDefs[$sKey]['oql'] = $oSearch->ToOQL($bDevelopParams, $aContextParams); - } - catch(Exception $e) - { + } catch (Exception $e) { IssueLog::Warning('Invalid OQL query: '.$sOQL.' in the parameter '.$sContextKey); unset($aContextDefs[$sKey]); } @@ -1434,7 +1270,7 @@ class DisplayableGraph extends SimpleGraph * * @since 3.1.1 3.2.0 N°3767 */ - function DisplayGraph(WebPage $oP, $sRelation, ApplicationContext $oAppContext, $aExcludedObjects, $sObjClass, $iObjKey, $sContextKey, $aContextParams = array(), bool $bLazyLoading = false): void + public function DisplayGraph(WebPage $oP, $sRelation, ApplicationContext $oAppContext, $aExcludedObjects, $sObjClass, $iObjKey, $sContextKey, $aContextParams = [], bool $bLazyLoading = false): void { list($aExcludedByClass, $aAdditionalContexts) = $this->GetFilteringData($sContextKey, $aContextParams, $aExcludedObjects); @@ -1464,16 +1300,16 @@ class DisplayableGraph extends SimpleGraph $oP->add_ready_script("$('.simple-graph').width(18/2.54*96).resizable({ stop: function() { $(window).trigger('resized'); }});"); // Default width about 18 cm, since most browsers assume 96 dpi } $oP->add('
      '); - $aParams = array( + $aParams = [ 'source_url' => $sLoadFromURL, 'sources' => ($this->bDirectionDown ? $this->aSourceObjects : $this->aSinkObjects), 'excluded' => $aExcludedByClass, 'grouping_threshold' => $iGroupingThreshold, - 'export_as_pdf' => array('url' => $sExportAsPdfURL, 'label' => Dict::S('UI:Relation:ExportAsPDF')), + 'export_as_pdf' => ['url' => $sExportAsPdfURL, 'label' => Dict::S('UI:Relation:ExportAsPDF')], 'transaction_id' => utils::GetNewTransactionId(), - 'export_as_attachment' => array('url' => $sExportAsDocumentURL, 'label' => Dict::S('UI:Relation:ExportAsAttachment'), 'obj_class' => $sObjClass, 'obj_key' => $iObjKey), - 'drill_down' => array('url' => $sDrillDownURL, 'label' => Dict::S('UI:Relation:DrillDown')), - 'labels' => array( + 'export_as_attachment' => ['url' => $sExportAsDocumentURL, 'label' => Dict::S('UI:Relation:ExportAsAttachment'), 'obj_class' => $sObjClass, 'obj_key' => $iObjKey], + 'drill_down' => ['url' => $sDrillDownURL, 'label' => Dict::S('UI:Relation:DrillDown')], + 'labels' => [ 'export_pdf_title' => Dict::S('UI:Relation:PDFExportOptions'), 'export_as_attachment_title' => $sAttachmentExportTitle, 'export' => Dict::S('UI:Button:Export'), @@ -1491,25 +1327,25 @@ class DisplayableGraph extends SimpleGraph 'additional_context_info' => Dict::S('UI:Relation:AdditionalContextInfo'), 'zoom' => Dict::S('UI:Relation:Zoom'), 'loading' => Dict::S('UI:Loading'), - ), - 'page_format' => array( + ], + 'page_format' => [ 'label' => Dict::S('UI:Relation:PDFExportPageFormat'), - 'values' => array( + 'values' => [ 'A3' => Dict::S('UI:PageFormat_A3'), 'A4' => Dict::S('UI:PageFormat_A4'), 'Letter' => Dict::S('UI:PageFormat_Letter'), - ), - ), - 'page_orientation' => array( + ], + ], + 'page_orientation' => [ 'label' => Dict::S('UI:Relation:PDFExportPageOrientation'), - 'values' => array( + 'values' => [ 'P' => Dict::S('UI:PageOrientation_Portrait'), 'L' => Dict::S('UI:PageOrientation_Landscape'), - ), - ), + ], + ], 'additional_contexts' => $aAdditionalContexts, 'context_key' => $sContextKey, - ); + ]; if (!extension_loaded('gd')) { // PDF export requires GD unset($aParams['export_as_pdf']); @@ -1524,8 +1360,7 @@ class DisplayableGraph extends SimpleGraph $oP->add_script("function Load(){var aExcluded = []; $('input[name^=excluded]').each( function() {if (!$(this).prop('checked')) { aExcluded.push($(this).val()); }} ); var params= $.extend(".json_encode($aParams).", {excluded_classes: aExcluded}); $('#$sId').simple_graph(params);}"); $oP->add_ready_script("$('#graph').html('".utils::TextToHtml(Dict::S('Relation:impacts/NoFilteredData'))."');$('#impacted_objects_lists').html('".utils::TextToHtml(Dict::S('Relation:impacts/NoFilteredData'))."');$('#impacted_groups').html('".utils::TextToHtml(Dict::S('Relation:impacts/NoFilteredData'))."');"); } - } - catch (Exception $e) { + } catch (Exception $e) { $oP->add('
      '.$e->getMessage().'
      '); } $oP->add_script( @@ -1599,7 +1434,7 @@ EOF } else { $oP->add_ready_script("$('#dh_flash').addClass('closed');"); } - $aSortedElements = array(); + $aSortedElements = []; foreach ($aResults as $sClassIdx => $aObjects) { foreach ($aObjects as $oCurrObj) { $sSubClass = get_class($oCurrObj); @@ -1636,19 +1471,19 @@ EOF public function GetFilteringData(string $sContextKey, array $aContextParams, array $aExcludedObjects): array { $aContextDefs = static::GetContextDefinitions($sContextKey, true, $aContextParams); - $aExcludedByClass = array(); + $aExcludedByClass = []; foreach ($aExcludedObjects as $oObj) { if (!array_key_exists(get_class($oObj), $aExcludedByClass)) { - $aExcludedByClass[get_class($oObj)] = array(); + $aExcludedByClass[get_class($oObj)] = []; } $aExcludedByClass[get_class($oObj)][] = $oObj->GetKey(); } - $aAdditionalContexts = array(); + $aAdditionalContexts = []; foreach ($aContextDefs as $sKey => $aDefinition) { - $aAdditionalContexts[] = array('key' => $sKey, 'label' => Dict::S($aDefinition['dict']), 'oql' => $aDefinition['oql'], 'default' => (array_key_exists('default', $aDefinition) && ($aDefinition['default'] == 'yes'))); + $aAdditionalContexts[] = ['key' => $sKey, 'label' => Dict::S($aDefinition['dict']), 'oql' => $aDefinition['oql'], 'default' => (array_key_exists('default', $aDefinition) && ($aDefinition['default'] == 'yes'))]; } - return array($aExcludedByClass, $aAdditionalContexts); + return [$aExcludedByClass, $aAdditionalContexts]; } } diff --git a/core/event.class.inc.php b/core/event.class.inc.php index cca37deaf..d87a40e91 100644 --- a/core/event.class.inc.php +++ b/core/event.class.inc.php @@ -24,31 +24,31 @@ class Event extends DBObject implements iDisplay { public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "core/cmdb,view_in_gui", "key_type" => "autoincrement", "name_attcode" => "", "state_attcode" => "", - "reconc_keys" => array(), + "reconc_keys" => [], "db_table" => "priv_event", "db_key_field" => "id", "db_finalclass_field" => "realclass", - "order_by_default" => array('date' => false) - ); + "order_by_default" => ['date' => false], + ]; MetaModel::Init_Params($aParams); //MetaModel::Init_InheritAttributes(); - MetaModel::Init_AddAttribute(new AttributeText("message", array("allowed_values"=>null, "sql"=>"message", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeDateTime("date", array("allowed_values"=>null, "sql"=>"date", "default_value"=>"NOW()", "is_null_allowed"=>false, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeString("userinfo", array("allowed_values"=>null, "sql"=>"userinfo", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); -// MetaModel::Init_AddAttribute(new AttributeString("userinfo", array("allowed_values"=>null, "sql"=>"userinfo", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); + MetaModel::Init_AddAttribute(new AttributeText("message", ["allowed_values" => null, "sql" => "message", "default_value" => null, "is_null_allowed" => false, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeDateTime("date", ["allowed_values" => null, "sql" => "date", "default_value" => "NOW()", "is_null_allowed" => false, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeString("userinfo", ["allowed_values" => null, "sql" => "userinfo", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); + // MetaModel::Init_AddAttribute(new AttributeString("userinfo", array("allowed_values"=>null, "sql"=>"userinfo", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); // Display lists - MetaModel::Init_SetZListItems('details', array('date', 'message', 'userinfo')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('date', 'finalclass', 'message')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['date', 'message', 'userinfo']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['date', 'finalclass', 'message']); // Attributes to be displayed for a list // Search criteria -// MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form -// MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form + // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form + // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form } /** @@ -58,12 +58,9 @@ class Event extends DBObject implements iDisplay */ public static function MapContextParam($sContextParam) { - if ($sContextParam == 'menu') - { + if ($sContextParam == 'menu') { return null; - } - else - { + } else { return $sContextParam; } } @@ -79,7 +76,7 @@ class Event extends DBObject implements iDisplay public function GetHilightClass() { // Possible return values are: - // HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE + // HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE return HILIGHT_CLASS_NONE; // Not hilighted by default } @@ -88,7 +85,7 @@ class Event extends DBObject implements iDisplay return 'UI.php'; } - function DisplayDetails(WebPage $oPage, $bEditMode = false) + public function DisplayDetails(WebPage $oPage, $bEditMode = false) { // Object's details //$this->DisplayBareHeader($oPage, $bEditMode); @@ -97,21 +94,23 @@ class Event extends DBObject implements iDisplay $oPage->SetCurrentTab('UI:PropertiesTab'); $this->DisplayBareProperties($oPage, $bEditMode); } - - function DisplayBareProperties(WebPage $oPage, $bEditMode = false, $sPrefix = '', $aExtraParams = array()) - { - if ($bEditMode) return array(); // Not editable - $aDetails = array(); + public function DisplayBareProperties(WebPage $oPage, $bEditMode = false, $sPrefix = '', $aExtraParams = []) + { + if ($bEditMode) { + return []; + } // Not editable + + $aDetails = []; $sClass = get_class($this); $aZList = MetaModel::FlattenZlist(MetaModel::GetZListItems($sClass, 'details')); foreach ($aZList as $sAttCode) { $sDisplayValue = $this->GetAsHTML($sAttCode); - $aDetails[] = array('label' => ''.MetaModel::GetLabel($sClass, $sAttCode).'', 'value' => $sDisplayValue); + $aDetails[] = ['label' => ''.MetaModel::GetLabel($sClass, $sAttCode).'', 'value' => $sDisplayValue]; } $oPage->Details($aDetails); - return array(); + return []; } } @@ -119,35 +118,35 @@ class EventNotification extends Event { public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "core/cmdb,view_in_gui", "key_type" => "autoincrement", "name_attcode" => "", "state_attcode" => "", - "reconc_keys" => array(), + "reconc_keys" => [], "db_table" => "priv_event_notification", "db_key_field" => "id", "db_finalclass_field" => "", - "order_by_default" => array('date' => false), - 'indexes' => array( - array( 'object_class', 'object_id'), - ) - ); + "order_by_default" => ['date' => false], + 'indexes' => [ + [ 'object_class', 'object_id'], + ], + ]; MetaModel::Init_Params($aParams); MetaModel::Init_InheritAttributes(); - MetaModel::Init_AddAttribute(new AttributeExternalKey("trigger_id", array("targetclass"=>"Trigger", "jointype"=> "", "allowed_values"=>null, "sql"=>"trigger_id", "is_null_allowed"=>false, "on_target_delete"=>DEL_AUTO, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeExternalKey("action_id", array("targetclass" => "Action", "jointype" => "", "allowed_values" => null, "sql" => "action_id", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => array()))); - MetaModel::Init_AddAttribute(new AttributeInteger("object_id", array("allowed_values" => null, "sql" => "object_id", "default_value" => 0, "is_null_allowed" => false, "depends_on" => array()))); - //@since 3.2.0 - MetaModel::Init_AddAttribute(new AttributeClass("object_class", array("class_category"=>"", "more_values"=>"", "sql"=>"object_class", "default_value"=>null, "is_null_allowed"=>true /*to avoid setting AbstractResource as default in database*/, "depends_on"=>array()))); + MetaModel::Init_AddAttribute(new AttributeExternalKey("trigger_id", ["targetclass" => "Trigger", "jointype" => "", "allowed_values" => null, "sql" => "trigger_id", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeExternalKey("action_id", ["targetclass" => "Action", "jointype" => "", "allowed_values" => null, "sql" => "action_id", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeInteger("object_id", ["allowed_values" => null, "sql" => "object_id", "default_value" => 0, "is_null_allowed" => false, "depends_on" => []])); + //@since 3.2.0 + MetaModel::Init_AddAttribute(new AttributeClass("object_class", ["class_category" => "", "more_values" => "", "sql" => "object_class", "default_value" => null, "is_null_allowed" => true /*to avoid setting AbstractResource as default in database*/, "depends_on" => []])); // Display lists - MetaModel::Init_SetZListItems('details', array('date', 'message', 'userinfo', 'trigger_id', 'action_id', 'object_class', 'object_id')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('date', 'message')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['date', 'message', 'userinfo', 'trigger_id', 'action_id', 'object_class', 'object_id']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['date', 'message']); // Attributes to be displayed for a list // Search criteria -// MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form -// MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form + // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form + // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form } } @@ -155,35 +154,35 @@ class EventNotificationEmail extends EventNotification { public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "core/cmdb,view_in_gui", "key_type" => "autoincrement", "name_attcode" => "", "state_attcode" => "", - "reconc_keys" => array(), + "reconc_keys" => [], "db_table" => "priv_event_email", "db_key_field" => "id", "db_finalclass_field" => "", - "order_by_default" => array('date' => false) - ); + "order_by_default" => ['date' => false], + ]; MetaModel::Init_Params($aParams); MetaModel::Init_InheritAttributes(); - MetaModel::Init_AddAttribute(new AttributeText("to", array("allowed_values"=>null, "sql"=>"to", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeText("cc", array("allowed_values"=>null, "sql"=>"cc", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeText("bcc", array("allowed_values"=>null, "sql"=>"bcc", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeText("from", array("allowed_values"=>null, "sql"=>"from", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeText("subject", array("allowed_values"=>null, "sql"=>"subject", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeHTML("body", array("allowed_values"=>null, "sql"=>"body", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeTable("attachments", array("allowed_values"=>null, "sql"=>"attachments", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); + MetaModel::Init_AddAttribute(new AttributeText("to", ["allowed_values" => null, "sql" => "to", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeText("cc", ["allowed_values" => null, "sql" => "cc", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeText("bcc", ["allowed_values" => null, "sql" => "bcc", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeText("from", ["allowed_values" => null, "sql" => "from", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeText("subject", ["allowed_values" => null, "sql" => "subject", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeHTML("body", ["allowed_values" => null, "sql" => "body", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeTable("attachments", ["allowed_values" => null, "sql" => "attachments", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); // Display lists - MetaModel::Init_SetZListItems('details', array('date', 'userinfo', 'message', 'trigger_id', 'action_id', 'object_class', 'object_id', 'to', 'cc', 'bcc', 'from', 'subject', 'body', 'attachments')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('date', 'message', 'to', 'subject', 'attachments')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['date', 'userinfo', 'message', 'trigger_id', 'action_id', 'object_class', 'object_id', 'to', 'cc', 'bcc', 'from', 'subject', 'body', 'attachments']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['date', 'message', 'to', 'subject', 'attachments']); // Attributes to be displayed for a list // Search criteria -// MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form -// MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form + // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form + // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form } } @@ -191,34 +190,34 @@ class EventIssue extends Event { public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "core/cmdb,view_in_gui", "key_type" => "autoincrement", "name_attcode" => "", "state_attcode" => "", - "reconc_keys" => array(), + "reconc_keys" => [], "db_table" => "priv_event_issue", "db_key_field" => "id", "db_finalclass_field" => "", - "order_by_default" => array('date' => false) - ); + "order_by_default" => ['date' => false], + ]; MetaModel::Init_Params($aParams); MetaModel::Init_InheritAttributes(); - MetaModel::Init_AddAttribute(new AttributeString("issue", array("allowed_values"=>null, "sql"=>"issue", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeString("impact", array("allowed_values"=>null, "sql"=>"impact", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeString("page", array("allowed_values"=>null, "sql"=>"page", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributePropertySet("arguments_post", array("allowed_values"=>null, "sql"=>"arguments_post", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributePropertySet("arguments_get", array("allowed_values"=>null, "sql"=>"arguments_get", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeTable("callstack", array("allowed_values"=>null, "sql"=>"callstack", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributePropertySet("data", array("allowed_values"=>null, "sql"=>"data", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); + MetaModel::Init_AddAttribute(new AttributeString("issue", ["allowed_values" => null, "sql" => "issue", "default_value" => null, "is_null_allowed" => false, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeString("impact", ["allowed_values" => null, "sql" => "impact", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeString("page", ["allowed_values" => null, "sql" => "page", "default_value" => null, "is_null_allowed" => false, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributePropertySet("arguments_post", ["allowed_values" => null, "sql" => "arguments_post", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributePropertySet("arguments_get", ["allowed_values" => null, "sql" => "arguments_get", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeTable("callstack", ["allowed_values" => null, "sql" => "callstack", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributePropertySet("data", ["allowed_values" => null, "sql" => "data", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); // Display lists - MetaModel::Init_SetZListItems('details', array('date', 'message', 'userinfo', 'issue', 'impact', 'page', 'arguments_post', 'arguments_get', 'callstack', 'data')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('date', 'userinfo', 'issue', 'impact')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['date', 'message', 'userinfo', 'issue', 'impact', 'page', 'arguments_post', 'arguments_get', 'callstack', 'data']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['date', 'userinfo', 'issue', 'impact']); // Attributes to be displayed for a list // Search criteria -// MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form -// MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form + // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form + // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form } protected function OnInsert() @@ -231,20 +230,16 @@ class EventIssue extends Event $this->Set('userinfo', UserRights::GetUserId()); } - if (array_key_exists('_GET', $GLOBALS) && is_array($GLOBALS['_GET'])) - { + if (array_key_exists('_GET', $GLOBALS) && is_array($GLOBALS['_GET'])) { $this->Set('arguments_get', $this->SanitizeRequestParams($GLOBALS['_GET'])); - } - else - { - $this->Set('arguments_get', array()); + } else { + $this->Set('arguments_get', []); } - if (array_key_exists('_POST', $GLOBALS) && is_array($GLOBALS['_POST'])) - { + if (array_key_exists('_POST', $GLOBALS) && is_array($GLOBALS['_POST'])) { $this->Set('arguments_post', $this->SanitizeRequestParams($GLOBALS['_POST'])); } else { - $this->Set('arguments_post', array()); + $this->Set('arguments_post', []); } $sLength = mb_strlen($this->Get('issue')); if ($sLength > 255) { @@ -281,44 +276,42 @@ class EventIssue extends Event } } - return $aSanitizedParams; } } - class EventWebService extends Event { public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "core/cmdb,view_in_gui", "key_type" => "autoincrement", "name_attcode" => "", "state_attcode" => "", - "reconc_keys" => array(), + "reconc_keys" => [], "db_table" => "priv_event_webservice", "db_key_field" => "id", "db_finalclass_field" => "", - "order_by_default" => array('date' => false) - ); + "order_by_default" => ['date' => false], + ]; MetaModel::Init_Params($aParams); MetaModel::Init_InheritAttributes(); - MetaModel::Init_AddAttribute(new AttributeString("verb", array("allowed_values"=>null, "sql"=>"verb", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array()))); + MetaModel::Init_AddAttribute(new AttributeString("verb", ["allowed_values" => null, "sql" => "verb", "default_value" => null, "is_null_allowed" => false, "depends_on" => []])); //MetaModel::Init_AddAttribute(new AttributeStructure("arguments", array("allowed_values"=>null, "sql"=>"data", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeBoolean("result", array("allowed_values"=>null, "sql"=>"result", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeText("log_info", array("allowed_values"=>null, "sql"=>"log_info", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeText("log_warning", array("allowed_values"=>null, "sql"=>"log_warning", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeText("log_error", array("allowed_values"=>null, "sql"=>"log_error", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeText("data", array("allowed_values"=>null, "sql"=>"data", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); + MetaModel::Init_AddAttribute(new AttributeBoolean("result", ["allowed_values" => null, "sql" => "result", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeText("log_info", ["allowed_values" => null, "sql" => "log_info", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeText("log_warning", ["allowed_values" => null, "sql" => "log_warning", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeText("log_error", ["allowed_values" => null, "sql" => "log_error", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeText("data", ["allowed_values" => null, "sql" => "data", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); // Display lists - MetaModel::Init_SetZListItems('details', array('date', 'userinfo', 'verb', 'result', 'log_info', 'log_warning', 'log_error', 'data')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('date', 'userinfo', 'verb', 'result')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['date', 'userinfo', 'verb', 'result', 'log_info', 'log_warning', 'log_error', 'data']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['date', 'userinfo', 'verb', 'result']); // Attributes to be displayed for a list // Search criteria -// MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form -// MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form + // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form + // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form } } @@ -326,34 +319,34 @@ class EventRestService extends Event { public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "core/cmdb,view_in_gui", "key_type" => "autoincrement", "name_attcode" => "", "state_attcode" => "", - "reconc_keys" => array(), + "reconc_keys" => [], "db_table" => "priv_event_restservice", "db_key_field" => "id", "db_finalclass_field" => "", - "order_by_default" => array('date' => false) - ); + "order_by_default" => ['date' => false], + ]; MetaModel::Init_Params($aParams); MetaModel::Init_InheritAttributes(); - MetaModel::Init_AddAttribute(new AttributeString("operation", array("allowed_values"=>null, "sql"=>"operation", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeString("version", array("allowed_values"=>null, "sql"=>"version", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeText("json_input", array("allowed_values"=>null, "sql"=>"json_input", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); + MetaModel::Init_AddAttribute(new AttributeString("operation", ["allowed_values" => null, "sql" => "operation", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeString("version", ["allowed_values" => null, "sql" => "version", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeText("json_input", ["allowed_values" => null, "sql" => "json_input", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); - MetaModel::Init_AddAttribute(new AttributeInteger("code", array("allowed_values"=>null, "sql"=>"code", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeText("json_output", array("allowed_values"=>null, "sql"=>"json_output", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeString("provider", array("allowed_values"=>null, "sql"=>"provider", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array()))); + MetaModel::Init_AddAttribute(new AttributeInteger("code", ["allowed_values" => null, "sql" => "code", "default_value" => 0, "is_null_allowed" => false, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeText("json_output", ["allowed_values" => null, "sql" => "json_output", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeString("provider", ["allowed_values" => null, "sql" => "provider", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); // Display lists - MetaModel::Init_SetZListItems('details', array('date', 'userinfo', 'operation', 'version', 'json_input', 'message', 'code', 'json_output', 'provider')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('date', 'userinfo', 'operation', 'message')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['date', 'userinfo', 'operation', 'version', 'json_input', 'message', 'code', 'json_output', 'provider']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['date', 'userinfo', 'operation', 'message']); // Attributes to be displayed for a list // Search criteria -// MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form -// MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form + // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form + // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form } } @@ -361,66 +354,64 @@ class EventLoginUsage extends Event { public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "core/cmdb,view_in_gui", "key_type" => "autoincrement", "name_attcode" => "", "state_attcode" => "", - "reconc_keys" => array(), + "reconc_keys" => [], "db_table" => "priv_event_loginusage", "db_key_field" => "id", "db_finalclass_field" => "", - "order_by_default" => array('date' => false) - ); + "order_by_default" => ['date' => false], + ]; MetaModel::Init_Params($aParams); MetaModel::Init_InheritAttributes(); - MetaModel::Init_AddAttribute(new AttributeExternalKey("user_id", array("targetclass"=>"User", "jointype"=> "", "allowed_values"=>null, "sql"=>"user_id", "is_null_allowed"=>false, "on_target_delete"=>DEL_SILENT, "depends_on"=>array()))); - $aZList = array('date', 'user_id'); - if (MetaModel::IsValidAttCode('Contact', 'name')) - { - MetaModel::Init_AddAttribute(new AttributeExternalField("contact_name", array("allowed_values"=>null, "extkey_attcode"=>"user_id", "target_attcode"=>"contactid", "is_null_allowed"=>true, "depends_on"=>array()))); + MetaModel::Init_AddAttribute(new AttributeExternalKey("user_id", ["targetclass" => "User", "jointype" => "", "allowed_values" => null, "sql" => "user_id", "is_null_allowed" => false, "on_target_delete" => DEL_SILENT, "depends_on" => []])); + $aZList = ['date', 'user_id']; + if (MetaModel::IsValidAttCode('Contact', 'name')) { + MetaModel::Init_AddAttribute(new AttributeExternalField("contact_name", ["allowed_values" => null, "extkey_attcode" => "user_id", "target_attcode" => "contactid", "is_null_allowed" => true, "depends_on" => []])); $aZList[] = 'contact_name'; } - if (MetaModel::IsValidAttCode('Contact', 'email')) - { - MetaModel::Init_AddAttribute(new AttributeExternalField("contact_email", array("allowed_values"=>null, "extkey_attcode"=>"user_id", "target_attcode"=>"email", "is_null_allowed"=>true, "depends_on"=>array()))); + if (MetaModel::IsValidAttCode('Contact', 'email')) { + MetaModel::Init_AddAttribute(new AttributeExternalField("contact_email", ["allowed_values" => null, "extkey_attcode" => "user_id", "target_attcode" => "email", "is_null_allowed" => true, "depends_on" => []])); $aZList[] = 'contact_email'; } // Display lists - MetaModel::Init_SetZListItems('details', array_merge($aZList, array('userinfo', 'message'))); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array_merge($aZList, array('userinfo'))); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', array_merge($aZList, ['userinfo', 'message'])); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', array_merge($aZList, ['userinfo'])); // Attributes to be displayed for a list // Search criteria MetaModel::Init_SetZListItems('standard_search', $aZList); // Criteria of the std search form -// MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form + // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form } } class EventOnObject extends Event { - public static function Init() - { - $aParams = array - ( - "category" => "core/cmdb,view_in_gui", - "key_type" => "autoincrement", - "name_attcode" => "", - "state_attcode" => "", - "reconc_keys" => array(), - "db_table" => "priv_event_onobject", - "db_key_field" => "id", - "db_finalclass_field" => "", - "display_template" => "", - "order_by_default" => array('date' => false) - ); - MetaModel::Init_Params($aParams); - MetaModel::Init_InheritAttributes(); - MetaModel::Init_AddAttribute(new AttributeString("obj_class", array("allowed_values"=>null, "sql"=>"obj_class", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeInteger("obj_key", array("allowed_values"=>null, "sql"=>"obj_key", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array()))); + public static function Init() + { + $aParams = + [ + "category" => "core/cmdb,view_in_gui", + "key_type" => "autoincrement", + "name_attcode" => "", + "state_attcode" => "", + "reconc_keys" => [], + "db_table" => "priv_event_onobject", + "db_key_field" => "id", + "db_finalclass_field" => "", + "display_template" => "", + "order_by_default" => ['date' => false], + ]; + MetaModel::Init_Params($aParams); + MetaModel::Init_InheritAttributes(); + MetaModel::Init_AddAttribute(new AttributeString("obj_class", ["allowed_values" => null, "sql" => "obj_class", "default_value" => null, "is_null_allowed" => false, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeInteger("obj_key", ["allowed_values" => null, "sql" => "obj_key", "default_value" => null, "is_null_allowed" => false, "depends_on" => []])); - // Display lists - MetaModel::Init_SetZListItems('details', array('date', 'userinfo', 'obj_class', 'obj_key', 'message')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('date', 'userinfo', 'obj_class', 'obj_key', 'message')); // Attributes to be displayed for a list - } + // Display lists + MetaModel::Init_SetZListItems('details', ['date', 'userinfo', 'obj_class', 'obj_key', 'message']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['date', 'userinfo', 'obj_class', 'obj_key', 'message']); // Attributes to be displayed for a list + } } diff --git a/core/inlineimage.class.inc.php b/core/inlineimage.class.inc.php index f14296681..b0cb500a8 100644 --- a/core/inlineimage.class.inc.php +++ b/core/inlineimage.class.inc.php @@ -1,4 +1,5 @@ 'addon', 'key_type' => 'autoincrement', - 'name_attcode' => array('item_class', 'temp_id'), + 'name_attcode' => ['item_class', 'temp_id'], 'state_attcode' => '', - 'reconc_keys' => array(''), + 'reconc_keys' => [''], 'db_table' => 'inline_image', 'db_key_field' => 'id', 'db_finalclass_field' => '', - 'indexes' => array( - array('temp_id'), - array('item_class', 'item_id'), - array('item_org_id'), - ), - ); + 'indexes' => [ + ['temp_id'], + ['item_class', 'item_id'], + ['item_org_id'], + ], + ]; MetaModel::Init_Params($aParams); MetaModel::Init_InheritAttributes(); - MetaModel::Init_AddAttribute(new AttributeDateTime("expire", array("allowed_values" => null, "sql" => 'expire', "default_value" => 'DATE_ADD(NOW(), INTERVAL 1 DAY)', "is_null_allowed" => false, "depends_on" => array(), "always_load_in_tables" => false))); - MetaModel::Init_AddAttribute(new AttributeString("temp_id", array("allowed_values"=>null, "sql"=>'temp_id', "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array(), "always_load_in_tables"=>false))); - MetaModel::Init_AddAttribute(new AttributeString("item_class", array("allowed_values"=>null, "sql"=>'item_class', "default_value"=>'', "is_null_allowed"=>false, "depends_on"=>array(), "always_load_in_tables"=>false))); - MetaModel::Init_AddAttribute(new AttributeObjectKey("item_id", array("class_attcode"=>'item_class', "allowed_values"=>null, "sql"=>'item_id', "is_null_allowed"=>true, "depends_on"=>array(), "always_load_in_tables"=>false))); - MetaModel::Init_AddAttribute(new AttributeInteger("item_org_id", array("allowed_values"=>null, "sql"=>'item_org_id', "default_value"=>'0', "is_null_allowed"=>true, "depends_on"=>array(), "always_load_in_tables"=>false))); - MetaModel::Init_AddAttribute(new AttributeBlob("contents", array("is_null_allowed"=>false, "depends_on"=>array(), "always_load_in_tables"=>false))); - MetaModel::Init_AddAttribute(new AttributeString("secret", array("allowed_values"=>null, "sql" => "secret", "default_value"=>'', "is_null_allowed"=>false, "depends_on"=>array(), "always_load_in_tables"=>false))); + MetaModel::Init_AddAttribute(new AttributeDateTime("expire", ["allowed_values" => null, "sql" => 'expire', "default_value" => 'DATE_ADD(NOW(), INTERVAL 1 DAY)', "is_null_allowed" => false, "depends_on" => [], "always_load_in_tables" => false])); + MetaModel::Init_AddAttribute(new AttributeString("temp_id", ["allowed_values" => null, "sql" => 'temp_id', "default_value" => '', "is_null_allowed" => true, "depends_on" => [], "always_load_in_tables" => false])); + MetaModel::Init_AddAttribute(new AttributeString("item_class", ["allowed_values" => null, "sql" => 'item_class', "default_value" => '', "is_null_allowed" => false, "depends_on" => [], "always_load_in_tables" => false])); + MetaModel::Init_AddAttribute(new AttributeObjectKey("item_id", ["class_attcode" => 'item_class', "allowed_values" => null, "sql" => 'item_id', "is_null_allowed" => true, "depends_on" => [], "always_load_in_tables" => false])); + MetaModel::Init_AddAttribute(new AttributeInteger("item_org_id", ["allowed_values" => null, "sql" => 'item_org_id', "default_value" => '0', "is_null_allowed" => true, "depends_on" => [], "always_load_in_tables" => false])); + MetaModel::Init_AddAttribute(new AttributeBlob("contents", ["is_null_allowed" => false, "depends_on" => [], "always_load_in_tables" => false])); + MetaModel::Init_AddAttribute(new AttributeString("secret", ["allowed_values" => null, "sql" => "secret", "default_value" => '', "is_null_allowed" => false, "depends_on" => [], "always_load_in_tables" => false])); - - MetaModel::Init_SetZListItems('details', array('temp_id', 'item_class', 'item_id', 'item_org_id')); - MetaModel::Init_SetZListItems('standard_search', array('temp_id', 'item_class', 'item_id')); - MetaModel::Init_SetZListItems('list', array('temp_id', 'item_class', 'item_id' )); + MetaModel::Init_SetZListItems('details', ['temp_id', 'item_class', 'item_id', 'item_org_id']); + MetaModel::Init_SetZListItems('standard_search', ['temp_id', 'item_class', 'item_id']); + MetaModel::Init_SetZListItems('list', ['temp_id', 'item_class', 'item_id' ]); } - /** * Maps the given context parameter name to the appropriate filter/search code for this class * @@ -77,12 +76,9 @@ class InlineImage extends DBObject */ public static function MapContextParam($sContextParam) { - if ($sContextParam == 'org_id') - { + if ($sContextParam == 'org_id') { return 'item_org_id'; - } - else - { + } else { return null; } } @@ -104,23 +100,18 @@ class InlineImage extends DBObject $sClass = get_class($oItem); $iItemId = $oItem->GetKey(); - $this->Set('item_class', $sClass); - $this->Set('item_id', $iItemId); + $this->Set('item_class', $sClass); + $this->Set('item_id', $iItemId); - $aCallSpec = array($sClass, 'MapContextParam'); - if (is_callable($aCallSpec)) - { + $aCallSpec = [$sClass, 'MapContextParam']; + if (is_callable($aCallSpec)) { $sAttCode = call_user_func($aCallSpec, 'org_id'); // Returns null when there is no mapping for this parameter - if (MetaModel::IsValidAttCode($sClass, $sAttCode)) - { + if (MetaModel::IsValidAttCode($sClass, $sAttCode)) { $iOrgId = $oItem->Get($sAttCode); - if ($iOrgId > 0) - { - if ($iOrgId != $this->Get('item_org_id')) - { + if ($iOrgId > 0) { + if ($iOrgId != $this->Get('item_org_id')) { $this->Set('item_org_id', $iOrgId); - if ($bUpdateOnChange) - { + if ($bUpdateOnChange) { $this->DBUpdate(); } } @@ -143,29 +134,23 @@ class InlineImage extends DBObject // First check that the organization CAN be fetched from the target class // $sClass = $this->Get('item_class'); - $aCallSpec = array($sClass, 'MapContextParam'); - if (is_callable($aCallSpec)) - { + $aCallSpec = [$sClass, 'MapContextParam']; + if (is_callable($aCallSpec)) { $sAttCode = call_user_func($aCallSpec, 'org_id'); // Returns null when there is no mapping for this parameter - if (MetaModel::IsValidAttCode($sClass, $sAttCode)) - { + if (MetaModel::IsValidAttCode($sClass, $sAttCode)) { // Second: check that the organization CAN be fetched from the current user // - if (MetaModel::IsValidClass('Person')) - { - $aCallSpec = array($sClass, 'MapContextParam'); - if (is_callable($aCallSpec)) - { + if (MetaModel::IsValidClass('Person')) { + $aCallSpec = [$sClass, 'MapContextParam']; + if (is_callable($aCallSpec)) { $sAttCode = call_user_func($aCallSpec, 'org_id'); // Returns null when there is no mapping for this parameter - if (MetaModel::IsValidAttCode($sClass, $sAttCode)) - { + if (MetaModel::IsValidAttCode($sClass, $sAttCode)) { // OK - try it // $oCurrentPerson = MetaModel::GetObject('Person', UserRights::GetContactId(), false); - if ($oCurrentPerson) - { - $this->Set('item_org_id', $oCurrentPerson->Get($sAttCode)); - } + if ($oCurrentPerson) { + $this->Set('item_org_id', $oCurrentPerson->Get($sAttCode)); + } } } } @@ -189,39 +174,37 @@ class InlineImage extends DBObject public static function FinalizeInlineImages(DBObject $oObject) { $iTransactionId = utils::ReadParam('transaction_id', null, false, 'transaction_id'); - if (!is_null($iTransactionId)) - { + if (!is_null($iTransactionId)) { // Attach new (temporary) inline images $sTempId = utils::GetUploadTempId($iTransactionId); // The object is being created from a form, check if there are pending inline images for this object $sOQL = 'SELECT InlineImage WHERE temp_id = :temp_id'; $oSearch = DBObjectSearch::FromOQL($sOQL); - $oSet = new DBObjectSet($oSearch, array(), array('temp_id' => $sTempId)); - $aInlineImagesId = array(); + $oSet = new DBObjectSet($oSearch, [], ['temp_id' => $sTempId]); + $aInlineImagesId = []; while ($oInlineImage = $oSet->Fetch()) { $aInlineImagesId[] = $oInlineImage->GetKey(); $oInlineImage->SetItem($oObject); $oInlineImage->Set('temp_id', ''); $oInlineImage->DBUpdate(); } - IssueLog::Trace('FinalizeInlineImages (see $aInlineImagesId for the id list)', LogChannels::INLINE_IMAGE, array( + IssueLog::Trace('FinalizeInlineImages (see $aInlineImagesId for the id list)', LogChannels::INLINE_IMAGE, [ '$sObjectClass' => get_class($oObject), '$sTransactionId' => $iTransactionId, '$sTempId' => $sTempId, '$aInlineImagesId' => $aInlineImagesId, '$sUser' => UserRights::GetUser(), 'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'], - )); + ]); + } else { + IssueLog::Trace('FinalizeInlineImages "error" $iTransactionId is null', LogChannels::INLINE_IMAGE, [ + '$sObjectClass' => get_class($oObject), + '$sTransactionId' => $iTransactionId, + '$sUser' => UserRights::GetUser(), + 'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'], + ]); } - else { - IssueLog::Trace('FinalizeInlineImages "error" $iTransactionId is null', LogChannels::INLINE_IMAGE, array( - '$sObjectClass' => get_class($oObject), - '$sTransactionId' => $iTransactionId, - '$sUser' => UserRights::GetUser(), - 'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'], - )); - } } /** @@ -243,11 +226,11 @@ class InlineImage extends DBObject { // Protection against unfortunate massive delete of inline images when a null temp ID is passed if (utils::IsNullOrEmptyString($sTempId)) { - IssueLog::Trace('OnFormCancel "error" $sTempId is null or empty', LogChannels::INLINE_IMAGE, array( + IssueLog::Trace('OnFormCancel "error" $sTempId is null or empty', LogChannels::INLINE_IMAGE, [ '$sTempId' => $sTempId, '$sUser' => UserRights::GetUser(), 'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'], - )); + ]); return false; } @@ -255,19 +238,18 @@ class InlineImage extends DBObject // Delete all "pending" InlineImages for this form $sOQL = 'SELECT InlineImage WHERE temp_id = :temp_id'; $oSearch = DBObjectSearch::FromOQL($sOQL); - $oSet = new DBObjectSet($oSearch, array(), array('temp_id' => $sTempId)); - $aInlineImagesId = array(); - while($oInlineImage = $oSet->Fetch()) - { - $aInlineImagesId[] = $oInlineImage->GetKey(); + $oSet = new DBObjectSet($oSearch, [], ['temp_id' => $sTempId]); + $aInlineImagesId = []; + while ($oInlineImage = $oSet->Fetch()) { + $aInlineImagesId[] = $oInlineImage->GetKey(); $oInlineImage->DBDelete(); } - IssueLog::Trace('OnFormCancel', LogChannels::INLINE_IMAGE, array( + IssueLog::Trace('OnFormCancel', LogChannels::INLINE_IMAGE, [ '$sTempId' => $sTempId, '$aInlineImagesId' => $aInlineImagesId, '$sUser' => UserRights::GetUser(), 'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'], - )); + ]); return true; } @@ -284,15 +266,17 @@ class InlineImage extends DBObject */ public static function FixUrls($sHtml) { - $aNeedles = array(); - $aReplacements = array(); + $aNeedles = []; + $aReplacements = []; // Find img tags with an attribute data-img-id - if (preg_match_all('/]*)'.self::DOM_ATTR_ID.'="([0-9]+)"([^>]*)>/i', - $sHtml, $aMatches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE)) - { + if (preg_match_all( + '/]*)'.self::DOM_ATTR_ID.'="([0-9]+)"([^>]*)>/i', + $sHtml, + $aMatches, + PREG_SET_ORDER | PREG_OFFSET_CAPTURE + )) { $sUrl = utils::GetAbsoluteUrlAppRoot().INLINEIMAGE_DOWNLOAD_URL; - foreach($aMatches as $aImgInfo) - { + foreach ($aMatches as $aImgInfo) { $sImgTag = $aImgInfo[0][0]; $sSecret = ''; if (preg_match('/data-img-secret="([0-9a-f]+)"/', $sImgTag, $aSecretMatches)) { @@ -321,11 +305,10 @@ class InlineImage extends DBObject public static function ProcessImageTag(DOMElement $oElement) { $sSrc = $oElement->getAttribute('src'); - $sDownloadUrl = str_replace(array('.', '?'), array('\.', '\?'), INLINEIMAGE_DOWNLOAD_URL); // Escape . and ? + $sDownloadUrl = str_replace(['.', '?'], ['\.', '\?'], INLINEIMAGE_DOWNLOAD_URL); // Escape . and ? $sUrlPattern = '|'.$sDownloadUrl.'([0-9]+)&s=([0-9a-f]+)|'; $bIsInlineImage = preg_match($sUrlPattern, $sSrc, $aMatches); - if (!$bIsInlineImage) - { + if (!$bIsInlineImage) { return; } $iInlineImageId = $aMatches[1]; @@ -334,8 +317,7 @@ class InlineImage extends DBObject $sAppRoot = utils::GetAbsoluteUrlAppRoot(); $sAppRootPattern = '/^'.preg_quote($sAppRoot, '/').'/'; $bIsSameItop = preg_match($sAppRootPattern, $sSrc); - if (!$bIsSameItop) - { + if (!$bIsSameItop) { // @see N°1921 // image from another iTop should be treated as external images $oElement->removeAttribute(self::DOM_ATTR_ID); @@ -357,8 +339,7 @@ class InlineImage extends DBObject { $iMaxWidth = (int)MetaModel::GetConfig()->Get('inline_image_max_display_width', 0); $sJS = ''; - if ($iMaxWidth != 0) - { + if ($iMaxWidth != 0) { $sJS = << 1024*1024*1024) - { - $sRet = Dict::Format('Attachment:Max_Go', sprintf('%0.2f', $iMaxUpload/(1024*1024*1024))); - } - else if ($iMaxUpload > 1024*1024) - { - $sRet = Dict::Format('Attachment:Max_Mo', sprintf('%0.2f', $iMaxUpload/(1024*1024))); - } - else - { - $sRet = Dict::Format('Attachment:Max_Ko', sprintf('%0.2f', $iMaxUpload/(1024))); + if ($iMaxUpload > 1024 * 1024 * 1024) { + $sRet = Dict::Format('Attachment:Max_Go', sprintf('%0.2f', $iMaxUpload / (1024 * 1024 * 1024))); + } elseif ($iMaxUpload > 1024 * 1024) { + $sRet = Dict::Format('Attachment:Max_Mo', sprintf('%0.2f', $iMaxUpload / (1024 * 1024))); + } else { + $sRet = Dict::Format('Attachment:Max_Ko', sprintf('%0.2f', $iMaxUpload / (1024))); } } return $sRet; @@ -469,73 +443,71 @@ JS JS; } + /** + * @inheritDoc + */ + protected function AfterInsert() + { + IssueLog::Trace(__METHOD__, LogChannels::INLINE_IMAGE, [ + 'id' => $this->GetKey(), + 'expire' => $this->Get('expire'), + 'temp_id' => $this->Get('temp_id'), + 'item_class' => $this->Get('item_class'), + 'item_id' => $this->Get('item_id'), + 'item_org_id' => $this->Get('item_org_id'), + 'secret' => $this->Get('secret'), + 'user' => $sUser = UserRights::GetUser(), + 'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'], + 'REQUEST_URI' => @$_SERVER['REQUEST_URI'], + ]); + + parent::AfterInsert(); + } /** * @inheritDoc */ - protected function AfterInsert() - { - IssueLog::Trace(__METHOD__, LogChannels::INLINE_IMAGE, array( - 'id' => $this->GetKey(), - 'expire' => $this->Get('expire'), - 'temp_id' => $this->Get('temp_id'), - 'item_class' => $this->Get('item_class'), - 'item_id' => $this->Get('item_id'), - 'item_org_id' => $this->Get('item_org_id'), - 'secret' => $this->Get('secret'), - 'user' => $sUser = UserRights::GetUser(), - 'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'], - 'REQUEST_URI' => @$_SERVER['REQUEST_URI'], - )); + protected function AfterUpdate() + { + IssueLog::Trace(__METHOD__, LogChannels::INLINE_IMAGE, [ + 'id' => $this->GetKey(), + 'expire' => $this->Get('expire'), + 'temp_id' => $this->Get('temp_id'), + 'item_class' => $this->Get('item_class'), + 'item_id' => $this->Get('item_id'), + 'item_org_id' => $this->Get('item_org_id'), + 'secret' => $this->Get('secret'), + 'user' => $sUser = UserRights::GetUser(), + 'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'], + 'REQUEST_URI' => @$_SERVER['REQUEST_URI'], + ]); - parent::AfterInsert(); - } - - /** - * @inheritDoc - */ - protected function AfterUpdate() - { - IssueLog::Trace(__METHOD__, LogChannels::INLINE_IMAGE, array( - 'id' => $this->GetKey(), - 'expire' => $this->Get('expire'), - 'temp_id' => $this->Get('temp_id'), - 'item_class' => $this->Get('item_class'), - 'item_id' => $this->Get('item_id'), - 'item_org_id' => $this->Get('item_org_id'), - 'secret' => $this->Get('secret'), - 'user' => $sUser = UserRights::GetUser(), - 'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'], - 'REQUEST_URI' => @$_SERVER['REQUEST_URI'], - )); - - parent::AfterUpdate(); - } + parent::AfterUpdate(); + } /** * @inheritDoc */ protected function AfterDelete() - { - IssueLog::Trace(__METHOD__, LogChannels::INLINE_IMAGE, array( - 'id' => $this->GetKey(), - 'expire' => $this->Get('expire'), - 'temp_id' => $this->Get('temp_id'), - 'item_class' => $this->Get('item_class'), - 'item_id' => $this->Get('item_id'), - 'item_org_id' => $this->Get('item_org_id'), - 'secret' => $this->Get('secret'), - 'user' => $sUser = UserRights::GetUser(), - 'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'], - 'REQUEST_URI' => @$_SERVER['REQUEST_URI'], - )); + { + IssueLog::Trace(__METHOD__, LogChannels::INLINE_IMAGE, [ + 'id' => $this->GetKey(), + 'expire' => $this->Get('expire'), + 'temp_id' => $this->Get('temp_id'), + 'item_class' => $this->Get('item_class'), + 'item_id' => $this->Get('item_id'), + 'item_org_id' => $this->Get('item_org_id'), + 'secret' => $this->Get('secret'), + 'user' => $sUser = UserRights::GetUser(), + 'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'], + 'REQUEST_URI' => @$_SERVER['REQUEST_URI'], + ]); - parent::AfterDelete(); - } + parent::AfterDelete(); + } } - /** * Garbage collector for cleaning "old" temporary InlineImages (and Attachments). */ @@ -545,9 +517,9 @@ class InlineImageGC implements iBackgroundProcess * @inheritDoc */ public function GetPeriodicity() - { - return 1; - } + { + return 1; + } /** * @inheritDoc @@ -556,13 +528,11 @@ class InlineImageGC implements iBackgroundProcess { $sDateLimit = date(AttributeDateTime::GetSQLFormat(), time()); // Every temporary InlineImage/Attachment expired will be deleted - $aResults = array(); - $aClasses = array('InlineImage', 'Attachment'); - foreach($aClasses as $sClass) - { + $aResults = []; + $aClasses = ['InlineImage', 'Attachment']; + foreach ($aClasses as $sClass) { $iProcessed = 0; - if(class_exists($sClass)) - { + if (class_exists($sClass)) { $iProcessed = $this->DeleteExpiredDocuments($sClass, $iTimeLimit, $sDateLimit); } $aResults[] = "$iProcessed old temporary $sClass(s)"; @@ -591,11 +561,15 @@ class InlineImageGC implements iBackgroundProcess $iProcessed = 0; $sOQL = "SELECT $sClass WHERE (item_id = 0) AND (expire < '$sDateLimit')"; // Next one ? - $oSet = new CMDBObjectSet(DBObjectSearch::FromOQL($sOQL), array('expire' => true) /* order by*/, array(), null, - 1 /* limit count */); - $oSet->OptimizeColumnLoad(array()); - while ((time() < $iTimeLimit) && ($oResult = $oSet->Fetch())) - { + $oSet = new CMDBObjectSet( + DBObjectSearch::FromOQL($sOQL), + ['expire' => true] /* order by*/, + [], + null, + 1 /* limit count */ + ); + $oSet->OptimizeColumnLoad([]); + while ((time() < $iTimeLimit) && ($oResult = $oSet->Fetch())) { /** @var \ormDocument $oDocument */ $oDocument = $oResult->Get('contents'); IssueLog::Info($sClass.' GC: Removed temp. file '.$oDocument->GetFileName().' on "'.$oResult->Get('item_class').'" #'.$oResult->Get('item_id').' as it has expired.'); @@ -605,4 +579,4 @@ class InlineImageGC implements iBackgroundProcess return $iProcessed; } -} \ No newline at end of file +} diff --git a/core/kpi.class.inc.php b/core/kpi.class.inc.php index 86a1d2671..fd6f83feb 100644 --- a/core/kpi.class.inc.php +++ b/core/kpi.class.inc.php @@ -1,4 +1,5 @@ 0) { self::$m_bEnabled_Duration = true; @@ -47,7 +47,7 @@ class ExecutionKPI } } - static public function EnableMemory($iLevel) + public static function EnableMemory($iLevel) { if ($iLevel > 0) { self::$m_bEnabled_Memory = true; @@ -57,91 +57,94 @@ class ExecutionKPI } /** - * @param string sUser A user login or * for all users - */ - static public function SetAllowedUser($sUser) + * @param string sUser A user login or * for all users + */ + public static function SetAllowedUser($sUser) { self::$m_sAllowedUser = $sUser; } - static public function IsEnabled() + public static function IsEnabled() { - if (self::$m_bEnabled_Duration || self::$m_bEnabled_Memory) - { - if ((self::$m_sAllowedUser == '*') || (UserRights::GetUser() == trim(self::$m_sAllowedUser))) - { + if (self::$m_bEnabled_Duration || self::$m_bEnabled_Memory) { + if ((self::$m_sAllowedUser == '*') || (UserRights::GetUser() == trim(self::$m_sAllowedUser))) { return true; } } return false; } - static public function SetGenerateLegacyReport($bReportExtensionsOnly) - { - self::$m_bGenerateLegacyReport = $bReportExtensionsOnly; - } - - static public function SetSlowQueries($fSlowQueries) - { - self::$m_fSlowQueries = $fSlowQueries; - } - - static public function GetDescription() + public static function SetGenerateLegacyReport($bReportExtensionsOnly) { - $aFeatures = array(); - if (self::$m_bEnabled_Duration) $aFeatures[] = 'Duration'; - if (self::$m_bEnabled_Memory) $aFeatures[] = 'Memory usage'; - $sFeatures = 'Measures: '.implode(', ', $aFeatures); - $sFor = self::$m_sAllowedUser == '*' ? 'EVERYBODY' : "'".trim(self::$m_sAllowedUser)."'"; - $sSlowQueries = ''; - if (self::$m_fSlowQueries > 0) { - $sSlowQueries = ". Slow Queries: ".self::$m_fSlowQueries."s"; - } - - $aExtensions = []; - /** @var \iKPILoggerExtension $oExtensionInstance */ - foreach (MetaModel::EnumPlugins('iKPILoggerExtension') as $oExtensionInstance) { - $aExtensions[] = ModuleService::GetInstance()->GetModuleNameFromObject($oExtensionInstance); - } - $sExtensions = ''; - if (count($aExtensions) > 0) { - $sExtensions = '. KPI Extensions: ['.implode(', ', $aExtensions).']'; - } - - return "KPI logging is active for $sFor. $sFeatures$sSlowQueries$sExtensions"; + self::$m_bGenerateLegacyReport = $bReportExtensionsOnly; } - static public function ReportStats() + public static function SetSlowQueries($fSlowQueries) { - if (!self::IsEnabled()) return; + self::$m_fSlowQueries = $fSlowQueries; + } + + public static function GetDescription() + { + $aFeatures = []; + if (self::$m_bEnabled_Duration) { + $aFeatures[] = 'Duration'; + } + if (self::$m_bEnabled_Memory) { + $aFeatures[] = 'Memory usage'; + } + $sFeatures = 'Measures: '.implode(', ', $aFeatures); + $sFor = self::$m_sAllowedUser == '*' ? 'EVERYBODY' : "'".trim(self::$m_sAllowedUser)."'"; + $sSlowQueries = ''; + if (self::$m_fSlowQueries > 0) { + $sSlowQueries = ". Slow Queries: ".self::$m_fSlowQueries."s"; + } + + $aExtensions = []; + /** @var \iKPILoggerExtension $oExtensionInstance */ + foreach (MetaModel::EnumPlugins('iKPILoggerExtension') as $oExtensionInstance) { + $aExtensions[] = ModuleService::GetInstance()->GetModuleNameFromObject($oExtensionInstance); + } + $sExtensions = ''; + if (count($aExtensions) > 0) { + $sExtensions = '. KPI Extensions: ['.implode(', ', $aExtensions).']'; + } + + return "KPI logging is active for $sFor. $sFeatures$sSlowQueries$sExtensions"; + } + + public static function ReportStats() + { + if (!self::IsEnabled()) { + return; + } global $fItopStarted; - global $iItopInitialMemory; + global $iItopInitialMemory; $sExecId = microtime(); // id to differentiate the hrefs! - $sRequest = $_SERVER['REQUEST_URI'].' ('.$_SERVER['REQUEST_METHOD'].')'; - if (isset($_POST['operation'])) { - $sRequest .= ' operation: '.$_POST['operation']; - } + $sRequest = $_SERVER['REQUEST_URI'].' ('.$_SERVER['REQUEST_METHOD'].')'; + if (isset($_POST['operation'])) { + $sRequest .= ' operation: '.$_POST['operation']; + } - $fStop = MyHelpers::getmicrotime(); - if (($fStop - $fItopStarted) > self::$m_fSlowQueries) { - // Invoke extensions to log the KPI operation - /** @var \iKPILoggerExtension $oExtensionInstance */ - $iCurrentMemory = self::memory_get_usage(); - $iPeakMemory = self::memory_get_peak_usage(); - foreach (MetaModel::EnumPlugins('iKPILoggerExtension') as $oExtensionInstance) { - $oKPILogData = new KpiLogData(KpiLogData::TYPE_REQUEST, 'Page', $sRequest, $fItopStarted, $fStop, '', $iItopInitialMemory, $iCurrentMemory, $iPeakMemory); - $oExtensionInstance->LogOperation($oKPILogData); - } - } + $fStop = MyHelpers::getmicrotime(); + if (($fStop - $fItopStarted) > self::$m_fSlowQueries) { + // Invoke extensions to log the KPI operation + /** @var \iKPILoggerExtension $oExtensionInstance */ + $iCurrentMemory = self::memory_get_usage(); + $iPeakMemory = self::memory_get_peak_usage(); + foreach (MetaModel::EnumPlugins('iKPILoggerExtension') as $oExtensionInstance) { + $oKPILogData = new KpiLogData(KpiLogData::TYPE_REQUEST, 'Page', $sRequest, $fItopStarted, $fStop, '', $iItopInitialMemory, $iCurrentMemory, $iPeakMemory); + $oExtensionInstance->LogOperation($oKPILogData); + } + } - if (!self::$m_bGenerateLegacyReport) { - return; - } + if (!self::$m_bGenerateLegacyReport) { + return; + } - $aBeginTimes = array(); - foreach (self::$m_aExecData as $aOpStats) - { + $aBeginTimes = []; + foreach (self::$m_aExecData as $aOpStats) { $aBeginTimes[] = $aOpStats['time_begin']; } array_multisort($aBeginTimes, self::$m_aExecData); @@ -150,7 +153,7 @@ class ExecutionKPI $sHtml = "
      "; $sHtml .= "
      "; - $sHtml .= "

      KPIs - $sRequest

      "; + $sHtml .= "

      KPIs - $sRequest

      "; $oStarted = DateTime::createFromFormat('U.u', $fItopStarted); $sHtml .= '

      '.$oStarted->format('Y-m-d H:i:s.u').'

      '; $sHtml .= "

      log_kpi_user_id: ".UserRights::GetUserId()."

      "; @@ -159,8 +162,7 @@ class ExecutionKPI $sHtml .= "
      OperationBeginEndDurationMemory startMemory endMemory peak
      "; $sHtml .= "
"; - $aConsolidatedStats = array(); - foreach (self::$m_aStats as $sOperation => $aOpStats) - { + $aConsolidatedStats = []; + foreach (self::$m_aStats as $sOperation => $aOpStats) { $fTotalOp = 0; $iTotalOp = 0; $fMinOp = null; $fMaxOp = 0; $sMaxOpArguments = null; - foreach ($aOpStats as $sArguments => $aEvents) - { - foreach ($aEvents as $aEventData) - { + foreach ($aOpStats as $sArguments => $aEvents) { + foreach ($aEvents as $aEventData) { $fDuration = $aEventData['time']; $fTotalOp += $fDuration; $iTotalOp++; $fMinOp = is_null($fMinOp) ? $fDuration : min($fMinOp, $fDuration); - if ($fDuration > $fMaxOp) - { + if ($fDuration > $fMaxOp) { $sMaxOpArguments = $sArguments; $fMaxOp = $fDuration; } } } - $aConsolidatedStats[$sOperation] = array( + $aConsolidatedStats[$sOperation] = [ 'count' => $iTotalOp, 'duration' => $fTotalOp, 'min' => $fMinOp, 'max' => $fMaxOp, 'avg' => $fTotalOp / $iTotalOp, - 'max_args' => $sMaxOpArguments - ); + 'max_args' => $sMaxOpArguments, + ]; } $sHtml .= "
"; @@ -226,8 +222,7 @@ class ExecutionKPI $sHtml .= ""; $sHtml .= " OperationCountDurationMinMaxAvg"; $sHtml .= ""; - foreach ($aConsolidatedStats as $sOperation => $aOpStats) - { + foreach ($aConsolidatedStats as $sOperation => $aOpStats) { $sOperation = ''.$sOperation.''; $sCount = $aOpStats['count']; $sDuration = round($aOpStats['duration'], 3); @@ -250,25 +245,20 @@ class ExecutionKPI self::Report($sHtml); // Report operation details - foreach (self::$m_aStats as $sOperation => $aOpStats) - { + foreach (self::$m_aStats as $sOperation => $aOpStats) { $sHtml = ''; $bDisplayHeader = true; - foreach ($aOpStats as $sArguments => $aEvents) - { + foreach ($aOpStats as $sArguments => $aEvents) { $sHtmlArguments = '
'.$sArguments.'
'; - if ($aConsolidatedStats[$sOperation]['max_args'] == $sArguments) - { + if ($aConsolidatedStats[$sOperation]['max_args'] == $sArguments) { $sHtmlArguments = ''.$sHtmlArguments.''; } - if (isset($aEvents[0]['callers'])) - { + if (isset($aEvents[0]['callers'])) { $sHtmlArguments .= '
'; $sHtmlArguments .= ''; $sHtmlArguments .= ''; - foreach ($aEvents[0]['callers'] as $aCall) - { + foreach ($aEvents[0]['callers'] as $aCall) { $sHtmlArguments .= ''; $sHtmlArguments .= ''; $sHtmlArguments .= ''; @@ -281,8 +271,7 @@ class ExecutionKPI $fTotalInter = 0; $fMinInter = null; $fMaxInter = 0; - foreach ($aEvents as $aEventData) - { + foreach ($aEvents as $aEventData) { $fDuration = $aEventData['time']; $fTotalInter += $fDuration; $fMinInter = is_null($fMinInter) ? $fDuration : min($fMinInter, $fDuration); @@ -293,10 +282,8 @@ class ExecutionKPI $sTotalInter = round($fTotalInter, 3); $sMinInter = round($fMinInter, 3); $sMaxInter = round($fMaxInter, 3); - if (($fTotalInter >= self::$m_fSlowQueries)) - { - if ($bDisplayHeader) - { + if (($fTotalInter >= self::$m_fSlowQueries)) { + if ($bDisplayHeader) { $sOperationHtml = ''.$sOperation.''; $sHtml .= "

$sOperationHtml

"; $sHtml .= "
Call stack for the FIRST caller
'.$aCall['Function'].''.$aCall['File'].':'.$aCall['Line'].'
"; @@ -310,8 +297,7 @@ class ExecutionKPI $sHtml .= ""; } } - if (!$bDisplayHeader) - { + if (!$bDisplayHeader) { $sHtml .= "
"; $sHtml .= "

Back to page stats

"; } @@ -321,19 +307,19 @@ class ExecutionKPI self::Report($sHtml); } - public static function InitStats() - { - // Invoke extensions to initialize the KPI statistics - /** @var \iKPILoggerExtension $oExtensionInstance */ - foreach (MetaModel::EnumPlugins('iKPILoggerExtension') as $oExtensionInstance) { - $oExtensionInstance->InitStats(); - } - } + public static function InitStats() + { + // Invoke extensions to initialize the KPI statistics + /** @var \iKPILoggerExtension $oExtensionInstance */ + foreach (MetaModel::EnumPlugins('iKPILoggerExtension') as $oExtensionInstance) { + $oExtensionInstance->InitStats(); + } + } public function __construct() { $this->ResetCounters(); - } + } // Get the duration since startup, and reset the counter for the next measure // @@ -341,65 +327,62 @@ class ExecutionKPI { global $fItopStarted; - if (!self::IsEnabled()) { - return; - } + if (!self::IsEnabled()) { + return; + } $aNewEntry = null; - $fStarted = $this->m_fStarted; - $fStopped = $this->m_fStarted; - if (self::$m_bEnabled_Duration) { + $fStarted = $this->m_fStarted; + $fStopped = $this->m_fStarted; + if (self::$m_bEnabled_Duration) { $fStopped = MyHelpers::getmicrotime(); - $aNewEntry = array( + $aNewEntry = [ 'op' => $sOperationDesc, 'time_begin' => $this->m_fStarted - $fItopStarted, 'time_end' => $fStopped - $fItopStarted, - ); + ]; // Reset for the next operation (if the object is recycled) $this->m_fStarted = $fStopped; } - $iInitialMemory = is_null($this->m_iInitialMemory) ? 0 : $this->m_iInitialMemory; - $iCurrentMemory = 0; - $iPeakMemory = 0; - if (self::$m_bEnabled_Memory) - { + $iInitialMemory = is_null($this->m_iInitialMemory) ? 0 : $this->m_iInitialMemory; + $iCurrentMemory = 0; + $iPeakMemory = 0; + if (self::$m_bEnabled_Memory) { $iCurrentMemory = self::memory_get_usage(); - if (is_null($aNewEntry)) - { - $aNewEntry = array('op' => $sOperationDesc); + if (is_null($aNewEntry)) { + $aNewEntry = ['op' => $sOperationDesc]; } $aNewEntry['mem_begin'] = $this->m_iInitialMemory; $aNewEntry['mem_end'] = $iCurrentMemory; - $iPeakMemory = self::memory_get_peak_usage(); - $aNewEntry['mem_peak'] = $iPeakMemory; + $iPeakMemory = self::memory_get_peak_usage(); + $aNewEntry['mem_peak'] = $iPeakMemory; // Reset for the next operation (if the object is recycled) $this->m_iInitialMemory = $iCurrentMemory; } - if (self::$m_bEnabled_Duration || self::$m_bEnabled_Memory) { - // Invoke extensions to log the KPI operation - /** @var \iKPILoggerExtension $oExtensionInstance */ - foreach(MetaModel::EnumPlugins('iKPILoggerExtension') as $oExtensionInstance) - { - $sExtension = ModuleService::GetInstance()->GetModuleNameFromCallStack(1); - $oKPILogData = new KpiLogData( - KpiLogData::TYPE_REPORT, - 'Step', - $sOperationDesc, - $fStarted, - $fStopped, - $sExtension, - $iInitialMemory, - $iCurrentMemory, - $iPeakMemory); - $oExtensionInstance->LogOperation($oKPILogData); - } - } + if (self::$m_bEnabled_Duration || self::$m_bEnabled_Memory) { + // Invoke extensions to log the KPI operation + /** @var \iKPILoggerExtension $oExtensionInstance */ + foreach (MetaModel::EnumPlugins('iKPILoggerExtension') as $oExtensionInstance) { + $sExtension = ModuleService::GetInstance()->GetModuleNameFromCallStack(1); + $oKPILogData = new KpiLogData( + KpiLogData::TYPE_REPORT, + 'Step', + $sOperationDesc, + $fStarted, + $fStopped, + $sExtension, + $iInitialMemory, + $iCurrentMemory, + $iPeakMemory + ); + $oExtensionInstance->LogOperation($oKPILogData); + } + } - if (!is_null($aNewEntry) && self::$m_bGenerateLegacyReport) - { + if (!is_null($aNewEntry) && self::$m_bGenerateLegacyReport) { self::$m_aExecData[] = $aNewEntry; } $this->ResetCounters(); @@ -417,20 +400,20 @@ class ExecutionKPI * @throws \ReflectionException */ public function ComputeStatsForExtension($object, string $sMethod, string $sMessage = ''): bool - { - if (!self::IsEnabled()) { - return true; - } + { + if (!self::IsEnabled()) { + return true; + } - $sSignature = ModuleService::GetInstance()->GetModuleMethodSignature($object, $sMethod); - if (utils::StartsWith($sSignature, '[')) { - $this->ComputeStats('Extension', "$sSignature $sMessage"); + $sSignature = ModuleService::GetInstance()->GetModuleMethodSignature($object, $sMethod); + if (utils::StartsWith($sSignature, '[')) { + $this->ComputeStats('Extension', "$sSignature $sMessage"); return true; - } + } return false; - } + } public function ComputeStats($sOperation, $sArguments) { @@ -442,85 +425,82 @@ class ExecutionKPI if (self::$m_bEnabled_Duration) { $fStopped = MyHelpers::getmicrotime(); $fDuration = $fStopped - $this->m_fStarted; - $aCallstack = []; - if (self::$m_bGenerateLegacyReport) { - if (self::$m_bBlameCaller) { - $aCallstack = MyHelpers::get_callstack(1); - self::$m_aStats[$sOperation][$sArguments][] = [ - 'time' => $fDuration, - 'callers' => $aCallstack, - ]; - } else { - self::$m_aStats[$sOperation][$sArguments][] = [ - 'time' => $fDuration - ]; - } - } + $aCallstack = []; + if (self::$m_bGenerateLegacyReport) { + if (self::$m_bBlameCaller) { + $aCallstack = MyHelpers::get_callstack(1); + self::$m_aStats[$sOperation][$sArguments][] = [ + 'time' => $fDuration, + 'callers' => $aCallstack, + ]; + } else { + self::$m_aStats[$sOperation][$sArguments][] = [ + 'time' => $fDuration, + ]; + } + } - $iInitialMemory = is_null($this->m_iInitialMemory) ? 0 : $this->m_iInitialMemory; - $iCurrentMemory = 0; - $iPeakMemory = 0; - if (self::$m_bEnabled_Memory) - { - $iCurrentMemory = self::memory_get_usage(); - $iPeakMemory = self::memory_get_peak_usage(); - } + $iInitialMemory = is_null($this->m_iInitialMemory) ? 0 : $this->m_iInitialMemory; + $iCurrentMemory = 0; + $iPeakMemory = 0; + if (self::$m_bEnabled_Memory) { + $iCurrentMemory = self::memory_get_usage(); + $iPeakMemory = self::memory_get_peak_usage(); + } - // Invoke extensions to log the KPI operation - /** @var \iKPILoggerExtension $oExtensionInstance */ - foreach (MetaModel::EnumPlugins('iKPILoggerExtension') as $oExtensionInstance) { - //$sExtension = ModuleService::GetInstance()->GetModuleNameFromCallStack(1); - $sExtension = ''; - $oKPILogData = new KpiLogData( - KpiLogData::TYPE_STATS, - $sOperation, - $sArguments, - $this->m_fStarted, - $fStopped, - $sExtension, - $iInitialMemory, - $iCurrentMemory, - $iPeakMemory, - $aCallstack); - $oExtensionInstance->LogOperation($oKPILogData); - } - } + // Invoke extensions to log the KPI operation + /** @var \iKPILoggerExtension $oExtensionInstance */ + foreach (MetaModel::EnumPlugins('iKPILoggerExtension') as $oExtensionInstance) { + //$sExtension = ModuleService::GetInstance()->GetModuleNameFromCallStack(1); + $sExtension = ''; + $oKPILogData = new KpiLogData( + KpiLogData::TYPE_STATS, + $sOperation, + $sArguments, + $this->m_fStarted, + $fStopped, + $sExtension, + $iInitialMemory, + $iCurrentMemory, + $iPeakMemory, + $aCallstack + ); + $oExtensionInstance->LogOperation($oKPILogData); + } + } } protected function ResetCounters() { - if (self::$m_bEnabled_Duration) - { + if (self::$m_bEnabled_Duration) { $this->m_fStarted = microtime(true); } - if (self::$m_bEnabled_Memory) - { + if (self::$m_bEnabled_Memory) { $this->m_iInitialMemory = self::memory_get_usage(); } } - const HTML_REPORT_FILE = 'log/kpi.html'; + public const HTML_REPORT_FILE = 'log/kpi.html'; - static protected function Report($sText) + protected static function Report($sText) { file_put_contents(APPROOT.self::HTML_REPORT_FILE, "$sText\n", FILE_APPEND | LOCK_EX); } - static protected function MemStr($iMemory) + protected static function MemStr($iMemory) { return round($iMemory / 1024).' Kb'; } - static protected function memory_get_usage() + protected static function memory_get_usage() { - return memory_get_usage(true); + return memory_get_usage(true); } - static public function memory_get_peak_usage($bRealUsage = false) + public static function memory_get_peak_usage($bRealUsage = false) { - if (function_exists('memory_get_peak_usage')) - { + if (function_exists('memory_get_peak_usage')) { return memory_get_peak_usage($bRealUsage); } // PHP > 5.2.1 - this verb depends on a compilation option diff --git a/core/metamodel.class.php b/core/metamodel.class.php index 3375e991d..c5d6ae1be 100644 --- a/core/metamodel.class.php +++ b/core/metamodel.class.php @@ -1,4 +1,5 @@ "rootclass" * * @var array */ - private static $m_aRootClasses = array(); + private static $m_aRootClasses = []; /** * array of ("classname" => array of "parentclass") * * @var array */ - private static $m_aParentClasses = array(); + private static $m_aParentClasses = []; /** * array of ("classname" => array of "childclass") * * @var array */ - private static $m_aChildClasses = array(); + private static $m_aChildClasses = []; /** * array of ("classname" => array of class information) * * @var array */ - private static $m_aClassParams = array(); + private static $m_aClassParams = []; /** * array of ("classname" => array of highlightscale information) * * @var array */ - private static $m_aHighlightScales = array(); + private static $m_aHighlightScales = []; /** * @param string $sRefClass @@ -641,47 +637,37 @@ abstract class MetaModel */ final public static function GetUniquenessRules($sClass, $bClassDefinitionOnly = false) { - if (!isset(self::$m_aClassParams[$sClass])) - { - return array(); + if (!isset(self::$m_aClassParams[$sClass])) { + return []; } - $aCurrentUniquenessRules = array(); + $aCurrentUniquenessRules = []; - if (array_key_exists('uniqueness_rules', self::$m_aClassParams[$sClass])) - { + if (array_key_exists('uniqueness_rules', self::$m_aClassParams[$sClass])) { $aCurrentUniquenessRules = self::$m_aClassParams[$sClass]['uniqueness_rules']; } - if ($bClassDefinitionOnly) - { + if ($bClassDefinitionOnly) { return $aCurrentUniquenessRules; } $sParentClass = self::GetParentClass($sClass); - if ($sParentClass) - { + if ($sParentClass) { $aParentUniquenessRules = self::GetUniquenessRules($sParentClass); - foreach ($aParentUniquenessRules as $sUniquenessRuleId => $aParentUniquenessRuleProperties) - { + foreach ($aParentUniquenessRules as $sUniquenessRuleId => $aParentUniquenessRuleProperties) { $bCopyDisabledKey = true; $bCurrentDisabledValue = null; - if (array_key_exists($sUniquenessRuleId, $aCurrentUniquenessRules)) - { - if (self::IsUniquenessRuleContainingOnlyDisabledKey($aCurrentUniquenessRules[$sUniquenessRuleId])) - { + if (array_key_exists($sUniquenessRuleId, $aCurrentUniquenessRules)) { + if (self::IsUniquenessRuleContainingOnlyDisabledKey($aCurrentUniquenessRules[$sUniquenessRuleId])) { $bCopyDisabledKey = false; - } - else - { + } else { continue; } } $aMergedUniquenessProperties = $aParentUniquenessRuleProperties; - if (!$bCopyDisabledKey) - { + if (!$bCopyDisabledKey) { $aMergedUniquenessProperties['disabled'] = $aCurrentUniquenessRules[$sUniquenessRuleId]['disabled']; } $aCurrentUniquenessRules[$sUniquenessRuleId] = $aMergedUniquenessProperties; @@ -701,8 +687,7 @@ abstract class MetaModel */ private static function SetUniquenessRuleRootClass($sRootClass, $sRuleId) { - foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_ALL) as $sClass) - { + foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_ALL) as $sClass) { self::$m_aClassParams[$sClass]['uniqueness_rules'][$sRuleId]['root_class'] = $sClass; } } @@ -716,17 +701,14 @@ abstract class MetaModel final public static function GetRootClassForUniquenessRule($sRuleId, $sLeafClassName) { $sFirstClassWithRuleId = null; - if (isset(self::$m_aClassParams[$sLeafClassName]['uniqueness_rules'][$sRuleId])) - { + if (isset(self::$m_aClassParams[$sLeafClassName]['uniqueness_rules'][$sRuleId])) { $sFirstClassWithRuleId = $sLeafClassName; } $sParentClass = self::GetParentClass($sLeafClassName); - if ($sParentClass) - { + if ($sParentClass) { $sParentClassWithRuleId = self::GetRootClassForUniquenessRule($sRuleId, $sParentClass); - if (!is_null($sParentClassWithRuleId)) - { + if (!is_null($sParentClassWithRuleId)) { $sFirstClassWithRuleId = $sParentClassWithRuleId; } } @@ -745,29 +727,22 @@ abstract class MetaModel */ final public static function GetChildClassesWithDisabledUniquenessRule($sRootClass, $sRuleId) { - $aClassesWithDisabledRule = array(); - foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_EXCLUDETOP) as $sChildClass) - { - if (array_key_exists($sChildClass, $aClassesWithDisabledRule)) - { + $aClassesWithDisabledRule = []; + foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_EXCLUDETOP) as $sChildClass) { + if (array_key_exists($sChildClass, $aClassesWithDisabledRule)) { continue; } - if (!array_key_exists('uniqueness_rules', self::$m_aClassParams[$sChildClass])) - { + if (!array_key_exists('uniqueness_rules', self::$m_aClassParams[$sChildClass])) { continue; } - if (!array_key_exists($sRuleId, self::$m_aClassParams[$sChildClass]['uniqueness_rules'])) - { + if (!array_key_exists($sRuleId, self::$m_aClassParams[$sChildClass]['uniqueness_rules'])) { continue; } - if (self::$m_aClassParams[$sChildClass]['uniqueness_rules'][$sRuleId]['disabled'] === true) - { + if (self::$m_aClassParams[$sChildClass]['uniqueness_rules'][$sRuleId]['disabled'] === true) { $aDisabledClassChildren = self::EnumChildClasses($sChildClass, ENUM_CHILD_CLASSES_ALL); - foreach ($aDisabledClassChildren as $sDisabledClassChild) - { - if (!self::IsAbstract($sDisabledClassChild)) - { + foreach ($aDisabledClassChildren as $sDisabledClassChild) { + if (!self::IsAbstract($sDisabledClassChild)) { $aClassesWithDisabledRule[] = $sDisabledClassChild; } } @@ -792,7 +767,6 @@ abstract class MetaModel return ((count($aNonNullRuleProperties) == 1) && (array_key_exists('disabled', $aNonNullRuleProperties))); } - /** * @param string $sClass * @param string $sType {@see \Combodo\iTop\Core\MetaModel\FriendlyNameType} @@ -957,7 +931,7 @@ abstract class MetaModel $aAttributes = $aNameSpec[1]; $aPieces = preg_split('/%([0-9])\\$s/', $sFormat, -1, PREG_SPLIT_DELIM_CAPTURE); - $aExpressions = array(); + $aExpressions = []; foreach ($aPieces as $i => $sPiece) { if ($i & 1) { // $i is ODD - sPiece is a delimiter @@ -968,12 +942,10 @@ abstract class MetaModel $sAttCode = $aAttributes[$iReplacement]; $aExpressions[] = new FieldExpression($sAttCode); } - } else - { + } else { // $i is EVEN - sPiece is a literal // - if (strlen($sPiece) > 0) - { + if (strlen($sPiece) > 0) { $aExpressions[] = new ScalarExpression($sPiece); } } @@ -1132,8 +1104,10 @@ abstract class MetaModel final public static function GetOrderByDefault($sClass, $bOnlyDeclared = false) { self::_check_subclass($sClass); - $aOrderBy = array_key_exists("order_by_default", - self::$m_aClassParams[$sClass]) ? self::$m_aClassParams[$sClass]["order_by_default"] : array(); + $aOrderBy = array_key_exists( + "order_by_default", + self::$m_aClassParams[$sClass] + ) ? self::$m_aClassParams[$sClass]["order_by_default"] : []; if ($bOnlyDeclared) { // Used to reverse engineer the declaration of the data model return $aOrderBy; @@ -1188,7 +1162,7 @@ abstract class MetaModel */ final public static function GetDependentAttributes($sClass, $sAttCode) { - $aResults = array(); + $aResults = []; self::_check_subclass($sClass); foreach (self::ListAttributeDefs($sClass) as $sDependentAttCode => $void) { $aPrerequisites = self::GetPrerequisiteAttributes($sClass, $sDependentAttCode); @@ -1244,7 +1218,7 @@ abstract class MetaModel // This API does not rely on our capability to query the DB and retrieve // the list of existing tables // Rather, it uses the list of expected tables, corresponding to the data model - $aTables = array(); + $aTables = []; foreach (self::GetClasses() as $sClass) { if (!self::HasTable($sClass)) { continue; @@ -1253,7 +1227,7 @@ abstract class MetaModel // Could be completed later with all the classes that are using a given table if (!array_key_exists($sTable, $aTables)) { - $aTables[$sTable] = array(); + $aTables[$sTable] = []; } $aTables[$sTable][] = $sClass; } @@ -1273,13 +1247,12 @@ abstract class MetaModel if (isset(self::$m_aClassParams[$sClass]['indexes'])) { $aRet = self::$m_aClassParams[$sClass]['indexes']; } else { - $aRet = array(); + $aRet = []; } return $aRet; } - /** * @param $sClass * @param $aColumns @@ -1290,15 +1263,12 @@ abstract class MetaModel */ private static function DBGetIndexesLength($sClass, $aColumns, $aTableInfo) { - $aLength = array(); + $aLength = []; $aAttDefs = self::ListAttributeDefs($sClass); - foreach($aColumns as $sAttSqlCode) - { + foreach ($aColumns as $sAttSqlCode) { $iLength = null; - foreach($aAttDefs as $sAttCode => $oAttDef) - { - if (($sAttCode == $sAttSqlCode) || ($oAttDef->IsParam('sql') && ($oAttDef->Get('sql') == $sAttSqlCode))) - { + foreach ($aAttDefs as $sAttCode => $oAttDef) { + if (($sAttCode == $sAttSqlCode) || ($oAttDef->IsParam('sql') && ($oAttDef->Get('sql') == $sAttSqlCode))) { $iLength = $oAttDef->GetIndexLength(); break; } @@ -1430,25 +1400,25 @@ abstract class MetaModel * * @var \AttributeDefinition[][] */ - private static $m_aAttribDefs = array(); + private static $m_aAttribDefs = []; /** * array of ("classname" => array of ("attcode"=>"sourceclass")) * * @var array */ - private static $m_aAttribOrigins = array(); + private static $m_aAttribOrigins = []; /** * array of ("classname" => array of ("attcode")) * * @var array */ - private static $m_aIgnoredAttributes = array(); + private static $m_aIgnoredAttributes = []; /** * array of ("classname" => array of ("attcode" => array of ("metaattcode" => oMetaAttDef)) * * @var array */ - private static $m_aEnumToMeta = array(); + private static $m_aEnumToMeta = []; /** * @param string $sClass @@ -1529,7 +1499,7 @@ abstract class MetaModel } if (array_key_exists($sClass, self::$m_aMagicFields)) { // Add the magic fields - $aFilterList = array_merge($aFilterList,self::$m_aMagicFields[$sClass]); + $aFilterList = array_merge($aFilterList, self::$m_aMagicFields[$sClass]); } $aFilterList[] = 'id'; return $aFilterList; @@ -1544,11 +1514,9 @@ abstract class MetaModel final public static function GetKeysList($sClass) { self::_check_subclass($sClass); - $aExtKeys = array(); - foreach(self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef) - { - if ($oAttDef->IsExternalKey()) - { + $aExtKeys = []; + foreach (self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef) { + if ($oAttDef->IsExternalKey()) { $aExtKeys[] = $sAttCode; } } @@ -1606,9 +1574,7 @@ abstract class MetaModel $bRes = false; } } - } - else - { + } else { $bRes = array_key_exists($sAttCode, self::$m_aAttribDefs[$sClass]); } @@ -1667,8 +1633,7 @@ abstract class MetaModel */ public static function IsValidObject($oObject) { - if (!is_object($oObject)) - { + if (!is_object($oObject)) { return false; } return (self::IsValidClass(get_class($oObject))); @@ -1704,9 +1669,7 @@ abstract class MetaModel $oKeyAttDef = self::GetAttributeDef($sClass, $sExtKeyAttCode); $sRemoteClass = $oKeyAttDef->GetTargetClass(); return self::GetAttributeDef($sRemoteClass, $sRemoteAttCode); - } - else - { + } else { throw new Exception("Unknown attribute $sAttCode from class $sClass"); } } @@ -1719,7 +1682,7 @@ abstract class MetaModel */ final public static function GetExternalKeys($sClass) { - $aExtKeys = array(); + $aExtKeys = []; foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt) { if ($oAtt->IsExternalKey()) { $aExtKeys[$sAttCode] = $oAtt; @@ -1737,7 +1700,7 @@ abstract class MetaModel */ final public static function GetLinkedSets($sClass) { - $aLinkedSets = array(); + $aLinkedSets = []; foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt) { // Note: Careful, this will only return SUB-classes, which does NOT include AttributeLinkedset itself! We might want to use "is_a()" instead. if (is_subclass_of($oAtt, 'AttributeLinkedSet')) { @@ -1757,9 +1720,9 @@ abstract class MetaModel */ final public static function GetExternalFields($sClass, $sKeyAttCode) { - static $aExtFields = array(); + static $aExtFields = []; if (!isset($aExtFields[$sClass][$sKeyAttCode])) { - $aExtFields[$sClass][$sKeyAttCode] = array(); + $aExtFields[$sClass][$sKeyAttCode] = []; foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt) { if ($oAtt->IsExternalField() && ($oAtt->GetKeyAttCode() == $sKeyAttCode)) { $aExtFields[$sClass][$sKeyAttCode][$oAtt->GetExtAttCode()] = $oAtt; @@ -1811,7 +1774,7 @@ abstract class MetaModel } /** @var array */ - protected static $m_aTrackForwardCache = array(); + protected static $m_aTrackForwardCache = []; /** * List external keys for which there is a LinkSet (direct or indirect) on the other end @@ -1827,20 +1790,17 @@ abstract class MetaModel final public static function GetTrackForwardExternalKeys($sClass) { if (!isset(self::$m_aTrackForwardCache[$sClass])) { - $aRes = array(); + $aRes = []; foreach (MetaModel::GetExternalKeys($sClass) as $sAttCode => $oAttDef) { $sRemoteClass = $oAttDef->GetTargetClass(); foreach (MetaModel::ListAttributeDefs($sRemoteClass) as $sRemoteAttCode => $oRemoteAttDef) { - if (!$oRemoteAttDef->IsLinkSet()) - { + if (!$oRemoteAttDef->IsLinkSet()) { continue; } - if (!is_subclass_of($sClass, $oRemoteAttDef->GetLinkedClass()) && $oRemoteAttDef->GetLinkedClass() != $sClass) - { + if (!is_subclass_of($sClass, $oRemoteAttDef->GetLinkedClass()) && $oRemoteAttDef->GetLinkedClass() != $sClass) { continue; } - if ($oRemoteAttDef->GetExtKeyToMe() != $sAttCode) - { + if ($oRemoteAttDef->GetExtKeyToMe() != $sAttCode) { continue; } $aRes[$sAttCode] = $oRemoteAttDef; @@ -1863,7 +1823,7 @@ abstract class MetaModel if (isset(self::$m_aEnumToMeta[$sClass][$sAttCode])) { $aRet = self::$m_aEnumToMeta[$sClass][$sAttCode]; } else { - $aRet = array(); + $aRet = []; } return $aRet; @@ -1882,21 +1842,15 @@ abstract class MetaModel */ public static function GetLabel($sClass, $sAttCodeEx, $bShowMandatory = false) { - if (($iPos = strpos($sAttCodeEx, '->')) === false) - { - if ($sAttCodeEx == 'id') - { + if (($iPos = strpos($sAttCodeEx, '->')) === false) { + if ($sAttCodeEx == 'id') { $sLabel = Dict::S('UI:CSVImport:idField'); - } - else - { + } else { $oAttDef = self::GetAttributeDef($sClass, $sAttCodeEx); $sMandatory = ($bShowMandatory && !$oAttDef->IsNullAllowed()) ? '*' : ''; $sLabel = $oAttDef->GetLabel().$sMandatory; } - } - else - { + } else { $sExtKeyAttCode = substr($sAttCodeEx, 0, $iPos); $sRemoteAttCode = substr($sAttCodeEx, $iPos + 2); $oKeyAttDef = MetaModel::GetAttributeDef($sClass, $sExtKeyAttCode); @@ -1938,7 +1892,7 @@ abstract class MetaModel /** * @var array array of ("listcode" => various info on the list, common to every classes) */ - private static $m_aListInfos = array(); + private static $m_aListInfos = []; /** * array of ("classname" => array of "listcode" => list) * list may be an array of attcode / fltcode @@ -1946,7 +1900,7 @@ abstract class MetaModel * * @var array */ - private static $m_aListData = array(); + private static $m_aListData = []; /** * @return array @@ -1961,7 +1915,7 @@ abstract class MetaModel * * @return mixed */ - final static public function GetZListInfo($sListCode) + final public static function GetZListInfo($sListCode) { return self::$m_aListInfos[$sListCode]; } @@ -1974,17 +1928,14 @@ abstract class MetaModel */ public static function GetZListItems($sClass, $sListCode) { - if (array_key_exists($sClass, self::$m_aListData)) - { - if (array_key_exists($sListCode, self::$m_aListData[$sClass])) - { + if (array_key_exists($sClass, self::$m_aListData)) { + if (array_key_exists($sListCode, self::$m_aListData[$sClass])) { return self::$m_aListData[$sClass][$sListCode]; } } $sParentClass = self::GetParentPersistentClass($sClass); - if (empty($sParentClass)) - { - return array(); + if (empty($sParentClass)) { + return []; } // nothing for the mother of all classes // Dig recursively return self::GetZListItems($sParentClass, $sListCode); @@ -2037,28 +1988,23 @@ abstract class MetaModel $sStateAttCode = MetaModel::GetStateAttributeCode($sClass); $sDefaultState = MetaModel::GetDefaultState($sClass); - foreach (MetaModel::FlattenZList(MetaModel::GetZListItems($sLinkedClass, 'list')) as $sLnkAttCode) - { + foreach (MetaModel::FlattenZList(MetaModel::GetZListItems($sLinkedClass, 'list')) as $sLnkAttCode) { $oLnkAttDef = MetaModel::GetAttributeDef($sLinkedClass, $sLnkAttCode); - if ($sStateAttCode == $sLnkAttCode) - { + if ($sStateAttCode == $sLnkAttCode) { // State attribute is always hidden from the UI continue; } if (($sLnkAttCode == $sExtKeyToMe) || ($sLnkAttCode == $sExtKeyToRemote) - || ($sLnkAttCode == 'finalclass')) - { + || ($sLnkAttCode == 'finalclass')) { continue; } - if (!($oLnkAttDef->IsWritable())) - { + if (!($oLnkAttDef->IsWritable())) { continue; } $iFlags = MetaModel::GetAttributeFlags($sLinkedClass, $sDefaultState, $sLnkAttCode); - if (!($iFlags & OPT_ATT_HIDDEN) && !($iFlags & OPT_ATT_READONLY)) - { + if (!($iFlags & OPT_ATT_HIDDEN) && !($iFlags & OPT_ATT_READONLY)) { $aAttCodesToPrint[] = $oLnkAttDef; } } @@ -2078,7 +2024,7 @@ abstract class MetaModel * @since 3.0.0 N°2334 added code for n-n relations in {@see BlockIndirectLinkSetViewTable::GetAttCodesToDisplay} * @since 3.1.0 N°3200 method creation so that it can be used elsewhere */ - public static function GetAttributeLinkedSetIndirectDatatableAttCodesToDisplay(string $sObjectClass, string $sObjectLinkedSetIndirectAttCode, string $sRemoteClass, string $sLnkExternalKeyToRemoteClassAttCode):array + public static function GetAttributeLinkedSetIndirectDatatableAttCodesToDisplay(string $sObjectClass, string $sObjectLinkedSetIndirectAttCode, string $sRemoteClass, string $sLnkExternalKeyToRemoteClassAttCode): array { $aLnkAttDefsToDisplay = MetaModel::GetZListAttDefsFilteredForIndirectLinkClass($sObjectClass, $sObjectLinkedSetIndirectAttCode); $aRemoteAttDefsToDisplay = MetaModel::GetZListAttDefsFilteredForIndirectRemoteClass($sRemoteClass); @@ -2114,8 +2060,7 @@ abstract class MetaModel public static function IsAttributeInZList($sClass, $sListCode, $sAttCodeOrFltCode, $sGroup = null) { $aZList = self::FlattenZlist(self::GetZListItems($sClass, $sListCode)); - if (!$sGroup) - { + if (!$sGroup) { return (in_array($sAttCodeOrFltCode, $aZList)); } return (in_array($sAttCodeOrFltCode, $aZList[$sGroup])); @@ -2129,7 +2074,7 @@ abstract class MetaModel * * @var array */ - private static $m_aRelationInfos = array(); + private static $m_aRelationInfos = []; /** * @param string $sClass @@ -2144,18 +2089,15 @@ abstract class MetaModel $aRelationInfo = array_keys(self::$m_aRelationInfos); // Return only the relations that have a meaning (i.e. for which at least one query is defined) // for the specified class - $aClassRelations = array(); - foreach($aRelationInfo as $sRelCode) - { + $aClassRelations = []; + foreach ($aRelationInfo as $sRelCode) { $aQueriesDown = self::EnumRelationQueries($sClass, $sRelCode, true /* Down */); - if (count($aQueriesDown) > 0) - { + if (count($aQueriesDown) > 0) { $aClassRelations[$sRelCode]['down'] = self::GetRelationLabel($sRelCode, true); } $aQueriesUp = self::EnumRelationQueries($sClass, $sRelCode, false /* Up */); - if (count($aQueriesUp) > 0) - { + if (count($aQueriesUp) > 0) { $aClassRelations[$sRelCode]['up'] = self::GetRelationLabel($sRelCode, false); } } @@ -2170,18 +2112,15 @@ abstract class MetaModel * @return string * @throws \DictExceptionMissingString */ - final static public function GetRelationDescription($sRelCode, $bDown = true) + final public static function GetRelationDescription($sRelCode, $bDown = true) { // Legacy convention had only one description describing the relation. // Now, as the relation is bidirectional, we have a description for each directions. $sLegacy = Dict::S("Relation:$sRelCode/Description"); - if($bDown) - { + if ($bDown) { $sKey = "Relation:$sRelCode/DownStream+"; - } - else - { + } else { $sKey = "Relation:$sRelCode/UpStream+"; } $sRet = Dict::S($sKey, $sLegacy); @@ -2204,8 +2143,7 @@ abstract class MetaModel // Now, the relation from A to B says that something is transmitted from A to B, thus going DOWNstream as described in a petri net. $sKey = "Relation:$sRelCode/DownStream"; $sLegacy = Dict::S("Relation:$sRelCode/VerbUp", $sKey); - } else - { + } else { $sKey = "Relation:$sRelCode/UpStream"; $sLegacy = Dict::S("Relation:$sRelCode/VerbDown", $sKey); } @@ -2223,23 +2161,19 @@ abstract class MetaModel */ protected static function ComputeRelationQueries($sRelCode) { - $aQueries = array(); - foreach(self::GetClasses() as $sClass) - { - $aQueries[$sClass]['down'] = array(); - if (!array_key_exists('up', $aQueries[$sClass])) - { - $aQueries[$sClass]['up'] = array(); + $aQueries = []; + foreach (self::GetClasses() as $sClass) { + $aQueries[$sClass]['down'] = []; + if (!array_key_exists('up', $aQueries[$sClass])) { + $aQueries[$sClass]['up'] = []; } - $aNeighboursDown = call_user_func_array(array($sClass, 'GetRelationQueriesEx'), array($sRelCode)); + $aNeighboursDown = call_user_func_array([$sClass, 'GetRelationQueriesEx'], [$sRelCode]); // Translate attributes into queries (new style of spec only) - foreach($aNeighboursDown as $sNeighbourId => $aNeighbourData) - { + foreach ($aNeighboursDown as $sNeighbourId => $aNeighbourData) { $aNeighbourData['sFromClass'] = $aNeighbourData['sDefinedInClass']; - try - { + try { if (Utils::StrLen($aNeighbourData['sQueryDown']) == 0) { $oAttDef = self::GetAttributeDef($sClass, $aNeighbourData['sAttribute']); if ($oAttDef instanceof AttributeExternalKey) { @@ -2247,12 +2181,10 @@ abstract class MetaModel $aNeighbourData['sToClass'] = $sTargetClass; $aNeighbourData['sQueryDown'] = 'SELECT '.$sTargetClass.' AS o WHERE o.id = :this->'.$aNeighbourData['sAttribute']; $aNeighbourData['sQueryUp'] = 'SELECT '.$aNeighbourData['sFromClass'].' AS o WHERE o.'.$aNeighbourData['sAttribute'].' = :this->id'; - } elseif ($oAttDef instanceof AttributeLinkedSet) - { + } elseif ($oAttDef instanceof AttributeLinkedSet) { $sLinkedClass = $oAttDef->GetLinkedClass(); $sExtKeyToMe = $oAttDef->GetExtKeyToMe(); - if ($oAttDef->IsIndirect()) - { + if ($oAttDef->IsIndirect()) { $sExtKeyToRemote = $oAttDef->GetExtKeyToRemote(); $oRemoteAttDef = self::GetAttributeDef($sLinkedClass, $sExtKeyToRemote); $sRemoteClass = $oRemoteAttDef->GetTargetClass(); @@ -2260,32 +2192,23 @@ abstract class MetaModel $aNeighbourData['sToClass'] = $sRemoteClass; $aNeighbourData['sQueryDown'] = "SELECT $sRemoteClass AS o JOIN $sLinkedClass AS lnk ON lnk.$sExtKeyToRemote = o.id WHERE lnk.$sExtKeyToMe = :this->id"; $aNeighbourData['sQueryUp'] = "SELECT ".$aNeighbourData['sFromClass']." AS o JOIN $sLinkedClass AS lnk ON lnk.$sExtKeyToMe = o.id WHERE lnk.$sExtKeyToRemote = :this->id"; - } - else - { + } else { $aNeighbourData['sToClass'] = $sLinkedClass; $aNeighbourData['sQueryDown'] = "SELECT $sLinkedClass AS o WHERE o.$sExtKeyToMe = :this->id"; $aNeighbourData['sQueryUp'] = "SELECT ".$aNeighbourData['sFromClass']." AS o WHERE o.id = :this->$sExtKeyToMe"; } - } - else - { + } else { throw new Exception("Unexpected attribute type for '{$aNeighbourData['sAttribute']}'. Expecting a link set or external key."); } - } - else - { + } else { $oSearch = DBObjectSearch::FromOQL($aNeighbourData['sQueryDown']); $aNeighbourData['sToClass'] = $oSearch->GetClass(); } - } - catch (Exception $e) - { + } catch (Exception $e) { throw new Exception("Wrong definition for the relation $sRelCode/{$aNeighbourData['sDefinedInClass']}/{$aNeighbourData['sNeighbour']}: ".$e->getMessage()); } - if ($aNeighbourData['sDirection'] == 'down') - { + if ($aNeighbourData['sDirection'] == 'down') { $aNeighbourData['sQueryUp'] = null; } @@ -2293,13 +2216,10 @@ abstract class MetaModel $aQueries[$sClass]['down'][$sArrowId] = $aNeighbourData; // Compute the reverse index - if ($aNeighbourData['sDefinedInClass'] == $sClass) - { - if ($aNeighbourData['sDirection'] == 'both') - { + if ($aNeighbourData['sDefinedInClass'] == $sClass) { + if ($aNeighbourData['sDirection'] == 'both') { $sToClass = $aNeighbourData['sToClass']; - foreach(self::EnumChildClasses($sToClass, ENUM_CHILD_CLASSES_ALL) as $sSubClass) - { + foreach (self::EnumChildClasses($sToClass, ENUM_CHILD_CLASSES_ALL) as $sSubClass) { $aQueries[$sSubClass]['up'][$sArrowId] = $aNeighbourData; } } @@ -2322,19 +2242,15 @@ abstract class MetaModel */ public static function EnumRelationQueries($sClass, $sRelCode, $bDown = true) { - static $aQueries = array(); - if (!isset($aQueries[$sRelCode])) - { + static $aQueries = []; + if (!isset($aQueries[$sRelCode])) { $aQueries[$sRelCode] = self::ComputeRelationQueries($sRelCode); } $sDirection = $bDown ? 'down' : 'up'; - if (isset($aQueries[$sRelCode][$sClass][$sDirection])) - { + if (isset($aQueries[$sRelCode][$sClass][$sDirection])) { return $aQueries[$sRelCode][$sClass][$sDirection]; - } - else - { - return array(); + } else { + return []; } } @@ -2352,9 +2268,13 @@ abstract class MetaModel * @throws \Exception */ public static function GetRelatedObjectsDown( - $sRelCode, $aSourceObjects, $iMaxDepth = 99, $bEnableRedundancy = true, $aUnreachable = array(), $aContexts = array() - ) - { + $sRelCode, + $aSourceObjects, + $iMaxDepth = 99, + $bEnableRedundancy = true, + $aUnreachable = [], + $aContexts = [] + ) { $oGraph = new RelationGraph(); foreach ($aSourceObjects as $oObject) { $oGraph->AddSourceObject($oObject); @@ -2378,7 +2298,7 @@ abstract class MetaModel * @return RelationGraph The graph of all the related objects * @throws \Exception */ - public static function GetRelatedObjectsUp($sRelCode, $aSourceObjects, $iMaxDepth = 99, $bEnableRedundancy = true, $aContexts = array()) + public static function GetRelatedObjectsUp($sRelCode, $aSourceObjects, $iMaxDepth = 99, $bEnableRedundancy = true, $aContexts = []) { $oGraph = new RelationGraph(); foreach ($aSourceObjects as $oObject) { @@ -2399,19 +2319,19 @@ abstract class MetaModel * * @var array */ - private static $m_aStates = array(); + private static $m_aStates = []; /** * array of ("classname" => array of ("stimuluscode"=>array('label'=>...))) * * @var array */ - private static $m_aStimuli = array(); + private static $m_aStimuli = []; /** * array of ("classname" => array of ("statcode_from"=>array of ("stimuluscode" => array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD))) * * @var array */ - private static $m_aTransitions = array(); + private static $m_aTransitions = []; /** * @param string $sClass @@ -2420,18 +2340,14 @@ abstract class MetaModel */ public static function EnumStates($sClass) { - if (array_key_exists($sClass, self::$m_aStates)) - { + if (array_key_exists($sClass, self::$m_aStates)) { return self::$m_aStates[$sClass]; - } - elseif (self::HasStateAttributeCode($sClass)) - { + } elseif (self::HasStateAttributeCode($sClass)) { $sStateAttCode = self::GetStateAttributeCode($sClass); $oAttDef = self::GetAttributeDef($sClass, $sStateAttCode); $aStates = []; - foreach($oAttDef->GetAllowedValues() as $sStateCode => $sStateLabel) - { + foreach ($oAttDef->GetAllowedValues() as $sStateCode => $sStateLabel) { $aStates[$sStateCode] = [ 'attribute_inherit' => '', 'attribute_list' => [], @@ -2439,10 +2355,8 @@ abstract class MetaModel } return $aStates; - } - else - { - return array(); + } else { + return []; } } @@ -2455,28 +2369,22 @@ abstract class MetaModel */ public static function EnumInitialStates($sClass) { - if (array_key_exists($sClass, self::$m_aStates)) - { - $aRet = array(); + if (array_key_exists($sClass, self::$m_aStates)) { + $aRet = []; // Add the states for which the flag 'is_initial_state' is set to - foreach(self::$m_aStates[$sClass] as $aStateCode => $aProps) - { - if (isset($aProps['initial_state_path'])) - { + foreach (self::$m_aStates[$sClass] as $aStateCode => $aProps) { + if (isset($aProps['initial_state_path'])) { $aRet[$aStateCode] = $aProps['initial_state_path']; } } // Add the default initial state $sMainInitialState = self::GetDefaultState($sClass); - if (!isset($aRet[$sMainInitialState])) - { - $aRet[$sMainInitialState] = array(); + if (!isset($aRet[$sMainInitialState])) { + $aRet[$sMainInitialState] = []; } return $aRet; - } - else - { - return array(); + } else { + return []; } } @@ -2487,13 +2395,10 @@ abstract class MetaModel */ public static function EnumStimuli($sClass) { - if (array_key_exists($sClass, self::$m_aStimuli)) - { + if (array_key_exists($sClass, self::$m_aStimuli)) { return self::$m_aStimuli[$sClass]; - } - else - { - return array(); + } else { + return []; } } @@ -2550,14 +2455,12 @@ abstract class MetaModel */ public static function EnumTransitions($sClass, $sStateCode) { - if (array_key_exists($sClass, self::$m_aTransitions)) - { - if (array_key_exists($sStateCode, self::$m_aTransitions[$sClass])) - { + if (array_key_exists($sClass, self::$m_aTransitions)) { + if (array_key_exists($sStateCode, self::$m_aTransitions[$sClass])) { return self::$m_aTransitions[$sClass][$sStateCode]; } } - return array(); + return []; } /** @@ -2575,15 +2478,15 @@ abstract class MetaModel */ public static function EnumPossibleAttributeFlags() { - return $aPossibleAttFlags = array( + return $aPossibleAttFlags = [ 'normal' => OPT_ATT_NORMAL, 'hidden' => OPT_ATT_HIDDEN, 'read_only' => OPT_ATT_READONLY, 'mandatory' => OPT_ATT_MANDATORY, 'must_change' => OPT_ATT_MUSTCHANGE, 'must_prompt' => OPT_ATT_MUSTPROMPT, - 'slave' => OPT_ATT_SLAVE - ); + 'slave' => OPT_ATT_SLAVE, + ]; } /** @@ -2651,7 +2554,7 @@ abstract class MetaModel */ public static function GetTransitionAttributes($sClass, $sStimulus, $sOriginState) { - $aAttributes = array(); + $aAttributes = []; // Retrieving target state $aTransitions = MetaModel::EnumTransitions($sClass, $sOriginState); @@ -2663,19 +2566,15 @@ abstract class MetaModel $aTargetState = $aStates[$sTargetState]; $aTargetStateAttributes = $aTargetState['attribute_list']; // - Merging with results (only MUST_XXX and MANDATORY) - foreach($aTargetStateAttributes as $sTargetStateAttCode => $iTargetStateAttFlags) - { + foreach ($aTargetStateAttributes as $sTargetStateAttCode => $iTargetStateAttFlags) { $iTmpAttFlags = OPT_ATT_NORMAL; - if ($iTargetStateAttFlags & OPT_ATT_MUSTPROMPT) - { + if ($iTargetStateAttFlags & OPT_ATT_MUSTPROMPT) { $iTmpAttFlags = $iTmpAttFlags | OPT_ATT_MUSTPROMPT; } - if ($iTargetStateAttFlags & OPT_ATT_MUSTCHANGE) - { + if ($iTargetStateAttFlags & OPT_ATT_MUSTCHANGE) { $iTmpAttFlags = $iTmpAttFlags | OPT_ATT_MUSTCHANGE; } - if ($iTargetStateAttFlags & OPT_ATT_MANDATORY) - { + if ($iTargetStateAttFlags & OPT_ATT_MANDATORY) { $iTmpAttFlags = $iTmpAttFlags | OPT_ATT_MANDATORY; } @@ -2685,14 +2584,10 @@ abstract class MetaModel // Retrieving attributes from transition $aTransitionAttributes = $aTransition['attribute_list']; // - Merging with results - foreach($aTransitionAttributes as $sAttCode => $iAttributeFlags) - { - if (array_key_exists($sAttCode, $aAttributes)) - { + foreach ($aTransitionAttributes as $sAttCode => $iAttributeFlags) { + if (array_key_exists($sAttCode, $aAttributes)) { $aAttributes[$sAttCode] = $aAttributes[$sAttCode] | $iAttributeFlags; - } - else - { + } else { $aAttributes[$sAttCode] = $iAttributeFlags; } } @@ -2717,7 +2612,7 @@ abstract class MetaModel if (array_key_exists($sState, $aStates)) { $bReadOnly = (($iFlags & OPT_ATT_READONLY) == OPT_ATT_READONLY); $bHidden = (($iFlags & OPT_ATT_HIDDEN) == OPT_ATT_HIDDEN); - foreach($aStates[$sState] as $sPrevState) { + foreach ($aStates[$sState] as $sPrevState) { $iPrevFlags = self::GetAttributeFlags($sClass, $sPrevState, $sAttCode); if (($iPrevFlags & OPT_ATT_HIDDEN) != OPT_ATT_HIDDEN) { $bReadOnly = $bReadOnly && (($iPrevFlags & OPT_ATT_READONLY) == OPT_ATT_READONLY); // if it is/was not readonly => then it's not @@ -2727,15 +2622,13 @@ abstract class MetaModel if ($bReadOnly) { $iFlags = $iFlags | OPT_ATT_READONLY; - } - else { + } else { $iFlags = $iFlags & ~OPT_ATT_READONLY; } if ($bHidden) { $iFlags = $iFlags | OPT_ATT_HIDDEN; - } - else { + } else { $iFlags = $iFlags & ~OPT_ATT_HIDDEN; } } @@ -2752,7 +2645,7 @@ abstract class MetaModel * @return mixed * @throws \Exception */ - public static function GetAllowedValues_att($sClass, $sAttCode, $aArgs = array(), $sContains = '') + public static function GetAllowedValues_att($sClass, $sAttCode, $aArgs = [], $sContains = '') { $oAttDef = self::GetAttributeDef($sClass, $sAttCode); return $oAttDef->GetAllowedValues($aArgs, $sContains); @@ -2768,7 +2661,7 @@ abstract class MetaModel * @return mixed * @throws \Exception */ - public static function GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs = array(), $sContains = '', $iAdditionalValue = null) + public static function GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs = [], $sContains = '', $iAdditionalValue = null) { /** @var \AttributeExternalKey $oAttDef */ $oAttDef = self::GetAttributeDef($sClass, $sAttCode); @@ -2776,8 +2669,6 @@ abstract class MetaModel return $oAttDef->GetAllowedValuesAsObjectSet($aArgs, $sContains, $iAdditionalValue); } - - // // Business model declaration verbs (should be static) // @@ -2790,14 +2681,12 @@ abstract class MetaModel public static function RegisterZList($sListCode, $aListInfo) { // Check mandatory params - $aMandatParams = array( + $aMandatParams = [ "description" => "detailed (though one line) description of the list", "type" => "attributes | filters", - ); - foreach($aMandatParams as $sParamName => $sParamDesc) - { - if (!array_key_exists($sParamName, $aListInfo)) - { + ]; + foreach ($aMandatParams as $sParamName => $sParamDesc) { + if (!array_key_exists($sParamName, $aListInfo)) { throw new CoreException("Declaration of list $sListCode - missing parameter $sParamName"); } } @@ -2842,8 +2731,7 @@ abstract class MetaModel */ public static function InitClasses($sTablePrefix) { - if (count(self::GetClasses()) > 0) - { + if (count(self::GetClasses()) > 0) { throw new CoreException("InitClasses should not be called more than once -skipped"); } @@ -2852,54 +2740,43 @@ abstract class MetaModel // Initialize the classes (declared attributes, etc.) // - $aObsoletableRootClasses = array(); - foreach(get_declared_classes() as $sPHPClass) - { - if (is_subclass_of($sPHPClass, 'DBObject')) - { + $aObsoletableRootClasses = []; + foreach (get_declared_classes() as $sPHPClass) { + if (is_subclass_of($sPHPClass, 'DBObject')) { $sParent = self::GetParentPersistentClass($sPHPClass); - if (array_key_exists($sParent, self::$m_aIgnoredAttributes)) - { + if (array_key_exists($sParent, self::$m_aIgnoredAttributes)) { // Inherit info about attributes to ignore self::$m_aIgnoredAttributes[$sPHPClass] = self::$m_aIgnoredAttributes[$sParent]; } - try - { + try { $oMethod = new ReflectionMethod($sPHPClass, 'Init'); - if ($oMethod->getDeclaringClass()->name == $sPHPClass) - { - call_user_func(array($sPHPClass, 'Init')); + if ($oMethod->getDeclaringClass()->name == $sPHPClass) { + call_user_func([$sPHPClass, 'Init']); // Inherit archive flag $bParentArchivable = isset(self::$m_aClassParams[$sParent]['archive']) ? self::$m_aClassParams[$sParent]['archive'] : false; $bArchivable = isset(self::$m_aClassParams[$sPHPClass]['archive']) ? self::$m_aClassParams[$sPHPClass]['archive'] : null; - if (!$bParentArchivable && $bArchivable && !self::IsRootClass($sPHPClass)) - { + if (!$bParentArchivable && $bArchivable && !self::IsRootClass($sPHPClass)) { throw new Exception("Archivability must be declared on top of the class hierarchy above $sPHPClass (consistency throughout the whole class tree is a must)"); } - if ($bParentArchivable && ($bArchivable === false)) - { + if ($bParentArchivable && ($bArchivable === false)) { throw new Exception("$sPHPClass must be archivable (consistency throughout the whole class tree is a must)"); } $bReallyArchivable = $bParentArchivable || $bArchivable; self::$m_aClassParams[$sPHPClass]['archive'] = $bReallyArchivable; $bArchiveRoot = $bReallyArchivable && !$bParentArchivable; self::$m_aClassParams[$sPHPClass]['archive_root'] = $bArchiveRoot; - if ($bReallyArchivable) - { + if ($bReallyArchivable) { self::$m_aClassParams[$sPHPClass]['archive_root_class'] = $bArchiveRoot ? $sPHPClass : self::$m_aClassParams[$sParent]['archive_root_class']; } // Inherit obsolescence expression $sObsolescence = null; - if (isset(self::$m_aClassParams[$sPHPClass]['obsolescence_expression'])) - { + if (isset(self::$m_aClassParams[$sPHPClass]['obsolescence_expression'])) { // Defined or overloaded $sObsolescence = self::$m_aClassParams[$sPHPClass]['obsolescence_expression']; $aObsoletableRootClasses[self::$m_aRootClasses[$sPHPClass]] = true; - } - elseif (isset(self::$m_aClassParams[$sParent]['obsolescence_expression'])) - { + } elseif (isset(self::$m_aClassParams[$sParent]['obsolescence_expression'])) { // Inherited $sObsolescence = self::$m_aClassParams[$sParent]['obsolescence_expression']; } @@ -2909,7 +2786,7 @@ abstract class MetaModel // - State attribute $bParentHasStateAttribute = (isset(self::$m_aClassParams[$sParent]['state_attcode']) && !empty(self::$m_aClassParams[$sParent]['state_attcode'])); $bHasStateAttribute = (isset(self::$m_aClassParams[$sPHPClass]['state_attcode']) && !empty(self::$m_aClassParams[$sPHPClass]['state_attcode'])); - if($bParentHasStateAttribute && !$bHasStateAttribute) { + if ($bParentHasStateAttribute && !$bHasStateAttribute) { // Set attribute code self::$m_aClassParams[$sPHPClass]['state_attcode'] = self::$m_aClassParams[$sParent]['state_attcode']; @@ -2918,43 +2795,34 @@ abstract class MetaModel // - Image attribute $bParentHasImageAttribute = (isset(self::$m_aClassParams[$sParent]['image_attcode']) && !empty(self::$m_aClassParams[$sParent]['image_attcode'])); $bHasImageAttribute = (isset(self::$m_aClassParams[$sPHPClass]['image_attcode']) && !empty(self::$m_aClassParams[$sPHPClass]['image_attcode'])); - if($bParentHasImageAttribute && !$bHasImageAttribute) { + if ($bParentHasImageAttribute && !$bHasImageAttribute) { // Set attribute code self::$m_aClassParams[$sPHPClass]['image_attcode'] = self::$m_aClassParams[$sParent]['image_attcode']; } - foreach(MetaModel::EnumPlugins('iOnClassInitialization') as $sPluginClass => $oClassInit) - { + foreach (MetaModel::EnumPlugins('iOnClassInitialization') as $sPluginClass => $oClassInit) { $oClassInit->OnAfterClassInitialization($sPHPClass); } } $aCurrentClassUniquenessRules = MetaModel::GetUniquenessRules($sPHPClass, true); - if (!empty($aCurrentClassUniquenessRules)) - { + if (!empty($aCurrentClassUniquenessRules)) { $aClassFields = self::GetAttributesList($sPHPClass); - foreach ($aCurrentClassUniquenessRules as $sUniquenessRuleId => $aUniquenessRuleProperties) - { + foreach ($aCurrentClassUniquenessRules as $sUniquenessRuleId => $aUniquenessRuleProperties) { $bIsRuleOverride = self::HasSameUniquenessRuleInParent($sPHPClass, $sUniquenessRuleId); - try - { + try { self::CheckUniquenessRuleValidity($aUniquenessRuleProperties, $bIsRuleOverride, $aClassFields); - } - catch (CoreUnexpectedValue $e) - { + } catch (CoreUnexpectedValue $e) { throw new Exception("Invalid uniqueness rule declaration : class={$sPHPClass}, rule=$sUniquenessRuleId, reason={$e->getMessage()}"); } - if (!$bIsRuleOverride) - { + if (!$bIsRuleOverride) { self::SetUniquenessRuleRootClass($sPHPClass, $sUniquenessRuleId); } } } - } - catch (ReflectionException $e) - { + } catch (ReflectionException $e) { // This class is only implementing methods, ignore it from the MetaModel perspective } } @@ -2962,25 +2830,22 @@ abstract class MetaModel // Add a 'class' attribute/filter to the root classes and their children // - foreach(self::EnumRootClasses() as $sRootClass) - { - if (self::IsStandaloneClass($sRootClass)) - { + foreach (self::EnumRootClasses() as $sRootClass) { + if (self::IsStandaloneClass($sRootClass)) { continue; } $sDbFinalClassField = self::DBGetClassField($sRootClass); - if (strlen($sDbFinalClassField) == 0) - { + if (strlen($sDbFinalClassField) == 0) { $sDbFinalClassField = 'finalclass'; self::$m_aClassParams[$sRootClass]["db_finalclass_field"] = 'finalclass'; } - $oClassAtt = new AttributeFinalClass('finalclass', array( + $oClassAtt = new AttributeFinalClass('finalclass', [ "sql" => $sDbFinalClassField, "default_value" => $sRootClass, "is_null_allowed" => false, - "depends_on" => array(), - )); + "depends_on" => [], + ]); self::AddMagicAttribute($oClassAtt, $sRootClass); $bObsoletable = array_key_exists($sRootClass, $aObsoletableRootClasses); @@ -2988,7 +2853,6 @@ abstract class MetaModel self::$m_aClassParams[$sRootClass]['obsolescence_expression'] = '0'; } - foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_EXCLUDETOP) as $sChildClass) { if (array_key_exists('finalclass', self::$m_aAttribDefs[$sChildClass])) { throw new CoreException("Class $sChildClass, 'finalclass' is a reserved keyword, it cannot be used as an attribute code"); @@ -3017,7 +2881,7 @@ abstract class MetaModel $oArchiveFlag = new AttributeArchiveFlag('archive_flag'); self::AddMagicAttribute($oArchiveFlag, $sClass); - $oArchiveDate = new AttributeArchiveDate('archive_date', array('magic' => true, "allowed_values" => null, "sql" => 'archive_date', "default_value" => '', "is_null_allowed" => true, "depends_on" => array())); + $oArchiveDate = new AttributeArchiveDate('archive_date', ['magic' => true, "allowed_values" => null, "sql" => 'archive_date', "default_value" => '', "is_null_allowed" => true, "depends_on" => []]); self::AddMagicAttribute($oArchiveDate, $sClass); } elseif (self::$m_aClassParams[$sClass]["archive"]) { $sArchiveRoot = self::$m_aClassParams[$sClass]['archive_root_class']; @@ -3038,7 +2902,7 @@ abstract class MetaModel self::AddMagicAttribute($oObsolescenceFlag, $sClass); if (self::$m_aRootClasses[$sClass] == $sClass) { - $oObsolescenceDate = new AttributeObsolescenceDate('obsolescence_date', array('magic' => true, "allowed_values" => null, "sql" => 'obsolescence_date', "default_value" => '', "is_null_allowed" => true, "depends_on" => array())); + $oObsolescenceDate = new AttributeObsolescenceDate('obsolescence_date', ['magic' => true, "allowed_values" => null, "sql" => 'obsolescence_date', "default_value" => '', "is_null_allowed" => true, "depends_on" => []]); self::AddMagicAttribute($oObsolescenceDate, $sClass); } else { $oObsolescenceDate = clone self::$m_aAttribDefs[$sRootClass]['obsolescence_date']; @@ -3057,13 +2921,13 @@ abstract class MetaModel // Compute the filter codes // foreach ($oAttDef->GetMagicFields() as $sCode) { - if(!array_key_exists($sClass, self::$m_aMagicFields)) { + if (!array_key_exists($sClass, self::$m_aMagicFields)) { self::$m_aMagicFields[] = $sClass; } self::$m_aMagicFields[$sClass][] = $sCode; } - if(!$oAttDef->IsSearchable()){ - if(!array_key_exists($sClass, self::$m_aFilterForbiddenAttributes)) { + if (!$oAttDef->IsSearchable()) { + if (!array_key_exists($sClass, self::$m_aFilterForbiddenAttributes)) { self::$m_aFilterForbiddenAttributes[] = $sClass; } self::$m_aFilterForbiddenAttributes[$sClass][] = $sAttCode; @@ -3084,41 +2948,37 @@ abstract class MetaModel $sKeyAttCode = $oAttDef->GetKeyAttCode(); $sRemoteAttCode = $oAttDef->GetExtAttCode()."_friendlyname"; $sFriendlyNameAttCode = $sAttCode.'_friendlyname'; - $oFriendlyName = new AttributeExternalField($sFriendlyNameAttCode, array("allowed_values" => null, "extkey_attcode" => $sKeyAttCode, "target_attcode" => $sRemoteAttCode, "depends_on" => array())); + $oFriendlyName = new AttributeExternalField($sFriendlyNameAttCode, ["allowed_values" => null, "extkey_attcode" => $sKeyAttCode, "target_attcode" => $sRemoteAttCode, "depends_on" => []]); self::AddMagicAttribute($oFriendlyName, $sClass, self::$m_aAttribOrigins[$sClass][$sKeyAttCode]); } else { // Create the friendly name attribute $sFriendlyNameAttCode = $sAttCode.'_friendlyname'; - $oFriendlyName = new AttributeExternalField($sFriendlyNameAttCode, array('allowed_values' => null, 'extkey_attcode' => $sAttCode, "target_attcode" => 'friendlyname', 'depends_on' => array())); + $oFriendlyName = new AttributeExternalField($sFriendlyNameAttCode, ['allowed_values' => null, 'extkey_attcode' => $sAttCode, "target_attcode" => 'friendlyname', 'depends_on' => []]); self::AddMagicAttribute($oFriendlyName, $sClass, self::$m_aAttribOrigins[$sClass][$sAttCode]); if (self::HasChildrenClasses($sRemoteClass)) { // First, create an external field attribute, that gets the final class $sClassRecallAttCode = $sAttCode.'_finalclass_recall'; - $oClassRecall = new AttributeExternalField($sClassRecallAttCode, array( + $oClassRecall = new AttributeExternalField($sClassRecallAttCode, [ "allowed_values" => null, "extkey_attcode" => $sAttCode, "target_attcode" => "finalclass", "is_null_allowed" => true, - "depends_on" => array(), - )); + "depends_on" => [], + ]); self::AddMagicAttribute($oClassRecall, $sClass, self::$m_aAttribOrigins[$sClass][$sAttCode]); // Add it to the ZLists where the external key is present //foreach(self::$m_aListData[$sClass] as $sListCode => $aAttributes) $sListCode = 'list'; - if (isset(self::$m_aListData[$sClass][$sListCode])) - { + if (isset(self::$m_aListData[$sClass][$sListCode])) { $aAttributes = self::$m_aListData[$sClass][$sListCode]; // temporary.... no loop { - if (in_array($sAttCode, $aAttributes)) - { - $aNewList = array(); - foreach($aAttributes as $iPos => $sAttToDisplay) - { - if (is_string($sAttToDisplay) && ($sAttToDisplay == $sAttCode)) - { + if (in_array($sAttCode, $aAttributes)) { + $aNewList = []; + foreach ($aAttributes as $iPos => $sAttToDisplay) { + if (is_string($sAttToDisplay) && ($sAttToDisplay == $sAttCode)) { // Insert the final class right before $aNewList[] = $sClassRecallAttCode; } @@ -3142,7 +3002,7 @@ abstract class MetaModel $sKeyAttCode = $sAttCode; $sRemoteAttCode = 'archive_flag'; } - $oMagic = new AttributeExternalField($sCode, array("allowed_values" => null, "extkey_attcode" => $sKeyAttCode, "target_attcode" => $sRemoteAttCode, "depends_on" => array())); + $oMagic = new AttributeExternalField($sCode, ["allowed_values" => null, "extkey_attcode" => $sKeyAttCode, "target_attcode" => $sRemoteAttCode, "depends_on" => []]); self::AddMagicAttribute($oMagic, $sClass, self::$m_aAttribOrigins[$sClass][$sKeyAttCode]); } @@ -3157,7 +3017,7 @@ abstract class MetaModel $sKeyAttCode = $sAttCode; $sRemoteAttCode = 'obsolescence_flag'; } - $oMagic = new AttributeExternalField($sCode, array("allowed_values" => null, "extkey_attcode" => $sKeyAttCode, "target_attcode" => $sRemoteAttCode, "depends_on" => array())); + $oMagic = new AttributeExternalField($sCode, ["allowed_values" => null, "extkey_attcode" => $sKeyAttCode, "target_attcode" => $sRemoteAttCode, "depends_on" => []]); self::AddMagicAttribute($oMagic, $sClass, self::$m_aAttribOrigins[$sClass][$sKeyAttCode]); } } @@ -3188,14 +3048,12 @@ abstract class MetaModel private static function HasSameUniquenessRuleInParent($sClassName, $sUniquenessRuleId) { $sParentClass = self::GetParentClass($sClassName); - if (empty($sParentClass)) - { + if (empty($sParentClass)) { return false; } $aParentClassUniquenessRules = self::GetUniquenessRules($sParentClass); - if (array_key_exists($sUniquenessRuleId, $aParentClassUniquenessRules)) - { + if (array_key_exists($sUniquenessRuleId, $aParentClassUniquenessRules)) { return true; } @@ -3213,9 +3071,9 @@ abstract class MetaModel * @since 2.6.0 N°659 uniqueness constraint * @since 2.6.1 N°1968 (joli mois de mai...) disallow overrides of 'attributes' properties */ - public static function CheckUniquenessRuleValidity($aUniquenessRuleProperties, $bRuleOverride = true, $aExistingClassFields = array()) + public static function CheckUniquenessRuleValidity($aUniquenessRuleProperties, $bRuleOverride = true, $aExistingClassFields = []) { - $MANDATORY_ATTRIBUTES = array('attributes'); + $MANDATORY_ATTRIBUTES = ['attributes']; $UNIQUENESS_MANDATORY_KEYS_NB = count($MANDATORY_ATTRIBUTES); $bHasMissingMandatoryKey = true; @@ -3224,18 +3082,14 @@ abstract class MetaModel $bHasNonDisabledKeys = false; $bDisabledKeyValue = null; - foreach ($aUniquenessRuleProperties as $sUniquenessRuleKey => $aUniquenessRuleProperty) - { - if ($sUniquenessRuleKey === 'disabled') - { + foreach ($aUniquenessRuleProperties as $sUniquenessRuleKey => $aUniquenessRuleProperty) { + if ($sUniquenessRuleKey === 'disabled') { $bDisabledKeyValue = $aUniquenessRuleProperty; - if (!is_null($aUniquenessRuleProperty)) - { + if (!is_null($aUniquenessRuleProperty)) { continue; } } - if (is_null($aUniquenessRuleProperty)) - { + if (is_null($aUniquenessRuleProperty)) { continue; } @@ -3245,14 +3099,10 @@ abstract class MetaModel $iMissingMandatoryKeysNb--; } - if ($sUniquenessRuleKey === 'attributes') - { - if (!empty($aExistingClassFields)) - { - foreach ($aUniquenessRuleProperties[$sUniquenessRuleKey] as $sRuleAttribute) - { - if (!in_array($sRuleAttribute, $aExistingClassFields, true)) - { + if ($sUniquenessRuleKey === 'attributes') { + if (!empty($aExistingClassFields)) { + foreach ($aUniquenessRuleProperties[$sUniquenessRuleKey] as $sRuleAttribute) { + if (!in_array($sRuleAttribute, $aExistingClassFields, true)) { throw new CoreUnexpectedValue("Uniqueness rule : non existing field '$sRuleAttribute'"); } } @@ -3260,21 +3110,17 @@ abstract class MetaModel } } - if ($iMissingMandatoryKeysNb === 0) - { + if ($iMissingMandatoryKeysNb === 0) { $bHasMissingMandatoryKey = false; } - if ($bRuleOverride && $bHasNonDisabledKeys) - { + if ($bRuleOverride && $bHasNonDisabledKeys) { throw new CoreUnexpectedValue('Uniqueness rule : only the \'disabled\' key can be overridden'); } - if ($bRuleOverride && is_null($bDisabledKeyValue)) - { + if ($bRuleOverride && is_null($bDisabledKeyValue)) { throw new CoreUnexpectedValue('Uniqueness rule : when overriding a rule, value must be set for the \'disabled\' key'); } - if (!$bRuleOverride && $bHasMissingMandatoryKey) - { + if (!$bRuleOverride && $bHasMissingMandatoryKey) { throw new CoreUnexpectedValue('Uniqueness rule : missing mandatory property'); } } @@ -3287,7 +3133,6 @@ abstract class MetaModel // In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation) } - /** * @param array $aParams * @@ -3297,7 +3142,7 @@ abstract class MetaModel { // Check mandatory params // Warning: Do not put image_attcode as a mandatory attribute or it will break all PHP datamodel classes - $aMandatParams = array( + $aMandatParams = [ "category" => "group classes by modules defining their visibility in the UI", "key_type" => "autoincrement | string", "name_attcode" => "define which attribute is the class name, may be an array of attributes (format specified in the dictionary as 'Class:myclass/Name' => '%1\$s %2\$s...'", @@ -3306,34 +3151,30 @@ abstract class MetaModel "db_table" => "database table", "db_key_field" => "database field which is the key", "db_finalclass_field" => "database field wich is the reference to the actual class of the object, considering that this will be a compound class", - ); + ]; $sClass = self::GetCallersPHPClass("Init", self::$m_bTraceSourceFiles); - foreach($aMandatParams as $sParamName => $sParamDesc) - { - if (!array_key_exists($sParamName, $aParams)) - { + foreach ($aMandatParams as $sParamName => $sParamDesc) { + if (!array_key_exists($sParamName, $aParams)) { throw new CoreException("Declaration of class $sClass - missing parameter $sParamName"); } } $aCategories = explode(',', $aParams['category']); - foreach($aCategories as $sCategory) - { + foreach ($aCategories as $sCategory) { self::$m_Category2Class[$sCategory][] = $sClass; } self::$m_Category2Class[''][] = $sClass; // all categories, include this one - self::$m_aRootClasses[$sClass] = $sClass; // first, let consider that I am the root... updated on inheritance - self::$m_aParentClasses[$sClass] = array(); - self::$m_aChildClasses[$sClass] = array(); + self::$m_aParentClasses[$sClass] = []; + self::$m_aChildClasses[$sClass] = []; self::$m_aClassParams[$sClass] = $aParams; - self::$m_aAttribDefs[$sClass] = array(); - self::$m_aAttribOrigins[$sClass] = array(); + self::$m_aAttribDefs[$sClass] = []; + self::$m_aAttribOrigins[$sClass] = []; } /** @@ -3344,13 +3185,11 @@ abstract class MetaModel */ protected static function object_array_mergeclone($aSource1, $aSource2) { - $aRes = array(); - foreach($aSource1 as $key => $object) - { + $aRes = []; + foreach ($aSource1 as $key => $object) { $aRes[$key] = clone $object; } - foreach($aSource2 as $key => $object) - { + foreach ($aSource2 as $key => $object) { $aRes[$key] = clone $object; } @@ -3372,8 +3211,8 @@ abstract class MetaModel } if (isset(self::$m_aAttribDefs[$sSourceClass])) { if (!isset(self::$m_aAttribDefs[$sTargetClass])) { - self::$m_aAttribDefs[$sTargetClass] = array(); - self::$m_aAttribOrigins[$sTargetClass] = array(); + self::$m_aAttribDefs[$sTargetClass] = []; + self::$m_aAttribOrigins[$sTargetClass] = []; } self::$m_aAttribDefs[$sTargetClass] = self::object_array_mergeclone(self::$m_aAttribDefs[$sTargetClass], self::$m_aAttribDefs[$sSourceClass]); foreach (self::$m_aAttribDefs[$sTargetClass] as $sAttCode => $oAttDef) { @@ -3382,13 +3221,10 @@ abstract class MetaModel self::$m_aAttribOrigins[$sTargetClass] = array_merge(self::$m_aAttribOrigins[$sTargetClass], self::$m_aAttribOrigins[$sSourceClass]); } // Build root class information - if (array_key_exists($sSourceClass, self::$m_aRootClasses)) - { + if (array_key_exists($sSourceClass, self::$m_aRootClasses)) { // Inherit... self::$m_aRootClasses[$sTargetClass] = self::$m_aRootClasses[$sSourceClass]; - } - else - { + } else { // This class will be the root class self::$m_aRootClasses[$sSourceClass] = $sSourceClass; self::$m_aRootClasses[$sTargetClass] = $sSourceClass; @@ -3396,8 +3232,7 @@ abstract class MetaModel self::$m_aParentClasses[$sTargetClass] += self::$m_aParentClasses[$sSourceClass]; self::$m_aParentClasses[$sTargetClass][] = $sSourceClass; // I am the child of each and every parent... - foreach(self::$m_aParentClasses[$sTargetClass] as $sAncestorClass) - { + foreach (self::$m_aParentClasses[$sTargetClass] as $sAncestorClass) { self::$m_aChildClasses[$sAncestorClass][] = $sTargetClass; } } @@ -3411,12 +3246,10 @@ abstract class MetaModel { // Differs from self::IsValidClass() // because it is being called before all the classes have been initialized - if (!class_exists($sClass)) - { + if (!class_exists($sClass)) { return false; } - if (!is_subclass_of($sClass, 'DBObject')) - { + if (!is_subclass_of($sClass, 'DBObject')) { return false; } @@ -3454,29 +3287,21 @@ abstract class MetaModel // declared in a module which is currently not installed/active // We simply discard those attributes // - if ($oAtt->IsLinkSet()) - { + if ($oAtt->IsLinkSet()) { $sRemoteClass = $oAtt->GetLinkedClass(); - if (!self::Init_IsKnownClass($sRemoteClass)) - { + if (!self::Init_IsKnownClass($sRemoteClass)) { self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = $sRemoteClass; return; } - } - elseif ($oAtt->IsExternalKey()) - { + } elseif ($oAtt->IsExternalKey()) { $sRemoteClass = $oAtt->GetTargetClass(); - if (!self::Init_IsKnownClass($sRemoteClass)) - { + if (!self::Init_IsKnownClass($sRemoteClass)) { self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = $sRemoteClass; return; } - } - elseif ($oAtt->IsExternalField()) - { + } elseif ($oAtt->IsExternalField()) { $sExtKeyAttCode = $oAtt->GetKeyAttCode(); - if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode])) - { + if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode])) { // The corresponding external key has already been ignored self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode]; @@ -3518,22 +3343,16 @@ abstract class MetaModel */ protected static function Init_CheckZListItems(&$aItems, $sTargetClass) { - foreach($aItems as $iFoo => $attCode) - { - if (is_array($attCode)) - { + foreach ($aItems as $iFoo => $attCode) { + if (is_array($attCode)) { // Note: to make sure that the values will be updated recursively, // do not pass $attCode, but $aItems[$iFoo] instead self::Init_CheckZListItems($aItems[$iFoo], $sTargetClass); - if (count($aItems[$iFoo]) == 0) - { + if (count($aItems[$iFoo]) == 0) { unset($aItems[$iFoo]); } - } - else - { - if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$attCode])) - { + } else { + if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$attCode])) { unset($aItems[$iFoo]); } } @@ -3547,15 +3366,11 @@ abstract class MetaModel */ public static function FlattenZList($aList) { - $aResult = array(); - foreach($aList as $value) - { - if (!is_array($value)) - { + $aResult = []; + foreach ($aList as $value) { + if (!is_array($value)) { $aResult[] = $value; - } - else - { + } else { $aResult = array_merge($aResult, self::FlattenZList($value)); } } @@ -3570,22 +3385,19 @@ abstract class MetaModel public static function Init_DefineState($sStateCode, $aStateDef) { $sTargetClass = self::GetCallersPHPClass("Init"); - if (is_null($aStateDef['attribute_list'])) - { - $aStateDef['attribute_list'] = array(); + if (is_null($aStateDef['attribute_list'])) { + $aStateDef['attribute_list'] = []; } $sParentState = $aStateDef['attribute_inherit']; - if (!empty($sParentState)) - { + if (!empty($sParentState)) { // Inherit from the given state (must be defined !) // $aToInherit = self::$m_aStates[$sTargetClass][$sParentState]; // Reset the constraint when it was mandatory to set the value at the previous state // - foreach($aToInherit['attribute_list'] as $sState => $iFlags) - { + foreach ($aToInherit['attribute_list'] as $sState => $iFlags) { $iFlags = $iFlags & ~OPT_ATT_MUSTPROMPT; $iFlags = $iFlags & ~OPT_ATT_MUSTCHANGE; $aToInherit['attribute_list'][$sState] = $iFlags; @@ -3595,10 +3407,8 @@ abstract class MetaModel $aStateDef['attribute_list'] = array_merge($aToInherit['attribute_list'], $aStateDef['attribute_list']); } - foreach($aStateDef['attribute_list'] as $sAttCode => $iFlags) - { - if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sAttCode])) - { + foreach ($aStateDef['attribute_list'] as $sAttCode => $iFlags) { + if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sAttCode])) { unset($aStateDef['attribute_list'][$sAttCode]); } } @@ -3606,7 +3416,7 @@ abstract class MetaModel self::$m_aStates[$sTargetClass][$sStateCode] = $aStateDef; // by default, create an empty set of transitions associated to that state - self::$m_aTransitions[$sTargetClass][$sStateCode] = array(); + self::$m_aTransitions[$sTargetClass][$sStateCode] = []; } /** @@ -3646,16 +3456,14 @@ abstract class MetaModel */ public static function GetHighlightScale($sTargetClass) { - $aScale = array(); - $aParentScale = array(); + $aScale = []; + $aParentScale = []; $sParentClass = self::GetParentPersistentClass($sTargetClass); - if (!empty($sParentClass)) - { + if (!empty($sParentClass)) { // inherit the scale from the parent class $aParentScale = self::GetHighlightScale($sParentClass); } - if (array_key_exists($sTargetClass, self::$m_aHighlightScales)) - { + if (array_key_exists($sTargetClass, self::$m_aHighlightScales)) { $aScale = self::$m_aHighlightScales[$sTargetClass]; } return array_merge($aParentScale, $aScale); // Merge both arrays, the values from the last one have precedence @@ -3672,16 +3480,12 @@ abstract class MetaModel $sCode = ''; if (array_key_exists($sTargetClass, self::$m_aStates) && array_key_exists($sStateCode, self::$m_aStates[$sTargetClass]) - && array_key_exists('highlight', self::$m_aStates[$sTargetClass][$sStateCode])) - { + && array_key_exists('highlight', self::$m_aStates[$sTargetClass][$sStateCode])) { $sCode = self::$m_aStates[$sTargetClass][$sStateCode]['highlight']['code']; - } - else - { + } else { // Check the parent's definition $sParentClass = self::GetParentPersistentClass($sTargetClass); - if (!empty($sParentClass)) - { + if (!empty($sParentClass)) { $sCode = self::GetHighlightCode($sParentClass, $sStateCode); } } @@ -3722,9 +3526,8 @@ abstract class MetaModel public static function Init_DefineTransition($sStateCode, $sStimulusCode, $aTransitionDef) { $sTargetClass = self::GetCallersPHPClass("Init"); - if (is_null($aTransitionDef['actions'])) - { - $aTransitionDef['actions'] = array(); + if (is_null($aTransitionDef['actions'])) { + $aTransitionDef['actions'] = []; } self::$m_aTransitions[$sTargetClass][$sStateCode][$sStimulusCode] = $aTransitionDef; } @@ -3735,12 +3538,10 @@ abstract class MetaModel public static function Init_InheritLifecycle($sSourceClass = '') { $sTargetClass = self::GetCallersPHPClass("Init"); - if (empty($sSourceClass)) - { + if (empty($sSourceClass)) { // Default: inherit from parent class $sSourceClass = self::GetParentPersistentClass($sTargetClass); - if (empty($sSourceClass)) - { + if (empty($sSourceClass)) { return; } // no attributes for the mother of all classes } @@ -3787,12 +3588,9 @@ abstract class MetaModel */ public static function GetParentClass($sClass) { - if (count(self::$m_aParentClasses[$sClass]) == 0) - { + if (count(self::$m_aParentClasses[$sClass]) == 0) { return null; - } - else - { + } else { return end(self::$m_aParentClasses[$sClass]); } } @@ -3806,24 +3604,16 @@ abstract class MetaModel public static function GetLowestCommonAncestor($aClasses) { $sAncestor = null; - foreach($aClasses as $sClass) - { - if (is_null($sAncestor)) - { + foreach ($aClasses as $sClass) { + if (is_null($sAncestor)) { // first loop $sAncestor = $sClass; - } - elseif ($sClass == $sAncestor) - { + } elseif ($sClass == $sAncestor) { // remains the same - } - elseif (self::GetRootClass($sClass) != self::GetRootClass($sAncestor)) - { + } elseif (self::GetRootClass($sClass) != self::GetRootClass($sAncestor)) { $sAncestor = null; break; - } - else - { + } else { $sAncestor = self::LowestCommonAncestor($sAncestor, $sClass); } } @@ -3840,20 +3630,13 @@ abstract class MetaModel */ protected static function LowestCommonAncestor($sClassA, $sClassB) { - if ($sClassA == $sClassB) - { + if ($sClassA == $sClassB) { $sRet = $sClassA; - } - elseif (is_subclass_of($sClassA, $sClassB)) - { + } elseif (is_subclass_of($sClassA, $sClassB)) { $sRet = $sClassB; - } - elseif (is_subclass_of($sClassB, $sClassA)) - { + } elseif (is_subclass_of($sClassB, $sClassA)) { $sRet = $sClassA; - } - else - { + } else { // Recurse $sRet = self::LowestCommonAncestor($sClassA, self::GetParentClass($sClassB)); } @@ -3871,10 +3654,8 @@ abstract class MetaModel public static function IsHierarchicalClass($sClass) { $sHierarchicalKeyCode = false; - foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAtt) - { - if ($oAtt->IsHierarchicalKey()) - { + foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt) { + if ($oAtt->IsHierarchicalKey()) { $sHierarchicalKeyCode = $sAttCode; // Found the hierarchical key, no need to continue break; } @@ -3901,23 +3682,16 @@ abstract class MetaModel public static function EnumParentClasses($sClass, $iOption = ENUM_PARENT_CLASSES_EXCLUDELEAF, $bRootFirst = true) { self::_check_subclass($sClass); - if ($bRootFirst) - { + if ($bRootFirst) { $aRes = self::$m_aParentClasses[$sClass]; - } - else - { + } else { $aRes = array_reverse(self::$m_aParentClasses[$sClass], true); } - if ($iOption != ENUM_PARENT_CLASSES_EXCLUDELEAF) - { - if ($bRootFirst) - { + if ($iOption != ENUM_PARENT_CLASSES_EXCLUDELEAF) { + if ($bRootFirst) { // Leaf class at the end $aRes[] = $sClass; - } - else - { + } else { // Leaf class on top array_unshift($aRes, $sClass); } @@ -3940,8 +3714,7 @@ abstract class MetaModel self::_check_subclass($sClass); $aRes = self::$m_aChildClasses[$sClass]; - if ($iOption != ENUM_CHILD_CLASSES_EXCLUDETOP) - { + if ($iOption != ENUM_CHILD_CLASSES_EXCLUDETOP) { if ($bRootFirst) { // Root class on top array_unshift($aRes, $sClass); @@ -3960,11 +3733,9 @@ abstract class MetaModel */ public static function EnumArchivableClasses() { - $aRes = array(); - foreach(self::GetClasses() as $sClass) - { - if (self::IsArchivable($sClass)) - { + $aRes = []; + foreach (self::GetClasses() as $sClass) { + if (self::IsArchivable($sClass)) { $aRes[] = $sClass; } } @@ -3980,13 +3751,10 @@ abstract class MetaModel */ public static function EnumObsoletableClasses($bRootClassesOnly = true) { - $aRes = array(); - foreach(self::GetClasses() as $sClass) - { - if (self::IsObsoletable($sClass)) - { - if ($bRootClassesOnly && !static::IsRootClass($sClass)) - { + $aRes = []; + foreach (self::GetClasses() as $sClass) { + if (self::IsObsoletable($sClass)) { + if ($bRootClassesOnly && !static::IsRootClass($sClass)) { continue; } $aRes[] = $sClass; @@ -4024,11 +3792,9 @@ abstract class MetaModel public static function GetSubclasses($sClass) { self::_check_subclass($sClass); - $aSubClasses = array(); - foreach(self::$m_aClassParams as $sSubClass => $foo) - { - if (is_subclass_of($sSubClass, $sClass)) - { + $aSubClasses = []; + foreach (self::$m_aClassParams as $sSubClass => $foo) { + if (is_subclass_of($sSubClass, $sClass)) { $aSubClasses[] = $sSubClass; } } @@ -4046,21 +3812,16 @@ abstract class MetaModel public static function GetClasses($sCategories = '', $bStrict = false) { $aCategories = explode(',', $sCategories); - $aClasses = array(); - foreach($aCategories as $sCategory) - { + $aClasses = []; + foreach ($aCategories as $sCategory) { $sCategory = trim($sCategory); - if (strlen($sCategory) == 0) - { + if (strlen($sCategory) == 0) { return array_keys(self::$m_aClassParams); } - if (array_key_exists($sCategory, self::$m_Category2Class)) - { + if (array_key_exists($sCategory, self::$m_Category2Class)) { $aClasses = array_merge($aClasses, self::$m_Category2Class[$sCategory]); - } - elseif ($bStrict) - { + } elseif ($bStrict) { throw new CoreException("unkown class category '$sCategory', expecting a value in {".implode(', ', array_keys(self::$m_Category2Class))."}"); } } @@ -4076,8 +3837,7 @@ abstract class MetaModel */ public static function HasTable($sClass) { - if (strlen(self::DBGetTable($sClass)) == 0) - { + if (strlen(self::DBGetTable($sClass)) == 0) { return false; } return true; @@ -4106,13 +3866,11 @@ abstract class MetaModel * * @return array */ - public static function PrepareQueryArguments($aArgs, $aMoreArgs = array(), $aExpectedArgs = null) + public static function PrepareQueryArguments($aArgs, $aMoreArgs = [], $aExpectedArgs = null) { - $aScalarArgs = array(); - if (is_null($aExpectedArgs) || count($aExpectedArgs) > 0 || count($aMoreArgs)>0) - { - foreach (array_merge($aArgs, $aMoreArgs) as $sArgName => $value) - { + $aScalarArgs = []; + if (is_null($aExpectedArgs) || count($aExpectedArgs) > 0 || count($aMoreArgs) > 0) { + foreach (array_merge($aArgs, $aMoreArgs) as $sArgName => $value) { if (self::IsValidObject($value)) { if (strpos($sArgName, '->object()') === false) { // Normalize object arguments @@ -4132,10 +3890,8 @@ abstract class MetaModel } } return static::AddMagicPlaceholders($aScalarArgs, $aExpectedArgs); - } - else - { - return array(); + } else { + return []; } } @@ -4148,33 +3904,27 @@ abstract class MetaModel { // Add standard magic arguments // - if (is_null($aExpectedArgs)) - { + if (is_null($aExpectedArgs)) { $aPlaceholders['current_contact_id'] = UserRights::GetContactId(); // legacy $oUser = UserRights::GetUserObject(); - if (!is_null($oUser)) - { + if (!is_null($oUser)) { $aPlaceholders['current_user->object()'] = $oUser; $oContact = UserRights::GetContactObject(); - if (!is_null($oContact)) - { + if (!is_null($oContact)) { $aPlaceholders['current_contact->object()'] = $oContact; } } - } - else - { + } else { $aCurrentUser = []; $aCurrentContact = []; - foreach ($aExpectedArgs as $expression) - { + foreach ($aExpectedArgs as $expression) { $aName = explode('->', $expression->GetName()); if ($aName[0] == 'current_contact_id') { $aPlaceholders['current_contact_id'] = UserRights::GetContactId(); - } else if ($aName[0] == 'current_user') { + } elseif ($aName[0] == 'current_user') { array_push($aCurrentUser, $aName[1]); - } else if ($aName[0] == 'current_contact') { + } elseif ($aName[0] == 'current_contact') { array_push($aCurrentContact, $aName[1]); } } @@ -4199,35 +3949,42 @@ abstract class MetaModel * @return void * */ - private static function FillObjectPlaceholders(array &$aPlaceholders, string $sPlaceHolderPrefix, ?\DBObject $oObject, array $aCurrentUser) : void { + private static function FillObjectPlaceholders(array &$aPlaceholders, string $sPlaceHolderPrefix, ?\DBObject $oObject, array $aCurrentUser): void + { $sPlaceHolderKey = $sPlaceHolderPrefix."->object()"; - if (is_null($oObject)){ + if (is_null($oObject)) { $aContext = [ "current_user_id" => UserRights::GetUserId(), "null object type" => $sPlaceHolderPrefix, "fields" => $aCurrentUser, ]; - IssueLog::Warning("Unresolved placeholders due to null object in current context", null, - $aContext); + IssueLog::Warning( + "Unresolved placeholders due to null object in current context", + null, + $aContext + ); $aPlaceholders[$sPlaceHolderKey] = Dict::Format("Core:Placeholder:CannotBeResolved", $sPlaceHolderKey); foreach ($aCurrentUser as $sField) { - $sPlaceHolderKey = $sPlaceHolderPrefix . "->$sField"; + $sPlaceHolderKey = $sPlaceHolderPrefix."->$sField"; $aPlaceholders[$sPlaceHolderKey] = Dict::Format("Core:Placeholder:CannotBeResolved", $sPlaceHolderKey); } } else { $aPlaceholders[$sPlaceHolderKey] = $oObject; foreach ($aCurrentUser as $sField) { - $sPlaceHolderKey = $sPlaceHolderPrefix . "->$sField"; + $sPlaceHolderKey = $sPlaceHolderPrefix."->$sField"; // Mind that the "id" is not viewed as a valid att. code by \MetaModel::IsValidAttCode() so we have to test it manually - if ($sField !== "id" && false === MetaModel::IsValidAttCode(get_class($oObject), $sField)){ + if ($sField !== "id" && false === MetaModel::IsValidAttCode(get_class($oObject), $sField)) { $aContext = [ "current_user_id" => UserRights::GetUserId(), "obj_class" => get_class($oObject), "placeholder" => $sPlaceHolderKey, "invalid_field" => $sField, ]; - IssueLog::Warning("Unresolved placeholder due to invalid attribute", null, - $aContext); + IssueLog::Warning( + "Unresolved placeholder due to invalid attribute", + null, + $aContext + ); $aPlaceholders[$sPlaceHolderKey] = Dict::Format("Core:Placeholder:CannotBeResolved", $sPlaceHolderKey); continue; } @@ -4246,29 +4003,25 @@ abstract class MetaModel { // Compute query modifiers properties (can be set in the search itself, by the context, etc.) // - $aModifierProperties = array(); + $aModifierProperties = []; /** * @var string $sPluginClass * @var iQueryModifier $oQueryModifier */ - foreach(MetaModel::EnumPlugins('iQueryModifier') as $sPluginClass => $oQueryModifier) - { + foreach (MetaModel::EnumPlugins('iQueryModifier') as $sPluginClass => $oQueryModifier) { // Lowest precedence: the application context $aPluginProps = ApplicationContext::GetPluginProperties($sPluginClass); // Highest precedence: programmatically specified (or OQL) - foreach($oFilter->GetModifierProperties($sPluginClass) as $sProp => $value) - { + foreach ($oFilter->GetModifierProperties($sPluginClass) as $sProp => $value) { $aPluginProps[$sProp] = $value; } - if (count($aPluginProps) > 0) - { + if (count($aPluginProps) > 0) { $aModifierProperties[$sPluginClass] = $aPluginProps; } } return $aModifierProperties; } - /** * Special processing for the hierarchical keys stored as nested sets * @@ -4281,22 +4034,16 @@ abstract class MetaModel public static function HKInsertChildUnder($iId, $oAttDef, $sTable) { // Get the parent id.right value - if ($iId == 0) - { + if ($iId == 0) { // No parent, insert completely at the right of the tree $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`"; $aRes = CMDBSource::QueryToArray($sSQL); - if (count($aRes) == 0) - { + if (count($aRes) == 0) { $iMyRight = 1; - } - else - { + } else { $iMyRight = $aRes[0]['max'] + 1; } - } - else - { + } else { $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` FROM `$sTable` WHERE id=".$iId; $iMyRight = CMDBSource::QueryToScalar($sSQL); $sSQLUpdateRight = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` + 2 WHERE `".$oAttDef->GetSQLRight()."` >= $iMyRight"; @@ -4304,7 +4051,7 @@ abstract class MetaModel $sSQLUpdateLeft = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` + 2 WHERE `".$oAttDef->GetSQLLeft()."` > $iMyRight"; CMDBSource::Query($sSQLUpdateLeft); } - return array($oAttDef->GetSQLRight() => $iMyRight + 1, $oAttDef->GetSQLLeft() => $iMyRight); + return [$oAttDef->GetSQLRight() => $iMyRight + 1, $oAttDef->GetSQLLeft() => $iMyRight]; } /** @@ -4366,26 +4113,20 @@ abstract class MetaModel public static function CheckHKeys(bool $bDiagnosticsOnly = false, bool $bVerbose = false, bool $bForceComputation = false) { $bChangeNeeded = false; - foreach(self::GetClasses() as $sClass) - { - if (!self::HasTable($sClass)) - { + foreach (self::GetClasses() as $sClass) { + if (!self::HasTable($sClass)) { continue; } - foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) - { + foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) { // Check (once) all the attributes that are hierarchical keys - if ((self::GetAttributeOrigin($sClass, $sAttCode) == $sClass) && $oAttDef->IsHierarchicalKey()) - { - if ($bVerbose) - { + if ((self::GetAttributeOrigin($sClass, $sAttCode) == $sClass) && $oAttDef->IsHierarchicalKey()) { + if ($bVerbose) { echo "The attribute $sAttCode from $sClass is a hierarchical key.\n"; } $bResult = self::HKInit($sClass, $sAttCode, $bDiagnosticsOnly, $bVerbose, $bForceComputation); $bChangeNeeded |= $bResult; - if ($bVerbose && !$bResult) - { + if ($bVerbose && !$bResult) { echo "Ok, the attribute $sAttCode from class $sClass seems up to date.\n"; } } @@ -4416,40 +4157,31 @@ abstract class MetaModel $bUpdateNeeded = $bForceComputation; $oAttDef = self::GetAttributeDef($sClass, $sAttCode); $sTable = self::DBGetTable($sClass, $sAttCode); - if ($oAttDef->IsHierarchicalKey()) - { + if ($oAttDef->IsHierarchicalKey()) { // Check if some values already exist in the table for the _right value, if so, do nothing $sRight = $oAttDef->GetSQLRight(); $sSQL = "SELECT MAX(`$sRight`) AS MaxRight FROM `$sTable`"; $iMaxRight = CMDBSource::QueryToScalar($sSQL); $sSQL = "SELECT COUNT(*) AS Count FROM `$sTable`"; // Note: COUNT(field) returns zero if the given field contains only NULLs $iCount = CMDBSource::QueryToScalar($sSQL); - if (!$bForceComputation && ($iCount != 0) && ($iMaxRight == 0)) - { + if (!$bForceComputation && ($iCount != 0) && ($iMaxRight == 0)) { $bUpdateNeeded = true; - if ($bVerbose) - { + if ($bVerbose) { echo "The table '$sTable' must be updated to compute the fields $sRight and ".$oAttDef->GetSQLLeft()."\n"; } } - if ($bForceComputation && !$bDiagnosticsOnly) - { + if ($bForceComputation && !$bDiagnosticsOnly) { echo "Rebuilding the fields $sRight and ".$oAttDef->GetSQLLeft()." from table '$sTable'...\n"; } - if ($bUpdateNeeded && !$bDiagnosticsOnly) - { - try - { + if ($bUpdateNeeded && !$bDiagnosticsOnly) { + try { CMDBSource::Query('START TRANSACTION'); self::HKInitChildren($sTable, $sAttCode, $oAttDef, 0, $idx); CMDBSource::Query('COMMIT'); - if ($bVerbose) - { + if ($bVerbose) { echo "Ok, table '$sTable' successfully updated.\n"; } - } - catch (Exception $e) - { + } catch (Exception $e) { CMDBSource::Query('ROLLBACK'); throw new Exception("An error occured (".$e->getMessage().") while initializing the hierarchy for ($sClass, $sAttCode). The database was not modified."); } @@ -4476,8 +4208,7 @@ abstract class MetaModel $aRes = CMDBSource::QueryToArray($sSQL); $sLeft = $oAttDef->GetSQLLeft(); $sRight = $oAttDef->GetSQLRight(); - foreach($aRes as $aValues) - { + foreach ($aRes as $aValues) { $iChildId = $aValues['id']; $iLeft = $iCurrIndex++; self::HKInitChildren($sTable, $sAttCode, $oAttDef, $iChildId, $iCurrIndex); @@ -4499,49 +4230,33 @@ abstract class MetaModel */ public static function RebuildMetaEnums($bVerbose = false) { - foreach(self::GetClasses() as $sClass) - { - if (!self::HasTable($sClass)) - { + foreach (self::GetClasses() as $sClass) { + if (!self::HasTable($sClass)) { continue; } - foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) - { + foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) { // Check (once) all the attributes that are hierarchical keys - if ((self::GetAttributeOrigin($sClass, $sAttCode) == $sClass) && $oAttDef instanceof AttributeEnum) - { - if (isset(self::$m_aEnumToMeta[$sClass][$sAttCode])) - { - foreach(self::$m_aEnumToMeta[$sClass][$sAttCode] as $sMetaAttCode => $oMetaAttDef) - { - $aMetaValues = array(); // array of (metavalue => array of values) - foreach($oAttDef->GetAllowedValues() as $sCode => $sLabel) - { + if ((self::GetAttributeOrigin($sClass, $sAttCode) == $sClass) && $oAttDef instanceof AttributeEnum) { + if (isset(self::$m_aEnumToMeta[$sClass][$sAttCode])) { + foreach (self::$m_aEnumToMeta[$sClass][$sAttCode] as $sMetaAttCode => $oMetaAttDef) { + $aMetaValues = []; // array of (metavalue => array of values) + foreach ($oAttDef->GetAllowedValues() as $sCode => $sLabel) { $aMappingData = $oMetaAttDef->GetMapRule($sClass); - if ($aMappingData == null) - { + if ($aMappingData == null) { $sMetaValue = $oMetaAttDef->GetDefaultValue(); - } - else - { - if (array_key_exists($sCode, $aMappingData['values'])) - { + } else { + if (array_key_exists($sCode, $aMappingData['values'])) { $sMetaValue = $aMappingData['values'][$sCode]; - } - elseif ($oMetaAttDef->GetDefaultValue() != '') - { + } elseif ($oMetaAttDef->GetDefaultValue() != '') { $sMetaValue = $oMetaAttDef->GetDefaultValue(); - } - else - { + } else { throw new Exception('MetaModel::RebuildMetaEnums(): mapping not found for value "'.$sCode.'"" in '.$sClass.', on attribute '.self::GetAttributeOrigin($sClass, $oMetaAttDef->GetCode()).'::'.$oMetaAttDef->GetCode()); } } $aMetaValues[$sMetaValue][] = $sCode; } - foreach($aMetaValues as $sMetaValue => $aEnumValues) - { + foreach ($aMetaValues as $sMetaValue => $aEnumValues) { $sMetaTable = self::DBGetTable($sClass, $sMetaAttCode); $sEnumTable = self::DBGetTable($sClass); $aColumns = array_keys($oMetaAttDef->GetSQLColumns()); @@ -4550,8 +4265,7 @@ abstract class MetaModel $sEnumColumn = reset($aColumns); $sValueList = implode(', ', CMDBSource::Quote($aEnumValues)); $sSql = "UPDATE `$sMetaTable` JOIN `$sEnumTable` ON `$sEnumTable`.id = `$sMetaTable`.id SET `$sMetaTable`.`$sMetaColumn` = '$sMetaValue' WHERE `$sEnumTable`.`$sEnumColumn` IN ($sValueList) AND `$sMetaTable`.`$sMetaColumn` != '$sMetaValue'"; - if ($bVerbose) - { + if ($bVerbose) { echo "Executing query: $sSql\n"; } CMDBSource::Query($sSql); @@ -4563,7 +4277,6 @@ abstract class MetaModel } } - /** * @param boolean $bDiagnostics * @param boolean $bVerbose @@ -4576,20 +4289,16 @@ abstract class MetaModel $sOQL = 'SELECT SynchroDataSource'; $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL)); $bFixNeeded = false; - if ($bVerbose && $oSet->Count() == 0) - { + if ($bVerbose && $oSet->Count() == 0) { echo "There are no Data Sources in the database.\n"; } - while ($oSource = $oSet->Fetch()) - { - if ($bVerbose) - { + while ($oSource = $oSet->Fetch()) { + if ($bVerbose) { echo "Checking Data Source '".$oSource->GetName()."'...\n"; $bFixNeeded = $bFixNeeded | $oSource->CheckDBConsistency($bDiagnostics, $bVerbose); } } - if (!$bFixNeeded && $bVerbose) - { + if (!$bFixNeeded && $bVerbose) { echo "Ok.\n"; } @@ -4606,23 +4315,20 @@ abstract class MetaModel */ public static function GenerateUniqueAlias(&$aAliases, $sNewName, $sRealName) { - if (!array_key_exists($sNewName, $aAliases)) - { + if (!array_key_exists($sNewName, $aAliases)) { $aAliases[$sNewName] = $sRealName; return $sNewName; } - for($i = 1; $i < 100; $i++) - { + for ($i = 1; $i < 100; $i++) { $sAnAlias = $sNewName.$i; - if (!array_key_exists($sAnAlias, $aAliases)) - { + if (!array_key_exists($sAnAlias, $aAliases)) { // Create that new alias $aAliases[$sAnAlias] = $sRealName; return $sAnAlias; } } - throw new CoreException('Failed to create an alias', array('aliases' => $aAliases, 'new' => $sNewName)); + throw new CoreException('Failed to create an alias', ['aliases' => $aAliases, 'new' => $sNewName]); } /** @@ -4634,106 +4340,76 @@ abstract class MetaModel */ public static function CheckDefinitions($bExitOnError = true) { - if (count(self::GetClasses()) == 0) - { + if (count(self::GetClasses()) == 0) { throw new CoreException("MetaModel::InitClasses() has not been called, or no class has been declared ?!?!"); } - $aErrors = array(); - $aSugFix = array(); - foreach(self::GetClasses() as $sClass) - { + $aErrors = []; + $aSugFix = []; + foreach (self::GetClasses() as $sClass) { $sTable = self::DBGetTable($sClass); $sTableLowercase = strtolower($sTable); - if ($sTableLowercase != $sTable) - { + if ($sTableLowercase != $sTable) { $aErrors[$sClass][] = "Table name '".$sTable."' has upper case characters. You might encounter issues when moving your installation between Linux and Windows."; $aSugFix[$sClass][] = "Use '$sTableLowercase' instead. Step 1: If already installed, then rename manually in the DB: RENAME TABLE `$sTable` TO `{$sTableLowercase}_tempname`, `{$sTableLowercase}_tempname` TO `$sTableLowercase`; Step 2: Rename the table in the datamodel and compile the application. Note: the MySQL statement provided in step 1 has been designed to be compatible with Windows or Linux."; } $aNameSpec = self::GetNameSpec($sClass); - foreach($aNameSpec[1] as $i => $sAttCode) - { - if (!self::IsValidAttCode($sClass, $sAttCode)) - { + foreach ($aNameSpec[1] as $i => $sAttCode) { + if (!self::IsValidAttCode($sClass, $sAttCode)) { $aErrors[$sClass][] = "Unknown attribute code '".$sAttCode."' for the name definition"; $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass)); } } - foreach(self::GetReconcKeys($sClass) as $sReconcKeyAttCode) - { - if (!empty($sReconcKeyAttCode) && !self::IsValidAttCode($sClass, $sReconcKeyAttCode)) - { + foreach (self::GetReconcKeys($sClass) as $sReconcKeyAttCode) { + if (!empty($sReconcKeyAttCode) && !self::IsValidAttCode($sClass, $sReconcKeyAttCode)) { $aErrors[$sClass][] = "Unknown attribute code '".$sReconcKeyAttCode."' in the list of reconciliation keys"; $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass)); } } $bHasWritableAttribute = false; - foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) - { + foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) { // It makes no sense to check the attributes again and again in the subclasses - if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) - { + if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) { continue; } - if ($oAttDef->IsExternalKey()) - { - if (!self::IsValidClass($oAttDef->GetTargetClass())) - { + if ($oAttDef->IsExternalKey()) { + if (!self::IsValidClass($oAttDef->GetTargetClass())) { $aErrors[$sClass][] = "Unknown class '".$oAttDef->GetTargetClass()."' for the external key '$sAttCode'"; $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetClasses())."}"; } - } - elseif ($oAttDef->IsExternalField()) - { + } elseif ($oAttDef->IsExternalField()) { $sKeyAttCode = $oAttDef->GetKeyAttCode(); - if (!self::IsValidAttCode($sClass, $sKeyAttCode) || !self::IsValidKeyAttCode($sClass, $sKeyAttCode)) - { + if (!self::IsValidAttCode($sClass, $sKeyAttCode) || !self::IsValidKeyAttCode($sClass, $sKeyAttCode)) { $aErrors[$sClass][] = "Unknown key attribute code '".$sKeyAttCode."' for the external field $sAttCode"; $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sClass))."}"; - } - else - { + } else { $oKeyAttDef = self::GetAttributeDef($sClass, $sKeyAttCode); $sTargetClass = $oKeyAttDef->GetTargetClass(); $sExtAttCode = $oAttDef->GetExtAttCode(); - if (!self::IsValidAttCode($sTargetClass, $sExtAttCode)) - { + if (!self::IsValidAttCode($sTargetClass, $sExtAttCode)) { $aErrors[$sClass][] = "Unknown key attribute code '".$sExtAttCode."' for the external field $sAttCode"; $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sTargetClass))."}"; } } - } - else - { - if ($oAttDef->IsLinkSet()) - { + } else { + if ($oAttDef->IsLinkSet()) { // Do nothing... - } - else - { - if ($oAttDef instanceof AttributeStopWatch) - { + } else { + if ($oAttDef instanceof AttributeStopWatch) { $aThresholds = $oAttDef->ListThresholds(); - if (is_array($aThresholds)) - { - foreach($aThresholds as $iPercent => $aDef) - { - if (array_key_exists('highlight', $aDef)) - { - if (!array_key_exists('code', $aDef['highlight'])) - { + if (is_array($aThresholds)) { + foreach ($aThresholds as $iPercent => $aDef) { + if (array_key_exists('highlight', $aDef)) { + if (!array_key_exists('code', $aDef['highlight'])) { $aErrors[$sClass][] = "The 'code' element is missing for the 'highlight' property of the $iPercent% threshold in the attribute: '$sAttCode'."; $aSugFix[$sClass][] = "Add a 'code' entry specifying the value of the highlight code for this threshold."; - } - else - { + } else { $aScale = self::GetHighlightScale($sClass); - if (!array_key_exists($aDef['highlight']['code'], $aScale)) - { + if (!array_key_exists($aDef['highlight']['code'], $aScale)) { $aErrors[$sClass][] = "'{$aDef['highlight']['code']}' is not a valid value for the 'code' element of the $iPercent% threshold in the attribute: '$sAttCode'."; $aSugFix[$sClass][] = "The possible highlight codes for this class are: ".implode(', ', array_keys($aScale))."."; } @@ -4741,25 +4417,18 @@ abstract class MetaModel } } } - } - else // standard attributes - { + } else { // standard attributes // Check that the default values definition is a valid object! $oValSetDef = $oAttDef->GetValuesDef(); - if (!is_null($oValSetDef) && !$oValSetDef instanceof ValueSetDefinition) - { + if (!is_null($oValSetDef) && !$oValSetDef instanceof ValueSetDefinition) { $aErrors[$sClass][] = "Allowed values for attribute $sAttCode is not of the relevant type"; $aSugFix[$sClass][] = "Please set it as an instance of a ValueSetDefinition object."; - } - else - { + } else { // Default value must be listed in the allowed values (if defined) $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode); - if (!is_null($aAllowedValues)) - { + if (!is_null($aAllowedValues)) { $sDefaultValue = $oAttDef->GetDefaultValue(); - if (is_string($sDefaultValue) && !array_key_exists($sDefaultValue, $aAllowedValues)) - { + if (is_string($sDefaultValue) && !array_key_exists($sDefaultValue, $aAllowedValues)) { $aErrors[$sClass][] = "Default value '".$sDefaultValue."' for attribute $sAttCode is not an allowed value"; $aSugFix[$sClass][] = "Please pickup the default value out of {'".implode(", ", array_keys($aAllowedValues))."'}"; } @@ -4769,13 +4438,10 @@ abstract class MetaModel } } // Check dependencies - if ($oAttDef->IsWritable()) - { + if ($oAttDef->IsWritable()) { $bHasWritableAttribute = true; - foreach($oAttDef->GetPrerequisiteAttributes() as $sDependOnAttCode) - { - if (!self::IsValidAttCode($sClass, $sDependOnAttCode)) - { + foreach ($oAttDef->GetPrerequisiteAttributes() as $sDependOnAttCode) { + if (!self::IsValidAttCode($sClass, $sDependOnAttCode)) { $aErrors[$sClass][] = "Unknown attribute code '".$sDependOnAttCode."' in the list of prerequisite attributes"; $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass)); } @@ -4786,43 +4452,32 @@ abstract class MetaModel // Lifecycle // $sStateAttCode = self::GetStateAttributeCode($sClass); - if (strlen($sStateAttCode) > 0) - { + if (strlen($sStateAttCode) > 0) { // Lifecycle - check that the state attribute does exist as an attribute - if (!self::IsValidAttCode($sClass, $sStateAttCode)) - { + if (!self::IsValidAttCode($sClass, $sStateAttCode)) { $aErrors[$sClass][] = "Unknown attribute code '".$sStateAttCode."' for the state definition"; $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}"; - } - else - { + } else { // Lifecycle - check that there is a value set constraint on the state attribute $aAllowedValuesRaw = self::GetAllowedValues_att($sClass, $sStateAttCode); $aStates = array_keys(self::EnumStates($sClass)); - if (is_null($aAllowedValuesRaw)) - { + if (is_null($aAllowedValuesRaw)) { $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' will reflect the state of the object. It must be restricted to a set of values"; $aSugFix[$sClass][] = "Please define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')]"; - } - else - { + } else { $aAllowedValues = array_keys($aAllowedValuesRaw); // Lifecycle - check the the state attribute allowed values are defined states - foreach($aAllowedValues as $sValue) - { - if (!in_array($sValue, $aStates)) - { + foreach ($aAllowedValues as $sValue) { + if (!in_array($sValue, $aStates)) { $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has an allowed value ($sValue) which is not a known state"; $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states"; } } // Lifecycle - check that defined states are allowed values - foreach($aStates as $sStateValue) - { - if (!in_array($sStateValue, $aAllowedValues)) - { + foreach ($aStates as $sStateValue) { + if (!in_array($sStateValue, $aAllowedValues)) { $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has a state ($sStateValue) which is not an allowed value"; $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states"; } @@ -4830,43 +4485,30 @@ abstract class MetaModel } // Lifecycle - check that the action handlers are defined - foreach(self::EnumStates($sClass) as $sStateCode => $aStateDef) - { - foreach(self::EnumTransitions($sClass, $sStateCode) as $sStimulusCode => $aTransitionDef) - { - foreach($aTransitionDef['actions'] as $actionHandler) - { - if (is_string($actionHandler)) - { - if (!method_exists($sClass, $actionHandler)) - { + foreach (self::EnumStates($sClass) as $sStateCode => $aStateDef) { + foreach (self::EnumTransitions($sClass, $sStateCode) as $sStimulusCode => $aTransitionDef) { + foreach ($aTransitionDef['actions'] as $actionHandler) { + if (is_string($actionHandler)) { + if (!method_exists($sClass, $actionHandler)) { $aErrors[$sClass][] = "Unknown function '$actionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'"; $aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $actionHandler(\$sStimulusCode){return true;}]"; } - } - else // if(is_array($actionHandler)) - { + } else { // if(is_array($actionHandler)) $sActionHandler = $actionHandler['verb']; - if (!method_exists($sClass, $sActionHandler)) - { + if (!method_exists($sClass, $sActionHandler)) { $aErrors[$sClass][] = "Unknown function '$sActionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'"; $aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $sActionHandler(...){return true;}]"; } } } } - if (array_key_exists('highlight', $aStateDef)) - { - if (!array_key_exists('code', $aStateDef['highlight'])) - { + if (array_key_exists('highlight', $aStateDef)) { + if (!array_key_exists('code', $aStateDef['highlight'])) { $aErrors[$sClass][] = "The 'code' element is missing for the 'highlight' property of state: '$sStateCode'."; $aSugFix[$sClass][] = "Add a 'code' entry specifying the value of the highlight code for this state."; - } - else - { + } else { $aScale = self::GetHighlightScale($sClass); - if (!array_key_exists($aStateDef['highlight']['code'], $aScale)) - { + if (!array_key_exists($aStateDef['highlight']['code'], $aScale)) { $aErrors[$sClass][] = "'{$aStateDef['highlight']['code']}' is not a valid value for the 'code' element in the 'highlight' property of state: '$sStateCode'."; $aSugFix[$sClass][] = "The possible highlight codes for this class are: ".implode(', ', array_keys($aScale))."."; } @@ -4876,24 +4518,18 @@ abstract class MetaModel } } - if ($bHasWritableAttribute) - { - if (!self::HasTable($sClass)) - { + if ($bHasWritableAttribute) { + if (!self::HasTable($sClass)) { $aErrors[$sClass][] = "No table has been defined for this class"; $aSugFix[$sClass][] = "Either define a table name or move the attributes elsewhere"; } } - // ZList // - foreach(self::EnumZLists() as $sListCode) - { - foreach(self::FlattenZList(self::GetZListItems($sClass, $sListCode)) as $sMyAttCode) - { - if (!self::IsValidAttCode($sClass, $sMyAttCode)) - { + foreach (self::EnumZLists() as $sListCode) { + foreach (self::FlattenZList(self::GetZListItems($sClass, $sListCode)) as $sMyAttCode) { + if (!self::IsValidAttCode($sClass, $sMyAttCode)) { $aErrors[$sClass][] = "Unknown attribute code '".$sMyAttCode."' from ZList '$sListCode'"; $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}"; } @@ -4902,30 +4538,23 @@ abstract class MetaModel // Check SQL columns uniqueness // - if (self::HasTable($sClass)) - { - $aTableColumns = array(); // array of column => attcode (the column is used by this attribute) + if (self::HasTable($sClass)) { + $aTableColumns = []; // array of column => attcode (the column is used by this attribute) $aTableColumns[self::DBGetKey($sClass)] = 'id'; // Check that SQL columns are declared only once // - foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) - { + foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) { // Skip this attribute if not originally defined in this class - if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) - { + if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) { continue; } - foreach($oAttDef->GetSQLColumns() as $sField => $sDBFieldType) - { - if (array_key_exists($sField, $aTableColumns)) - { + foreach ($oAttDef->GetSQLColumns() as $sField => $sDBFieldType) { + if (array_key_exists($sField, $aTableColumns)) { $aErrors[$sClass][] = "Column '$sField' declared for attribute $sAttCode, but already used for attribute ".$aTableColumns[$sField]; $aSugFix[$sClass][] = "Please find another name for the SQL column"; - } - else - { + } else { $aTableColumns[$sField] = $sAttCode; } } @@ -4933,30 +4562,25 @@ abstract class MetaModel } } // foreach class - if (count($aErrors) > 0) - { + if (count($aErrors) > 0) { echo "
"; echo "

Business model inconsistencies have been found

\n"; // #@# later -> this is the responsibility of the caller to format the output - foreach($aErrors as $sClass => $aMessages) - { + foreach ($aErrors as $sClass => $aMessages) { echo "

Wrong declaration for class $sClass

\n"; echo "
    \n"; $i = 0; - foreach($aMessages as $sMsg) - { + foreach ($aMessages as $sMsg) { echo "
  • $sMsg ({$aSugFix[$sClass][$i]})
  • \n"; $i++; } echo "
\n"; } - if ($bExitOnError) - { + if ($bExitOnError) { echo "

Aborting...

\n"; } echo "
\n"; - if ($bExitOnError) - { + if ($bExitOnError) { exit; } } @@ -4974,7 +4598,7 @@ abstract class MetaModel } // By design, some queries might be blank, we have to ignore them - $aCleanFixes = array(); + $aCleanFixes = []; foreach ($aSQLFixes as $sSQLFix) { if (!empty($sSQLFix)) { $aCleanFixes[] = $sSQLFix; @@ -4999,40 +4623,29 @@ abstract class MetaModel */ public static function DBExists($bMustBeComplete = true) { - if (!CMDBSource::IsDB(self::$m_sDBName)) - { + if (!CMDBSource::IsDB(self::$m_sDBName)) { return false; } CMDBSource::SelectDB(self::$m_sDBName); - $aFound = array(); - $aMissing = array(); - foreach(self::DBEnumTables() as $sTable => $aClasses) - { - if (CMDBSource::IsTable($sTable)) - { + $aFound = []; + $aMissing = []; + foreach (self::DBEnumTables() as $sTable => $aClasses) { + if (CMDBSource::IsTable($sTable)) { $aFound[] = $sTable; - } - else - { + } else { $aMissing[] = $sTable; } } - if (count($aFound) == 0) - { + if (count($aFound) == 0) { // no expected table has been found return false; - } - else - { - if (count($aMissing) == 0) - { + } else { + if (count($aMissing) == 0) { // the database is complete (still, could be some fields missing!) return true; - } - else - { + } else { // not all the tables, could be an older version return !$bMustBeComplete; } @@ -5047,30 +4660,23 @@ abstract class MetaModel { $bDropEntireDB = true; - if (!empty(self::$m_sTablePrefix)) - { - foreach(self::DBEnumTables() as $sTable) - { + if (!empty(self::$m_sTablePrefix)) { + foreach (self::DBEnumTables() as $sTable) { // perform a case-insensitive test because on Windows the table names become lowercase :-( - if (strtolower(substr($sTable, 0, strlen(self::$m_sTablePrefix))) == strtolower(self::$m_sTablePrefix)) - { + if (strtolower(substr($sTable, 0, strlen(self::$m_sTablePrefix))) == strtolower(self::$m_sTablePrefix)) { CMDBSource::DropTable($sTable); - } - else - { + } else { // There is at least one table which is out of the scope of the current application $bDropEntireDB = false; } } } - if ($bDropEntireDB) - { + if ($bDropEntireDB) { CMDBSource::DropDB(self::$m_sDBName); } } - /** * @param callable $aCallback * @@ -5083,8 +4689,7 @@ abstract class MetaModel { // Note: we have to check if the DB does exist, because we may share the DB // with other applications (in which case the DB does exist, not the tables with the given prefix) - if (!CMDBSource::IsDB(self::$m_sDBName)) - { + if (!CMDBSource::IsDB(self::$m_sDBName)) { CMDBSource::CreateDB(self::$m_sDBName); } self::DBCreateTables($aCallback); @@ -5101,13 +4706,11 @@ abstract class MetaModel [$aErrors, $aSugFix, $aCondensedQueries] = self::DBCheckFormat(); //$sSQL = implode('; ', $aCondensedQueries); Does not work - multiple queries not allowed - foreach($aCondensedQueries as $sQuery) - { + foreach ($aCondensedQueries as $sQuery) { $fStart = microtime(true); CMDBSource::CreateTable($sQuery); $fDuration = microtime(true) - $fStart; - if ($aCallback != null) - { + if ($aCallback != null) { call_user_func($aCallback, $sQuery, $fDuration); } } @@ -5122,14 +4725,10 @@ abstract class MetaModel { [$aErrors, $aSugFix] = self::DBCleanLegacyViews(); - foreach($aSugFix as $sClass => $aTarget) - { - foreach($aTarget as $aQueries) - { - foreach($aQueries as $sQuery) - { - if (!empty($sQuery)) - { + foreach ($aSugFix as $sClass => $aTarget) { + foreach ($aTarget as $aQueries) { + foreach ($aQueries as $sQuery) { + if (!empty($sQuery)) { // forces a refresh of cached information CMDBSource::CreateTable($sQuery); } @@ -5145,9 +4744,8 @@ abstract class MetaModel */ public static function DBDump() { - $aDataDump = array(); - foreach(self::DBEnumTables() as $sTable => $aClasses) - { + $aDataDump = []; + foreach (self::DBEnumTables() as $sTable => $aClasses) { $aRows = CMDBSource::DumpTable($sTable); $aDataDump[$sTable] = $aRows; } @@ -5163,16 +4761,12 @@ abstract class MetaModel { // Improvement: check the mySQL variable -> Read-only - if (utils::IsArchiveMode()) - { + if (utils::IsArchiveMode()) { return true; } - if (UserRights::IsAdministrator()) - { + if (UserRights::IsAdministrator()) { return (!self::DBHasAccess(ACCESS_ADMIN_WRITE)); - } - else - { + } else { return (!self::DBHasAccess(ACCESS_USER_WRITE)); } } @@ -5185,8 +4779,7 @@ abstract class MetaModel public static function DBHasAccess($iRequested = ACCESS_FULL) { $iMode = self::$m_oConfig->Get('access_mode'); - if (($iMode & $iRequested) == 0) - { + if (($iMode & $iRequested) == 0) { return false; } @@ -5205,12 +4798,10 @@ abstract class MetaModel protected static function MakeDictEntry($sKey, $sValueFromOldSystem, $sDefaultValue, &$bNotInDico) { $sValue = Dict::S($sKey, 'x-no-nothing'); - if ($sValue == 'x-no-nothing') - { + if ($sValue == 'x-no-nothing') { $bNotInDico = true; $sValue = $sValueFromOldSystem; - if (strlen($sValue) == 0) - { + if (strlen($sValue) == 0) { $sValue = $sDefaultValue; } } @@ -5244,7 +4835,7 @@ abstract class MetaModel // Note: I did not use EnumCategories(), because a given class maybe found in several categories // Need to invent the "module", to characterize the origins of a class if (strlen($sModules) == 0) { - $aModules = array('bizmodel', 'core/cmdb', 'gui', 'application', 'addon/userrights'); + $aModules = ['bizmodel', 'core/cmdb', 'gui', 'application', 'addon/userrights']; } else { $aModules = explode(', ', $sModules); } @@ -5273,54 +4864,39 @@ abstract class MetaModel $sClassRes .= "Dict::Add('EN US', 'English', 'English', array(\n"; $sClassRes .= self::MakeDictEntry("Class:$sClass", self::GetName_Obsolete($sClass), $sClass, $bNotInDico); $sClassRes .= self::MakeDictEntry("Class:$sClass+", self::GetClassDescription_Obsolete($sClass), '', $bNotInDico); - foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) - { + foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) { // Skip this attribute if not originally defined in this class - if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) - { + if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) { continue; } $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode", $oAttDef->GetLabel_Obsolete(), $sAttCode, $bNotInDico); $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode+", $oAttDef->GetDescription_Obsolete(), '', $bNotInDico); - if ($oAttDef instanceof AttributeEnum) - { - if (self::GetStateAttributeCode($sClass) == $sAttCode) - { - foreach(self::EnumStates($sClass) as $sStateCode => $aStateData) - { - if (array_key_exists('label', $aStateData)) - { + if ($oAttDef instanceof AttributeEnum) { + if (self::GetStateAttributeCode($sClass) == $sAttCode) { + foreach (self::EnumStates($sClass) as $sStateCode => $aStateData) { + if (array_key_exists('label', $aStateData)) { $sValue = $aStateData['label']; - } - else - { + } else { $sValue = MetaModel::GetStateLabel($sClass, $sStateCode); } - if (array_key_exists('description', $aStateData)) - { + if (array_key_exists('description', $aStateData)) { $sValuePlus = $aStateData['description']; - } - else - { + } else { $sValuePlus = MetaModel::GetStateDescription($sClass, $sStateCode); } $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode", $sValue, '', $bNotInDico); $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode+", $sValuePlus, '', $bNotInDico); } - } - else - { - foreach($oAttDef->GetAllowedValues() as $sKey => $value) - { + } else { + foreach ($oAttDef->GetAllowedValues() as $sKey => $value) { $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey", $value, '', $bNotInDico); $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey+", $value, '', $bNotInDico); } } } } - foreach(self::EnumStimuli($sClass) as $sStimulusCode => $oStimulus) - { + foreach (self::EnumStimuli($sClass) as $sStimulusCode => $oStimulus) { $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode", $oStimulus->GetLabel_Obsolete(), '', $bNotInDico); $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode+", $oStimulus->GetDescription_Obsolete(), '', $bNotInDico); } @@ -5328,8 +4904,7 @@ abstract class MetaModel $sClassRes .= "));\n"; $sClassRes .= "\n"; - if ($bNotInDico || ($sOutputFilter != 'NotInDictionary')) - { + if ($bNotInDico || ($sOutputFilter != 'NotInDictionary')) { $sRes .= $sClassRes; } } @@ -5338,7 +4913,6 @@ abstract class MetaModel return $sRes; } - /** * @return array * @throws \CoreException @@ -5346,29 +4920,27 @@ abstract class MetaModel */ public static function DBCheckFormat() { - $aErrors = array(); - $aSugFix = array(); + $aErrors = []; + $aSugFix = []; $sAlterDBMetaData = CMDBSource::DBCheckCharsetAndCollation(); // A new way of representing things to be done - quicker to execute ! - $aCreateTable = array(); // array of =>
- $aCreateTableItems = array(); // array of
=> array of - $aAlterTableMetaData = array(); - $aAlterTableItems = array(); // array of
=> - $aPostTableAlteration = array(); // array of
=> post alteration queries + $aCreateTable = []; // array of
=>
+ $aCreateTableItems = []; // array of
=> array of + $aAlterTableMetaData = []; + $aAlterTableItems = []; // array of
=> + $aPostTableAlteration = []; // array of
=> post alteration queries - foreach(self::GetClasses() as $sClass) - { - if (!self::HasTable($sClass)) - { + foreach (self::GetClasses() as $sClass) { + if (!self::HasTable($sClass)) { continue; } // Check that the table exists // $sTable = self::DBGetTable($sClass); - $aSugFix[$sClass]['*First'] = array(); + $aSugFix[$sClass]['*First'] = []; $aTableInfo = CMDBSource::GetTableInfo($sTable); @@ -5379,8 +4951,7 @@ abstract class MetaModel $sAutoIncrement = (self::IsAutoIncrementKey($sClass) ? "AUTO_INCREMENT" : ""); $sKeyFieldDefinition = "`$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY"; $aTableInfo['Indexes']['PRIMARY']['used'] = true; - if (!CMDBSource::IsTable($sTable)) - { + if (!CMDBSource::IsTable($sTable)) { $bTableToCreate = true; $aErrors[$sClass]['*'][] = "table '$sTable' could not be found in the DB"; $aSugFix[$sClass]['*'][] = "CREATE TABLE `$sTable` ($sKeyFieldDefinition) ENGINE = ".MYSQL_ENGINE." CHARACTER SET $sDbCharset COLLATE $sDbCollation"; @@ -5389,44 +4960,34 @@ abstract class MetaModel } // Check that the key field exists // - elseif (!CMDBSource::IsField($sTable, $sKeyField)) - { + elseif (!CMDBSource::IsField($sTable, $sKeyField)) { $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) could not be found"; $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` ADD $sKeyFieldDefinition"; - if (!$bTableToCreate) - { + if (!$bTableToCreate) { $aAlterTableItems[$sTable]['field'][$sKeyField] = "ADD $sKeyFieldDefinition"; } - } - else - { + } else { // Check the key field properties // - if (!CMDBSource::IsKey($sTable, $sKeyField)) - { + if (!CMDBSource::IsKey($sTable, $sKeyField)) { $aErrors[$sClass]['id'][] = "key '$sKeyField' is not a key for table '$sTable'"; $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable`, DROP PRIMARY KEY, ADD PRIMARY key(`$sKeyField`)"; - if (!$bTableToCreate) - { + if (!$bTableToCreate) { $aAlterTableItems[$sTable]['field'][$sKeyField] = "CHANGE `$sKeyField` $sKeyFieldDefinition"; } } - if (self::IsAutoIncrementKey($sClass) && !CMDBSource::IsAutoIncrement($sTable, $sKeyField)) - { + if (self::IsAutoIncrementKey($sClass) && !CMDBSource::IsAutoIncrement($sTable, $sKeyField)) { $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) is not automatically incremented"; $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` CHANGE `$sKeyField` $sKeyFieldDefinition"; - if (!$bTableToCreate) - { + if (!$bTableToCreate) { $aAlterTableItems[$sTable]['field'][$sKeyField] = "CHANGE `$sKeyField` $sKeyFieldDefinition"; } } } - if (!$bTableToCreate) - { + if (!$bTableToCreate) { $sAlterTableMetaDataQuery = CMDBSource::DBCheckTableCharsetAndCollation($sTable); - if (!empty($sAlterTableMetaDataQuery)) - { + if (!empty($sAlterTableMetaDataQuery)) { $aAlterTableMetaData[$sTable] = $sAlterTableMetaDataQuery; } } @@ -5435,135 +4996,101 @@ abstract class MetaModel // $aTableInfo['Fields'][$sKeyField]['used'] = true; $aFriendlynameAttcodes = self::GetFriendlyNameAttributeCodeList($sClass); - foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) - { - if (!$oAttDef->CopyOnAllTables()) - { + foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) { + if (!$oAttDef->CopyOnAllTables()) { // Skip this attribute if not originally defined in this class - if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) - { + if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) { continue; } } - foreach($oAttDef->GetSQLColumns(true) as $sField => $sDBFieldSpec) - { + foreach ($oAttDef->GetSQLColumns(true) as $sField => $sDBFieldSpec) { // Keep track of columns used by iTop $aTableInfo['Fields'][$sField]['used'] = true; $bIndexNeeded = $oAttDef->RequiresIndex(); $bFullTextIndexNeeded = false; - if (!$bIndexNeeded) - { + if (!$bIndexNeeded) { // Add an index on the columns of the friendlyname - if (in_array($sField, $aFriendlynameAttcodes)) - { + if (in_array($sField, $aFriendlynameAttcodes)) { $bIndexNeeded = true; } - } - else - { - if ($oAttDef->RequiresFullTextIndex()) - { + } else { + if ($oAttDef->RequiresFullTextIndex()) { $bFullTextIndexNeeded = true; } } $sFieldDefinition = "`$sField` $sDBFieldSpec"; - if (!CMDBSource::IsField($sTable, $sField)) - { + if (!CMDBSource::IsField($sTable, $sField)) { $aErrors[$sClass][$sAttCode][] = "field '$sField' could not be found in table '$sTable'"; $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD $sFieldDefinition"; - if ($bTableToCreate) - { + if ($bTableToCreate) { $aCreateTableItems[$sTable][$sField] = $sFieldDefinition; - } - else - { + } else { $aAlterTableItems[$sTable]['field'][$sField] = "ADD $sFieldDefinition"; $aAdditionalRequests = self::GetAdditionalRequestAfterAlter($sClass, $sTable, $sField); - if (!empty($aAdditionalRequests)) - { - foreach ($aAdditionalRequests as $sAdditionalRequest) - { + if (!empty($aAdditionalRequests)) { + foreach ($aAdditionalRequests as $sAdditionalRequest) { $aPostTableAlteration[$sTable][] = $sAdditionalRequest; } } } - if ($bIndexNeeded) - { + if ($bIndexNeeded) { $aTableInfo['Indexes'][$sField]['used'] = true; $sIndexName = $sField; $sColumns = '`'.$sField.'`'; - if ($bFullTextIndexNeeded) - { + if ($bFullTextIndexNeeded) { $sIndexType = 'FULLTEXT INDEX'; - } - else - { + } else { $sIndexType = 'INDEX'; - $aColumns = array($sField); + $aColumns = [$sField]; $aLength = self::DBGetIndexesLength($sClass, $aColumns, $aTableInfo); - if (!is_null($aLength[0])) - { + if (!is_null($aLength[0])) { $sColumns .= ' ('.$aLength[0].')'; } } $sSugFix = "ALTER TABLE `$sTable` ADD $sIndexType `$sIndexName` ($sColumns)"; $aSugFix[$sClass][$sAttCode][] = $sSugFix; - if ($bFullTextIndexNeeded) - { + if ($bFullTextIndexNeeded) { // MySQL does not support multi fulltext index creation in a single query (mysql_errno = 1795) $aPostTableAlteration[$sTable][] = $sSugFix; - } - elseif ($bTableToCreate) - { + } elseif ($bTableToCreate) { $aCreateTableItems[$sTable][] = "$sIndexType `$sIndexName` ($sColumns)"; - } - else - { + } else { $aAlterTableItems[$sTable]['index'][] = "ADD $sIndexType `$sIndexName` ($sColumns)"; } } - } - else - { + } else { // Create indexes (external keys only... so far) // (drop before change, add after change) $sSugFixAfterChange = ''; $sAlterTableItemsAfterChange = ''; - if ($bIndexNeeded) - { + if ($bIndexNeeded) { $aTableInfo['Indexes'][$sField]['used'] = true; - if ($bFullTextIndexNeeded) - { + if ($bFullTextIndexNeeded) { $sIndexType = 'FULLTEXT INDEX'; $aColumns = null; $aLength = null; - } - else - { + } else { $sIndexType = 'INDEX'; - $aColumns = array($sField); + $aColumns = [$sField]; $aLength = self::DBGetIndexesLength($sClass, $aColumns, $aTableInfo); } - if (!CMDBSource::HasIndex($sTable, $sField, $aColumns, $aLength)) - { + if (!CMDBSource::HasIndex($sTable, $sField, $aColumns, $aLength)) { $sIndexName = $sField; $sColumns = '`'.$sField.'`'; - if (isset($aLength[0])) - { + if (isset($aLength[0])) { $sColumns .= ' ('.$aLength[0].')'; } $aErrors[$sClass][$sAttCode][] = "Foreign key '$sField' in table '$sTable' should have an index"; - if (CMDBSource::HasIndex($sTable, $sField)) - { + if (CMDBSource::HasIndex($sTable, $sField)) { $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` DROP INDEX `$sIndexName`"; $aAlterTableItems[$sTable]['index'][] = "DROP INDEX `$sIndexName`"; } @@ -5575,8 +5102,7 @@ abstract class MetaModel // The field already exists, does it have the relevant properties? // $sActualFieldSpec = CMDBSource::GetFieldSpec($sTable, $sField); - if (!CMDBSource::IsSameFieldTypes($sDBFieldSpec, $sActualFieldSpec)) - { + if (!CMDBSource::IsSameFieldTypes($sDBFieldSpec, $sActualFieldSpec)) { $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' has a wrong type: found $sActualFieldSpec while expecting $sDBFieldSpec"; $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` $sFieldDefinition"; $aAlterTableItems[$sTable]['field'][$sField] = "CHANGE `$sField` $sFieldDefinition"; @@ -5584,16 +5110,12 @@ abstract class MetaModel // Create indexes (external keys only... so far) // - if (!empty($sSugFixAfterChange)) - { + if (!empty($sSugFixAfterChange)) { $aSugFix[$sClass][$sAttCode][] = $sSugFixAfterChange; - if ($bFullTextIndexNeeded) - { + if ($bFullTextIndexNeeded) { // MySQL does not support multi fulltext index creation in a single query (mysql_errno = 1795) $aPostTableAlteration[$sTable][] = $sSugFixAfterChange; - } - else - { + } else { $aAlterTableItems[$sTable]['index'][] = $sAlterTableItemsAfterChange; } } @@ -5602,60 +5124,45 @@ abstract class MetaModel } // Check indexes - foreach(self::DBGetIndexes($sClass) as $aColumns) - { + foreach (self::DBGetIndexes($sClass) as $aColumns) { $sIndexId = implode('_', $aColumns); - if (isset($aTableInfo['Indexes'][$sIndexId]['used']) && $aTableInfo['Indexes'][$sIndexId]['used']) - { + if (isset($aTableInfo['Indexes'][$sIndexId]['used']) && $aTableInfo['Indexes'][$sIndexId]['used']) { continue; } $aLength = self::DBGetIndexesLength($sClass, $aColumns, $aTableInfo); $aTableInfo['Indexes'][$sIndexId]['used'] = true; - if (!CMDBSource::HasIndex($sTable, $sIndexId, $aColumns, $aLength)) - { + if (!CMDBSource::HasIndex($sTable, $sIndexId, $aColumns, $aLength)) { $sColumns = ''; - for ($i = 0; $i < count($aColumns); $i++) - { - if (!empty($sColumns)) - { + for ($i = 0; $i < count($aColumns); $i++) { + if (!empty($sColumns)) { $sColumns .= ', '; } $sColumns .= '`'.$aColumns[$i].'`'; - if (!is_null($aLength[$i])) - { + if (!is_null($aLength[$i])) { $sColumns .= ' ('.$aLength[$i].')'; } } - if (CMDBSource::HasIndex($sTable, $sIndexId)) - { + if (CMDBSource::HasIndex($sTable, $sIndexId)) { $aErrors[$sClass]['*'][] = "Wrong index '$sIndexId' ($sColumns) in table '$sTable'"; $aSugFix[$sClass]['*First'][] = "ALTER TABLE `$sTable` DROP INDEX `$sIndexId`"; $aSugFix[$sClass]['*'][] = "ALTER TABLE `$sTable` ADD INDEX `$sIndexId` ($sColumns)"; - } - else - { + } else { $aErrors[$sClass]['*'][] = "Missing index '$sIndexId' ($sColumns) in table '$sTable'"; $aSugFix[$sClass]['*'][] = "ALTER TABLE `$sTable` ADD INDEX `$sIndexId` ($sColumns)"; } - if ($bTableToCreate) - { + if ($bTableToCreate) { $aCreateTableItems[$sTable][] = "INDEX `$sIndexId` ($sColumns)"; - } - else - { - if (CMDBSource::HasIndex($sTable, $sIndexId)) - { + } else { + if (CMDBSource::HasIndex($sTable, $sIndexId)) { // Add the drop before CHARSET alteration - if (!isset($aAlterTableItems[$sTable])) - { - $aAlterTableItems[$sTable] = array(); + if (!isset($aAlterTableItems[$sTable])) { + $aAlterTableItems[$sTable] = []; } - if (isset($aAlterTableItems[$sTable]['index'])) - { + if (isset($aAlterTableItems[$sTable]['index'])) { array_unshift($aAlterTableItems[$sTable]['index'], "DROP INDEX `$sIndexId`"); } } @@ -5666,13 +5173,10 @@ abstract class MetaModel // Find out unused columns // - foreach($aTableInfo['Fields'] as $sField => $aFieldData) - { - if (!isset($aFieldData['used']) || !$aFieldData['used']) - { + foreach ($aTableInfo['Fields'] as $sField => $aFieldData) { + if (!isset($aFieldData['used']) || !$aFieldData['used']) { $aErrors[$sClass]['*'][] = "Column '$sField' in table '$sTable' is not used"; - if (!CMDBSource::IsNullAllowed($sTable, $sField)) - { + if (!CMDBSource::IsNullAllowed($sTable, $sField)) { // Allow null values so that new record can be inserted // without specifying the value of this unknown column $sFieldDefinition = "`$sField` ".CMDBSource::GetFieldType($sTable, $sField).' NULL'; @@ -5685,86 +5189,71 @@ abstract class MetaModel // Find out unused indexes // - foreach($aTableInfo['Indexes'] as $sIndexId => $aIndexData) - { - if (!isset($aIndexData['used']) || !$aIndexData['used']) - { + foreach ($aTableInfo['Indexes'] as $sIndexId => $aIndexData) { + if (!isset($aIndexData['used']) || !$aIndexData['used']) { $aErrors[$sClass]['*'][] = "Index '$sIndexId' in table '$sTable' is not used and will be removed"; $aSugFix[$sClass]['*First'][] = "ALTER TABLE `$sTable` DROP INDEX `$sIndexId`"; // Add the drop before CHARSET alteration - if (!isset($aAlterTableItems[$sTable])) - { - $aAlterTableItems[$sTable] = array(); + if (!isset($aAlterTableItems[$sTable])) { + $aAlterTableItems[$sTable] = []; } - if (isset($aAlterTableItems[$sTable]['index'])) - { + if (isset($aAlterTableItems[$sTable]['index'])) { array_unshift($aAlterTableItems[$sTable]['index'], "DROP INDEX `$sIndexId`"); } } } - if (empty($aSugFix[$sClass]['*First'])) unset($aSugFix[$sClass]['*First']); + if (empty($aSugFix[$sClass]['*First'])) { + unset($aSugFix[$sClass]['*First']); + } } - $aCondensedQueries = array(); - if (!empty($sAlterDBMetaData)) - { + $aCondensedQueries = []; + if (!empty($sAlterDBMetaData)) { $aCondensedQueries[] = $sAlterDBMetaData; } - foreach($aCreateTable as $sTable => $sTableOptions) - { + foreach ($aCreateTable as $sTable => $sTableOptions) { $sTableItems = implode(', ', $aCreateTableItems[$sTable]); $aCondensedQueries[] = "CREATE TABLE `$sTable` ($sTableItems) $sTableOptions"; // Add request right after the CREATE TABLE - if (isset($aPostTableAlteration[$sTable])) - { - foreach ($aPostTableAlteration[$sTable] as $sQuery) - { + if (isset($aPostTableAlteration[$sTable])) { + foreach ($aPostTableAlteration[$sTable] as $sQuery) { $aCondensedQueries[] = $sQuery; } unset($aPostTableAlteration[$sTable]); } } - foreach ($aAlterTableMetaData as $sTableAlterQuery) - { + foreach ($aAlterTableMetaData as $sTableAlterQuery) { $aCondensedQueries[] = $sTableAlterQuery; } - foreach ($aAlterTableItems as $sTable => $aChangeList) - { - if (isset($aAlterTableItems[$sTable]['field'])) - { + foreach ($aAlterTableItems as $sTable => $aChangeList) { + if (isset($aAlterTableItems[$sTable]['field'])) { $sChangeList = implode(', ', $aChangeList['field']); $aCondensedQueries[] = "ALTER TABLE `$sTable` $sChangeList"; } - if (isset($aAlterTableItems[$sTable]['index'])) - { + if (isset($aAlterTableItems[$sTable]['index'])) { $sChangeList = implode(', ', $aChangeList['index']); $aCondensedQueries[] = "ALTER TABLE `$sTable` $sChangeList"; } // Add request right after the ALTER TABLE - if (isset($aPostTableAlteration[$sTable])) - { - foreach ($aPostTableAlteration[$sTable] as $sQuery) - { + if (isset($aPostTableAlteration[$sTable])) { + foreach ($aPostTableAlteration[$sTable] as $sQuery) { $aCondensedQueries[] = $sQuery; } unset($aPostTableAlteration[$sTable]); - } + } } // Add alterations not yet managed - foreach ($aPostTableAlteration as $aQueries) - { - foreach ($aQueries as $sQuery) - { + foreach ($aPostTableAlteration as $aQueries) { + foreach ($aQueries as $sQuery) { $aCondensedQueries[] = $sQuery; } } - return array($aErrors, $aSugFix, $aCondensedQueries); + return [$aErrors, $aSugFix, $aCondensedQueries]; } - /** * @internal * @deprecated will be remove when 2.7 will not be supported anymore @@ -5781,11 +5270,9 @@ abstract class MetaModel // Reporting views (must be created after any other table) // - foreach(self::GetClasses() as $sClass) - { + foreach (self::GetClasses() as $sClass) { $sView = self::DBGetView($sClass); - if (CMDBSource::IsTable($sView)) - { + if (CMDBSource::IsTable($sView)) { // Remove deprecated views $aErrors[$sClass]['*'][] = "Remove view '$sView' (deprecated, consider installing combodo-views if needed)"; $aSugFix[$sClass]['*'][] = "DROP VIEW `$sView`"; @@ -5812,31 +5299,24 @@ abstract class MetaModel $sTable = self::DBGetTable($sClass); $sKeyField = self::DBGetKey($sClass); - if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0) - { + if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0) { $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')"; } $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id"); - if (count($aWrongRecords) == 0) - { + if (count($aWrongRecords) == 0) { return; } - if (!array_key_exists($sRootClass, $aErrorsAndFixes)) - { - $aErrorsAndFixes[$sRootClass] = array(); + if (!array_key_exists($sRootClass, $aErrorsAndFixes)) { + $aErrorsAndFixes[$sRootClass] = []; } - if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) - { - $aErrorsAndFixes[$sRootClass][$sTable] = array(); + if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) { + $aErrorsAndFixes[$sRootClass][$sTable] = []; } - foreach($aWrongRecords as $iRecordId) - { - if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable])) - { - switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action']) - { + foreach ($aWrongRecords as $iRecordId) { + if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable])) { + switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action']) { case 'Delete': // Already planned for a deletion // Let's concatenate the errors description together @@ -5847,48 +5327,46 @@ abstract class MetaModel // Let's plan a deletion break; } - } - else - { + } else { $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc; } - if (!$bProcessingFriends) - { - if (!array_key_exists($sTable, $aPlannedDel) || !in_array($iRecordId, $aPlannedDel[$sTable])) - { + if (!$bProcessingFriends) { + if (!array_key_exists($sTable, $aPlannedDel) || !in_array($iRecordId, $aPlannedDel[$sTable])) { // Something new to be deleted... $iNewDelCount++; } } $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Delete'; - $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array(); + $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = []; $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123; $aPlannedDel[$sTable][] = $iRecordId; } // Now make sure that we would delete the records of the other tables for that class // - if (!$bProcessingFriends) - { + if (!$bProcessingFriends) { $sDeleteKeys = "'".implode("', '", $aWrongRecords)."'"; - foreach(self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_ALL) as $sFriendClass) - { + foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_ALL) as $sFriendClass) { $sFriendTable = self::DBGetTable($sFriendClass); $sFriendKey = self::DBGetKey($sFriendClass); // skip the current table - if ($sFriendTable == $sTable) - { + if ($sFriendTable == $sTable) { continue; } $sFindRelatedRec = "SELECT DISTINCT maintable.`$sFriendKey` AS id FROM `$sFriendTable` AS maintable WHERE maintable.`$sFriendKey` IN ($sDeleteKeys)"; - self::DBCheckIntegrity_Check2Delete($sFindRelatedRec, - "Cascading deletion of record in friend table `$sTable`", $sFriendClass, $aErrorsAndFixes, - $iNewDelCount, $aPlannedDel, - true); + self::DBCheckIntegrity_Check2Delete( + $sFindRelatedRec, + "Cascading deletion of record in friend table `$sTable`", + $sFriendClass, + $aErrorsAndFixes, + $iNewDelCount, + $aPlannedDel, + true + ); } } } @@ -5911,63 +5389,51 @@ abstract class MetaModel $sTable = self::DBGetTable($sClass); $sKeyField = self::DBGetKey($sClass); - if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0) - { + if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0) { $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')"; } $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id"); - if (count($aWrongRecords) == 0) - { + if (count($aWrongRecords) == 0) { return; } - if (!array_key_exists($sRootClass, $aErrorsAndFixes)) - { - $aErrorsAndFixes[$sRootClass] = array(); + if (!array_key_exists($sRootClass, $aErrorsAndFixes)) { + $aErrorsAndFixes[$sRootClass] = []; } - if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) - { - $aErrorsAndFixes[$sRootClass][$sTable] = array(); + if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) { + $aErrorsAndFixes[$sRootClass][$sTable] = []; } - foreach($aWrongRecords as $iRecordId) - { - if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable])) - { + foreach ($aWrongRecords as $iRecordId) { + if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable])) { $sAction = $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action']; //if ($sAction == 'Delete') //{ - // No need to update, the record will be deleted! + // No need to update, the record will be deleted! //} - if ($sAction == 'Update') - { + if ($sAction == 'Update') { // Already planned for an update // Add this new update spec to the list $bFoundSameSpec = false; - foreach ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] as $aUpdateSpec) - { - if (($sColumn == $aUpdateSpec['column']) && ($sNewValue == $aUpdateSpec['newvalue'])) - { + foreach ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] as $aUpdateSpec) { + if (($sColumn == $aUpdateSpec['column']) && ($sNewValue == $aUpdateSpec['newvalue'])) { $bFoundSameSpec = true; } } - if (!$bFoundSameSpec) - { - $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'][] = (array( + if (!$bFoundSameSpec) { + $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'][] = ([ 'column' => $sColumn, - 'newvalue' => $sNewValue - )); + 'newvalue' => $sNewValue, + ]); $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc; } } - } - else - { + } else { $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc; $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Update'; - $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array(array('column' => $sColumn, 'newvalue' => $sNewValue)); + $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = [['column' => $sColumn, 'newvalue' => $sNewValue]]; $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123; } @@ -5984,20 +5450,16 @@ abstract class MetaModel */ public static function DBCheckIntegrity_SinglePass(&$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel) { - foreach(self::GetClasses() as $sClass) - { - if (!self::HasTable($sClass)) - { + foreach (self::GetClasses() as $sClass) { + if (!self::HasTable($sClass)) { continue; } $sRootClass = self::GetRootClass($sClass); $sTable = self::DBGetTable($sClass); $sKeyField = self::DBGetKey($sClass); - if (!self::IsStandaloneClass($sClass)) - { - if (self::IsRootClass($sClass)) - { + if (!self::IsStandaloneClass($sClass)) { + if (self::IsRootClass($sClass)) { // Check that the final class field contains the name of a class which inherited from the current class // $sFinalClassField = self::DBGetClassField($sClass); @@ -6007,9 +5469,7 @@ abstract class MetaModel $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE `$sFinalClassField` NOT IN ($sAllowedValues)"; self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "final class (field `$sFinalClassField`) is wrong (expected a value in {".$sAllowedValues."})", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel); - } - else - { + } else { $sRootTable = self::DBGetTable($sRootClass); $sRootKey = self::DBGetKey($sRootClass); $sFinalClassField = self::DBGetClassField($sRootClass); @@ -6031,16 +5491,13 @@ abstract class MetaModel } } - foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) - { + foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) { // Skip this attribute if not defined in this table - if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) - { + if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) { continue; } - if ($oAttDef->IsExternalKey()) - { + if ($oAttDef->IsExternalKey()) { // Check that any external field is pointing to an existing object // $sRemoteClass = $oAttDef->GetTargetClass(); @@ -6054,46 +5511,35 @@ abstract class MetaModel $sSelBase = "SELECT DISTINCT maintable.`$sKeyField` AS id, maintable.`$sExtKeyField` AS extkey FROM `$sTable` AS maintable LEFT JOIN `$sRemoteTable` ON maintable.`$sExtKeyField` = `$sRemoteTable`.`$sRemoteKey`"; $sSelWrongRecs = $sSelBase." WHERE `$sRemoteTable`.`$sRemoteKey` IS NULL"; - if ($oAttDef->IsNullAllowed()) - { + if ($oAttDef->IsNullAllowed()) { // Exclude the records pointing to 0/null from the errors $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL"; $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0"; self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '$sAttCode') non existing objects", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel); - } - else - { + } else { self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '$sAttCode') non existing objects", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel); } // Do almost the same, taking into account the records planned for deletion - if (array_key_exists($sRemoteTable, $aPlannedDel) && count($aPlannedDel[$sRemoteTable]) > 0) - { + if (array_key_exists($sRemoteTable, $aPlannedDel) && count($aPlannedDel[$sRemoteTable]) > 0) { // This could be done by the mean of a 'OR ... IN (aIgnoreRecords) // but in that case you won't be able to track the root cause (cascading) $sSelWrongRecs = $sSelBase." WHERE maintable.`$sExtKeyField` IN ('".implode("', '", $aPlannedDel[$sRemoteTable])."')"; - if ($oAttDef->IsNullAllowed()) - { + if ($oAttDef->IsNullAllowed()) { // Exclude the records pointing to 0/null from the errors $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL"; $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0"; self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '$sAttCode') a record planned for deletion", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel); - } - else - { + } else { self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '$sAttCode') a record planned for deletion", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel); } } - } - else - { - if ($oAttDef->IsBasedOnDBColumns()) - { + } else { + if ($oAttDef->IsBasedOnDBColumns()) { // Check that the values fit the allowed values // $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode); - if (!is_null($aAllowedValues) && count($aAllowedValues) > 0) - { + if (!is_null($aAllowedValues) && count($aAllowedValues) > 0) { $sExpectedValues = implode(",", CMDBSource::Quote(array_keys($aAllowedValues), true)); $aCols = $oAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc()) @@ -6120,11 +5566,11 @@ abstract class MetaModel { // Records in error, and action to be taken: delete or update // by RootClass/Table/Record - $aErrorsAndFixes = array(); + $aErrorsAndFixes = []; // Records to be ignored in the current/next pass // by Table = array of RecordId - $aPlannedDel = array(); + $aPlannedDel = []; // Count of errors in the next pass: no error means that we can leave... $iErrorCount = 0; @@ -6132,8 +5578,7 @@ abstract class MetaModel $iLoopCount = 0; $iNewDelCount = 1; // startup... - while ($iNewDelCount > 0) - { + while ($iNewDelCount > 0) { $iNewDelCount = 0; self::DBCheckIntegrity_SinglePass($aErrorsAndFixes, $iNewDelCount, $aPlannedDel); $iErrorCount += $iNewDelCount; @@ -6142,20 +5587,17 @@ abstract class MetaModel // $iMaxDel = 1000; $iPlannedDel = 0; - foreach($aPlannedDel as $sTable => $aPlannedDelOnTable) - { + foreach ($aPlannedDel as $sTable => $aPlannedDelOnTable) { $iPlannedDel += count($aPlannedDelOnTable); } - if ($iPlannedDel > $iMaxDel) - { + if ($iPlannedDel > $iMaxDel) { throw new CoreWarning("DB Integrity Check safety net - Exceeding the limit of $iMaxDel planned record deletion"); } // Safety net #2 - limit the iterations // $iLoopCount++; $iMaxLoops = 10; - if ($iLoopCount > $iMaxLoops) - { + if ($iLoopCount > $iMaxLoops) { throw new CoreWarning("DB Integrity Check safety net - Reached the limit of $iMaxLoops loops"); } } @@ -6163,29 +5605,24 @@ abstract class MetaModel // Display the results // $iIssueCount = 0; - $aFixesDelete = array(); - $aFixesUpdate = array(); + $aFixesDelete = []; + $aFixesUpdate = []; - foreach($aErrorsAndFixes as $sRootClass => $aTables) - { - foreach($aTables as $sTable => $aRecords) - { - foreach($aRecords as $iRecord => $aError) - { + foreach ($aErrorsAndFixes as $sRootClass => $aTables) { + foreach ($aTables as $sTable => $aRecords) { + foreach ($aRecords as $iRecord => $aError) { $sAction = $aError['Action']; $sReason = $aError['Reason']; - switch ($sAction) - { + switch ($sAction) { case 'Delete': $sActionDetails = ""; $aFixesDelete[$sTable][] = $iRecord; break; case 'Update': - $aUpdateDesc = array(); - foreach($aError['Action_Details'] as $aUpdateSpec) - { + $aUpdateDesc = []; + foreach ($aError['Action_Details'] as $aUpdateSpec) { $aUpdateDesc[] = $aUpdateSpec['column']." -> ".$aUpdateSpec['newvalue']; $aFixesUpdate[$sTable][$aUpdateSpec['column']][$aUpdateSpec['newvalue']][] = $iRecord; } @@ -6202,17 +5639,14 @@ abstract class MetaModel } } - if ($iIssueCount > 0) - { + if ($iIssueCount > 0) { // Build the queries to fix in the database // // First step, be able to get class data out of the table name // Could be optimized, because we've made the job earlier... but few benefits, so... - $aTable2ClassProp = array(); - foreach(self::GetClasses() as $sClass) - { - if (!self::HasTable($sClass)) - { + $aTable2ClassProp = []; + foreach (self::GetClasses() as $sClass) { + if (!self::HasTable($sClass)) { continue; } @@ -6220,18 +5654,15 @@ abstract class MetaModel $sTable = self::DBGetTable($sClass); $sKeyField = self::DBGetKey($sClass); - $aErrorsAndFixes[$sRootClass][$sTable] = array(); - $aTable2ClassProp[$sTable] = array('rootclass' => $sRootClass, 'class' => $sClass, 'keyfield' => $sKeyField); + $aErrorsAndFixes[$sRootClass][$sTable] = []; + $aTable2ClassProp[$sTable] = ['rootclass' => $sRootClass, 'class' => $sClass, 'keyfield' => $sKeyField]; } // Second step, build a flat list of SQL queries - $aSQLFixes = array(); + $aSQLFixes = []; $iPlannedUpdate = 0; - foreach($aFixesUpdate as $sTable => $aColumns) - { - foreach($aColumns as $sColumn => $aNewValues) - { - foreach($aNewValues as $sNewValue => $aRecords) - { + foreach ($aFixesUpdate as $sTable => $aColumns) { + foreach ($aColumns as $sColumn => $aNewValues) { + foreach ($aNewValues as $sNewValue => $aRecords) { $iPlannedUpdate += count($aRecords); $sWrongRecords = "'".implode("', '", $aRecords)."'"; $sKeyField = $aTable2ClassProp[$sTable]['keyfield']; @@ -6241,8 +5672,7 @@ abstract class MetaModel } } $iPlannedDel = 0; - foreach($aFixesDelete as $sTable => $aRecords) - { + foreach ($aFixesDelete as $sTable => $aRecords) { $iPlannedDel += count($aRecords); $sWrongRecords = "'".implode("', '", $aRecords)."'"; $sKeyField = $aTable2ClassProp[$sTable]['keyfield']; @@ -6256,8 +5686,7 @@ abstract class MetaModel echo "

Database corruption error(s): $iErrorCount issues have been encountered. $iPlannedDel records will be deleted, $iPlannedUpdate records will be updated:

\n"; // #@# later -> this is the responsibility of the caller to format the output echo "
    \n"; - foreach($aIssues as $sIssueDesc) - { + foreach ($aIssues as $sIssueDesc) { echo "
  • $sIssueDesc
  • \n"; } echo "
\n"; @@ -6316,8 +5745,7 @@ abstract class MetaModel } ExpressionCache::Warmup(); - } - finally { + } finally { // Event service must be initialized after the MetaModel startup, otherwise it cannot discover classes implementing the iEventServiceSetup interface EventService::InitService(); EventService::FireEvent(new EventData(ApplicationEvents::APPLICATION_EVENT_METAMODEL_STARTED)); @@ -6344,8 +5772,7 @@ abstract class MetaModel utils::SetConfig($oConfiguration); // Set log ASAP - if (self::$m_oConfig->GetLogGlobal()) - { + if (self::$m_oConfig->GetLogGlobal()) { if (self::$m_oConfig->GetLogIssue()) { self::$m_bLogIssue = true; IssueLog::Enable(APPROOT.'log/error.log'); @@ -6357,9 +5784,7 @@ abstract class MetaModel DeadLockLog::Enable(); DeprecatedCallsLog::Enable(); ExceptionLog::Enable(); - } - else - { + } else { self::$m_bLogIssue = false; self::$m_bLogNotification = false; self::$m_bLogWebService = false; @@ -6367,9 +5792,9 @@ abstract class MetaModel ExecutionKPI::EnableDuration(self::$m_oConfig->Get('log_kpi_duration')); ExecutionKPI::EnableMemory(self::$m_oConfig->Get('log_kpi_memory')); - ExecutionKPI::SetAllowedUser(self::$m_oConfig->Get('log_kpi_user_id')); - ExecutionKPI::SetGenerateLegacyReport(self::$m_oConfig->Get('log_kpi_generate_legacy_report')); - ExecutionKPI::SetSlowQueries(self::$m_oConfig->Get('log_kpi_slow_queries')); + ExecutionKPI::SetAllowedUser(self::$m_oConfig->Get('log_kpi_user_id')); + ExecutionKPI::SetGenerateLegacyReport(self::$m_oConfig->Get('log_kpi_generate_legacy_report')); + ExecutionKPI::SetSlowQueries(self::$m_oConfig->Get('log_kpi_slow_queries')); self::$m_bSkipCheckToWrite = self::$m_oConfig->Get('skip_check_to_write'); self::$m_bSkipCheckExtKeys = self::$m_oConfig->Get('skip_check_ext_keys'); @@ -6387,8 +5812,7 @@ abstract class MetaModel // Note: load the dictionary as soon as possible, because it might be // needed when some error occur $sAppIdentity = 'itop-'.MetaModel::GetEnvironmentId(); - if (self::$m_bUseAPCCache) - { + if (self::$m_bUseAPCCache) { Dict::EnableCache($sAppIdentity); } require_once(APPROOT.'env-'.self::$m_sEnvironment.'/dictionaries/languages.php'); @@ -6447,8 +5871,7 @@ abstract class MetaModel $oKPI->ComputeAndReport('Metamodel APC (fetch + read)'); } - if (count(self::$m_aAttribDefs) == 0) - { + if (count(self::$m_aAttribDefs) == 0) { // The includes have been included, let's browse the existing classes and // develop some data based on the proposed model $oKPI = new ExecutionKPI(); @@ -6456,11 +5879,10 @@ abstract class MetaModel self::InitClasses($sTablePrefix); $oKPI->ComputeAndReport('Initialization of Data model structures'); - if (self::$m_bUseAPCCache) - { + if (self::$m_bUseAPCCache) { $oKPI = new ExecutionKPI(); - $aCache = array(); + $aCache = []; $aCache['m_aExtensionClassNames'] = self::$m_aExtensionClassNames; $aCache['m_Category2Class'] = self::$m_Category2Class; $aCache['m_aRootClasses'] = self::$m_aRootClasses; // array of "classname" => "rootclass" @@ -6490,7 +5912,7 @@ abstract class MetaModel CMDBSource::InitFromConfig(self::$m_oConfig); // Later when timezone implementation is correctly done: CMDBSource::SetTimezone($sDBTimezone); - ExecutionKPI::InitStats(); + ExecutionKPI::InitStats(); } /** @@ -6515,8 +5937,7 @@ abstract class MetaModel public static function GetModuleParameter($sModule, $sProperty, $defaultvalue = null) { $value = $defaultvalue; - if (!self::$m_aModulesParameters[$sModule] == null) - { + if (!self::$m_aModulesParameters[$sModule] == null) { $value = self::$m_aModulesParameters[$sModule]->Get($sProperty, $defaultvalue); } return $value; @@ -6559,8 +5980,8 @@ abstract class MetaModel return md5(APPROOT).'-'.self::$m_sEnvironment; } - /** @var array */ - protected static $m_aExtensionClassNames = []; + /** @var array */ + protected static $m_aExtensionClassNames = []; /** * @param string $sToInclude @@ -6572,42 +5993,29 @@ abstract class MetaModel { $sFirstChar = substr($sToInclude, 0, 1); $sSecondChar = substr($sToInclude, 1, 1); - if (($sFirstChar != '/') && ($sFirstChar != '\\') && ($sSecondChar != ':')) - { + if (($sFirstChar != '/') && ($sFirstChar != '\\') && ($sSecondChar != ':')) { // It is a relative path, prepend APPROOT - if (substr($sToInclude, 0, 3) == '../') - { + if (substr($sToInclude, 0, 3) == '../') { // Preserve compatibility with config files written before 1.0.1 // Replace '../' by '/' $sFile = APPROOT.'/'.substr($sToInclude, 3); - } - else - { + } else { $sFile = APPROOT.'/'.$sToInclude; } - } - else - { + } else { // Leave as is - should be an absolute path $sFile = $sToInclude; } - if (!file_exists($sFile)) - { + if (!file_exists($sFile)) { $sConfigFile = self::$m_oConfig->GetLoadedFile(); - if ($sModuleType == null) - { + if ($sModuleType == null) { throw new CoreException("Include: unable to load the file '$sFile'"); - } - else - { - if (strlen($sConfigFile) > 0) - { - throw new CoreException('Include: wrong file name in configuration file', array('config file' => $sConfigFile, 'section' => $sModuleType, 'filename' => $sFile)); - } - else - { + } else { + if (strlen($sConfigFile) > 0) { + throw new CoreException('Include: wrong file name in configuration file', ['config file' => $sConfigFile, 'section' => $sModuleType, 'filename' => $sFile]); + } else { // The configuration is in memory only - throw new CoreException('Include: wrong file name in configuration file (in memory)', array('section' => $sModuleType, 'filename' => $sFile)); + throw new CoreException('Include: wrong file name in configuration file (in memory)', ['section' => $sModuleType, 'filename' => $sFile]); } } } @@ -6620,10 +6028,8 @@ abstract class MetaModel ob_start(); require_once($sFile); $sPreviousContent = ob_get_clean(); - if (self::$m_oConfig->Get('debug_report_spurious_chars')) - { - if ($sPreviousContent != '') - { + if (self::$m_oConfig->Get('debug_report_spurious_chars')) { + if ($sPreviousContent != '') { IssueLog::Error("Spurious characters injected by '$sFile'"); } } @@ -6633,19 +6039,18 @@ abstract class MetaModel // // /** @var array */ - private static $aQueryCacheGetObject = array(); + private static $aQueryCacheGetObject = []; /** @var array */ - private static $aQueryCacheGetObjectHits = array(); + private static $aQueryCacheGetObjectHits = []; /** * @return string */ public static function GetQueryCacheStatus() { - $aRes = array(); + $aRes = []; $iTotalHits = 0; - foreach(self::$aQueryCacheGetObjectHits as $sClassSign => $iHits) - { + foreach (self::$aQueryCacheGetObjectHits as $sClassSign => $iHits) { $aRes[] = "$sClassSign: $iHits"; $iTotalHits += $iHits; } @@ -6670,20 +6075,17 @@ abstract class MetaModel // Build the query cache signature // $sQuerySign = $sClass; - if ($bAllowAllData) - { + if ($bAllowAllData) { $sQuerySign .= '_all_'; } - if (is_array($aModifierProperties) && (count($aModifierProperties) > 0)) - { + if (is_array($aModifierProperties) && (count($aModifierProperties) > 0)) { array_multisort($aModifierProperties); $sModifierProperties = json_encode($aModifierProperties); $sQuerySign .= '_all_'.md5($sModifierProperties); } $sQuerySign .= utils::IsArchiveMode() ? '_arch_' : ''; - if (!array_key_exists($sQuerySign, self::$aQueryCacheGetObject)) - { + if (!array_key_exists($sQuerySign, self::$aQueryCacheGetObject)) { // NOTE: Quick and VERY dirty caching mechanism which relies on // the fact that the string '987654321' will never appear in the // standard query @@ -6691,27 +6093,21 @@ abstract class MetaModel // but this would slow down -by how much time?- the application $oFilter = new DBObjectSearch($sClass); $oFilter->AddCondition('id', 987654321, '='); - if ($aModifierProperties) - { - foreach($aModifierProperties as $sPluginClass => $aProperties) - { - foreach($aProperties as $sProperty => $value) - { + if ($aModifierProperties) { + foreach ($aModifierProperties as $sPluginClass => $aProperties) { + foreach ($aProperties as $sProperty => $value) { $oFilter->SetModifierProperty($sPluginClass, $sProperty, $value); } } } - if ($bAllowAllData) - { + if ($bAllowAllData) { $oFilter->AllowAllData(); } $oFilter->NoContextParameters(); $sSQL = $oFilter->MakeSelectQuery(); self::$aQueryCacheGetObject[$sQuerySign] = $sSQL; self::$aQueryCacheGetObjectHits[$sQuerySign] = 0; - } - else - { + } else { $sSQL = self::$aQueryCacheGetObject[$sQuerySign]; self::$aQueryCacheGetObjectHits[$sQuerySign] += 1; } @@ -6721,8 +6117,7 @@ abstract class MetaModel $aRow = CMDBSource::FetchArray($res); CMDBSource::FreeResult($res); - if ($bMustBeFound && empty($aRow)) - { + if ($bMustBeFound && empty($aRow)) { $sNotFoundErrorMessage = "No result for the single row query"; IssueLog::Info($sNotFoundErrorMessage, LogChannels::CMDB_SOURCE, [ 'class' => $sClass, @@ -6752,40 +6147,31 @@ abstract class MetaModel { self::_check_subclass($sClass); - if (strlen($sClassAlias) == 0) - { + if (strlen($sClassAlias) == 0) { $sClassAlias = $sClass; } // Compound objects: if available, get the final object class // - if (!array_key_exists($sClassAlias."finalclass", $aRow)) - { + if (!array_key_exists($sClassAlias."finalclass", $aRow)) { // Either this is a bug (forgot to specify a root class with a finalclass field // Or this is the expected behavior, because the object is not made of several tables - if (self::IsAbstract($sClass)) - { + if (self::IsAbstract($sClass)) { throw new CoreUnexpectedValue("Querying the abstract '$sClass' class without finalClass attribute"); } - if (self::HasChildrenClasses($sClass)) - { + if (self::HasChildrenClasses($sClass)) { throw new CoreUnexpectedValue("Querying the '$sClass' class without the finalClass attribute, whereas this class has children"); } - } - elseif (empty($aRow[$sClassAlias."finalclass"])) - { + } elseif (empty($aRow[$sClassAlias."finalclass"])) { // The data is missing in the DB // @#@ possible improvement: check that the class is valid ! $sRootClass = self::GetRootClass($sClass); $sFinalClassField = self::DBGetClassField($sRootClass); throw new CoreException("Empty class name for object $sClass::{$aRow["id"]} (root class '$sRootClass', field '{$sFinalClassField}' is empty)"); - } - else - { + } else { // do the job for the real target class - if (!class_exists($aRow[$sClassAlias."finalclass"])) - { - throw new CoreException("Class {$aRow[$sClassAlias."finalclass"]} derived from $sClass does not exist anymore, please remove corresponding tables in the database", array('row' => $aRow)); + if (!class_exists($aRow[$sClassAlias."finalclass"])) { + throw new CoreException("Class {$aRow[$sClassAlias."finalclass"]} derived from $sClass does not exist anymore, please remove corresponding tables in the database", ['row' => $aRow]); } $sClass = $aRow[$sClassAlias."finalclass"]; } @@ -6902,23 +6288,17 @@ abstract class MetaModel self::_check_subclass($sClass); utils::PushArchiveMode(true); - try - { + try { $aRow = self::MakeSingleRow($sClass, $iKey, $bMustBeFound, $bAllowAllData, $aModifierProperties); - } - catch(Exception $e) - { + } catch (Exception $e) { // In the finally block we will pop the pushed archived mode // otherwise the application stays in ArchiveMode true which has caused hazardious behavior! throw $e; - } - finally - { + } finally { utils::PopArchiveMode(); } - if (empty($aRow)) - { + if (empty($aRow)) { return null; } @@ -6940,11 +6320,9 @@ abstract class MetaModel $oObjSearch = new DBObjectSearch($sClass); $oObjSearch->AddNameCondition($sName); $oSet = new DBObjectSet($oObjSearch); - if ($oSet->Count() != 1) - { - if ($bMustBeFound) - { - throw new CoreException('Failed to get an object by its name', array('class' => $sClass, 'name' => $sName)); + if ($oSet->Count() != 1) { + if ($bMustBeFound) { + throw new CoreException('Failed to get an object by its name', ['class' => $sClass, 'name' => $sName]); } return null; } @@ -6953,7 +6331,7 @@ abstract class MetaModel } /** @var array */ - static protected $m_aCacheObjectByColumn = array(); + protected static $m_aCacheObjectByColumn = []; /** * @param string $sClass @@ -6982,15 +6360,11 @@ abstract class MetaModel $oObjSearch->AllowAllData($bAllowAllData); $oObjSearch->AddCondition($sAttCode, $value, '='); $oSet = new DBObjectSet($oObjSearch); - if ($oSet->Count() == 1) - { + if ($oSet->Count() == 1) { self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value] = $oSet->fetch(); - } - else - { - if ($bMustBeFoundUnique) - { - throw new CoreException('Failed to get an object by column', array('class' => $sClass, 'attcode' => $sAttCode, 'value' => $value, 'matches' => $oSet->Count())); + } else { + if ($bMustBeFoundUnique) { + throw new CoreException('Failed to get an object by column', ['class' => $sClass, 'attcode' => $sAttCode, 'value' => $value, 'matches' => $oSet->Count()]); } self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value] = null; } @@ -7010,8 +6384,7 @@ abstract class MetaModel public static function GetObjectFromOQL($sQuery, $aParams = null, $bAllowAllData = false) { $oFilter = DBObjectSearch::FromOQL($sQuery, $aParams); - if ($bAllowAllData) - { + if ($bAllowAllData) { $oFilter->AllowAllData(); } $oSet = new DBObjectSet($oFilter); @@ -7035,11 +6408,11 @@ abstract class MetaModel if ($iKey < 0) { return "$sTargetClass: $iKey (invalid value)"; } - $oObj = self::GetObject($sTargetClass, $iKey, false); + $oObj = self::GetObject($sTargetClass, $iKey, false); if (is_null($oObj)) { // Whatever we are looking for, the root class is the key to search for $sRootClass = self::GetRootClass($sTargetClass); - $oSearch = DBObjectSearch::FromOQL('SELECT CMDBChangeOpDelete WHERE objclass = :objclass AND objkey = :objkey', array('objclass' => $sRootClass, 'objkey' => $iKey)); + $oSearch = DBObjectSearch::FromOQL('SELECT CMDBChangeOpDelete WHERE objclass = :objclass AND objkey = :objkey', ['objclass' => $sRootClass, 'objkey' => $iKey]); $oSet = new DBObjectSet($oSearch); $oRecord = $oSet->Fetch(); // An empty fname is obtained with iTop < 2.0 @@ -7071,10 +6444,8 @@ abstract class MetaModel { self::_check_subclass($sClass); $oRet = new $sClass(); - if (is_array($aValues)) - { - foreach($aValues as $sAttCode => $value) - { + if (is_array($aValues)) { + foreach ($aValues as $sAttCode => $value) { $oRet->Set($sAttCode, $value); } } @@ -7124,7 +6495,7 @@ abstract class MetaModel while ($bExecuteQuery) { $oSet = new DBObjectSet($oFilter); $oSet->SetLimit($iMaxChunkSize); - $oSet->OptimizeColumnLoad(array($sTargetClass => array('finalclass'))); + $oSet->OptimizeColumnLoad([$sTargetClass => ['finalclass']]); $aIdToClass = $oSet->GetColumnAsArray('finalclass', true); $aIds = array_keys($aIdToClass); @@ -7168,11 +6539,9 @@ abstract class MetaModel self::_check_subclass($sClass); // 1-N links (referenced by my class), returns an array of sAttCode=>sClass - $aResult = array(); - foreach(self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef) - { - if ($oAttDef->IsExternalKey()) - { + $aResult = []; + foreach (self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef) { + if ($oAttDef->IsExternalKey()) { $aResult[$sAttCode] = $oAttDef->GetTargetClass(); } } @@ -7192,39 +6561,31 @@ abstract class MetaModel { self::_check_subclass($sClass); - if ($bSkipLinkingClasses) - { + if ($bSkipLinkingClasses) { $aLinksClasses = array_keys(self::GetLinkClasses()); } // 1-N links (referencing my class), array of sClass => array of sAttcode - $aResult = array(); - foreach(self::$m_aAttribDefs as $sSomeClass => $aClassAttributes) - { - if ($bSkipLinkingClasses && in_array($sSomeClass, $aLinksClasses)) - { + $aResult = []; + foreach (self::$m_aAttribDefs as $sSomeClass => $aClassAttributes) { + if ($bSkipLinkingClasses && in_array($sSomeClass, $aLinksClasses)) { continue; } - $aExtKeys = array(); - foreach($aClassAttributes as $sAttCode => $oAttDef) - { - if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) - { + $aExtKeys = []; + foreach ($aClassAttributes as $sAttCode => $oAttDef) { + if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) { continue; } - if ($oAttDef->IsExternalKey() && (self::IsParentClass($oAttDef->GetTargetClass(), $sClass))) - { - if ($bInnerJoinsOnly && $oAttDef->IsNullAllowed()) - { + if ($oAttDef->IsExternalKey() && (self::IsParentClass($oAttDef->GetTargetClass(), $sClass))) { + if ($bInnerJoinsOnly && $oAttDef->IsNullAllowed()) { continue; } // Ok, I want this one $aExtKeys[$sAttCode] = $oAttDef; } } - if (count($aExtKeys) != 0) - { + if (count($aExtKeys) != 0) { $aResult[$sSomeClass] = $aExtKeys; } } @@ -7254,11 +6615,11 @@ abstract class MetaModel */ public static function GetLinkClasses(): array { - $aRet = array(); - foreach(self::GetClasses() as $sClass) { + $aRet = []; + foreach (self::GetClasses() as $sClass) { if (self::IsLinkClass($sClass)) { - $aExtKeys = array(); - foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) { + $aExtKeys = []; + foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) { if ($oAttDef->IsExternalKey()) { $aExtKeys[$sAttCode] = $oAttDef->GetTargetClass(); } @@ -7309,8 +6670,8 @@ abstract class MetaModel $aParams['APP_URL'] = utils::GetAbsoluteUrlAppRoot(); $aParams['MODULES_URL'] = utils::GetAbsoluteUrlModulesRoot(); - $aSearches = array(); - $aReplacements = array(); + $aSearches = []; + $aReplacements = []; foreach ($aParams as $sSearch => $replace) { // Some environment parameters are objects, we just need scalars if (is_object($replace)) { @@ -7322,10 +6683,10 @@ abstract class MetaModel // 1 - The delimiter // 2 - The arrow // 3 - The attribute code - $aRegExps = array( + $aRegExps = [ '/(\\$)'.$sName.'-(>|>)([^\\$]+)\\$/', // Support both syntaxes: $this->xxx$ or $this->xxx$ for HTML compatibility '/(%24)'.$sName.'-(>|>)([^%24]+)%24/', // Support for urlencoded in HTML attributes (%20this->xxx%20) - ); + ]; foreach ($aRegExps as $sRegExp) { if (preg_match_all($sRegExp, $sInput, $aMatches)) { foreach ($aMatches[3] as $idx => $sPlaceholderAttCode) { @@ -7335,8 +6696,7 @@ abstract class MetaModel $aReplacements[] = $sReplacement; $aSearches[] = $aMatches[1][$idx].$sName.'-'.$aMatches[2][$idx].$sPlaceholderAttCode.$aMatches[1][$idx]; } - } - catch (Exception $e) { + } catch (Exception $e) { $aContext = [ 'placeholder' => $sPlaceholderAttCode, 'replace class' => get_class($replace), @@ -7357,13 +6717,13 @@ abstract class MetaModel continue; // Ignore this non-scalar value } } else { - $aRegExps = array( + $aRegExps = [ '/(\$)'.$sSearch.'\$/', // Regular placeholders (eg. $APP_URL$) or placeholders with an arrow in plain text (eg. $foo->bar$) '/(%24)'.$sSearch.'%24/', // Regular placeholders url-encoded in HTML attributes (eg. %24APP_URL%24) '/(\$)'.utils::EscapeHtml($sSearch).'\$/', // Placeholders with an arrow in HTML (eg. $foo->bar$) '/(%24)'.utils::EscapeHtml($sSearch).'%24/', // Placeholders with an arrow url-encoded in HTML attributes (eg. %24->bar%24) - ); + ]; foreach ($aRegExps as $sRegExp) { if (preg_match_all($sRegExp, $sInput, $aMatches)) { foreach ($aMatches[1] as $idx => $sDelimiter) { @@ -7375,8 +6735,7 @@ abstract class MetaModel // With an arrow in HTML $aReplacements[] = (string) $replace; $aSearches[] = $aMatches[1][$idx].utils::EscapeHtml($sSearch).$aMatches[1][$idx]; - } - catch (Exception $e) { + } catch (Exception $e) { IssueLog::Debug( 'Invalid placeholder in notification, no replacement will occur !', LogChannels::NOTIFICATIONS, @@ -7430,21 +6789,17 @@ abstract class MetaModel */ public static function GetCacheEntries($sEnvironment = null) { - if (is_null($sEnvironment)) - { + if (is_null($sEnvironment)) { $sEnvironment = MetaModel::GetEnvironmentId(); } - $aEntries = array(); + $aEntries = []; $aCacheUserData = apc_cache_info_compat(); - if (is_array($aCacheUserData) && isset($aCacheUserData['cache_list'])) - { + if (is_array($aCacheUserData) && isset($aCacheUserData['cache_list'])) { $sPrefix = 'itop-'.$sEnvironment.'-'; - foreach($aCacheUserData['cache_list'] as $i => $aEntry) - { + foreach ($aCacheUserData['cache_list'] as $i => $aEntry) { $sEntryKey = array_key_exists('info', $aEntry) ? $aEntry['info'] : $aEntry['key']; - if (strpos($sEntryKey, $sPrefix) === 0) - { + if (strpos($sEntryKey, $sPrefix) === 0) { $sCleanKey = substr($sEntryKey, strlen($sPrefix)); $aEntries[$sCleanKey] = $aEntry; $aEntries[$sCleanKey]['info'] = $sEntryKey; @@ -7507,42 +6862,29 @@ abstract class MetaModel { $sRet = $sField; - if ($sField == 'id') - { + if ($sField == 'id') { $sRet = 'id'; - } - elseif ($sField == 'friendlyname') - { + } elseif ($sField == 'friendlyname') { $sFriendlyNameAttCode = static::GetFriendlyNameAttributeCode($sClass); - if (!is_null($sFriendlyNameAttCode)) - { + if (!is_null($sFriendlyNameAttCode)) { // The friendly name is made of a single attribute $sRet = $sFriendlyNameAttCode; } - } - else - { + } else { $oAttDef = static::GetAttributeDef($sClass, $sField); - if ($oAttDef->IsExternalField()) - { - if ($oAttDef->IsFriendlyName()) - { + if ($oAttDef->IsExternalField()) { + if ($oAttDef->IsFriendlyName()) { $oKeyAttDef = MetaModel::GetAttributeDef($sClass, $oAttDef->GetKeyAttCode()); $sRemoteClass = $oKeyAttDef->GetTargetClass(); $sFriendlyNameAttCode = static::GetFriendlyNameAttributeCode($sRemoteClass); - if (is_null($sFriendlyNameAttCode)) - { + if (is_null($sFriendlyNameAttCode)) { // The friendly name is made of several attributes $sRet = $oAttDef->GetKeyAttCode().'->friendlyname'; - } - else - { + } else { // The friendly name is made of a single attribute $sRet = $oAttDef->GetKeyAttCode().'->'.$sFriendlyNameAttCode; } - } - else - { + } else { $sRet = $oAttDef->GetKeyAttCode().'->'.$oAttDef->GetExtAttCode(); } } @@ -7552,11 +6894,10 @@ abstract class MetaModel private static function GetAdditionalRequestAfterAlter($sClass, $sTable, $sField) { - $aRequests = array(); + $aRequests = []; // Copy finalclass fields from root class to intermediate classes - if ($sField == self::DBGetClassField($sClass)) - { + if ($sField == self::DBGetClassField($sClass)) { $sRootClass = MetaModel::GetRootClass($sClass); $sRootTable = self::DBGetTable($sRootClass); $sKey = self::DBGetKey($sClass); @@ -7670,7 +7011,7 @@ abstract class MetaModel 'ModuleHandlerApiInterface', ]; foreach ($aInterfaces as $sInterface) { - self::$m_aExtensionClassNames[$sInterface] = array(); + self::$m_aExtensionClassNames[$sInterface] = []; } foreach (get_declared_classes() as $sPHPClass) { @@ -7685,15 +7026,14 @@ abstract class MetaModel } } - // Standard attribute lists -MetaModel::RegisterZList("noneditable", array("description" => "non editable fields", "type" => "attributes")); +MetaModel::RegisterZList("noneditable", ["description" => "non editable fields", "type" => "attributes"]); -MetaModel::RegisterZList("details", array("description" => "All attributes to be displayed for the 'details' of an object", "type" => "attributes")); -MetaModel::RegisterZList("summary", array("description" => "All attributes to be displayed for shorter 'details' of an object", "type" => "attributes")); -MetaModel::RegisterZList("list", array("description" => "All attributes to be displayed for a list of objects", "type" => "attributes")); -MetaModel::RegisterZList("preview", array("description" => "All attributes visible in preview mode", "type" => "attributes")); +MetaModel::RegisterZList("details", ["description" => "All attributes to be displayed for the 'details' of an object", "type" => "attributes"]); +MetaModel::RegisterZList("summary", ["description" => "All attributes to be displayed for shorter 'details' of an object", "type" => "attributes"]); +MetaModel::RegisterZList("list", ["description" => "All attributes to be displayed for a list of objects", "type" => "attributes"]); +MetaModel::RegisterZList("preview", ["description" => "All attributes visible in preview mode", "type" => "attributes"]); -MetaModel::RegisterZList("standard_search", array("description" => "List of criteria for the standard search", "type" => "filters")); -MetaModel::RegisterZList("advanced_search", array("description" => "List of criteria for the advanced search", "type" => "filters")); -MetaModel::RegisterZList("default_search", array("description" => "List of criteria displayed by default during search", "type" => "filters")); +MetaModel::RegisterZList("standard_search", ["description" => "List of criteria for the standard search", "type" => "filters"]); +MetaModel::RegisterZList("advanced_search", ["description" => "List of criteria for the advanced search", "type" => "filters"]); +MetaModel::RegisterZList("default_search", ["description" => "List of criteria displayed by default during search", "type" => "filters"]); diff --git a/core/oqlactualclasstreeresolver.class.inc.php b/core/oqlactualclasstreeresolver.class.inc.php index 59a9bb34e..46fdb0470 100644 --- a/core/oqlactualclasstreeresolver.class.inc.php +++ b/core/oqlactualclasstreeresolver.class.inc.php @@ -1,10 +1,10 @@ oOQLClassNode->GetNodeClass(); $sClassAlias = $this->oOQLClassNode->GetNodeClassAlias(); $aExpectedAttributes = $this->oBuild->m_oQBExpressions->GetUnresolvedFields($sClassAlias); - if (!is_null($sIncomingKeyAttCode) && !isset($aExpectedAttributes[$sIncomingKeyAttCode])) - { + if (!is_null($sIncomingKeyAttCode) && !isset($aExpectedAttributes[$sIncomingKeyAttCode])) { // Add entry point as expected attribute $aExpectedAttributes[$sIncomingKeyAttCode] = new FieldExpression($sIncomingKeyAttCode, $sClassAlias); } $aClasses = MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL, false); /** @var OQLClassNode[] $aClassAndAncestorsNodes */ - $aClassAndAncestorsNodes = array(); - foreach ($aClasses as $sFamilyClass) - { + $aClassAndAncestorsNodes = []; + foreach ($aClasses as $sFamilyClass) { // Remove unnecessary classes - if (MetaModel::HasTable($sFamilyClass)) - { + if (MetaModel::HasTable($sFamilyClass)) { $aClassAndAncestorsNodes[$sFamilyClass] = null; } } - if (empty($aClassAndAncestorsNodes)) - { + if (empty($aClassAndAncestorsNodes)) { throw new CoreException("Impossible to query the class $sClass"); } $oBaseNode = null; - $aTranslateFields = array(); - foreach ($aExpectedAttributes as $sAttCode => $oExpression) - { + $aTranslateFields = []; + foreach ($aExpectedAttributes as $sAttCode => $oExpression) { // 'id' is managed later - if ($sAttCode == 'id') - { + if ($sAttCode == 'id') { continue; } // Attributes can be stored in attributes list or for magic ones into filter codes list. $sOriginClass = null; if (MetaModel::IsValidAttCode($sClass, $sAttCode)) { $sOriginClass = MetaModel::GetAttributeOrigin($sClass, $sAttCode); - } else if ($sAttCode == 'id') { + } elseif ($sAttCode == 'id') { $sOriginClass = $sClass; } else { continue; } - if (!isset($aClassAndAncestorsNodes[$sOriginClass]) || is_null($aClassAndAncestorsNodes[$sOriginClass])) - { - if ($sOriginClass == $sClass) - { + if (!isset($aClassAndAncestorsNodes[$sOriginClass]) || is_null($aClassAndAncestorsNodes[$sOriginClass])) { + if ($sOriginClass == $sClass) { $sOriginClassAlias = $sClassAlias; - } - else - { + } else { $sOriginClassAlias = $this->oBuild->GenerateTableAlias($sClassAlias.'_'.$sOriginClass, $sClass); } $oOriginClassNode = new OQLClassNode($this->oBuild, $sOriginClass, $sOriginClassAlias, $sClassAlias); $aClassAndAncestorsNodes[$sOriginClass] = $oOriginClassNode; - } - else - { + } else { $oOriginClassNode = $aClassAndAncestorsNodes[$sOriginClass]; } - if ($sOriginClass != $sClass) - { + if ($sOriginClass != $sClass) { // Alias changed, set a new translation $sOriginClassAlias = $oOriginClassNode->GetNodeClassAlias(); $aTranslateFields[$sClassAlias][$sAttCode] = new FieldExpression($sAttCode, $sOriginClassAlias); @@ -107,8 +94,7 @@ class OQLActualClassTreeResolver // Add Joins corresponding to external keys $this->ResolveJoins($sAttCode, $oOriginClassNode); - if ($sAttCode === $sIncomingKeyAttCode) - { + if ($sAttCode === $sIncomingKeyAttCode) { // This is the entry point of the class $oBaseNode = $oOriginClassNode; } @@ -117,47 +103,37 @@ class OQLActualClassTreeResolver // Create joins for ancestor classes /** @var \OQLClassNode $oBaseNode */ $sFirstValidAncestor = null; - foreach ($aClassAndAncestorsNodes as $sOriginClass => $oOriginClassNode) - { - if (is_null($sFirstValidAncestor)) - { + foreach ($aClassAndAncestorsNodes as $sOriginClass => $oOriginClassNode) { + if (is_null($sFirstValidAncestor)) { $sFirstValidAncestor = $sOriginClass; } - if (is_null($oOriginClassNode)) - { + if (is_null($oOriginClassNode)) { continue; } - if (is_null($oBaseNode)) - { + if (is_null($oBaseNode)) { $oBaseNode = $oOriginClassNode; continue; } - if ($oBaseNode === $oOriginClassNode) - { + if ($oBaseNode === $oOriginClassNode) { // Don't link to itself continue; } $oBaseNode->AddInnerJoin($oOriginClassNode, 'id', 'id'); } - if (is_null($oBaseNode)) - { + if (is_null($oBaseNode)) { // If no class was generated above, keep the first valid ancestor - if (is_null($sFirstValidAncestor) || ($sFirstValidAncestor == $sClass)) - { + if (is_null($sFirstValidAncestor) || ($sFirstValidAncestor == $sClass)) { // take current node $oBaseNode = $this->oOQLClassNode->CloneNode(); - } - else - { + } else { // Use the first valid class to build a default node $sDefaultClassAlias = $this->oBuild->GenerateTableAlias($sClassAlias.'_'.$sFirstValidAncestor, $sClass); $oBaseNode = new OQLClassNode($this->oBuild, $sFirstValidAncestor, $sDefaultClassAlias); } } - if (isset($aExpectedAttributes['id']) && !isset($aClassAndAncestorsNodes[$sClass])) - { + if (isset($aExpectedAttributes['id']) && !isset($aClassAndAncestorsNodes[$sClass])) { $sFirstClassAlias = $oBaseNode->GetNodeClassAlias(); $aTranslateFields[$sClassAlias]['id'] = new FieldExpression('id', $sFirstClassAlias); } @@ -167,12 +143,11 @@ class OQLActualClassTreeResolver $this->ResolveJoins('id', $oBaseNode); // Add finalclass condition if not the requested class - if ($oBaseNode->GetNodeClass() != $sClass) - { + if ($oBaseNode->GetNodeClass() != $sClass) { $sExpectedClasses = implode("', '", MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL)); $oInExpression = Expression::FromOQL("`".$oBaseNode->GetNodeClassAlias()."`.finalclass IN ('$sExpectedClasses')"); $oTrueExpression = new TrueExpression(); - $aCoalesceAttr = array($oInExpression, $oTrueExpression); + $aCoalesceAttr = [$oInExpression, $oTrueExpression]; $oFinalClassRestriction = new FunctionExpression("COALESCE", $aCoalesceAttr); $this->oBuild->m_oQBExpressions->AddCondition($oFinalClassRestriction); } @@ -194,10 +169,8 @@ class OQLActualClassTreeResolver // Joins on the selected class $aJoins = $this->oOQLClassNode->GetJoins(); - if (isset($aJoins[$sAttCode])) - { - foreach ($aJoins[$sAttCode] as $oBaseOQLJoin) - { + if (isset($aJoins[$sAttCode])) { + foreach ($aJoins[$sAttCode] as $oBaseOQLJoin) { // transfer the join from OQL class tree to actual class tree $oBaseJoinedClassNode = $oBaseOQLJoin->GetOOQLClassNode(); $oOQLActualClassTreeResolver = new OQLActualClassTreeResolver($oBaseJoinedClassNode, $this->oBuild); diff --git a/core/ormdocument.class.inc.php b/core/ormdocument.class.inc.php index 527465d4f..56618dcaf 100644 --- a/core/ormdocument.class.inc.php +++ b/core/ormdocument.class.inc.php @@ -407,16 +407,16 @@ class ormDocument * @return ormDocument The resampled image * */ - public function ResizeImageToFit(int $iMaxWidth, int $iMaxHeight, array|null &$aFinalDimensions = null) : static + public function ResizeImageToFit(int $iMaxWidth, int $iMaxHeight, array|null &$aFinalDimensions = null): static { $aFinalDimensions = null; // If gd extension is not loaded, we put a warning in the log and return the image as is if (extension_loaded('gd') === false) { - IssueLog::Warning('Image could not be resized as the "gd" extension does not seem to be loaded. Its dimensions will remain the same instead of ' . $iMaxWidth . 'x' . $iMaxHeight); + IssueLog::Warning('Image could not be resized as the "gd" extension does not seem to be loaded. Its dimensions will remain the same instead of '.$iMaxWidth.'x'.$iMaxHeight); return $this; } $oGdImage = false; - switch($this->GetMimeType()) { + switch ($this->GetMimeType()) { case 'image/gif': case 'image/jpeg': case 'image/png': @@ -428,18 +428,18 @@ class ormDocument } if ($oGdImage === false) { - IssueLog::Warning('Image could not be resized as . It will remain as imagecreatefromstring could not read its data.Its dimensions will remain the same instead of ' . $iMaxWidth . 'x' . $iMaxHeight); + IssueLog::Warning('Image could not be resized as . It will remain as imagecreatefromstring could not read its data.Its dimensions will remain the same instead of '.$iMaxWidth.'x'.$iMaxHeight); return $this; } $iWidth = imagesx($oGdImage); $iHeight = imagesy($oGdImage); - if ( ($iMaxWidth === 0 || $iWidth <= $iMaxWidth) && ($iMaxHeight === 0 || $iHeight <= $iMaxHeight)) { + if (($iMaxWidth === 0 || $iWidth <= $iMaxWidth) && ($iMaxHeight === 0 || $iHeight <= $iMaxHeight)) { // No need to resize $aFinalDimensions = [ 'width' => $iWidth, - 'height' =>$iHeight + 'height' => $iHeight, ]; return $this; } @@ -456,14 +456,13 @@ class ormDocument $oNewGdImage = imagecreatetruecolor($iNewWidth, $iNewHeight); - $aFinalDimensions = [ 'width' => $iNewWidth, - 'height' =>$iNewHeight + 'height' => $iNewHeight, ]; // Preserve transparency - if($this->GetMimeType() == "image/gif" || $this->GetMimeType() == "image/png") { + if ($this->GetMimeType() == "image/gif" || $this->GetMimeType() == "image/png") { imagecolortransparent($oNewGdImage, imagecolorallocatealpha($oNewGdImage, 0, 0, 0, 127)); imagealphablending($oNewGdImage, false); imagesavealpha($oNewGdImage, true); @@ -473,16 +472,16 @@ class ormDocument ob_start(); switch ($this->GetMimeType()) { case 'image/gif': - imagegif($oNewGdImage); // send image to output buffer - break; + imagegif($oNewGdImage); // send image to output buffer + break; case 'image/jpeg': - imagejpeg($oNewGdImage, null, 80); // null = send image to output buffer, 80 = good quality - break; + imagejpeg($oNewGdImage, null, 80); // null = send image to output buffer, 80 = good quality + break; case 'image/png': - imagepng($oNewGdImage, null, 5); // null = send image to output buffer, 5 = medium compression - break; + imagepng($oNewGdImage, null, 5); // null = send image to output buffer, 5 = medium compression + break; } $oResampledImage = new ormDocument(ob_get_contents(), $this->GetMimeType(), $this->GetFileName()); @ob_end_clean(); @@ -502,5 +501,4 @@ class ormDocument return md5($this->GetData() ?? ''); } - } diff --git a/core/ormlinkset.class.inc.php b/core/ormlinkset.class.inc.php index 872b6e3bf..56573dc51 100644 --- a/core/ormlinkset.class.inc.php +++ b/core/ormlinkset.class.inc.php @@ -1,4 +1,5 @@ DBObject */ - protected $aPreserved = array(); + protected $aPreserved = []; /** * @var DBObject[] New items */ - protected $aAdded = array(); + protected $aAdded = []; /** * @var DBObject[] Modified items (could also be found in aPreserved) */ - protected $aModified = array(); + protected $aModified = []; /** * @var int[] Removed items */ - protected $aRemoved = array(); + protected $aRemoved = []; /** * @var int Position in the collection @@ -100,13 +100,11 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator $this->oOriginalSet = $oOriginalSet ? clone $oOriginalSet : null; $oAttDef = MetaModel::GetAttributeDef($sHostClass, $sAttCode); - if (!$oAttDef instanceof AttributeLinkedSet) - { + if (!$oAttDef instanceof AttributeLinkedSet) { throw new Exception("ormLinkSet: $sAttCode is not a link set"); } $this->sClass = $oAttDef->GetLinkedClass(); - if ($oOriginalSet && ($oOriginalSet->GetClass() != $this->sClass)) - { + if ($oOriginalSet && ($oOriginalSet->GetClass() != $this->sClass)) { throw new Exception("ormLinkSet: wrong class for the original set, found {$oOriginalSet->GetClass()} while expecting {$oAttDef->GetLinkedClass()}"); } } @@ -140,7 +138,7 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator { assert($oLink instanceof $this->sClass); // No impact on the iteration algorithm - $iObjectId = $oLink->GetKey(); + $iObjectId = $oLink->GetKey(); $this->aAdded[$iObjectId] = $oLink; $this->bHasDelta = true; } @@ -150,19 +148,15 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator */ public function RemoveItem($iObjectId) { - if (array_key_exists($iObjectId, $this->aPreserved)) - { + if (array_key_exists($iObjectId, $this->aPreserved)) { unset($this->aPreserved[$iObjectId]); $this->aRemoved[$iObjectId] = $iObjectId; $this->bHasDelta = true; + } else { + if (array_key_exists($iObjectId, $this->aAdded)) { + unset($this->aAdded[$iObjectId]); + } } - else - { - if (array_key_exists($iObjectId, $this->aAdded)) - { - unset($this->aAdded[$iObjectId]); - } - } } /** @@ -173,12 +167,11 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator assert($oLink instanceof $this->sClass); $iObjectId = $oLink->GetKey(); - if (array_key_exists($iObjectId, $this->aPreserved)) - { - unset($this->aPreserved[$iObjectId]); - $this->aModified[$iObjectId] = $oLink; - $this->bHasDelta = true; - } + if (array_key_exists($iObjectId, $this->aPreserved)) { + unset($this->aPreserved[$iObjectId]); + $this->aModified[$iObjectId] = $oLink; + $this->bHasDelta = true; + } } /** @@ -188,33 +181,25 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator */ protected function LoadOriginalIds() { - if ($this->aOriginalObjects === null) - { - if ($this->oOriginalSet) - { + if ($this->aOriginalObjects === null) { + if ($this->oOriginalSet) { $this->aOriginalObjects = $this->GetArrayOfIndex(); $this->aPreserved = $this->aOriginalObjects; // Copy (not effective until aPreserved gets modified) - foreach ($this->aRemoved as $iObjectId) - { - if (array_key_exists($iObjectId, $this->aPreserved)) - { - unset($this->aPreserved[$iObjectId]); - } - } - foreach ($this->aModified as $iObjectId => $oLink) - { - if (array_key_exists($iObjectId, $this->aPreserved)) - { - unset($this->aPreserved[$iObjectId]); - } - } - } - else - { + foreach ($this->aRemoved as $iObjectId) { + if (array_key_exists($iObjectId, $this->aPreserved)) { + unset($this->aPreserved[$iObjectId]); + } + } + foreach ($this->aModified as $iObjectId => $oLink) { + if (array_key_exists($iObjectId, $this->aPreserved)) { + unset($this->aPreserved[$iObjectId]); + } + } + } else { // Nothing to load - $this->aOriginalObjects = array(); - $this->aPreserved = array(); + $this->aOriginalObjects = []; + $this->aPreserved = []; } } } @@ -230,39 +215,34 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator */ protected function GetArrayOfIndex() { - $aRet = array(); + $aRet = []; $this->oOriginalSet->Rewind(); $iRow = 0; - while ($oObject = $this->oOriginalSet->Fetch()) - { + while ($oObject = $this->oOriginalSet->Fetch()) { $aRet[$oObject->GetKey()] = $iRow++; } return $aRet; } - /** - * @param string $sAttCode - * @param bool $bWithId - * @return array - */ - public function GetColumnAsArray($sAttCode, $bWithId = true) - { - $aRet = array(); - foreach($this as $oItem) - { - if ($bWithId) - { - $aRet[$oItem->GetKey()] = $oItem->Get($sAttCode); - } - else - { - $aRet[] = $oItem->Get($sAttCode); - } - } - return $aRet; - } + /** + * @param string $sAttCode + * @param bool $bWithId + * @return array + */ + public function GetColumnAsArray($sAttCode, $bWithId = true) + { + $aRet = []; + foreach ($this as $oItem) { + if ($bWithId) { + $aRet[$oItem->GetKey()] = $oItem->Get($sAttCode); + } else { + $aRet[] = $oItem->Get($sAttCode); + } + } + return $aRet; + } - /** + /** * The class of the objects of the collection (at least a common ancestor) * * @return string @@ -300,13 +280,11 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator $this->LoadOriginalIds(); $iCount = $this->Count(); - if ($iPosition >= $iCount) - { + if ($iPosition >= $iCount) { throw new Exception("Invalid position $iPosition: the link set is made of $iCount items."); } $this->rewind(); - for($iPos = 0 ; $iPos < $iPosition ; $iPos++) - { + for ($iPos = 0 ; $iPos < $iPosition ; $iPos++) { $this->next(); } } @@ -324,8 +302,7 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator $this->LoadOriginalIds(); $ret = $this->current(); - if ($ret === false) - { + if ($ret === false) { $ret = null; } $this->next(); @@ -350,22 +327,16 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator $this->LoadOriginalIds(); $iPreservedCount = count($this->aPreserved); - if ($this->iCursor < $iPreservedCount) - { + if ($this->iCursor < $iPreservedCount) { $sId = key($this->aPreserved); $oRet = MetaModel::GetObject($this->sClass, $sId); - } - else - { - $iModifiedCount = count($this->aModified); - if($this->iCursor < $iPreservedCount + $iModifiedCount) - { - $oRet = current($this->aModified); - } - else - { - $oRet = current($this->aAdded); - } + } else { + $iModifiedCount = count($this->aModified); + if ($this->iCursor < $iPreservedCount + $iModifiedCount) { + $oRet = current($this->aModified); + } else { + $oRet = current($this->aAdded); + } } return $oRet; } @@ -384,21 +355,15 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator $this->LoadOriginalIds(); $iPreservedCount = count($this->aPreserved); - if ($this->iCursor < $iPreservedCount) - { + if ($this->iCursor < $iPreservedCount) { next($this->aPreserved); - } - else - { - $iModifiedCount = count($this->aModified); - if($this->iCursor < $iPreservedCount + $iModifiedCount) - { - next($this->aModified); - } - else - { - next($this->aAdded); - } + } else { + $iModifiedCount = count($this->aModified); + if ($this->iCursor < $iPreservedCount + $iModifiedCount) { + next($this->aModified); + } else { + next($this->aAdded); + } } // Increment AFTER moving the internal cursors because when starting aModified / aAdded, we must leave it intact $this->iCursor++; @@ -446,12 +411,12 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator */ public function rewind(): void { - $this->LoadOriginalIds(); + $this->LoadOriginalIds(); - $this->iCursor = 0; + $this->iCursor = 0; reset($this->aPreserved); - reset($this->aAdded); - reset($this->aModified); + reset($this->aAdded); + reset($this->aModified); } /** @@ -473,19 +438,14 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator public function Equals(ormLinkSet $oFellow) { $bRet = null; - if ($this === $oFellow) - { + if ($this === $oFellow) { $bRet = true; - } - else - { - if ( ($this->oOriginalSet !== $oFellow->oOriginalSet) - && ($this->oOriginalSet->GetFilter()->ToOQL() != $oFellow->oOriginalSet->GetFilter()->ToOQL()) ) - { + } else { + if (($this->oOriginalSet !== $oFellow->oOriginalSet) + && ($this->oOriginalSet->GetFilter()->ToOQL() != $oFellow->oOriginalSet->GetFilter()->ToOQL())) { throw new Exception('ormLinkSet::Equals assumes that compared link sets have the same original scope'); } - if ($this->HasDelta()) - { + if ($this->HasDelta()) { throw new Exception('ormLinkSet::Equals assumes that left link set had no delta'); } $bRet = !$oFellow->HasDelta(); @@ -501,16 +461,13 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator */ public function UpdateFromCompleteList(iDBObjectSetIterator $oFellow) { - if ($oFellow === $this) - { + if ($oFellow === $this) { throw new Exception('ormLinkSet::UpdateFromCompleteList assumes that the passed link set is at least a clone of the current one'); } $bUpdateFromDelta = false; - if ($oFellow instanceof ormLinkSet) - { - if ( ($this->oOriginalSet === $oFellow->oOriginalSet) - || ($this->oOriginalSet->GetFilter()->ToOQL() == $oFellow->oOriginalSet->GetFilter()->ToOQL()) ) - { + if ($oFellow instanceof ormLinkSet) { + if (($this->oOriginalSet === $oFellow->oOriginalSet) + || ($this->oOriginalSet->GetFilter()->ToOQL() == $oFellow->oOriginalSet->GetFilter()->ToOQL())) { $bUpdateFromDelta = true; } } else { @@ -526,8 +483,7 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator } } - if ($bUpdateFromDelta) - { + if ($bUpdateFromDelta) { // Same original set -> simply update the delta $this->iCursor = 0; $this->aAdded = $oFellow->aAdded; @@ -535,42 +491,36 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator $this->aModified = $oFellow->aModified; $this->aPreserved = $oFellow->aPreserved; $this->bHasDelta = $oFellow->bHasDelta; - } - else - { + } else { // For backward compatibility reasons, let's rebuild a delta... // Reset the delta $this->iCursor = 0; - $this->aAdded = array(); - $this->aRemoved = array(); - $this->aModified = array(); - $this->aPreserved = ($this->aOriginalObjects === null) ? array() : $this->aOriginalObjects; + $this->aAdded = []; + $this->aRemoved = []; + $this->aModified = []; + $this->aPreserved = ($this->aOriginalObjects === null) ? [] : $this->aOriginalObjects; $this->bHasDelta = false; /** @var \AttributeLinkedSet|\AttributeLinkedSetIndirect $oAttDef */ $oAttDef = MetaModel::GetAttributeDef($this->sHostClass, $this->sAttCode); $sExtKeyToMe = $oAttDef->GetExtKeyToMe(); $sAdditionalKey = null; - if ($oAttDef->IsIndirect() && !$oAttDef->DuplicatesAllowed()) - { + if ($oAttDef->IsIndirect() && !$oAttDef->DuplicatesAllowed()) { $sAdditionalKey = $oAttDef->GetExtKeyToRemote(); } // Compare both collections by iterating the whole sets, order them, a build a fingerprint based on meaningful data (what make the difference) /** @var \DBObject $oLink */ - $oComparator = new DBObjectSetComparator($this, $oFellow, array($sExtKeyToMe), $sAdditionalKey); + $oComparator = new DBObjectSetComparator($this, $oFellow, [$sExtKeyToMe], $sAdditionalKey); $aChanges = $oComparator->GetDifferences(); - foreach ($aChanges['added'] as $oLink) - { + foreach ($aChanges['added'] as $oLink) { $this->AddItem($oLink); } - foreach ($aChanges['modified'] as $oLink) - { + foreach ($aChanges['modified'] as $oLink) { $this->ModifyItem($oLink); } - foreach ($aChanges['removed'] as $oLink) - { + foreach ($aChanges['removed'] as $oLink) { $this->RemoveItem($oLink->GetKey()); } } @@ -586,9 +536,8 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator { $aAdded = $this->aAdded; $aModified = $this->aModified; - $aRemoved = array(); - if (count($this->aRemoved) > 0) - { + $aRemoved = []; + if (count($this->aRemoved) > 0) { $oSearch = new DBObjectSearch($this->sClass); $oSearch->AddCondition('id', $this->aRemoved, 'IN'); $oSet = new DBObjectSet($oSearch); @@ -618,30 +567,23 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator $sExtKeyToMe = $oAttDef->GetExtKeyToMe(); $sExtKeyToRemote = $oAttDef->IsIndirect() ? $oAttDef->GetExtKeyToRemote() : 'n/a'; - $aCheckLinks = array(); - $aCheckRemote = array(); - foreach ($this->aAdded as $oLink) - { - if ($oLink->IsNew()) - { - if ($oAttDef->IsIndirect() && !$oAttDef->DuplicatesAllowed()) - { + $aCheckLinks = []; + $aCheckRemote = []; + foreach ($this->aAdded as $oLink) { + if ($oLink->IsNew()) { + if ($oAttDef->IsIndirect() && !$oAttDef->DuplicatesAllowed()) { //todo: faire un test qui passe dans cette branche ! $aCheckRemote[] = $oLink->Get($sExtKeyToRemote); } - } - else - { + } else { //todo: faire un test qui passe dans cette branche ! $aCheckLinks[] = $oLink->GetKey(); } } - foreach ($this->aRemoved as $iLinkId) - { + foreach ($this->aRemoved as $iLinkId) { $aCheckLinks[] = $iLinkId; } - foreach ($this->aModified as $iLinkId => $oLink) - { + foreach ($this->aModified as $iLinkId => $oLink) { $aCheckLinks[] = $oLink->GetKey(); } @@ -653,11 +595,10 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator // Check for the existing links // /** @var DBObject[] $aExistingLinks */ - $aExistingLinks = array(); + $aExistingLinks = []; /** @var Int[] $aExistingRemote */ - $aExistingRemote = array(); - if (count($aCheckLinks) > 0) - { + $aExistingRemote = []; + if (count($aCheckLinks) > 0) { $oSearch = new DBObjectSearch($this->sClass); $oSearch->AddCondition('id', $aCheckLinks, 'IN'); $oSet = new DBObjectSet($oSearch); @@ -666,8 +607,7 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator // Check for the existing remote objects // - if (count($aCheckRemote) > 0) - { + if (count($aCheckRemote) > 0) { $oSearch = new DBObjectSearch($this->sClass); $oSearch->AddCondition($sExtKeyToMe, $oHostObject->GetKey(), '='); $oSearch->AddCondition($sExtKeyToRemote, $aCheckRemote, 'IN'); @@ -677,33 +617,27 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator // Write the links according to the existing links // - foreach ($this->aAdded as $oLink) - { + foreach ($this->aAdded as $oLink) { // Make sure that the objects in the set point to "this" $oLink->Set($sExtKeyToMe, $oHostObject->GetKey()); - if ($oLink->IsNew()) - { - if (count($aCheckRemote) > 0) - { - $bIsDuplicate = false; - foreach($aExistingRemote as $sLinkKey => $sExtKey) - { - if ($sExtKey == $oLink->Get($sExtKeyToRemote)) - { - // Do not create a duplicate - // + In the case of a remove action followed by an add action - // of an existing link, - // the final state to consider is add action, - // so suppress the entry in the removed list. - if (array_key_exists($sLinkKey, $this->aRemoved)) - { - unset($this->aRemoved[$sLinkKey]); - } - $bIsDuplicate = true; - break; - } - } + if ($oLink->IsNew()) { + if (count($aCheckRemote) > 0) { + $bIsDuplicate = false; + foreach ($aExistingRemote as $sLinkKey => $sExtKey) { + if ($sExtKey == $oLink->Get($sExtKeyToRemote)) { + // Do not create a duplicate + // + In the case of a remove action followed by an add action + // of an existing link, + // the final state to consider is add action, + // so suppress the entry in the removed list. + if (array_key_exists($sLinkKey, $this->aRemoved)) { + unset($this->aRemoved[$sLinkKey]); + } + $bIsDuplicate = true; + break; + } + } if ($bIsDuplicate) { continue; } @@ -781,8 +715,7 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator /** @var \AttributeLinkedSet|\AttributeLinkedSetIndirect $oAttDef */ $oAttDef = MetaModel::GetAttributeDef($this->sHostClass, $this->sAttCode); $oLinkSearch = $this->GetFilter(); - if ($oAttDef->IsIndirect()) - { + if ($oAttDef->IsIndirect()) { $oLinkSearch->RenameAlias($oLinkSearch->GetClassAlias(), self::LINK_ALIAS); $sExtKeyToRemote = $oAttDef->GetExtKeyToRemote(); /** @var \AttributeExternalKey $oLinkingAttDef */ @@ -793,8 +726,7 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator $sTargetClass = $oLinkingAttDef->GetTargetClass(); $oRemoteClassSearch = new DBObjectSearch($sTargetClass, self::REMOTE_ALIAS); - if (!$bShowObsolete && MetaModel::IsObsoletable($sTargetClass)) - { + if (!$bShowObsolete && MetaModel::IsObsoletable($sTargetClass)) { $oNotObsolete = new BinaryExpression( new FieldExpression('obsolescence_flag', self::REMOTE_ALIAS), '=', @@ -803,8 +735,7 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator $oRemoteClassSearch->AddConditionExpression($oNotObsolete); } - if (!utils::IsArchiveMode() && MetaModel::IsArchivable($sTargetClass)) - { + if (!utils::IsArchiveMode() && MetaModel::IsArchivable($sTargetClass)) { $oNotArchived = new BinaryExpression( new FieldExpression('archive_flag', self::REMOTE_ALIAS), '=', @@ -845,7 +776,7 @@ class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator */ public function GetValues() { - $aValues = array(); + $aValues = []; foreach ($this->aPreserved as $sTagCode => $oTag) { $aValues[] = $sTagCode; } diff --git a/core/ormstopwatch.class.inc.php b/core/ormstopwatch.class.inc.php index 2f77667b3..0e4a673a3 100644 --- a/core/ormstopwatch.class.inc.php +++ b/core/ormstopwatch.class.inc.php @@ -1,9 +1,10 @@ iLastStart = $iLastStart; $this->iStopped = $iStopped; - $this->aThresholds = array(); + $this->aThresholds = []; } /** * Necessary for the triggers - */ + */ public function __toString() { return (string) $this->iTimeSpent; @@ -64,12 +64,12 @@ class ormStopWatch public function DefineThreshold($iPercent, $tDeadline = null, $bPassed = false, $bTriggered = false, $iOverrun = null, $aHighlightDef = null) { - $this->aThresholds[$iPercent] = array( + $this->aThresholds[$iPercent] = [ 'deadline' => $tDeadline, // unix time (seconds) 'triggered' => $bTriggered, 'overrun' => $iOverrun, 'highlight' => $aHighlightDef, // array('code' => string, 'persistent' => boolean) - ); + ]; } public function MarkThresholdAsTriggered($iPercent) @@ -94,18 +94,14 @@ class ormStopWatch */ public function GetElapsedTime($oAttDef, $oObject) { - if (is_null($this->iLastStart)) - { + if (is_null($this->iLastStart)) { return $this->GetTimeSpent(); - } - else - { + } else { $iElapsed = $this->ComputeDuration($oObject, $oAttDef, $this->iLastStart, time()); return $this->iTimeSpent + $iElapsed; } } - public function GetStartDate() { return $this->iStarted; @@ -123,39 +119,30 @@ class ormStopWatch public function GetThresholdDate($iPercent) { - if (array_key_exists($iPercent, $this->aThresholds)) - { + if (array_key_exists($iPercent, $this->aThresholds)) { return $this->aThresholds[$iPercent]['deadline']; - } - else - { + } else { return null; } } public function GetOverrun($iPercent) { - if (array_key_exists($iPercent, $this->aThresholds)) - { + if (array_key_exists($iPercent, $this->aThresholds)) { return $this->aThresholds[$iPercent]['overrun']; - } - else - { + } else { return null; } } public function IsThresholdPassed($iPercent) { $bRet = false; - if (array_key_exists($iPercent, $this->aThresholds)) - { + if (array_key_exists($iPercent, $this->aThresholds)) { $aThresholdData = $this->aThresholds[$iPercent]; - if (!is_null($aThresholdData['deadline']) && ($aThresholdData['deadline'] <= time())) - { + if (!is_null($aThresholdData['deadline']) && ($aThresholdData['deadline'] <= time())) { $bRet = true; } - if (isset($aThresholdData['overrun']) && ($aThresholdData['overrun'] > 0)) - { + if (isset($aThresholdData['overrun']) && ($aThresholdData['overrun'] > 0)) { $bRet = true; } } @@ -163,34 +150,27 @@ class ormStopWatch } public function IsThresholdTriggered($iPercent) { - if (array_key_exists($iPercent, $this->aThresholds)) - { + if (array_key_exists($iPercent, $this->aThresholds)) { return $this->aThresholds[$iPercent]['triggered']; - } - else - { + } else { return false; } } - + public function GetHighlightCode() { $sCode = ''; // Process the thresholds in ascending order - $aPercents = array(); - foreach($this->aThresholds as $iPercent => $aDefs) - { + $aPercents = []; + foreach ($this->aThresholds as $iPercent => $aDefs) { $aPercents[] = $iPercent; } sort($aPercents, SORT_NUMERIC); - foreach($aPercents as $iPercent) - { + foreach ($aPercents as $iPercent) { $aDefs = $this->aThresholds[$iPercent]; - if (array_key_exists('highlight', $aDefs) && is_array($aDefs['highlight']) && $this->IsThresholdPassed($iPercent)) - { + if (array_key_exists('highlight', $aDefs) && is_array($aDefs['highlight']) && $this->IsThresholdPassed($iPercent)) { // If persistant or SW running... - if (($aDefs['highlight']['persistent'] == true) || (($aDefs['highlight']['persistent'] == false) && !is_null($this->iLastStart))) - { + if (($aDefs['highlight']['persistent'] == true) || (($aDefs['highlight']['persistent'] == false) && !is_null($this->iLastStart))) { $sCode = $aDefs['highlight']['code']; } } @@ -200,47 +180,37 @@ class ormStopWatch public function GetAsHTML($oAttDef, $oHostObject = null) { - $aProperties = array(); + $aProperties = []; $aProperties['States'] = implode(', ', $oAttDef->GetStates()); - if (is_null($this->iLastStart)) - { - if (is_null($this->iStarted)) - { + if (is_null($this->iLastStart)) { + if (is_null($this->iStarted)) { $aProperties['Elapsed'] = 'never started'; - } - else - { + } else { $aProperties['Elapsed'] = $this->iTimeSpent.' s'; } - } - else - { - $aProperties['Elapsed'] = 'running '; + } else { + $aProperties['Elapsed'] = 'running '; } $aProperties['Started'] = $oAttDef->SecondsToDate($this->iStarted); $aProperties['LastStart'] = $oAttDef->SecondsToDate($this->iLastStart); $aProperties['Stopped'] = $oAttDef->SecondsToDate($this->iStopped); - foreach ($this->aThresholds as $iPercent => $aThresholdData) - { + foreach ($this->aThresholds as $iPercent => $aThresholdData) { $sThresholdDesc = $oAttDef->SecondsToDate($aThresholdData['deadline']); - if ($aThresholdData['triggered']) - { + if ($aThresholdData['triggered']) { $sThresholdDesc .= " TRIGGERED"; } - if ($aThresholdData['overrun']) - { + if ($aThresholdData['overrun']) { $sThresholdDesc .= " Overrun:".(int) $aThresholdData['overrun']." sec."; } $aProperties[$iPercent.'%'] = $sThresholdDesc; } $sRes = "
"; $sRes .= ""; - foreach ($aProperties as $sProperty => $sValue) - { + foreach ($aProperties as $sProperty => $sValue) { $sRes .= ""; $sCell = str_replace("\n", "
\n", $sValue ?? ''); $sRes .= ""; @@ -265,9 +235,8 @@ class ormStopWatch /** @var \iMetricComputer $oComputer */ $oComputer = new $sMetricComputer(); - $aCallSpec = array($oComputer, 'ComputeMetric'); - if (!is_callable($aCallSpec)) - { + $aCallSpec = [$oComputer, 'ComputeMetric']; + if (!is_callable($aCallSpec)) { throw new CoreException("Unknown class/verb '$sMetricComputer/ComputeMetric'"); } @@ -287,14 +256,12 @@ class ormStopWatch protected function ComputeDeadline($oObject, $oAttDef, $iPercent, $iStartTime, $iDurationSec) { $sWorkingTimeComputer = $oAttDef->Get('working_time_computing'); - if ($sWorkingTimeComputer == '') - { + if ($sWorkingTimeComputer == '') { $sWorkingTimeComputer = MetaModel::GetWorkingTime(get_class($oObject)); } $oComputer = new $sWorkingTimeComputer(); - $aCallSpec = array($oComputer, 'GetDeadline'); - if (!is_callable($aCallSpec)) - { + $aCallSpec = [$oComputer, 'GetDeadline']; + if (!is_callable($aCallSpec)) { throw new CoreException("Unknown class/verb '$sWorkingTimeComputer/GetDeadline'"); } // GetDeadline($oObject, $iDuration, DateTime $oStartDate) @@ -316,14 +283,12 @@ class ormStopWatch protected function ComputeDuration($oObject, $oAttDef, $iStartTime, $iEndTime) { $sWorkingTimeComputer = $oAttDef->Get('working_time_computing'); - if ($sWorkingTimeComputer == '') - { + if ($sWorkingTimeComputer == '') { $sWorkingTimeComputer = MetaModel::GetWorkingTime(get_class($oObject)); } $oComputer = new $sWorkingTimeComputer(); - $aCallSpec = array($oComputer, 'GetOpenDuration'); - if (!is_callable($aCallSpec)) - { + $aCallSpec = [$oComputer, 'GetOpenDuration']; + if (!is_callable($aCallSpec)) { throw new CoreException("Unknown class/verb '$sWorkingTimeComputer/GetOpenDuration'"); } // GetOpenDuration($oObject, DateTime $oStartDate, DateTime $oEndDate) @@ -339,14 +304,12 @@ class ormStopWatch $this->iStopped = null; $this->iStarted = null; - foreach ($this->aThresholds as $iPercent => &$aThresholdData) - { + foreach ($this->aThresholds as $iPercent => &$aThresholdData) { $aThresholdData['triggered'] = false; $aThresholdData['overrun'] = null; } - if (!is_null($this->iLastStart)) - { + if (!is_null($this->iLastStart)) { // Currently running... starting again from now! $this->iStarted = time(); $this->iLastStart = time(); @@ -357,23 +320,20 @@ class ormStopWatch /** * Start or continue * It is the responsibility of the caller to compute the deadlines - * (to avoid computing twice for the same result) - */ + * (to avoid computing twice for the same result) + */ public function Start($oObject, $oAttDef, $iNow = null) { - if (!is_null($this->iLastStart)) - { + if (!is_null($this->iLastStart)) { // Already started return false; } - if (is_null($iNow)) - { + if (is_null($iNow)) { $iNow = time(); } - if (is_null($this->iStarted)) - { + if (is_null($this->iStarted)) { $this->iStarted = $iNow; } $this->iLastStart = $iNow; @@ -384,39 +344,31 @@ class ormStopWatch /** * Compute or recompute the goal and threshold deadlines - */ + */ public function ComputeDeadlines($oObject, $oAttDef) { - if (is_null($this->iLastStart)) - { + if (is_null($this->iLastStart)) { // Currently stopped - do nothing return false; } $iDurationGoal = $this->ComputeGoal($oObject, $oAttDef); $iComputationRefTime = time(); - foreach ($this->aThresholds as $iPercent => &$aThresholdData) - { - if (is_null($iDurationGoal)) - { + foreach ($this->aThresholds as $iPercent => &$aThresholdData) { + if (is_null($iDurationGoal)) { // No limit: leave null thresholds $aThresholdData['deadline'] = null; - } - else - { + } else { $iThresholdDuration = round($iPercent * $iDurationGoal / 100); - if (class_exists('WorkingTimeRecorder')) - { + if (class_exists('WorkingTimeRecorder')) { $sClass = get_class($oObject); $sAttCode = $oAttDef->GetCode(); - WorkingTimeRecorder::Start($oObject, $iComputationRefTime, "ormStopWatch-Deadline-$iPercent-$sAttCode", 'Core:ExplainWTC:StopWatch-Deadline', array("Class:$sClass/Attribute:$sAttCode", $iPercent)); + WorkingTimeRecorder::Start($oObject, $iComputationRefTime, "ormStopWatch-Deadline-$iPercent-$sAttCode", 'Core:ExplainWTC:StopWatch-Deadline', ["Class:$sClass/Attribute:$sAttCode", $iPercent]); } $iRemaining = $iThresholdDuration - $this->iTimeSpent; - if ($iRemaining < 0) - { - if (class_exists('WorkingTimeRecorder')) - { + if ($iRemaining < 0) { + if (class_exists('WorkingTimeRecorder')) { $sClass = get_class($oObject); $sKey = $oObject->GetKey(); $sAttCode = $oAttDef->GetCode(); @@ -428,13 +380,11 @@ class ormStopWatch $aThresholdData['deadline'] = $this->ComputeDeadline($oObject, $oAttDef, $iPercent, $this->iLastStart, $iRemaining); // OR $aThresholdData['deadline'] = $this->ComputeDeadline($oObject, $oAttDef, $iPercent, $this->iStarted, $iThresholdDuration); - if (class_exists('WorkingTimeRecorder')) - { + if (class_exists('WorkingTimeRecorder')) { WorkingTimeRecorder::End(); } } - if (is_null($aThresholdData['deadline']) || ($aThresholdData['deadline'] > time())) - { + if (is_null($aThresholdData['deadline']) || ($aThresholdData['deadline'] > time())) { // The threshold is in the future, reset $aThresholdData['triggered'] = false; $aThresholdData['overrun'] = null; @@ -452,51 +402,41 @@ class ormStopWatch /** * Stop counting if not already done - */ + */ public function Stop($oObject, $oAttDef, $iNow = null) { - if (is_null($this->iLastStart)) - { + if (is_null($this->iLastStart)) { // Already stopped return false; } - if (is_null($iNow)) - { + if (is_null($iNow)) { $iNow = time(); } - if (class_exists('WorkingTimeRecorder')) - { + if (class_exists('WorkingTimeRecorder')) { $sClass = get_class($oObject); $sAttCode = $oAttDef->GetCode(); - WorkingTimeRecorder::Start($oObject, $iNow, "ormStopWatch-TimeSpent-$sAttCode", 'Core:ExplainWTC:StopWatch-TimeSpent', array("Class:$sClass/Attribute:$sAttCode"), true /*cumulative*/); + WorkingTimeRecorder::Start($oObject, $iNow, "ormStopWatch-TimeSpent-$sAttCode", 'Core:ExplainWTC:StopWatch-TimeSpent', ["Class:$sClass/Attribute:$sAttCode"], true /*cumulative*/); } $iElapsed = $this->ComputeDuration($oObject, $oAttDef, $this->iLastStart, $iNow); $this->iTimeSpent = $this->iTimeSpent + $iElapsed; - if (class_exists('WorkingTimeRecorder')) - { + if (class_exists('WorkingTimeRecorder')) { WorkingTimeRecorder::End(); } - foreach ($this->aThresholds as $iPercent => &$aThresholdData) - { - if (!is_null($aThresholdData['deadline']) && ($iNow > $aThresholdData['deadline'])) - { - if ($aThresholdData['overrun'] > 0) - { + foreach ($this->aThresholds as $iPercent => &$aThresholdData) { + if (!is_null($aThresholdData['deadline']) && ($iNow > $aThresholdData['deadline'])) { + if ($aThresholdData['overrun'] > 0) { // Accumulate from last start $aThresholdData['overrun'] += $iElapsed; - } - else - { + } else { // First stop after the deadline has been passed $iOverrun = $this->ComputeDuration($oObject, $oAttDef, $aThresholdData['deadline'], $iNow); $aThresholdData['overrun'] = $iOverrun; } } - if ($aThresholdData['overrun'] == 0) - { + if ($aThresholdData['overrun'] == 0) { $aThresholdData['deadline'] = null; } } @@ -510,76 +450,65 @@ class ormStopWatch /** * CheckStopWatchThresholds - * Implements the automatic actions + * Implements the automatic actions * * @package itopORM */ class CheckStopWatchThresholds implements iBackgroundProcess { public function GetPeriodicity() - { + { return 10; // seconds } public function Process($iTimeLimit) { - $aList = array(); - foreach (MetaModel::GetClasses() as $sClass) - { - foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) - { - if ($oAttDef instanceof AttributeStopWatch) - { - foreach ($oAttDef->ListThresholds() as $iThreshold => $aThresholdData) - { + $aList = []; + foreach (MetaModel::GetClasses() as $sClass) { + foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) { + if ($oAttDef instanceof AttributeStopWatch) { + foreach ($oAttDef->ListThresholds() as $iThreshold => $aThresholdData) { $iPercent = $aThresholdData['percent']; // could be different than the index ! - + $sNow = date(AttributeDateTime::GetSQLFormat()); $sExpression = "SELECT $sClass WHERE {$sAttCode}_laststart AND {$sAttCode}_{$iThreshold}_triggered = 0 AND {$sAttCode}_{$iThreshold}_deadline < :now"; $oFilter = DBObjectSearch::FromOQL($sExpression); - $oSet = new DBObjectSet($oFilter, array(), array('now' => $sNow)); - $oSet->OptimizeColumnLoad(array($sClass => array($sAttCode))); - while ((time() < $iTimeLimit) && ($oObj = $oSet->Fetch())) - { + $oSet = new DBObjectSet($oFilter, [], ['now' => $sNow]); + $oSet->OptimizeColumnLoad([$sClass => [$sAttCode]]); + while ((time() < $iTimeLimit) && ($oObj = $oSet->Fetch())) { $sClass = get_class($oObj); $aList[] = $sClass.'::'.$oObj->GetKey().' '.$sAttCode.' '.$iThreshold; // Execute planned actions // - foreach ($aThresholdData['actions'] as $aActionData) - { + foreach ($aThresholdData['actions'] as $aActionData) { $sVerb = $aActionData['verb']; $aParams = $aActionData['params']; - $aValues = array(); - foreach($aParams as $def) - { - if (is_string($def)) - { + $aValues = []; + foreach ($aParams as $def) { + if (is_string($def)) { // Old method (pre-2.1.0) non typed parameters $aValues[] = $def; - } - else // if(is_array($def)) - { + } else { // if(is_array($def)) $sParamType = array_key_exists('type', $def) ? $def['type'] : 'string'; - switch($sParamType) - { + switch ($sParamType) { case 'int': $value = (int)$def['value']; break; - + case 'float': $value = (float)$def['value']; break; - + case 'bool': $value = (bool)$def['value']; break; - + case 'reference': $value = ${$def['value']}; break; - + case 'string': default: $value = (string)$def['value']; @@ -587,7 +516,7 @@ class CheckStopWatchThresholds implements iBackgroundProcess $aValues[] = $value; } } - $aCallSpec = array($oObj, $sVerb); + $aCallSpec = [$oObj, $sVerb]; call_user_func_array($aCallSpec, $aValues); } @@ -604,22 +533,18 @@ class CheckStopWatchThresholds implements iBackgroundProcess } // Activate any existing trigger - // + // $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL)); $oTriggerSet = new DBObjectSet( DBObjectSearch::FromOQL("SELECT TriggerOnThresholdReached AS t WHERE t.target_class IN ('$sClassList') AND stop_watch_code MATCHES :stop_watch_code AND threshold_index = :threshold_index"), - array(), // order by - array('stop_watch_code' => $sAttCode, 'threshold_index' => $iThreshold) + [], // order by + ['stop_watch_code' => $sAttCode, 'threshold_index' => $iThreshold] ); - while ($oTrigger = $oTriggerSet->Fetch()) - { - try - { + while ($oTrigger = $oTriggerSet->Fetch()) { + try { $oTrigger->DoActivate($oObj->ToArgs('this')); - } - catch(Exception $e) - { + } catch (Exception $e) { utils::EnrichRaisedException($oTrigger, $e); } } diff --git a/core/restservices.class.inc.php b/core/restservices.class.inc.php index 76661e3d9..02bf355f8 100644 --- a/core/restservices.class.inc.php +++ b/core/restservices.class.inc.php @@ -1,9 +1,10 @@ message = ''; $this->class = $sClass; $this->key = $iId; - $this->fields = array(); + $this->fields = []; } /** @@ -84,36 +85,32 @@ class ObjectResult * @param boolean $bExtendedOutput Output all of the link set attributes ? * @param integer $iCode An error code (RestResult::OK is no issue has been found) * @param string $sMessage Description of the error if any, an empty string otherwise - * + * * @return ObjectResult */ - public static function FromDBObject(DBObject $oObj, ?array $aFieldSpec = null, $bExtendedOutput = false, $iCode = 0, $sMessage = '') : ObjectResult { + public static function FromDBObject(DBObject $oObj, ?array $aFieldSpec = null, $bExtendedOutput = false, $iCode = 0, $sMessage = ''): ObjectResult + { $oObjRes = new ObjectResult($oObj::class, $oObj->GetKey()); $oObjRes->code = $iCode; $oObjRes->message = $sMessage; $aFields = null; - if (!is_null($aFieldSpec)) - { + if (!is_null($aFieldSpec)) { // Enum all classes in the hierarchy, starting with the current one - foreach (MetaModel::EnumParentClasses($oObj::class, ENUM_PARENT_CLASSES_ALL, false) as $sRefClass) - { - if (array_key_exists($sRefClass, $aFieldSpec)) - { + foreach (MetaModel::EnumParentClasses($oObj::class, ENUM_PARENT_CLASSES_ALL, false) as $sRefClass) { + if (array_key_exists($sRefClass, $aFieldSpec)) { $aFields = $aFieldSpec[$sRefClass]; break; } } } - if (is_null($aFields)) - { + if (is_null($aFields)) { // No fieldspec given, or not found... - $aFields = array('id', 'friendlyname'); + $aFields = ['id', 'friendlyname']; } - foreach ($aFields as $sAttCode) - { + foreach ($aFields as $sAttCode) { $oObjRes->AddField($oObj, $sAttCode, $bExtendedOutput); } @@ -121,7 +118,6 @@ class ObjectResult } - /** * Helper to make an output value for a given attribute * @@ -138,48 +134,37 @@ class ObjectResult */ protected function MakeResultValue(DBObject $oObject, $sAttCode, $bExtendedOutput = false) { - if ($sAttCode == 'id') - { + if ($sAttCode == 'id') { $value = $oObject->GetKey(); - } - else - { + } else { $sClass = get_class($oObject); $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode); - if ($oAttDef instanceof AttributeLinkedSet) - { + if ($oAttDef instanceof AttributeLinkedSet) { // Iterate on the set and build an array of array of attcode=>value $oSet = $oObject->Get($sAttCode); - $value = array(); - while ($oLnk = $oSet->Fetch()) - { + $value = []; + while ($oLnk = $oSet->Fetch()) { $sLnkRefClass = $bExtendedOutput ? get_class($oLnk) : $oAttDef->GetLinkedClass(); - $aLnkValues = array(); - foreach (MetaModel::ListAttributeDefs($sLnkRefClass) as $sLnkAttCode => $oLnkAttDef) - { + $aLnkValues = []; + foreach (MetaModel::ListAttributeDefs($sLnkRefClass) as $sLnkAttCode => $oLnkAttDef) { // Skip attributes pointing to the current object (redundant data) - if ($sLnkAttCode == $oAttDef->GetExtKeyToMe()) - { + if ($sLnkAttCode == $oAttDef->GetExtKeyToMe()) { continue; } // Skip any attribute of the link that points to the current object $oLnkAttDef = MetaModel::GetAttributeDef($sLnkRefClass, $sLnkAttCode); - if (method_exists($oLnkAttDef, 'GetKeyAttCode')) - { - if ($oLnkAttDef->GetKeyAttCode() == $oAttDef->GetExtKeyToMe()) - { + if (method_exists($oLnkAttDef, 'GetKeyAttCode')) { + if ($oLnkAttDef->GetKeyAttCode() == $oAttDef->GetExtKeyToMe()) { continue; } } - + $aLnkValues[$sLnkAttCode] = $this->MakeResultValue($oLnk, $sLnkAttCode, $bExtendedOutput); } $value[] = $aLnkValues; } - } - else - { + } else { $value = $oAttDef->GetForJSON($oObject->Get($sAttCode)); } } @@ -207,19 +192,17 @@ class ObjectResult public function SanitizeContent() { - foreach($this->fields as $sFieldAttCode => $fieldValue) { - try { - $oAttDef = MetaModel::GetAttributeDef($this->class, $sFieldAttCode); - } catch (Exception $e) { // for special cases like ID - continue; - } + foreach ($this->fields as $sFieldAttCode => $fieldValue) { + try { + $oAttDef = MetaModel::GetAttributeDef($this->class, $sFieldAttCode); + } catch (Exception $e) { // for special cases like ID + continue; + } $this->SanitizeFieldIfSensitive($this->fields, $sFieldAttCode, $fieldValue, $oAttDef); } } } - - /** * REST response for services managing objects. Derive this structure to add information and/or constants * @@ -255,12 +238,11 @@ class RestResultWithObjects extends RestResult $this->objects[$sObjKey] = $oObjRes; } -public function SanitizeContent() + public function SanitizeContent() { parent::SanitizeContent(); - foreach($this->objects as $sObjKey => $oObjRes) - { + foreach ($this->objects as $sObjKey => $oObjRes) { $oObjRes->SanitizeContent(); } } @@ -280,7 +262,7 @@ class RestResultWithRelations extends RestResultWithObjects public function __construct() { parent::__construct(); - $this->relations = array(); + $this->relations = []; } /** @@ -292,11 +274,10 @@ class RestResultWithRelations extends RestResultWithObjects */ public function AddRelation($sSrcKey, $sDestKey) { - if (!array_key_exists($sSrcKey, $this->relations)) - { - $this->relations[$sSrcKey] = array(); + if (!array_key_exists($sSrcKey, $this->relations)) { + $this->relations[$sSrcKey] = []; } - $this->relations[$sSrcKey][] = array('key' => $sDestKey); + $this->relations[$sSrcKey][] = ['key' => $sDestKey]; } } @@ -305,7 +286,7 @@ class RestResultWithRelations extends RestResultWithObjects * * @package RESTAPI * @api - * @since 2.0.1 + * @since 2.0.1 */ class RestDelete { @@ -313,37 +294,37 @@ class RestDelete * Result: Object deleted as per the initial request * @api */ - const OK = 0; + public const OK = 0; /** * Result: general issue (user rights or ... ?) * @api */ - const ISSUE = 1; + public const ISSUE = 1; /** * Result: Must be deleted to preserve database integrity * @api */ - const AUTO_DELETE = 2; + public const AUTO_DELETE = 2; /** * Result: Must be deleted to preserve database integrity, but that is NOT possible * @api */ - const AUTO_DELETE_ISSUE = 3; + public const AUTO_DELETE_ISSUE = 3; /** * Result: Must be deleted to preserve database integrity, but this must be requested explicitly * @api */ - const REQUEST_EXPLICITELY = 4; + public const REQUEST_EXPLICITELY = 4; /** * Result: Must be updated to preserve database integrity * @api */ - const AUTO_UPDATE = 5; + public const AUTO_UPDATE = 5; /** * Result: Must be updated to preserve database integrity, but that is NOT possible * @api */ - const AUTO_UPDATE_ISSUE = 6; + public const AUTO_UPDATE_ISSUE = 6; } /** @@ -353,10 +334,10 @@ class RestDelete */ class CoreServices implements iRestServiceProvider, iRestInputSanitizer { - use SanitizeTrait; - /** + use SanitizeTrait; + /** * Enumerate services delivered by this class - * + * * @param string $sVersion The version (e.g. 1.0) supported by the services * @return array An array of hash 'verb' => verb, 'description' => description */ @@ -368,37 +349,36 @@ class CoreServices implements iRestServiceProvider, iRestInputSanitizer // 1.1 - In the reply, objects have a 'key' entry so that it is no more necessary to split class::key programmaticaly // 1.0 - Initial implementation in iTop 2.0.1 // - $aOps = array(); - if (in_array($sVersion, array('1.0', '1.1', '1.2', '1.3', '1.4'))) - { - $aOps[] = array( + $aOps = []; + if (in_array($sVersion, ['1.0', '1.1', '1.2', '1.3', '1.4'])) { + $aOps[] = [ 'verb' => 'core/create', - 'description' => 'Create an object' - ); - $aOps[] = array( + 'description' => 'Create an object', + ]; + $aOps[] = [ 'verb' => 'core/update', - 'description' => 'Update an object' - ); - $aOps[] = array( + 'description' => 'Update an object', + ]; + $aOps[] = [ 'verb' => 'core/apply_stimulus', - 'description' => 'Apply a stimulus to change the state of an object' - ); - $aOps[] = array( + 'description' => 'Apply a stimulus to change the state of an object', + ]; + $aOps[] = [ 'verb' => 'core/get', - 'description' => 'Search for objects' - ); - $aOps[] = array( + 'description' => 'Search for objects', + ]; + $aOps[] = [ 'verb' => 'core/delete', - 'description' => 'Delete objects' - ); - $aOps[] = array( + 'description' => 'Delete objects', + ]; + $aOps[] = [ 'verb' => 'core/get_related', - 'description' => 'Get related objects through the specified relation' - ); - $aOps[] = array( + 'description' => 'Get related objects through the specified relation', + ]; + $aOps[] = [ 'verb' => 'core/check_credentials', - 'description' => 'Check user credentials' - ); + 'description' => 'Check user credentials', + ]; } return $aOps; } @@ -419,457 +399,355 @@ class CoreServices implements iRestServiceProvider, iRestInputSanitizer public function ExecOperation($sVersion, $sVerb, $aParams) { $oResult = new RestResultWithObjects(); - switch ($sVerb) - { - case 'core/create': - RestUtils::InitTrackingComment($aParams); - $sClass = RestUtils::GetClass($aParams, 'class'); - $aFields = RestUtils::GetMandatoryParam($aParams, 'fields'); - $aShowFields = RestUtils::GetFieldList($sClass, $aParams, 'output_fields'); - $bExtendedOutput = (RestUtils::GetOptionalParam($aParams, 'output_fields', '*') == '*+'); + switch ($sVerb) { + case 'core/create': + RestUtils::InitTrackingComment($aParams); + $sClass = RestUtils::GetClass($aParams, 'class'); + $aFields = RestUtils::GetMandatoryParam($aParams, 'fields'); + $aShowFields = RestUtils::GetFieldList($sClass, $aParams, 'output_fields'); + $bExtendedOutput = (RestUtils::GetOptionalParam($aParams, 'output_fields', '*') == '*+'); - if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) != UR_ALLOWED_YES) - { - $oResult->code = RestResult::UNAUTHORIZED; - $oResult->message = "The current user does not have enough permissions for creating data of class $sClass"; - } - elseif (UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_MODIFY) != UR_ALLOWED_YES) - { - $oResult->code = RestResult::UNAUTHORIZED; - $oResult->message = "The current user does not have enough permissions for massively creating data of class $sClass"; - } - else - { - $oObject = RestUtils::MakeObjectFromFields($sClass, $aFields); - $oObject->DBInsert(); - $oResult->AddObject(0, 'created', $oObject, $aShowFields, $bExtendedOutput); - } - break; - - case 'core/update': - RestUtils::InitTrackingComment($aParams); - $sClass = RestUtils::GetClass($aParams, 'class'); - $key = RestUtils::GetMandatoryParam($aParams, 'key'); - $aFields = RestUtils::GetMandatoryParam($aParams, 'fields'); - $aShowFields = RestUtils::GetFieldList($sClass, $aParams, 'output_fields'); - $bExtendedOutput = (RestUtils::GetOptionalParam($aParams, 'output_fields', '*') == '*+'); - - // Note: the target class cannot be based on the result of FindObjectFromKey, because in case the user does not have read access, that function already fails with msg 'Nothing found' - $sTargetClass = RestUtils::GetObjectSetFromKey($sClass, $key)->GetFilter()->GetClass(); - if (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_MODIFY) != UR_ALLOWED_YES) - { - $oResult->code = RestResult::UNAUTHORIZED; - $oResult->message = "The current user does not have enough permissions for modifying data of class $sTargetClass"; - } - elseif (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_MODIFY) != UR_ALLOWED_YES) - { - $oResult->code = RestResult::UNAUTHORIZED; - $oResult->message = "The current user does not have enough permissions for massively modifying data of class $sTargetClass"; - } - else - { - $oObject = RestUtils::FindObjectFromKey($sClass, $key); - RestUtils::UpdateObjectFromFields($oObject, $aFields); - $oObject->DBUpdate(); - $oResult->AddObject(0, 'updated', $oObject, $aShowFields, $bExtendedOutput); - } - break; - - case 'core/apply_stimulus': - RestUtils::InitTrackingComment($aParams); - $sClass = RestUtils::GetClass($aParams, 'class'); - $key = RestUtils::GetMandatoryParam($aParams, 'key'); - $aFields = RestUtils::GetMandatoryParam($aParams, 'fields'); - $aShowFields = RestUtils::GetFieldList($sClass, $aParams, 'output_fields'); - $bExtendedOutput = (RestUtils::GetOptionalParam($aParams, 'output_fields', '*') == '*+'); - $sStimulus = RestUtils::GetMandatoryParam($aParams, 'stimulus'); - - // Note: the target class cannot be based on the result of FindObjectFromKey, because in case the user does not have read access, that function already fails with msg 'Nothing found' - $sTargetClass = RestUtils::GetObjectSetFromKey($sClass, $key)->GetFilter()->GetClass(); - if (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_MODIFY) != UR_ALLOWED_YES) - { - $oResult->code = RestResult::UNAUTHORIZED; - $oResult->message = "The current user does not have enough permissions for modifying data of class $sTargetClass"; - } - elseif (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_BULK_MODIFY) != UR_ALLOWED_YES) - { - $oResult->code = RestResult::UNAUTHORIZED; - $oResult->message = "The current user does not have enough permissions for massively modifying data of class $sTargetClass"; - } - else - { - $oObject = RestUtils::FindObjectFromKey($sClass, $key); - RestUtils::UpdateObjectFromFields($oObject, $aFields); - - $aTransitions = $oObject->EnumTransitions(); - $aStimuli = MetaModel::EnumStimuli(get_class($oObject)); - if (!isset($aTransitions[$sStimulus])) - { - // Invalid stimulus - $oResult->code = RestResult::INTERNAL_ERROR; - $oResult->message = "Invalid stimulus: '$sStimulus' on the object ".$oObject->GetName()." in state '".$oObject->GetState()."'"; + if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) != UR_ALLOWED_YES) { + $oResult->code = RestResult::UNAUTHORIZED; + $oResult->message = "The current user does not have enough permissions for creating data of class $sClass"; + } elseif (UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_MODIFY) != UR_ALLOWED_YES) { + $oResult->code = RestResult::UNAUTHORIZED; + $oResult->message = "The current user does not have enough permissions for massively creating data of class $sClass"; + } else { + $oObject = RestUtils::MakeObjectFromFields($sClass, $aFields); + $oObject->DBInsert(); + $oResult->AddObject(0, 'created', $oObject, $aShowFields, $bExtendedOutput); } - else - { - $aTransition = $aTransitions[$sStimulus]; - $sTargetState = $aTransition['target_state']; - $aStates = MetaModel::EnumStates($sClass); - $aTargetStateDef = $aStates[$sTargetState]; - $aExpectedAttributes = $aTargetStateDef['attribute_list']; - - $aMissingMandatory = array(); - foreach($aExpectedAttributes as $sAttCode => $iExpectCode) - { - if ( ($iExpectCode & OPT_ATT_MANDATORY) && ($oObject->Get($sAttCode) == '')) - { - $aMissingMandatory[] = $sAttCode; - } - } - if (count($aMissingMandatory) == 0) - { - // If all the mandatory fields are already present, just apply the transition silently... - if ($oObject->ApplyStimulus($sStimulus)) - { - $oObject->DBUpdate(); - $oResult->AddObject(0, 'updated', $oObject, $aShowFields, $bExtendedOutput); - } - } - else - { - // Missing mandatory attributes for the transition + break; + + case 'core/update': + RestUtils::InitTrackingComment($aParams); + $sClass = RestUtils::GetClass($aParams, 'class'); + $key = RestUtils::GetMandatoryParam($aParams, 'key'); + $aFields = RestUtils::GetMandatoryParam($aParams, 'fields'); + $aShowFields = RestUtils::GetFieldList($sClass, $aParams, 'output_fields'); + $bExtendedOutput = (RestUtils::GetOptionalParam($aParams, 'output_fields', '*') == '*+'); + + // Note: the target class cannot be based on the result of FindObjectFromKey, because in case the user does not have read access, that function already fails with msg 'Nothing found' + $sTargetClass = RestUtils::GetObjectSetFromKey($sClass, $key)->GetFilter()->GetClass(); + if (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_MODIFY) != UR_ALLOWED_YES) { + $oResult->code = RestResult::UNAUTHORIZED; + $oResult->message = "The current user does not have enough permissions for modifying data of class $sTargetClass"; + } elseif (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_MODIFY) != UR_ALLOWED_YES) { + $oResult->code = RestResult::UNAUTHORIZED; + $oResult->message = "The current user does not have enough permissions for massively modifying data of class $sTargetClass"; + } else { + $oObject = RestUtils::FindObjectFromKey($sClass, $key); + RestUtils::UpdateObjectFromFields($oObject, $aFields); + $oObject->DBUpdate(); + $oResult->AddObject(0, 'updated', $oObject, $aShowFields, $bExtendedOutput); + } + break; + + case 'core/apply_stimulus': + RestUtils::InitTrackingComment($aParams); + $sClass = RestUtils::GetClass($aParams, 'class'); + $key = RestUtils::GetMandatoryParam($aParams, 'key'); + $aFields = RestUtils::GetMandatoryParam($aParams, 'fields'); + $aShowFields = RestUtils::GetFieldList($sClass, $aParams, 'output_fields'); + $bExtendedOutput = (RestUtils::GetOptionalParam($aParams, 'output_fields', '*') == '*+'); + $sStimulus = RestUtils::GetMandatoryParam($aParams, 'stimulus'); + + // Note: the target class cannot be based on the result of FindObjectFromKey, because in case the user does not have read access, that function already fails with msg 'Nothing found' + $sTargetClass = RestUtils::GetObjectSetFromKey($sClass, $key)->GetFilter()->GetClass(); + if (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_MODIFY) != UR_ALLOWED_YES) { + $oResult->code = RestResult::UNAUTHORIZED; + $oResult->message = "The current user does not have enough permissions for modifying data of class $sTargetClass"; + } elseif (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_BULK_MODIFY) != UR_ALLOWED_YES) { + $oResult->code = RestResult::UNAUTHORIZED; + $oResult->message = "The current user does not have enough permissions for massively modifying data of class $sTargetClass"; + } else { + $oObject = RestUtils::FindObjectFromKey($sClass, $key); + RestUtils::UpdateObjectFromFields($oObject, $aFields); + + $aTransitions = $oObject->EnumTransitions(); + $aStimuli = MetaModel::EnumStimuli(get_class($oObject)); + if (!isset($aTransitions[$sStimulus])) { + // Invalid stimulus $oResult->code = RestResult::INTERNAL_ERROR; - $oResult->message = 'Missing mandatory attribute(s) for applying the stimulus: '.implode(', ', $aMissingMandatory).'.'; + $oResult->message = "Invalid stimulus: '$sStimulus' on the object ".$oObject->GetName()." in state '".$oObject->GetState()."'"; + } else { + $aTransition = $aTransitions[$sStimulus]; + $sTargetState = $aTransition['target_state']; + $aStates = MetaModel::EnumStates($sClass); + $aTargetStateDef = $aStates[$sTargetState]; + $aExpectedAttributes = $aTargetStateDef['attribute_list']; + + $aMissingMandatory = []; + foreach ($aExpectedAttributes as $sAttCode => $iExpectCode) { + if (($iExpectCode & OPT_ATT_MANDATORY) && ($oObject->Get($sAttCode) == '')) { + $aMissingMandatory[] = $sAttCode; + } + } + if (count($aMissingMandatory) == 0) { + // If all the mandatory fields are already present, just apply the transition silently... + if ($oObject->ApplyStimulus($sStimulus)) { + $oObject->DBUpdate(); + $oResult->AddObject(0, 'updated', $oObject, $aShowFields, $bExtendedOutput); + } + } else { + // Missing mandatory attributes for the transition + $oResult->code = RestResult::INTERNAL_ERROR; + $oResult->message = 'Missing mandatory attribute(s) for applying the stimulus: '.implode(', ', $aMissingMandatory).'.'; + } } } - } - break; - - case 'core/get': - $sClass = RestUtils::GetClass($aParams, 'class'); - $key = RestUtils::GetMandatoryParam($aParams, 'key'); - $aShowFields = RestUtils::GetFieldList($sClass, $aParams, 'output_fields'); - $bExtendedOutput = (RestUtils::GetOptionalParam($aParams, 'output_fields', '*') == '*+'); - $iLimit = (int)RestUtils::GetOptionalParam($aParams, 'limit', 0); - $iPage = (int)RestUtils::GetOptionalParam($aParams, 'page', 1); + break; - $oObjectSet = RestUtils::GetObjectSetFromKey($sClass, $key, $iLimit, self::getOffsetFromLimitAndPage($iLimit, $iPage)); - $sTargetClass = $oObjectSet->GetFilter()->GetClass(); - - if (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_READ) != UR_ALLOWED_YES) - { - $oResult->code = RestResult::UNAUTHORIZED; - $oResult->message = "The current user does not have enough permissions for reading data of class $sTargetClass"; - } - elseif (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_BULK_READ) != UR_ALLOWED_YES) - { - $oResult->code = RestResult::UNAUTHORIZED; - $oResult->message = "The current user does not have enough permissions for exporting data of class $sTargetClass"; - } - elseif ($iPage < 1) - { - $oResult->code = RestResult::INVALID_PAGE; - $oResult->message = "The request page number is not valid. It must be an integer greater than 0"; - } - else - { - if (!$bExtendedOutput && RestUtils::GetOptionalParam($aParams, 'output_fields', '*') != '*') - { - $aFields = $aShowFields[$sClass]; - //Id is not a valid attribute to optimize - if (in_array('id', $aFields)) - { - unset($aFields[array_search('id', $aFields)]); - } - $aAttToLoad = array($oObjectSet->GetClassAlias() => $aFields); - $oObjectSet->OptimizeColumnLoad($aAttToLoad); - } + case 'core/get': + $sClass = RestUtils::GetClass($aParams, 'class'); + $key = RestUtils::GetMandatoryParam($aParams, 'key'); + $aShowFields = RestUtils::GetFieldList($sClass, $aParams, 'output_fields'); + $bExtendedOutput = (RestUtils::GetOptionalParam($aParams, 'output_fields', '*') == '*+'); + $iLimit = (int)RestUtils::GetOptionalParam($aParams, 'limit', 0); + $iPage = (int)RestUtils::GetOptionalParam($aParams, 'page', 1); - while ($oObject = $oObjectSet->Fetch()) - { - $oResult->AddObject(0, '', $oObject, $aShowFields, $bExtendedOutput); + $oObjectSet = RestUtils::GetObjectSetFromKey($sClass, $key, $iLimit, self::getOffsetFromLimitAndPage($iLimit, $iPage)); + $sTargetClass = $oObjectSet->GetFilter()->GetClass(); + + if (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_READ) != UR_ALLOWED_YES) { + $oResult->code = RestResult::UNAUTHORIZED; + $oResult->message = "The current user does not have enough permissions for reading data of class $sTargetClass"; + } elseif (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_BULK_READ) != UR_ALLOWED_YES) { + $oResult->code = RestResult::UNAUTHORIZED; + $oResult->message = "The current user does not have enough permissions for exporting data of class $sTargetClass"; + } elseif ($iPage < 1) { + $oResult->code = RestResult::INVALID_PAGE; + $oResult->message = "The request page number is not valid. It must be an integer greater than 0"; + } else { + if (!$bExtendedOutput && RestUtils::GetOptionalParam($aParams, 'output_fields', '*') != '*') { + $aFields = $aShowFields[$sClass]; + //Id is not a valid attribute to optimize + if (in_array('id', $aFields)) { + unset($aFields[array_search('id', $aFields)]); + } + $aAttToLoad = [$oObjectSet->GetClassAlias() => $aFields]; + $oObjectSet->OptimizeColumnLoad($aAttToLoad); + } + + while ($oObject = $oObjectSet->Fetch()) { + $oResult->AddObject(0, '', $oObject, $aShowFields, $bExtendedOutput); + } + $oResult->message = "Found: ".$oObjectSet->Count(); } - $oResult->message = "Found: ".$oObjectSet->Count(); - } - break; + break; - case 'core/delete': - RestUtils::InitTrackingComment($aParams); - $sClass = RestUtils::GetClass($aParams, 'class'); - $key = RestUtils::GetMandatoryParam($aParams, 'key'); - $bSimulate = RestUtils::GetOptionalParam($aParams, 'simulate', false); - - $oObjectSet = RestUtils::GetObjectSetFromKey($sClass, $key); - $sTargetClass = $oObjectSet->GetFilter()->GetClass(); - - if (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_DELETE) != UR_ALLOWED_YES) - { - $oResult->code = RestResult::UNAUTHORIZED; - $oResult->message = "The current user does not have enough permissions for deleting data of class $sTargetClass"; - } - elseif (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_DELETE) != UR_ALLOWED_YES) - { - $oResult->code = RestResult::UNAUTHORIZED; - $oResult->message = "The current user does not have enough permissions for massively deleting data of class $sTargetClass"; - } - else - { - $aObjects = $oObjectSet->ToArray(); - $this->DeleteObjects($oResult, $aObjects, $bSimulate); - } - break; + case 'core/delete': + RestUtils::InitTrackingComment($aParams); + $sClass = RestUtils::GetClass($aParams, 'class'); + $key = RestUtils::GetMandatoryParam($aParams, 'key'); + $bSimulate = RestUtils::GetOptionalParam($aParams, 'simulate', false); - case 'core/get_related': - $oResult = new RestResultWithRelations(); - $sClass = RestUtils::GetClass($aParams, 'class'); - $key = RestUtils::GetMandatoryParam($aParams, 'key'); - $sRelation = RestUtils::GetMandatoryParam($aParams, 'relation'); - $iMaxRecursionDepth = RestUtils::GetOptionalParam($aParams, 'depth', 20 /* = MAX_RECURSION_DEPTH */); - $sDirection = RestUtils::GetOptionalParam($aParams, 'direction', null); - $bEnableRedundancy = RestUtils::GetOptionalParam($aParams, 'redundancy', false); - $bReverse = false; + $oObjectSet = RestUtils::GetObjectSetFromKey($sClass, $key); + $sTargetClass = $oObjectSet->GetFilter()->GetClass(); - if (is_null($sDirection) && ($sRelation == 'depends on')) - { - // Legacy behavior, consider "depends on" as a forward relation - $sRelation = 'impacts'; - $sDirection = 'up'; - $bReverse = true; // emulate the legacy behavior by returning the edges - } - else if(is_null($sDirection)) - { - $sDirection = 'down'; - } - - $oObjectSet = RestUtils::GetObjectSetFromKey($sClass, $key); - if ($sDirection == 'down') - { - $oRelationGraph = $oObjectSet->GetRelatedObjectsDown($sRelation, $iMaxRecursionDepth, $bEnableRedundancy); - } - else if ($sDirection == 'up') - { - $oRelationGraph = $oObjectSet->GetRelatedObjectsUp($sRelation, $iMaxRecursionDepth, $bEnableRedundancy); - } - else - { - $oResult->code = RestResult::INTERNAL_ERROR; - $oResult->message = "Invalid value: '$sDirection' for the parameter 'direction'. Valid values are 'up' and 'down'"; - return $oResult; - - } - - if ($bEnableRedundancy) - { - // Remove the redundancy nodes from the output - $oIterator = new RelationTypeIterator($oRelationGraph, 'Node'); - foreach($oIterator as $oNode) - { - if ($oNode instanceof RelationRedundancyNode) - { - $oRelationGraph->FilterNode($oNode); + if (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_DELETE) != UR_ALLOWED_YES) { + $oResult->code = RestResult::UNAUTHORIZED; + $oResult->message = "The current user does not have enough permissions for deleting data of class $sTargetClass"; + } elseif (UserRights::IsActionAllowed($sTargetClass, UR_ACTION_DELETE) != UR_ALLOWED_YES) { + $oResult->code = RestResult::UNAUTHORIZED; + $oResult->message = "The current user does not have enough permissions for massively deleting data of class $sTargetClass"; + } else { + $aObjects = $oObjectSet->ToArray(); + $this->DeleteObjects($oResult, $aObjects, $bSimulate); + } + break; + + case 'core/get_related': + $oResult = new RestResultWithRelations(); + $sClass = RestUtils::GetClass($aParams, 'class'); + $key = RestUtils::GetMandatoryParam($aParams, 'key'); + $sRelation = RestUtils::GetMandatoryParam($aParams, 'relation'); + $iMaxRecursionDepth = RestUtils::GetOptionalParam($aParams, 'depth', 20 /* = MAX_RECURSION_DEPTH */); + $sDirection = RestUtils::GetOptionalParam($aParams, 'direction', null); + $bEnableRedundancy = RestUtils::GetOptionalParam($aParams, 'redundancy', false); + $bReverse = false; + + if (is_null($sDirection) && ($sRelation == 'depends on')) { + // Legacy behavior, consider "depends on" as a forward relation + $sRelation = 'impacts'; + $sDirection = 'up'; + $bReverse = true; // emulate the legacy behavior by returning the edges + } elseif (is_null($sDirection)) { + $sDirection = 'down'; + } + + $oObjectSet = RestUtils::GetObjectSetFromKey($sClass, $key); + if ($sDirection == 'down') { + $oRelationGraph = $oObjectSet->GetRelatedObjectsDown($sRelation, $iMaxRecursionDepth, $bEnableRedundancy); + } elseif ($sDirection == 'up') { + $oRelationGraph = $oObjectSet->GetRelatedObjectsUp($sRelation, $iMaxRecursionDepth, $bEnableRedundancy); + } else { + $oResult->code = RestResult::INTERNAL_ERROR; + $oResult->message = "Invalid value: '$sDirection' for the parameter 'direction'. Valid values are 'up' and 'down'"; + return $oResult; + + } + + if ($bEnableRedundancy) { + // Remove the redundancy nodes from the output + $oIterator = new RelationTypeIterator($oRelationGraph, 'Node'); + foreach ($oIterator as $oNode) { + if ($oNode instanceof RelationRedundancyNode) { + $oRelationGraph->FilterNode($oNode); + } } } - } - - $aIndexByClass = array(); - $oIterator = new RelationTypeIterator($oRelationGraph); - foreach($oIterator as $oElement) - { - if ($oElement instanceof RelationObjectNode) - { - $oObject = $oElement->GetProperty('object'); - if ($oObject) - { - if ($bEnableRedundancy && $sDirection == 'down') - { - // Add only the "reached" objects - if ($oElement->GetProperty('is_reached')) - { + + $aIndexByClass = []; + $oIterator = new RelationTypeIterator($oRelationGraph); + foreach ($oIterator as $oElement) { + if ($oElement instanceof RelationObjectNode) { + $oObject = $oElement->GetProperty('object'); + if ($oObject) { + if ($bEnableRedundancy && $sDirection == 'down') { + // Add only the "reached" objects + if ($oElement->GetProperty('is_reached')) { + $aIndexByClass[get_class($oObject)][$oObject->GetKey()] = null; + $oResult->AddObject(0, '', $oObject); + } + } else { $aIndexByClass[get_class($oObject)][$oObject->GetKey()] = null; $oResult->AddObject(0, '', $oObject); } } - else - { - $aIndexByClass[get_class($oObject)][$oObject->GetKey()] = null; - $oResult->AddObject(0, '', $oObject); - } - } - } - else if ($oElement instanceof RelationEdge) - { - $oSrcObj = $oElement->GetSourceNode()->GetProperty('object'); - $oDestObj = $oElement->GetSinkNode()->GetProperty('object'); - $sSrcKey = get_class($oSrcObj).'::'.$oSrcObj->GetKey(); - $sDestKey = get_class($oDestObj).'::'.$oDestObj->GetKey(); - if ($bEnableRedundancy) - { - // Add only the edges where both source and destination are "reached" - if ($oElement->GetSourceNode()->GetProperty('is_reached') && $oElement->GetSinkNode()->GetProperty('is_reached')) - { - if ($bReverse) - { - $oResult->AddRelation($sDestKey, $sSrcKey); + } elseif ($oElement instanceof RelationEdge) { + $oSrcObj = $oElement->GetSourceNode()->GetProperty('object'); + $oDestObj = $oElement->GetSinkNode()->GetProperty('object'); + $sSrcKey = get_class($oSrcObj).'::'.$oSrcObj->GetKey(); + $sDestKey = get_class($oDestObj).'::'.$oDestObj->GetKey(); + if ($bEnableRedundancy) { + // Add only the edges where both source and destination are "reached" + if ($oElement->GetSourceNode()->GetProperty('is_reached') && $oElement->GetSinkNode()->GetProperty('is_reached')) { + if ($bReverse) { + $oResult->AddRelation($sDestKey, $sSrcKey); + } else { + $oResult->AddRelation($sSrcKey, $sDestKey); + } } - else - { + } else { + if ($bReverse) { + $oResult->AddRelation($sDestKey, $sSrcKey); + } else { $oResult->AddRelation($sSrcKey, $sDestKey); } } } - else - { - if ($bReverse) - { - $oResult->AddRelation($sDestKey, $sSrcKey); - } - else - { - $oResult->AddRelation($sSrcKey, $sDestKey); - } - } } - } - if (count($aIndexByClass) > 0) - { - $aStats = array(); - $aUnauthorizedClasses = array(); - foreach ($aIndexByClass as $sClass => $aIds) - { - if (UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_READ) != UR_ALLOWED_YES) - { - $aUnauthorizedClasses[$sClass] = true; + if (count($aIndexByClass) > 0) { + $aStats = []; + $aUnauthorizedClasses = []; + foreach ($aIndexByClass as $sClass => $aIds) { + if (UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_READ) != UR_ALLOWED_YES) { + $aUnauthorizedClasses[$sClass] = true; + } + $aStats[] = $sClass.'= '.count($aIds); } - $aStats[] = $sClass.'= '.count($aIds); + if (count($aUnauthorizedClasses) > 0) { + $sClasses = implode(', ', array_keys($aUnauthorizedClasses)); + $oResult = new RestResult(); + $oResult->code = RestResult::UNAUTHORIZED; + $oResult->message = "The current user does not have enough permissions for exporting data of class(es): $sClasses"; + } else { + $oResult->message = "Scope: ".$oObjectSet->Count()."; Related objects: ".implode(', ', $aStats); + } + } else { + $oResult->message = "Nothing found"; } - if (count($aUnauthorizedClasses) > 0) - { - $sClasses = implode(', ', array_keys($aUnauthorizedClasses)); - $oResult = new RestResult(); - $oResult->code = RestResult::UNAUTHORIZED; - $oResult->message = "The current user does not have enough permissions for exporting data of class(es): $sClasses"; - } - else - { - $oResult->message = "Scope: ".$oObjectSet->Count()."; Related objects: ".implode(', ', $aStats); - } - } - else - { - $oResult->message = "Nothing found"; - } - break; - - case 'core/check_credentials': - $oResult = new RestResult(); - $sUser = RestUtils::GetMandatoryParam($aParams, 'user'); - $sPassword = RestUtils::GetMandatoryParam($aParams, 'password'); + break; - if (UserRights::CheckCredentials($sUser, $sPassword) !== true) - { - $oResult->authorized = false; - } - else - { - $oResult->authorized = true; - } - break; - - default: - // unknown operation: handled at a higher level + case 'core/check_credentials': + $oResult = new RestResult(); + $sUser = RestUtils::GetMandatoryParam($aParams, 'user'); + $sPassword = RestUtils::GetMandatoryParam($aParams, 'password'); + + if (UserRights::CheckCredentials($sUser, $sPassword) !== true) { + $oResult->authorized = false; + } else { + $oResult->authorized = true; + } + break; + + default: + // unknown operation: handled at a higher level } return $oResult; } public function SanitizeJsonInput(string $sJsonInput): string { - $sSanitizedJsonInput = $sJsonInput; - $aJsonData = json_decode($sSanitizedJsonInput, true); - $sOperation = $aJsonData['operation']; + $sSanitizedJsonInput = $sJsonInput; + $aJsonData = json_decode($sSanitizedJsonInput, true); + $sOperation = $aJsonData['operation']; - switch ($sOperation) { - case 'core/check_credentials': - if (isset($aJsonData['password'])) { - $aJsonData['password'] = '*****'; - } - break; - case 'core/update': - case 'core/create': - default : - $sClass = $aJsonData['class']; - if (isset($aJsonData['fields'])) { - foreach ($aJsonData['fields'] as $sFieldAttCode => $fieldValue) { - $oAttDef = MetaModel::GetAttributeDef($sClass, $sFieldAttCode); - $this->SanitizeFieldIfSensitive($aJsonData['fields'], $sFieldAttCode, $fieldValue, $oAttDef); - } - } - break; - } + switch ($sOperation) { + case 'core/check_credentials': + if (isset($aJsonData['password'])) { + $aJsonData['password'] = '*****'; + } + break; + case 'core/update': + case 'core/create': + default: + $sClass = $aJsonData['class']; + if (isset($aJsonData['fields'])) { + foreach ($aJsonData['fields'] as $sFieldAttCode => $fieldValue) { + $oAttDef = MetaModel::GetAttributeDef($sClass, $sFieldAttCode); + $this->SanitizeFieldIfSensitive($aJsonData['fields'], $sFieldAttCode, $fieldValue, $oAttDef); + } + } + break; + } return json_encode($aJsonData, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); } /** - * Helper for object deletion + * Helper for object deletion */ public function DeleteObjects($oResult, $aObjects, $bSimulate) { $oDeletionPlan = new DeletionPlan(); - foreach($aObjects as $oObj) - { - if ($bSimulate) - { + foreach ($aObjects as $oObj) { + if ($bSimulate) { $oObj->CheckToDelete($oDeletionPlan); - } - else - { + } else { $oObj->DBDelete($oDeletionPlan); } } - foreach ($oDeletionPlan->ListDeletes() as $sTargetClass => $aDeletes) - { - foreach ($aDeletes as $iId => $aData) - { + foreach ($oDeletionPlan->ListDeletes() as $sTargetClass => $aDeletes) { + foreach ($aDeletes as $iId => $aData) { $oToDelete = $aData['to_delete']; $bAutoDel = (($aData['mode'] == DEL_SILENT) || ($aData['mode'] == DEL_AUTO)); - if (array_key_exists('issue', $aData)) - { - if ($bAutoDel) - { - if (isset($aData['requested_explicitely'])) // i.e. in the initial list of objects to delete - { + if (array_key_exists('issue', $aData)) { + if ($bAutoDel) { + if (isset($aData['requested_explicitely'])) { // i.e. in the initial list of objects to delete $iCode = RestDelete::ISSUE; $sPlanned = 'Cannot be deleted: '.$aData['issue']; - } - else - { + } else { $iCode = RestDelete::AUTO_DELETE_ISSUE; $sPlanned = 'Should be deleted automatically... but: '.$aData['issue']; } - } - else - { + } else { $iCode = RestDelete::REQUEST_EXPLICITELY; $sPlanned = 'Must be deleted explicitely... but: '.$aData['issue']; } - } - else - { - if ($bAutoDel) - { - if (isset($aData['requested_explicitely'])) - { + } else { + if ($bAutoDel) { + if (isset($aData['requested_explicitely'])) { $iCode = RestDelete::OK; - $sPlanned = ''; - } - else - { + $sPlanned = ''; + } else { $iCode = RestDelete::AUTO_DELETE; $sPlanned = 'Deleted automatically'; } - } - else - { + } else { $iCode = RestDelete::REQUEST_EXPLICITELY; $sPlanned = 'Must be deleted explicitely'; } @@ -877,60 +755,43 @@ class CoreServices implements iRestServiceProvider, iRestInputSanitizer $oResult->AddObject($iCode, $sPlanned, $oToDelete); } } - foreach ($oDeletionPlan->ListUpdates() as $sRemoteClass => $aToUpdate) - { - foreach ($aToUpdate as $iId => $aData) - { + foreach ($oDeletionPlan->ListUpdates() as $sRemoteClass => $aToUpdate) { + foreach ($aToUpdate as $iId => $aData) { $oToUpdate = $aData['to_reset']; - if (array_key_exists('issue', $aData)) - { + if (array_key_exists('issue', $aData)) { $iCode = RestDelete::AUTO_UPDATE_ISSUE; $sPlanned = 'Should be updated automatically... but: '.$aData['issue']; - } - else - { + } else { $iCode = RestDelete::AUTO_UPDATE; $sPlanned = 'Reset external keys: '.$aData['attributes_list']; } $oResult->AddObject($iCode, $sPlanned, $oToUpdate); } } - - if ($oDeletionPlan->FoundStopper()) - { - if ($oDeletionPlan->FoundSecurityIssue()) - { + + if ($oDeletionPlan->FoundStopper()) { + if ($oDeletionPlan->FoundSecurityIssue()) { $iRes = RestResult::UNAUTHORIZED; $sRes = 'Deletion not allowed on some objects'; - } - elseif ($oDeletionPlan->FoundManualOperation()) - { - $iRes = RestResult::UNSAFE; + } elseif ($oDeletionPlan->FoundManualOperation()) { + $iRes = RestResult::UNSAFE; $sRes = 'The deletion requires that other objects be deleted/updated, and those operations must be requested explicitely'; - } - else - { - $iRes = RestResult::INTERNAL_ERROR; + } else { + $iRes = RestResult::INTERNAL_ERROR; $sRes = 'Some issues have been encountered. See the list of planned changes for more information about the issue(s).'; - } - } - else - { - $iRes = RestResult::OK; + } + } else { + $iRes = RestResult::OK; $sRes = 'Deleted: '.count($aObjects); $iIndirect = $oDeletionPlan->GetTargetCount() - count($aObjects); - if ($iIndirect > 0) - { + if ($iIndirect > 0) { $sRes .= ' plus (for DB integrity) '.$iIndirect; } } $oResult->code = $iRes; - if ($bSimulate) - { + if ($bSimulate) { $oResult->message = 'SIMULATING: '.$sRes; - } - else - { + } else { $oResult->message = $sRes; } } @@ -953,46 +814,45 @@ class CoreServices implements iRestServiceProvider, iRestInputSanitizer */ trait SanitizeTrait { - /** - * Sanitize a field if it is sensitive. - * - * @param array $fields The fields array - * @param string $sFieldAttCode The attribute code - * @param mixed $oAttDef The attribute definition - * @throws Exception - */ - private function SanitizeFieldIfSensitive(array &$fields, string $sFieldAttCode, $fieldValue, $oAttDef): void - { - // for simple attribute - if ($oAttDef instanceof iAttributeNoGroupBy) { // iAttributeNoGroupBy is equivalent to sensitive attribute - $fields[$sFieldAttCode] = '*****'; - return; - } - // for 1-n / n-n relation - if ($oAttDef instanceof AttributeLinkedSet) { - foreach ($fieldValue as $i => $aLnkValues) { - foreach ($aLnkValues as $sLnkAttCode => $sLnkValue) { - $oLnkAttDef = MetaModel::GetAttributeDef($oAttDef->GetLinkedClass(), $sLnkAttCode); - if ($oLnkAttDef instanceof iAttributeNoGroupBy) { // 1-n relation - $fields[$sFieldAttCode][$i][$sLnkAttCode] = '*****'; - } - elseif ($oAttDef instanceof AttributeLinkedSetIndirect && $oLnkAttDef instanceof AttributeExternalField) { // for n-n relation - $oExtKeyAttDef = MetaModel::GetAttributeDef($oLnkAttDef->GetTargetClass(), $oLnkAttDef->GetExtAttCode()); - if ($oExtKeyAttDef instanceof iAttributeNoGroupBy) { - $fields[$sFieldAttCode][$i][$sLnkAttCode] = '*****'; - } - } - } - } - return; - } + /** + * Sanitize a field if it is sensitive. + * + * @param array $fields The fields array + * @param string $sFieldAttCode The attribute code + * @param mixed $oAttDef The attribute definition + * @throws Exception + */ + private function SanitizeFieldIfSensitive(array &$fields, string $sFieldAttCode, $fieldValue, $oAttDef): void + { + // for simple attribute + if ($oAttDef instanceof iAttributeNoGroupBy) { // iAttributeNoGroupBy is equivalent to sensitive attribute + $fields[$sFieldAttCode] = '*****'; + return; + } + // for 1-n / n-n relation + if ($oAttDef instanceof AttributeLinkedSet) { + foreach ($fieldValue as $i => $aLnkValues) { + foreach ($aLnkValues as $sLnkAttCode => $sLnkValue) { + $oLnkAttDef = MetaModel::GetAttributeDef($oAttDef->GetLinkedClass(), $sLnkAttCode); + if ($oLnkAttDef instanceof iAttributeNoGroupBy) { // 1-n relation + $fields[$sFieldAttCode][$i][$sLnkAttCode] = '*****'; + } elseif ($oAttDef instanceof AttributeLinkedSetIndirect && $oLnkAttDef instanceof AttributeExternalField) { // for n-n relation + $oExtKeyAttDef = MetaModel::GetAttributeDef($oLnkAttDef->GetTargetClass(), $oLnkAttDef->GetExtAttCode()); + if ($oExtKeyAttDef instanceof iAttributeNoGroupBy) { + $fields[$sFieldAttCode][$i][$sLnkAttCode] = '*****'; + } + } + } + } + return; + } - // for external attribute - if ($oAttDef instanceof AttributeExternalField) { - $oExtKeyAttDef = MetaModel::GetAttributeDef($oAttDef->GetTargetClass(), $oAttDef->GetExtAttCode()); - if ($oExtKeyAttDef instanceof iAttributeNoGroupBy) { - $fields[$sFieldAttCode] = '*****'; - } - } - } -} \ No newline at end of file + // for external attribute + if ($oAttDef instanceof AttributeExternalField) { + $oExtKeyAttDef = MetaModel::GetAttributeDef($oAttDef->GetTargetClass(), $oAttDef->GetExtAttCode()); + if ($oExtKeyAttDef instanceof iAttributeNoGroupBy) { + $fields[$sFieldAttCode] = '*****'; + } + } + } +} diff --git a/core/simplecrypt.class.inc.php b/core/simplecrypt.class.inc.php index e9c304f3d..ea6885d07 100644 --- a/core/simplecrypt.class.inc.php +++ b/core/simplecrypt.class.inc.php @@ -412,4 +412,4 @@ class SimpleCryptOpenSSLMcryptCompatibilityEngine implements CryptEngine return trim($plaintext); } -} \ No newline at end of file +} diff --git a/core/simplegraph.class.inc.php b/core/simplegraph.class.inc.php index 614ab031e..43084ba7f 100644 --- a/core/simplegraph.class.inc.php +++ b/core/simplegraph.class.inc.php @@ -1,4 +1,5 @@ sId = $sId; - $this->aProperties = array(); + $this->aProperties = []; } - + /** * Get the identifier of the object in the graph * @return string @@ -51,7 +51,7 @@ class GraphElement { return $this->sId; } - + /** * Get the value of the given named property for the object * @param string $sPropName The name of the property to get @@ -73,7 +73,7 @@ class GraphElement { $this->aProperties[$sPropName] = $value; } - + /** * Get all the known properties of the object * @return Ambigous @@ -91,7 +91,7 @@ class GraphNode extends GraphElement { protected $aIncomingEdges; protected $aOutgoingEdges; - + /** * Create a new node inside a graph * @param SimpleGraph $oGraph @@ -100,16 +100,15 @@ class GraphNode extends GraphElement public function __construct(SimpleGraph $oGraph, $sId) { parent::__construct($sId); - $this->aIncomingEdges = array(); - $this->aOutgoingEdges = array(); + $this->aIncomingEdges = []; + $this->aOutgoingEdges = []; $oGraph->_AddNode($this); } - + public function GetDotAttributes($bNoLabel = false) { $sDot = ''; - if (!$bNoLabel) - { + if (!$bNoLabel) { $sLabel = addslashes($this->GetProperty('label', $this->GetId())); $sDot = 'label="'.$sLabel.'"'; } @@ -133,7 +132,7 @@ class GraphNode extends GraphElement { $this->aOutgoingEdges[$oEdge->GetId()] = $oEdge; } - + /** * INTERNAL USE ONLY * @param GraphEdge $oEdge @@ -151,7 +150,7 @@ class GraphNode extends GraphElement { unset($this->aOutgoingEdges[$oEdge->GetId()]); } - + /** * Get the list of all incoming edges on the current node * @return Ambigous @@ -160,7 +159,7 @@ class GraphNode extends GraphElement { return $this->aIncomingEdges; } - + /** * Get the list of all outgoing edges from the current node * @return Ambigous @@ -169,7 +168,7 @@ class GraphNode extends GraphElement { return $this->aOutgoingEdges; } - + /** * Flood fill the chart with the given value for the specified property * @param string $sPropName The name of the property to set @@ -179,29 +178,24 @@ class GraphNode extends GraphElement */ public function FloodProperty($sPropName, $value, $bFloodDown, $bFloodUp) { - if ($this->GetProperty($sPropName, null) == null) - { + if ($this->GetProperty($sPropName, null) == null) { // Property not already set, let's do it $this->SetProperty($sPropName, $value); - if ($bFloodDown) - { - foreach($this->GetOutgoingEdges() as $oEdge) - { + if ($bFloodDown) { + foreach ($this->GetOutgoingEdges() as $oEdge) { $oEdge->SetProperty($sPropName, $value); $oEdge->GetSinkNode()->FloodProperty($sPropName, $value, $bFloodDown, $bFloodUp); } } - if ($bFloodUp) - { - foreach($this->GetIncomingEdges() as $oEdge) - { + if ($bFloodUp) { + foreach ($this->GetIncomingEdges() as $oEdge) { $oEdge->SetProperty($sPropName, $value); $oEdge->GetSourceNode()->FloodProperty($sPropName, $value, $bFloodDown, $bFloodUp); } } } } - + } /** @@ -237,7 +231,7 @@ class GraphEdge extends GraphElement { return $this->oSourceNode; } - + /** * Get the "sink" node for this edge * @return GraphNode @@ -250,8 +244,7 @@ class GraphEdge extends GraphElement public function GetDotAttributes($bNoLabel = false) { $sDot = ''; - if (!$bNoLabel) - { + if (!$bNoLabel) { $sLabel = addslashes($this->GetProperty('label', '')); $sDot = 'label="'.$sLabel.'"'; } @@ -266,16 +259,16 @@ class SimpleGraph { protected $aNodes; protected $aEdges; - + /** * Creates a new empty graph */ public function __construct() { - $this->aNodes = array(); - $this->aEdges = array(); + $this->aNodes = []; + $this->aEdges = []; } - + /** * INTERNAL USE ONLY * @return Ambigous @@ -284,7 +277,7 @@ class SimpleGraph { return $this->aNodes; } - + /** * INTERNAL USE ONLY * @return Ambigous @@ -293,32 +286,34 @@ class SimpleGraph { return $this->aEdges; } - + /** * INTERNAL USE ONLY * @return Ambigous */ public function _AddNode(GraphNode $oNode) { - if (array_key_exists($oNode->GetId(), $this->aNodes)) throw new SimpleGraphException('Cannot add node (id='.$oNode->GetId().') to the graph. A node with the same id already exists in the graph.'); - + if (array_key_exists($oNode->GetId(), $this->aNodes)) { + throw new SimpleGraphException('Cannot add node (id='.$oNode->GetId().') to the graph. A node with the same id already exists in the graph.'); + } + $this->aNodes[$oNode->GetId()] = $oNode; } - + /** * INTERNAL USE ONLY * @return Ambigous */ public function _RemoveNode(GraphNode $oNode) { - if (!array_key_exists($oNode->GetId(), $this->aNodes)) throw new SimpleGraphException('Cannot remove the node (id='.$oNode->GetId().') from the graph. The node was not found in the graph.'); - - foreach($oNode->GetOutgoingEdges() as $oEdge) - { + if (!array_key_exists($oNode->GetId(), $this->aNodes)) { + throw new SimpleGraphException('Cannot remove the node (id='.$oNode->GetId().') from the graph. The node was not found in the graph.'); + } + + foreach ($oNode->GetOutgoingEdges() as $oEdge) { $this->_RemoveEdge($oEdge); } - foreach($oNode->GetIncomingEdges() as $oEdge) - { + foreach ($oNode->GetIncomingEdges() as $oEdge) { $this->_RemoveEdge($oEdge); } unset($this->aNodes[$oNode->GetId()]); @@ -333,42 +328,37 @@ class SimpleGraph */ public function FilterNode(GraphNode $oNode, $bAllowLoopingEdge = false) { - if (!array_key_exists($oNode->GetId(), $this->aNodes)) throw new SimpleGraphException('Cannot filter the node (id='.$oNode->GetId().') from the graph. The node was not found in the graph.'); - - $aSourceNodes = array(); - $aSinkNodes = array(); - foreach($oNode->GetOutgoingEdges() as $oEdge) - { + if (!array_key_exists($oNode->GetId(), $this->aNodes)) { + throw new SimpleGraphException('Cannot filter the node (id='.$oNode->GetId().') from the graph. The node was not found in the graph.'); + } + + $aSourceNodes = []; + $aSinkNodes = []; + foreach ($oNode->GetOutgoingEdges() as $oEdge) { $sSinkId = $oEdge->GetSinkNode()->GetId(); - if ($sSinkId != $oNode->GetId()) - { + if ($sSinkId != $oNode->GetId()) { $aSinkNodes[$sSinkId] = $oEdge->GetSinkNode(); } $this->_RemoveEdge($oEdge); } - foreach($oNode->GetIncomingEdges() as $oEdge) - { + foreach ($oNode->GetIncomingEdges() as $oEdge) { $sSourceId = $oEdge->GetSourceNode()->GetId(); - if ($sSourceId != $oNode->GetId()) - { + if ($sSourceId != $oNode->GetId()) { $aSourceNodes[$sSourceId] = $oEdge->GetSourceNode(); } $this->_RemoveEdge($oEdge); } unset($this->aNodes[$oNode->GetId()]); - foreach($aSourceNodes as $sSourceId => $oSourceNode) - { - foreach($aSinkNodes as $sSinkId => $oSinkNode) - { - if ($bAllowLoopingEdge || ($oSourceNode->GetId() != $oSinkNode->GetId())) - { + foreach ($aSourceNodes as $sSourceId => $oSourceNode) { + foreach ($aSinkNodes as $sSinkId => $oSinkNode) { + if ($bAllowLoopingEdge || ($oSourceNode->GetId() != $oSinkNode->GetId())) { $oEdge = new RelationEdge($this, $oSourceNode, $oSinkNode); } } } } - + /** * Get the node identified by $sId or null if not found * @param string $sId @@ -376,7 +366,7 @@ class SimpleGraph */ public function GetNode($sId) { - return array_key_exists($sId, $this->aNodes) ? $this->aNodes[$sId] : null; + return array_key_exists($sId, $this->aNodes) ? $this->aNodes[$sId] : null; } /** @@ -386,7 +376,7 @@ class SimpleGraph */ public function HasNode($sId) { - return array_key_exists($sId, $this->aNodes); + return array_key_exists($sId, $this->aNodes); } /** @@ -397,23 +387,19 @@ class SimpleGraph */ public function _AddEdge(GraphEdge $oEdge, $bMustBeUnique = false) { - if (array_key_exists($oEdge->GetId(), $this->aEdges)) - { - if ($bMustBeUnique) - { - throw new SimpleGraphException('Cannot add edge (id=' . $oEdge->GetId() . ') to the graph. An edge with the same id already exists in the graph.'); - } - else - { + if (array_key_exists($oEdge->GetId(), $this->aEdges)) { + if ($bMustBeUnique) { + throw new SimpleGraphException('Cannot add edge (id='.$oEdge->GetId().') to the graph. An edge with the same id already exists in the graph.'); + } else { return; } } - + $this->aEdges[$oEdge->GetId()] = $oEdge; $oEdge->GetSourceNode()->_AddOutgoingEdge($oEdge); $oEdge->GetSinkNode()->_AddIncomingEdge($oEdge); } - + /** * INTERNAL USE ONLY * @param GraphEdge $oEdge @@ -421,14 +407,16 @@ class SimpleGraph */ public function _RemoveEdge(GraphEdge $oEdge) { - if (!array_key_exists($oEdge->GetId(), $this->aEdges)) throw new SimpleGraphException('Cannot remove edge (id='.$oEdge->GetId().') from the graph. The edge was not found.'); - + if (!array_key_exists($oEdge->GetId(), $this->aEdges)) { + throw new SimpleGraphException('Cannot remove edge (id='.$oEdge->GetId().') from the graph. The edge was not found.'); + } + $oEdge->GetSourceNode()->_RemoveOutgoingEdge($oEdge); $oEdge->GetSinkNode()->_RemoveIncomingEdge($oEdge); - + unset($this->aEdges[$oEdge->GetId()]); } - + /** * Get the edge indentified by $sId or null if not found * @param string $sId @@ -438,7 +426,7 @@ class SimpleGraph { return array_key_exists($sId, $this->aEdges) ? $this->aEdges[$sId] : null; } - + /** * Determine if the id already exists in amongst the existing edges * @param string $sId @@ -446,7 +434,7 @@ class SimpleGraph */ public function HasEdge($sId) { - return array_key_exists($sId, $this->aEdges); + return array_key_exists($sId, $this->aEdges); } /** @@ -470,23 +458,20 @@ EOF ; $oIterator = new RelationTypeIterator($this, 'Node'); - - foreach($oIterator as $key => $oNode) - { + + foreach ($oIterator as $key => $oNode) { $sDot .= "\t\"".$oNode->GetId()."\" [ ".$oNode->GetDotAttributes($bNoLabel)." ];\n"; - if (count($oNode->GetOutgoingEdges()) > 0) - { - foreach($oNode->GetOutgoingEdges() as $oEdge) - { + if (count($oNode->GetOutgoingEdges()) > 0) { + foreach ($oNode->GetOutgoingEdges() as $oEdge) { $sDot .= "\t\"".$oNode->GetId()."\" -> \"".$oEdge->GetSinkNode()->GetId()."\" [ ".$oEdge->GetDotAttributes($bNoLabel)." ];\n"; } } } - + $sDot .= "}\n"; - return $sDot; + return $sDot; } - + /** * Get the description of the graph as an embedded PNG image (using a data: url) as * generated by graphviz (requires graphviz to be installed on the machine and the path to @@ -497,51 +482,43 @@ EOF public function DumpAsHtmlImage() { $sDotExecutable = MetaModel::GetConfig()->Get('graphviz_path'); - if (file_exists($sDotExecutable)) - { + if (file_exists($sDotExecutable)) { // create the file with Graphviz - if (!is_dir(utils::GetDataPath())) - { + if (!is_dir(utils::GetDataPath())) { @mkdir(utils::GetDataPath()); } - if (!is_dir(utils::GetDataPath()."tmp")) - { + if (!is_dir(utils::GetDataPath()."tmp")) { @mkdir(utils::GetDataPath()."tmp"); } $sImageFilePath = tempnam(utils::GetDataPath()."tmp", 'png-'); $sDotDescription = $this->GetDotDescription(); $sDotFilePath = tempnam(utils::GetDataPath()."tmp", 'dot-'); - + $rFile = @fopen($sDotFilePath, "w"); @fwrite($rFile, $sDotDescription); @fclose($rFile); - $aOutput = array(); + $aOutput = []; $CommandLine = "\"$sDotExecutable\" -v -Tpng < \"$sDotFilePath\" -o\"$sImageFilePath\" 2>&1"; - + exec($CommandLine, $aOutput, $iRetCode); - if ($iRetCode != 0) - { + if ($iRetCode != 0) { $sHtml = ''; $sHtml .= "

Error:

"; $sHtml .= "

The command:

$CommandLine
returned $iRetCode

"; $sHtml .= "

The output of the command is:

\n".implode("\n", $aOutput)."

"; $sHtml .= "
"; $sHtml .= "

Content of the '".basename($sDotFilePath)."' file:

\n$sDotDescription
"; - } - else - { + } else { $sHtml = ''; @unlink($sImageFilePath); } @unlink($sDotFilePath); - } - else - { - throw new Exception('graphviz not found'); + } else { + throw new Exception('graphviz not found'); } return $sHtml; } - + /** * Get the description of the graph as text string in the XDot format * including the positions of the nodes and egdes (requires graphviz @@ -553,51 +530,42 @@ EOF public function DumpAsXDot() { $sDotExecutable = MetaModel::GetConfig()->Get('graphviz_path'); - if (file_exists($sDotExecutable)) - { + if (file_exists($sDotExecutable)) { // create the file with Graphviz - if (!is_dir(utils::GetDataPath())) - { + if (!is_dir(utils::GetDataPath())) { @mkdir(utils::GetDataPath()); } - if (!is_dir(utils::GetDataPath()."tmp")) - { + if (!is_dir(utils::GetDataPath()."tmp")) { @mkdir(utils::GetDataPath()."tmp"); } $sXdotFilePath = tempnam(utils::GetDataPath()."tmp", 'xdot-'); $sDotDescription = $this->GetDotDescription(true); // true => don't put (localized) labels in the file, since it makes it harder to parse $sDotFilePath = tempnam(utils::GetDataPath()."tmp", 'dot-'); - + $rFile = @fopen($sDotFilePath, "w"); @fwrite($rFile, $sDotDescription); @fclose($rFile); - $aOutput = array(); + $aOutput = []; $CommandLine = "\"$sDotExecutable\" -v -Tdot < \"$sDotFilePath\" -o\"$sXdotFilePath\" 2>&1"; - + exec($CommandLine, $aOutput, $iRetCode); - if ($iRetCode != 0) - { + if ($iRetCode != 0) { $sHtml = ''; $sHtml .= "

Error:

"; $sHtml .= "

The command:

$CommandLine
returned $iRetCode

"; $sHtml .= "

The output of the command is:

\n".implode("\n", $aOutput)."

"; IssueLog::Error($sHtml); - } - else - { + } else { $sHtml = '
'.file_get_contents($sXdotFilePath).'
'; @unlink($sXdotFilePath); } @unlink($sDotFilePath); - } - else - { - throw new Exception('graphviz not found'); + } else { + throw new Exception('graphviz not found'); } return $sHtml; } - - + /** * Get the description of the graph as some HTML text * @return string @@ -606,42 +574,36 @@ EOF { $sHtml = ''; $oIterator = new RelationTypeIterator($this); - - foreach($oIterator as $key => $oElement) - { + + foreach ($oIterator as $key => $oElement) { $sHtml .= "

$key: ".get_class($oElement)."::".$oElement->GetId()."

"; - - switch(get_class($oElement)) - { + + switch (get_class($oElement)) { case 'GraphNode': - if (count($oElement->GetIncomingEdges()) > 0) - { + if (count($oElement->GetIncomingEdges()) > 0) { $sHtml .= "
    Incoming edges:\n"; - foreach($oElement->GetIncomingEdges() as $oEdge) - { + foreach ($oElement->GetIncomingEdges() as $oEdge) { $sHtml .= "
  • From: ".$oEdge->GetSourceNode()->GetId()."
  • \n"; } $sHtml .= "
\n"; } - if (count($oElement->GetOutgoingEdges()) > 0) - { + if (count($oElement->GetOutgoingEdges()) > 0) { $sHtml .= "
    Outgoing edges:\n"; - foreach($oElement->GetOutgoingEdges() as $oEdge) - { + foreach ($oElement->GetOutgoingEdges() as $oEdge) { $sHtml .= "
  • To: ".$oEdge->GetSinkNode()->GetId()."
  • \n"; } $sHtml .= "
\n"; } break; - + case 'GraphEdge': $sHtml .= "

From: ".$oElement->GetSourceNode()->GetId().", to:".$oElement->GetSinkNode()->GetId()."

\n"; break; } } - return $sHtml; + return $sHtml; } - + /** * Split the graph in a array of non connected subgraphs * @return multitype:SimpleGraph unknown @@ -649,48 +611,40 @@ EOF public function GetSubgraphs() { $iNbColors = 0; - $aResult = array(); + $aResult = []; $oIterator = new RelationTypeIterator($this, 'Node'); - foreach($oIterator as $oNode) - { + foreach ($oIterator as $oNode) { $iPrevColor = $oNode->GetProperty('color', null); - - if ($iPrevColor == null) - { + + if ($iPrevColor == null) { $iNbColors++; // Start a new color $oNode->FloodProperty('color', $iNbColors, true, true); } } - if ($iNbColors == 1) - { + if ($iNbColors == 1) { // Everything is connected together, only one subgraph $aResult[] = $this; - } - else - { + } else { // Let's reconstruct each separate graph $sClass = get_class($this); - for($i = 1; $i <= $iNbColors; $i++) - { + for ($i = 1; $i <= $iNbColors; $i++) { $aResult[$i] = new $sClass(); } - - foreach($oIterator as $oNode) - { + + foreach ($oIterator as $oNode) { $iNodeColor = $oNode->GetProperty('color'); $aResult[$iNodeColor]->_AddNode($oNode); } - + $oIter2 = new RelationTypeIterator($this, 'Edge'); - foreach($oIter2 as $oEdge) - { + foreach ($oIter2 as $oEdge) { $iEdgeColor = $oEdge->GetProperty('color'); $aResult[$iEdgeColor]->_AddEdge($oEdge); } } - return $aResult; + return $aResult; } - + /** * Merge back two subgraphs into one * @param SimpleGraph $oGraph @@ -698,13 +652,11 @@ EOF public function Merge(SimpleGraph $oGraph) { $oIter1 = new RelationTypeIterator($oGraph, 'Node'); - foreach($oIter1 as $oNode) - { + foreach ($oIter1 as $oNode) { $this->_AddNode($oNode); } $oIter2 = new RelationTypeIterator($oGraph, 'Edge'); - foreach($oIter2 as $oEdge) - { + foreach ($oIter2 as $oEdge) { $this->_AddEdge($oEdge); } } @@ -718,7 +670,7 @@ class RelationTypeIterator implements Iterator { protected $iCurrentIdx; protected $aList; - + /** * Constructor * @param SimpleGraph $oGraph The graph to browse @@ -727,46 +679,53 @@ class RelationTypeIterator implements Iterator public function __construct(SimpleGraph $oGraph, $sType = null) { $this->iCurrentIdx = -1; - $this->aList = array(); - - switch($sType) - { + $this->aList = []; + + switch ($sType) { case 'Node': - foreach($oGraph->_GetNodes() as $oNode) $this->aList[] = $oNode; - break; - + foreach ($oGraph->_GetNodes() as $oNode) { + $this->aList[] = $oNode; + } + break; + case 'Edge': - foreach($oGraph->_GetEdges() as $oEdge) $this->aList[] = $oEdge; - break; - + foreach ($oGraph->_GetEdges() as $oEdge) { + $this->aList[] = $oEdge; + } + break; + default: - foreach($oGraph->_GetNodes() as $oNode) $this->aList[] = $oNode; - foreach($oGraph->_GetEdges() as $oEdge) $this->aList[] = $oEdge; + foreach ($oGraph->_GetNodes() as $oNode) { + $this->aList[] = $oNode; + } + foreach ($oGraph->_GetEdges() as $oEdge) { + $this->aList[] = $oEdge; + } } } - + public function rewind(): void { $this->iCurrentIdx = 0; } - + public function valid(): bool { return array_key_exists($this->iCurrentIdx, $this->aList); } - + public function next(): void { $this->iCurrentIdx++; } - + // Return type mixed is not supported by PHP 7.4, we can remove the following PHP attribute and add the return type once iTop min PHP version is PHP 8.0+ #[\ReturnTypeWillChange] public function current() { return $this->aList[$this->iCurrentIdx]; } - + // Return type mixed is not supported by PHP 7.4, we can remove the following PHP attribute and add the return type once iTop min PHP version is PHP 8.0+ #[\ReturnTypeWillChange] public function key() diff --git a/core/trigger.class.inc.php b/core/trigger.class.inc.php index cd6c56d01..fdd816e37 100644 --- a/core/trigger.class.inc.php +++ b/core/trigger.class.inc.php @@ -1,4 +1,5 @@ "grant_by_profile,core/cmdb", "key_type" => "autoincrement", "name_attcode" => "description", @@ -45,21 +46,23 @@ abstract class Trigger extends cmdbAbstractObject "db_key_field" => "id", "db_finalclass_field" => "realclass", 'style' => new ormStyle(null, null, null, null, null, '../images/icons/icons8-conflict.svg'), - ); + ]; MetaModel::Init_Params($aParams); //MetaModel::Init_InheritAttributes(); - MetaModel::Init_AddAttribute(new AttributeString("description", array("allowed_values" => null, "sql" => "description", "default_value" => null, "is_null_allowed" => false, "depends_on" => array()))); - MetaModel::Init_AddAttribute(new AttributeLinkedSetIndirect("action_list", - array("linked_class" => "lnkTriggerAction", "ext_key_to_me" => "trigger_id", "ext_key_to_remote" => "action_id", "allowed_values" => null, "count_min" => 1, "count_max" => 0, "depends_on" => array()))); + MetaModel::Init_AddAttribute(new AttributeString("description", ["allowed_values" => null, "sql" => "description", "default_value" => null, "is_null_allowed" => false, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeLinkedSetIndirect( + "action_list", + ["linked_class" => "lnkTriggerAction", "ext_key_to_me" => "trigger_id", "ext_key_to_remote" => "action_id", "allowed_values" => null, "count_min" => 1, "count_max" => 0, "depends_on" => []] + )); $aTags = ContextTag::GetTags(); - MetaModel::Init_AddAttribute(new AttributeEnumSet("context", array("allowed_values" => null, "possible_values" => new ValueSetEnumPadded($aTags, true), "sql" => "context", "depends_on" => array(), "is_null_allowed" => true, "max_items" => 12))); + MetaModel::Init_AddAttribute(new AttributeEnumSet("context", ["allowed_values" => null, "possible_values" => new ValueSetEnumPadded($aTags, true), "sql" => "context", "depends_on" => [], "is_null_allowed" => true, "max_items" => 12])); // "complement" is a computed field, fed by Trigger sub-classes, in general in ComputeValues method, for eg. the TriggerOnObject fed it with target_class info - MetaModel::Init_AddAttribute(new AttributeString("complement", array("allowed_values" => null, "sql" => "complement", "default_value" => null, "is_null_allowed" => true, "depends_on" => array()))); - MetaModel::Init_AddAttribute(new AttributeEnum("subscription_policy", array("allowed_values" => new ValueSetEnum(Combodo\iTop\Core\Trigger\Enum\SubscriptionPolicy::cases()), "sql" => "subscription_policy", "default_value" => \Combodo\iTop\Core\Trigger\Enum\SubscriptionPolicy::AllowNoChannel->value, "is_null_allowed" => false, "depends_on" => array()))); + MetaModel::Init_AddAttribute(new AttributeString("complement", ["allowed_values" => null, "sql" => "complement", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeEnum("subscription_policy", ["allowed_values" => new ValueSetEnum(Combodo\iTop\Core\Trigger\Enum\SubscriptionPolicy::cases()), "sql" => "subscription_policy", "default_value" => \Combodo\iTop\Core\Trigger\Enum\SubscriptionPolicy::AllowNoChannel->value, "is_null_allowed" => false, "depends_on" => []])); // Display lists - MetaModel::Init_SetZListItems('details', array('finalclass', 'description', 'context', 'subscription_policy', 'action_list', 'complement')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('finalclass', 'complement')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['finalclass', 'description', 'context', 'subscription_policy', 'action_list', 'complement']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['finalclass', 'complement']); // Attributes to be displayed for a list // Search criteria // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form @@ -78,17 +81,14 @@ abstract class Trigger extends cmdbAbstractObject $oContext = $this->Get('context'); $bChecked = false; $bValid = false; - foreach ($oContext->GetValues() as $sValue) - { + foreach ($oContext->GetValues() as $sValue) { $bChecked = true; - if (ContextTag::Check($sValue)) - { + if (ContextTag::Check($sValue)) { $bValid = true; break; } } - if ($bChecked && !$bValid) - { + if ($bChecked && !$bValid) { // Trigger does not match the current context return false; } @@ -105,8 +105,7 @@ abstract class Trigger extends cmdbAbstractObject public function DoActivate($aContextArgs) { // Check the context - if (!$this->IsContextValid()) - { + if (!$this->IsContextValid()) { // Trigger does not match the current context $sClass = get_class($this); $sName = $this->Get('friendlyname'); @@ -128,7 +127,7 @@ abstract class Trigger extends cmdbAbstractObject // Execute actions foreach ($aActionListOrdered as $aActionSubList) { - foreach ($aActionSubList as $oLink) /** @var \DBObject $oLink */ { + foreach ($aActionSubList as $oLink) { /** @var \DBObject $oLink */ /** @var \DBObject $oLink */ $iActionId = $oLink->Get('action_id'); /** @var \Action $oAction */ @@ -170,8 +169,8 @@ abstract class TriggerOnObject extends Trigger */ public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "grant_by_profile,core/cmdb", "key_type" => "autoincrement", "name_attcode" => "description", @@ -181,18 +180,20 @@ abstract class TriggerOnObject extends Trigger "db_table" => "priv_trigger_onobject", "db_key_field" => "id", "db_finalclass_field" => "", - ); + ]; MetaModel::Init_Params($aParams); MetaModel::Init_InheritAttributes(); - MetaModel::Init_AddAttribute(new AttributeClass("target_class", - array("class_category" => "bizmodel", "more_values" => "User,UserExternal,UserInternal,UserLDAP,UserLocal", "sql" => "target_class", "default_value" => null, "is_null_allowed" => false, "depends_on" => array(), "class_exclusion_list" => "Attachment"))); - MetaModel::Init_AddAttribute(new AttributeOQL("filter", array("allowed_values" => null, "sql" => "filter", "default_value" => null, "is_null_allowed" => true, "depends_on" => array()))); + MetaModel::Init_AddAttribute(new AttributeClass( + "target_class", + ["class_category" => "bizmodel", "more_values" => "User,UserExternal,UserInternal,UserLDAP,UserLocal", "sql" => "target_class", "default_value" => null, "is_null_allowed" => false, "depends_on" => [], "class_exclusion_list" => "Attachment"] + )); + MetaModel::Init_AddAttribute(new AttributeOQL("filter", ["allowed_values" => null, "sql" => "filter", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); // Display lists - MetaModel::Init_SetZListItems('details', array('description', 'context', 'target_class', 'filter', 'subscription_policy', 'action_list')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('finalclass', 'target_class', 'description')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['description', 'context', 'target_class', 'filter', 'subscription_policy', 'action_list']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['finalclass', 'target_class', 'description']); // Attributes to be displayed for a list // Search criteria - MetaModel::Init_SetZListItems('default_search', array('description', 'target_class')); // Default criteria of the search banner + MetaModel::Init_SetZListItems('default_search', ['description', 'target_class']); // Default criteria of the search banner // MetaModel::Init_SetZListItems('standard_search', array('name', 'target_class', 'description')); // Criteria of the search form } @@ -204,18 +205,14 @@ abstract class TriggerOnObject extends Trigger parent::DoCheckToWrite(); $sFilter = trim($this->Get('filter') ?? ''); - if (strlen($sFilter) > 0) - { - try - { + if (strlen($sFilter) > 0) { + try { $oSearch = DBObjectSearch::FromOQL($sFilter); - if (!MetaModel::IsParentClass($this->Get('target_class'), $oSearch->GetClass())) - { + if (!MetaModel::IsParentClass($this->Get('target_class'), $oSearch->GetClass())) { $this->m_aCheckIssues[] = Dict::Format('TriggerOnObject:WrongFilterClass', $this->Get('target_class')); } - } catch (OqlException $e) - { + } catch (OqlException $e) { $this->m_aCheckIssues[] = Dict::Format('TriggerOnObject:WrongFilterQuery', $e->getMessage()); } } @@ -235,7 +232,6 @@ abstract class TriggerOnObject extends Trigger $this->Set('complement', 'class restriction: '.$this->Get('target_class')); } - /** * Check whether the given object is in the scope of this trigger * and can potentially be the subject of notifications @@ -261,47 +257,44 @@ abstract class TriggerOnObject extends Trigger public function DoActivate($aContextArgs) { $bGo = true; - if (isset($aContextArgs['this->object()'])) - { + if (isset($aContextArgs['this->object()'])) { /** @var \DBObject $oObject */ $oObject = $aContextArgs['this->object()']; $bGo = $this->IsTargetObject($oObject->GetKey(), $oObject->ListPreviousValuesForUpdatedAttributes()); } - if ($bGo) - { + if ($bGo) { parent::DoActivate($aContextArgs); } } - /** - * if the target class is Attachment, then the trigger is read-only - * @param $sAttCode - * @param $aReasons - * @param $sTargetState - * @return int - * @throws ArchivedObjectException - * @throws CoreException - */ - public function GetAttributeFlags($sAttCode, &$aReasons = array(), $sTargetState='') + /** + * if the target class is Attachment, then the trigger is read-only + * @param $sAttCode + * @param $aReasons + * @param $sTargetState + * @return int + * @throws ArchivedObjectException + * @throws CoreException + */ + public function GetAttributeFlags($sAttCode, &$aReasons = [], $sTargetState = '') { - // Force the computed field to be read-only, preventing it to be written - if ($this->Get('target_class') == 'Attachment' ) { - return OPT_ATT_READONLY; - } - return parent::GetAttributeFlags($sAttCode, $aReasons, $sTargetState); + // Force the computed field to be read-only, preventing it to be written + if ($this->Get('target_class') == 'Attachment') { + return OPT_ATT_READONLY; + } + return parent::GetAttributeFlags($sAttCode, $aReasons, $sTargetState); } + public function DisplayBareHeader(WebPage $oPage, $bEditMode = false) + { + $aHeaderBlocks = parent::DisplayBareHeader($oPage, $bEditMode); + if ($this->Get('target_class') == 'Attachment') { + $oPage->AddUiBlock(AlertUIBlockFactory::MakeForWarning('', Dict::S('Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage'))); + $oPage->add_ready_script("$('#UIMenuModify').hide();"); + } - public function DisplayBareHeader(WebPage $oPage, $bEditMode = false) - { - $aHeaderBlocks = parent::DisplayBareHeader($oPage, $bEditMode); - if ($this->Get('target_class') == 'Attachment' ) { - $oPage->AddUiBlock(AlertUIBlockFactory::MakeForWarning('', Dict::S('Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage'))); - $oPage->add_ready_script("$('#UIMenuModify').hide();"); - } - - return $aHeaderBlocks; - } + return $aHeaderBlocks; + } /** * Activate trigger based on attribute list given instead of changed attributes @@ -319,8 +312,7 @@ abstract class TriggerOnObject extends Trigger */ public function DoActivateForSpecificAttributes(array $aContextArgs, ?array $aAttributes) { - if (isset($aContextArgs['this->object()'])) - { + if (isset($aContextArgs['this->object()'])) { /** @var \DBObject $oObject */ $oObject = $aContextArgs['this->object()']; if (is_null($aAttributes)) { @@ -347,7 +339,7 @@ abstract class TriggerOnObject extends Trigger * @throws \MySQLHasGoneAwayException * @throws \OQLException */ - public function IsTargetObject($iObjectId, $aChanges = array()) + public function IsTargetObject($iObjectId, $aChanges = []) { $sFilter = trim($this->Get('filter') ?? ''); if (strlen($sFilter) > 0) { @@ -404,8 +396,8 @@ class TriggerOnPortalUpdate extends TriggerOnObject */ public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "grant_by_profile,core/cmdb,application", "key_type" => "autoincrement", "name_attcode" => "description", @@ -415,13 +407,13 @@ class TriggerOnPortalUpdate extends TriggerOnObject "db_table" => "priv_trigger_onportalupdate", "db_key_field" => "id", "db_finalclass_field" => "", - ); + ]; MetaModel::Init_Params($aParams); MetaModel::Init_InheritAttributes(); // Display lists - MetaModel::Init_SetZListItems('details', array('description', 'context', 'target_class', 'filter', 'subscription_policy', 'action_list')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('finalclass', 'target_class', 'description')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['description', 'context', 'target_class', 'filter', 'subscription_policy', 'action_list']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['finalclass', 'target_class', 'description']); // Attributes to be displayed for a list // Search criteria } } @@ -437,8 +429,8 @@ abstract class TriggerOnStateChange extends TriggerOnObject */ public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "grant_by_profile,core/cmdb", "key_type" => "autoincrement", "name_attcode" => "description", @@ -448,16 +440,16 @@ abstract class TriggerOnStateChange extends TriggerOnObject "db_table" => "priv_trigger_onstatechange", "db_key_field" => "id", "db_finalclass_field" => "", - ); + ]; MetaModel::Init_Params($aParams); MetaModel::Init_InheritAttributes(); - MetaModel::Init_AddAttribute(new AttributeClassState("state", array("class_field" => 'target_class', "allowed_values" => null, "sql" => "state", "default_value" => null, "is_null_allowed" => false, "depends_on" => array('target_class')))); + MetaModel::Init_AddAttribute(new AttributeClassState("state", ["class_field" => 'target_class', "allowed_values" => null, "sql" => "state", "default_value" => null, "is_null_allowed" => false, "depends_on" => ['target_class']])); // Display lists - MetaModel::Init_SetZListItems('details', array('description', 'context', 'target_class', 'filter', 'state', 'subscription_policy', 'action_list')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('finalclass', 'target_class', 'state')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['description', 'context', 'target_class', 'filter', 'state', 'subscription_policy', 'action_list']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['finalclass', 'target_class', 'state']); // Attributes to be displayed for a list // Search criteria - MetaModel::Init_SetZListItems('standard_search', array('description', 'target_class', 'state')); // Criteria of the std search form + MetaModel::Init_SetZListItems('standard_search', ['description', 'target_class', 'state']); // Criteria of the std search form // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form } } @@ -472,8 +464,8 @@ class TriggerOnStateEnter extends TriggerOnStateChange */ public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "grant_by_profile,core/cmdb,application", "key_type" => "autoincrement", "name_attcode" => "description", @@ -483,15 +475,15 @@ class TriggerOnStateEnter extends TriggerOnStateChange "db_table" => "priv_trigger_onstateenter", "db_key_field" => "id", "db_finalclass_field" => "", - ); + ]; MetaModel::Init_Params($aParams); MetaModel::Init_InheritAttributes(); // Display lists - MetaModel::Init_SetZListItems('details', array('description', 'context', 'target_class', 'filter', 'state', 'subscription_policy', 'action_list')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('target_class', 'state')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['description', 'context', 'target_class', 'filter', 'state', 'subscription_policy', 'action_list']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['target_class', 'state']); // Attributes to be displayed for a list // Search criteria - MetaModel::Init_SetZListItems('standard_search', array('description', 'target_class', 'state')); // Criteria of the std search form + MetaModel::Init_SetZListItems('standard_search', ['description', 'target_class', 'state']); // Criteria of the std search form // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form } } @@ -506,8 +498,8 @@ class TriggerOnStateLeave extends TriggerOnStateChange */ public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "grant_by_profile,core/cmdb,application", "key_type" => "autoincrement", "name_attcode" => "description", @@ -517,15 +509,15 @@ class TriggerOnStateLeave extends TriggerOnStateChange "db_table" => "priv_trigger_onstateleave", "db_key_field" => "id", "db_finalclass_field" => "", - ); + ]; MetaModel::Init_Params($aParams); MetaModel::Init_InheritAttributes(); // Display lists - MetaModel::Init_SetZListItems('details', array('description', 'context', 'target_class', 'filter', 'state', 'subscription_policy', 'action_list')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('target_class', 'state')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['description', 'context', 'target_class', 'filter', 'state', 'subscription_policy', 'action_list']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['target_class', 'state']); // Attributes to be displayed for a list // Search criteria - MetaModel::Init_SetZListItems('standard_search', array('description', 'target_class', 'state')); // Criteria of the std search form + MetaModel::Init_SetZListItems('standard_search', ['description', 'target_class', 'state']); // Criteria of the std search form // MetaModel::Init_SetZListItems('advanced_search', array('')); // Criteria of the advanced search form } } @@ -540,8 +532,8 @@ class TriggerOnObjectCreate extends TriggerOnObject */ public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "grant_by_profile,core/cmdb,application", "key_type" => "autoincrement", "name_attcode" => "description", @@ -551,15 +543,15 @@ class TriggerOnObjectCreate extends TriggerOnObject "db_table" => "priv_trigger_onobjcreate", "db_key_field" => "id", "db_finalclass_field" => "", - ); + ]; MetaModel::Init_Params($aParams); MetaModel::Init_InheritAttributes(); // Display lists - MetaModel::Init_SetZListItems('details', array('description', 'context', 'target_class', 'filter', 'subscription_policy', 'action_list')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('finalclass', 'target_class')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['description', 'context', 'target_class', 'filter', 'subscription_policy', 'action_list']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['finalclass', 'target_class']); // Attributes to be displayed for a list // Search criteria - MetaModel::Init_SetZListItems('standard_search', array('description', 'target_class')); // Criteria of the std search form + MetaModel::Init_SetZListItems('standard_search', ['description', 'target_class']); // Criteria of the std search form // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form } @@ -575,8 +567,8 @@ class TriggerOnObjectDelete extends TriggerOnObject */ public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "grant_by_profile,core/cmdb,application", "key_type" => "autoincrement", "name_attcode" => "description", @@ -586,15 +578,15 @@ class TriggerOnObjectDelete extends TriggerOnObject "db_table" => "priv_trigger_onobjdelete", "db_key_field" => "id", "db_finalclass_field" => "", - ); + ]; MetaModel::Init_Params($aParams); MetaModel::Init_InheritAttributes(); // Display lists - MetaModel::Init_SetZListItems('details', array('description', 'context', 'target_class', 'filter', 'subscription_policy', 'action_list')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('finalclass', 'target_class')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['description', 'context', 'target_class', 'filter', 'subscription_policy', 'action_list']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['finalclass', 'target_class']); // Attributes to be displayed for a list // Search criteria - MetaModel::Init_SetZListItems('standard_search', array('description', 'target_class')); // Criteria of the std search form + MetaModel::Init_SetZListItems('standard_search', ['description', 'target_class']); // Criteria of the std search form // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form } } @@ -610,8 +602,8 @@ class TriggerOnObjectUpdate extends TriggerOnObject */ public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "grant_by_profile,core/cmdb,application", "key_type" => "autoincrement", "name_attcode" => "description", @@ -621,37 +613,33 @@ class TriggerOnObjectUpdate extends TriggerOnObject "db_table" => "priv_trigger_onobjupdate", "db_key_field" => "id", "db_finalclass_field" => "", - ); + ]; MetaModel::Init_Params($aParams); MetaModel::Init_InheritAttributes(); - MetaModel::Init_AddAttribute(new AttributeClassAttCodeSet('target_attcodes', array("allowed_values" => null, "class_field" => "target_class", "sql" => "target_attcodes", "default_value" => null, "is_null_allowed" => true, "max_items" => 20, "min_items" => 0, "attribute_definition_exclusion_list" => "AttributeDashboard,AttributeExternalField,AttributeFinalClass,AttributeFriendlyName,AttributeObsolescenceDate,AttributeObsolescenceFlag,AttributeSubItem", "attribute_definition_list" => null, "depends_on" => array('target_class')))); + MetaModel::Init_AddAttribute(new AttributeClassAttCodeSet('target_attcodes', ["allowed_values" => null, "class_field" => "target_class", "sql" => "target_attcodes", "default_value" => null, "is_null_allowed" => true, "max_items" => 20, "min_items" => 0, "attribute_definition_exclusion_list" => "AttributeDashboard,AttributeExternalField,AttributeFinalClass,AttributeFriendlyName,AttributeObsolescenceDate,AttributeObsolescenceFlag,AttributeSubItem", "attribute_definition_list" => null, "depends_on" => ['target_class']])); // Display lists - MetaModel::Init_SetZListItems('details', array('description', 'context', 'target_class', 'filter', 'target_attcodes', 'subscription_policy', 'action_list')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('finalclass', 'target_class')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['description', 'context', 'target_class', 'filter', 'target_attcodes', 'subscription_policy', 'action_list']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['finalclass', 'target_class']); // Attributes to be displayed for a list // Search criteria - MetaModel::Init_SetZListItems('standard_search', array('description', 'target_class')); // Criteria of the std search form + MetaModel::Init_SetZListItems('standard_search', ['description', 'target_class']); // Criteria of the std search form } - public function IsTargetObject($iObjectId, $aChanges = array()) + public function IsTargetObject($iObjectId, $aChanges = []) { - if (!parent::IsTargetObject($iObjectId, $aChanges)) - { + if (!parent::IsTargetObject($iObjectId, $aChanges)) { return false; } // Check the attribute $oAttCodeSet = $this->Get('target_attcodes'); $aAttCodes = $oAttCodeSet->GetValues(); - if (empty($aAttCodes)) - { + if (empty($aAttCodes)) { return true; } - foreach($aAttCodes as $sAttCode) - { - if (array_key_exists($sAttCode, $aChanges)) - { + foreach ($aAttCodes as $sAttCode) { + if (array_key_exists($sAttCode, $aChanges)) { return true; } } @@ -664,26 +652,22 @@ class TriggerOnObjectUpdate extends TriggerOnObject // Remove unwanted attribute codes $aChanges = $this->ListChanges(); - if (isset($aChanges['target_attcodes'])) - { + if (isset($aChanges['target_attcodes'])) { $oAttDef = MetaModel::GetAttributeDef(get_class($this), 'target_attcodes'); - $aArgs = array('this' => $this); + $aArgs = ['this' => $this]; $aAllowedValues = $oAttDef->GetAllowedValues($aArgs); /** @var \ormSet $oValue */ $oValue = $this->Get('target_attcodes'); $aValues = $oValue->GetValues(); $bChanged = false; - foreach($aValues as $key => $sValue) - { - if (!isset($aAllowedValues[$sValue])) - { + foreach ($aValues as $key => $sValue) { + if (!isset($aAllowedValues[$sValue])) { unset($aValues[$key]); $bChanged = true; } } - if ($bChanged) - { + if ($bChanged) { $oValue->SetValues($aValues); $this->Set('target_attcodes', $oValue); } @@ -706,8 +690,8 @@ class TriggerOnObjectMention extends TriggerOnObject */ public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "grant_by_profile,core/cmdb,application", "key_type" => "autoincrement", "name_attcode" => "description", @@ -718,16 +702,16 @@ class TriggerOnObjectMention extends TriggerOnObject "db_key_field" => "id", "db_finalclass_field" => "", "display_template" => "", - ); + ]; MetaModel::Init_Params($aParams); MetaModel::Init_InheritAttributes(); - MetaModel::Init_AddAttribute(new AttributeOQL("mentioned_filter", array("allowed_values" => null, "sql" => "mentioned_filter", "default_value" => null, "is_null_allowed" => true, "depends_on" => array()))); + MetaModel::Init_AddAttribute(new AttributeOQL("mentioned_filter", ["allowed_values" => null, "sql" => "mentioned_filter", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); // Display lists - MetaModel::Init_SetZListItems('details', array('description', 'context', 'target_class', 'filter', 'mentioned_filter', 'subscription_policy', 'action_list')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('finalclass', 'target_class')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['description', 'context', 'target_class', 'filter', 'mentioned_filter', 'subscription_policy', 'action_list']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['finalclass', 'target_class']); // Attributes to be displayed for a list // Search criteria - MetaModel::Init_SetZListItems('standard_search', array('description', 'target_class')); // Criteria of the std search form + MetaModel::Init_SetZListItems('standard_search', ['description', 'target_class']); // Criteria of the std search form } /** @@ -745,8 +729,7 @@ class TriggerOnObjectMention extends TriggerOnObject public function IsMentionedObjectInScope(DBObject $oObject) { $sFilter = trim($this->Get('mentioned_filter')); - if (strlen($sFilter) > 0) - { + if (strlen($sFilter) > 0) { $oSearch = DBObjectSearch::FromOQL($sFilter); $sSearchClass = $oSearch->GetClass(); @@ -763,9 +746,7 @@ class TriggerOnObjectMention extends TriggerOnObject $aParams = $oObject->ToArgs('this'); $oSet = new DBObjectSet($oSearch, [], $aParams); $bRet = $oSet->CountExceeds(0); - } - else - { + } else { $bRet = true; } @@ -787,8 +768,8 @@ class TriggerOnAttributeBlobDownload extends TriggerOnObject */ public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "grant_by_profile,core/cmdb,application", "key_type" => "autoincrement", "name_attcode" => "description", @@ -799,7 +780,7 @@ class TriggerOnAttributeBlobDownload extends TriggerOnObject "db_key_field" => "id", "db_finalclass_field" => "", "display_template" => "", - ); + ]; MetaModel::Init_Params($aParams); MetaModel::Init_InheritAttributes(); } @@ -816,42 +797,42 @@ class lnkTriggerAction extends cmdbAbstractObject */ public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "grant_by_profile,core/cmdb,application", "key_type" => "autoincrement", "name_attcode" => "", "state_attcode" => "", - "reconc_keys" => array('action_id', 'trigger_id'), + "reconc_keys" => ['action_id', 'trigger_id'], "db_table" => "priv_link_action_trigger", "db_key_field" => "link_id", "db_finalclass_field" => "", "is_link" => true, - 'uniqueness_rules' => array( - 'no_duplicate' => array( - 'attributes' => array( + 'uniqueness_rules' => [ + 'no_duplicate' => [ + 'attributes' => [ 0 => 'action_id', 1 => 'trigger_id', - ), + ], 'filter' => '', 'disabled' => false, 'is_blocking' => true, - ), - ), - ); + ], + ], + ]; MetaModel::Init_Params($aParams); - MetaModel::Init_AddAttribute(new AttributeExternalKey("action_id", array("targetclass" => "Action", "jointype" => '', "allowed_values" => null, "sql" => "action_id", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => array()))); - MetaModel::Init_AddAttribute(new AttributeExternalField("action_name", array("allowed_values" => null, "extkey_attcode" => 'action_id', "target_attcode" => "name"))); - MetaModel::Init_AddAttribute(new AttributeExternalKey("trigger_id", array("targetclass" => "Trigger", "jointype" => '', "allowed_values" => null, "sql" => "trigger_id", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => array()))); - MetaModel::Init_AddAttribute(new AttributeExternalField("trigger_name", array("allowed_values" => null, "extkey_attcode" => 'trigger_id', "target_attcode" => "description"))); - MetaModel::Init_AddAttribute(new AttributeInteger("order", array("allowed_values" => null, "sql" => "order", "default_value" => 0, "is_null_allowed" => true, "depends_on" => array()))); + MetaModel::Init_AddAttribute(new AttributeExternalKey("action_id", ["targetclass" => "Action", "jointype" => '', "allowed_values" => null, "sql" => "action_id", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeExternalField("action_name", ["allowed_values" => null, "extkey_attcode" => 'action_id', "target_attcode" => "name"])); + MetaModel::Init_AddAttribute(new AttributeExternalKey("trigger_id", ["targetclass" => "Trigger", "jointype" => '', "allowed_values" => null, "sql" => "trigger_id", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeExternalField("trigger_name", ["allowed_values" => null, "extkey_attcode" => 'trigger_id', "target_attcode" => "description"])); + MetaModel::Init_AddAttribute(new AttributeInteger("order", ["allowed_values" => null, "sql" => "order", "default_value" => 0, "is_null_allowed" => true, "depends_on" => []])); // Display lists - MetaModel::Init_SetZListItems('details', array('action_id', 'trigger_id', 'order')); // Attributes to be displayed for a list - MetaModel::Init_SetZListItems('list', array('action_id', 'trigger_id', 'order')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['action_id', 'trigger_id', 'order']); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('list', ['action_id', 'trigger_id', 'order']); // Attributes to be displayed for a list // Search criteria - MetaModel::Init_SetZListItems('standard_search', array('action_id', 'trigger_id', 'order')); // Criteria of the std search form - MetaModel::Init_SetZListItems('advanced_search', array('action_id', 'trigger_id', 'order')); // Criteria of the advanced search form + MetaModel::Init_SetZListItems('standard_search', ['action_id', 'trigger_id', 'order']); // Criteria of the std search form + MetaModel::Init_SetZListItems('advanced_search', ['action_id', 'trigger_id', 'order']); // Criteria of the advanced search form } } @@ -866,8 +847,8 @@ class TriggerOnThresholdReached extends TriggerOnObject */ public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "grant_by_profile,core/cmdb,application", "key_type" => "autoincrement", "name_attcode" => "description", @@ -877,18 +858,18 @@ class TriggerOnThresholdReached extends TriggerOnObject "db_table" => "priv_trigger_threshold", "db_key_field" => "id", "db_finalclass_field" => "", - ); + ]; MetaModel::Init_Params($aParams); MetaModel::Init_InheritAttributes(); - MetaModel::Init_AddAttribute(new AttributeClassAttCodeSet('stop_watch_code', array("allowed_values" => null, "class_field" => "target_class", "sql" => "stop_watch_code", "default_value" => null, "is_null_allowed" => false, "max_items" => 1, "min_items" => 1, "attribute_definition_exclusion_list" => null, "attribute_definition_list" => "AttributeStopWatch", "include_child_classes_attributes" => true, "depends_on" => array('target_class')))); - MetaModel::Init_AddAttribute(new AttributeString("threshold_index", array("allowed_values" => null, "sql" => "threshold_index", "default_value" => null, "is_null_allowed" => false, "depends_on" => array()))); + MetaModel::Init_AddAttribute(new AttributeClassAttCodeSet('stop_watch_code', ["allowed_values" => null, "class_field" => "target_class", "sql" => "stop_watch_code", "default_value" => null, "is_null_allowed" => false, "max_items" => 1, "min_items" => 1, "attribute_definition_exclusion_list" => null, "attribute_definition_list" => "AttributeStopWatch", "include_child_classes_attributes" => true, "depends_on" => ['target_class']])); + MetaModel::Init_AddAttribute(new AttributeString("threshold_index", ["allowed_values" => null, "sql" => "threshold_index", "default_value" => null, "is_null_allowed" => false, "depends_on" => []])); // Display lists - MetaModel::Init_SetZListItems('details', array('description', 'context', 'target_class', 'stop_watch_code', 'threshold_index', 'filter', 'subscription_policy', 'action_list')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('target_class', 'threshold_index', 'threshold_index')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['description', 'context', 'target_class', 'stop_watch_code', 'threshold_index', 'filter', 'subscription_policy', 'action_list']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['target_class', 'threshold_index', 'threshold_index']); // Attributes to be displayed for a list // Search criteria - MetaModel::Init_SetZListItems('standard_search', array('description', 'target_class')); // Criteria of the std search form + MetaModel::Init_SetZListItems('standard_search', ['description', 'target_class']); // Criteria of the std search form // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form } } diff --git a/core/valuesetdef.class.inc.php b/core/valuesetdef.class.inc.php index 5fed013b0..8a9c91494 100644 --- a/core/valuesetdef.class.inc.php +++ b/core/valuesetdef.class.inc.php @@ -1,4 +1,5 @@ - /** * Value set definitions (from a fixed list or from a query, etc.) * @@ -37,16 +37,14 @@ require_once('MyHelpers.class.inc.php'); abstract class ValueSetDefinition { protected $m_bIsLoaded = false; - protected $m_aValues = array(); - + protected $m_aValues = []; // Displayable description that could be computed out of the std usage context public function GetValuesDescription() { - $aValues = $this->GetValues(array(), ''); - $aDisplayedValues = array(); - foreach($aValues as $key => $value) - { + $aValues = $this->GetValues([], ''); + $aDisplayedValues = []; + foreach ($aValues as $key => $value) { $aDisplayedValues[] = "$key => $value"; } $sAllowedValues = implode(', ', $aDisplayedValues); @@ -62,24 +60,18 @@ abstract class ValueSetDefinition */ public function GetValues($aArgs, $sContains = '', $sOperation = 'contains') { - if (!$this->m_bIsLoaded) - { + if (!$this->m_bIsLoaded) { $this->LoadValues($aArgs); $this->m_bIsLoaded = true; } - if (strlen($sContains) == 0) - { + if (strlen($sContains) == 0) { // No filtering $aRet = $this->m_aValues; - } - else - { + } else { // Filter on results containing the needle - $aRet = array(); - foreach ($this->m_aValues as $sKey=>$sValue) - { - if (stripos($sValue, $sContains) !== false) - { + $aRet = []; + foreach ($this->m_aValues as $sKey => $sValue) { + if (stripos($sValue, $sContains) !== false) { $aRet[$sKey] = $sValue; } } @@ -103,7 +95,6 @@ abstract class ValueSetDefinition abstract protected function LoadValues($aArgs); } - /** * Set of existing values for an attribute, given a search filter * @@ -122,11 +113,10 @@ class ValueSetObjects extends ValueSetDefinition private $m_bSort; private $m_iLimit; - /** * @param hash $aOrderBy Array of '[.]attcode' => bAscending */ - public function __construct($sFilterExp, $sValueAttCode = '', $aOrderBy = array(), $bAllowAllData = false, $aModifierProperties = array()) + public function __construct($sFilterExp, $sValueAttCode = '', $aOrderBy = [], $bAllowAllData = false, $aModifierProperties = []) { $this->m_sContains = ''; $this->m_sOperation = ''; @@ -155,54 +145,48 @@ class ValueSetObjects extends ValueSetDefinition { $this->m_aOrderBy = $aOrderBy; } - public function ToObjectSet($aArgs = array(), $sContains = '', $iAdditionalValue = null) + public function ToObjectSet($aArgs = [], $sContains = '', $iAdditionalValue = null) { - if ($this->m_bAllowAllData) - { + if ($this->m_bAllowAllData) { $oFilter = DBObjectSearch::FromOQL_AllData($this->m_sFilterExpr); - } - else - { + } else { $oFilter = DBObjectSearch::FromOQL($this->m_sFilterExpr); } - if (!is_null($this->m_oExtraCondition)) - { + if (!is_null($this->m_oExtraCondition)) { $oFilter = $oFilter->Intersect($this->m_oExtraCondition); } - foreach($this->m_aModifierProperties as $sPluginClass => $aProperties) - { - foreach ($aProperties as $sProperty => $value) - { + foreach ($this->m_aModifierProperties as $sPluginClass => $aProperties) { + foreach ($aProperties as $sProperty => $value) { $oFilter->SetModifierProperty($sPluginClass, $sProperty, $value); } } - if ($iAdditionalValue > 0) - { + if ($iAdditionalValue > 0) { $oSearchAdditionalValue = new DBObjectSearch($oFilter->GetClass()); - $oSearchAdditionalValue->AddConditionExpression( new BinaryExpression( - new FieldExpression('id', $oSearchAdditionalValue->GetClassAlias()), - '=', - new VariableExpression('current_extkey_id')) - ); + $oSearchAdditionalValue->AddConditionExpression( + new BinaryExpression( + new FieldExpression('id', $oSearchAdditionalValue->GetClassAlias()), + '=', + new VariableExpression('current_extkey_id') + ) + ); $oSearchAdditionalValue->AllowAllData(); $oSearchAdditionalValue->SetArchiveMode(true); - $oSearchAdditionalValue->SetInternalParams( array('current_extkey_id' => $iAdditionalValue) ); + $oSearchAdditionalValue->SetInternalParams(['current_extkey_id' => $iAdditionalValue]); - $oFilter = new DBUnionSearch(array($oFilter, $oSearchAdditionalValue)); + $oFilter = new DBUnionSearch([$oFilter, $oSearchAdditionalValue]); } return new DBObjectSet($oFilter, $this->m_aOrderBy, $aArgs); } - /** - * @inheritDoc - * @throws CoreException - * @throws OQLException - */ - public function GetValues($aArgs, $sContains = '', $sOperation = 'contains') + /** + * @inheritDoc + * @throws CoreException + * @throws OQLException + */ + public function GetValues($aArgs, $sContains = '', $sOperation = 'contains') { - if (!$this->m_bIsLoaded || ($sContains != $this->m_sContains) || ($sOperation != $this->m_sOperation)) - { + if (!$this->m_bIsLoaded || ($sContains != $this->m_sContains) || ($sOperation != $this->m_sOperation)) { $this->LoadValues($aArgs, $sContains, $sOperation); $this->m_bIsLoaded = true; } @@ -225,15 +209,15 @@ class ValueSetObjects extends ValueSetDefinition $this->m_sContains = $sContains; $this->m_sOperation = $sOperation; - $this->m_aValues = array(); + $this->m_aValues = []; $oFilter = $this->GetFilter($sOperation, $sContains); $oObjects = new DBObjectSet($oFilter, $this->m_aOrderBy, $aArgs, null, $this->m_iLimit, 0, $this->m_bSort); if (empty($this->m_sValueAttCode)) { - $aAttToLoad = array($oFilter->GetClassAlias() => array('friendlyname')); + $aAttToLoad = [$oFilter->GetClassAlias() => ['friendlyname']]; } else { - $aAttToLoad = array($oFilter->GetClassAlias() => array($this->m_sValueAttCode)); + $aAttToLoad = [$oFilter->GetClassAlias() => [$this->m_sValueAttCode]]; } $oObjects->OptimizeColumnLoad($aAttToLoad); while ($oObject = $oObjects->Fetch()) { @@ -247,7 +231,6 @@ class ValueSetObjects extends ValueSetDefinition return true; } - /** * Get filter for functions LoadValues and LoadValuesForAutocomplete * @@ -297,7 +280,7 @@ class ValueSetObjects extends ValueSetDefinition $aAttributes = MetaModel::GetFriendlyNameAttributeCodeList($sClass); if (count($aAttributes) > 0) { $sClassAlias = $oFilter->GetClassAlias(); - $aFilters = array(); + $aFilters = []; $oValueExpr = new ScalarExpression($this->m_sContains); foreach ($aAttributes as $sAttribute) { $oNewFilter = $oFilter->DeepClone(); @@ -355,8 +338,7 @@ class ValueSetObjects extends ValueSetDefinition public function GetValuesForAutocomplete($aArgs, $sContains = '', $sOperation = 'contains') { - if (!$this->m_bIsLoaded || ($sContains != $this->m_sContains) || ($sOperation != $this->m_sOperation)) - { + if (!$this->m_bIsLoaded || ($sContains != $this->m_sContains) || ($sOperation != $this->m_sOperation)) { $this->LoadValuesForAutocomplete($aArgs, $sContains, $sOperation); $this->m_bIsLoaded = true; } @@ -376,7 +358,7 @@ class ValueSetObjects extends ValueSetDefinition */ protected function LoadValuesForAutocomplete($aArgs, $sContains = '', $sOperation = 'contains') { - $this->m_aValues = array(); + $this->m_aValues = []; $oFilter = $this->GetFilter($sOperation, $sContains); $sClass = $oFilter->GetClass(); @@ -444,7 +426,6 @@ class ValueSetObjects extends ValueSetDefinition } } - /** * Fixed set values (could be hardcoded in the business model) * @@ -514,8 +495,7 @@ class ValueSetEnum extends ValueSetDefinition protected function LoadValues($aArgs) { $aValues = []; - if (is_array($this->m_values)) - { + if (is_array($this->m_values)) { foreach ($this->m_values as $key => $value) { // Handle backed-enum case if (is_object($value) && enum_exists(get_class($value))) { @@ -525,18 +505,13 @@ class ValueSetEnum extends ValueSetDefinition $aValues[$key] = $value; } - } - elseif (is_string($this->m_values) && strlen($this->m_values) > 0) - { - foreach (explode(",", $this->m_values) as $sVal) - { + } elseif (is_string($this->m_values) && strlen($this->m_values) > 0) { + foreach (explode(",", $this->m_values) as $sVal) { $sVal = trim($sVal); $sKey = $sVal; $aValues[$sKey] = $sVal; } - } - else - { + } else { $aValues = []; } $this->m_aValues = $aValues; @@ -553,17 +528,13 @@ class ValueSetEnumPadded extends ValueSetEnum public function __construct($Values, bool $bSortByValues = false) { parent::__construct($Values, $bSortByValues); - if (is_string($Values)) - { + if (is_string($Values)) { $this->LoadValues(null); - } - else - { + } else { $this->m_aValues = $Values; } - $aPaddedValues = array(); - foreach ($this->m_aValues as $sKey => $sVal) - { + $aPaddedValues = []; + foreach ($this->m_aValues as $sKey => $sVal) { // Pad keys to the min. length required by the \AttributeSet $sKey = str_pad($sKey, 3, '_', STR_PAD_LEFT); $aPaddedValues[$sKey] = $sVal; @@ -592,15 +563,13 @@ class ValueSetRange extends ValueSetDefinition protected function LoadValues($aArgs) { $iValue = $this->m_iStart; - for($iValue = $this->m_iStart; $iValue <= $this->m_iEnd; $iValue += $this->m_iStep) - { + for ($iValue = $this->m_iStart; $iValue <= $this->m_iEnd; $iValue += $this->m_iStep) { $this->m_aValues[$iValue] = $iValue; } return true; } } - /** * Data model classes * @@ -622,27 +591,19 @@ class ValueSetEnumClasses extends ValueSetEnum parent::LoadValues($aArgs); // Translate the labels of the additional values - foreach($this->m_aValues as $sClass => $void) - { - if (MetaModel::IsValidClass($sClass)) - { + foreach ($this->m_aValues as $sClass => $void) { + if (MetaModel::IsValidClass($sClass)) { $this->m_aValues[$sClass] = MetaModel::GetName($sClass); - } - else - { + } else { unset($this->m_aValues[$sClass]); } } // Then, add the classes from the category definition - foreach (MetaModel::GetClasses($this->m_sCategories) as $sClass) - { - if (MetaModel::IsValidClass($sClass)) - { + foreach (MetaModel::GetClasses($this->m_sCategories) as $sClass) { + if (MetaModel::IsValidClass($sClass)) { $this->m_aValues[$sClass] = MetaModel::GetName($sClass); - } - else - { + } else { unset($this->m_aValues[$sClass]); } } diff --git a/datamodels/2.x/authent-cas/module.authent-cas.php b/datamodels/2.x/authent-cas/module.authent-cas.php index 7f67bf3d1..bce236835 100644 --- a/datamodels/2.x/authent-cas/module.authent-cas.php +++ b/datamodels/2.x/authent-cas/module.authent-cas.php @@ -1,4 +1,5 @@ 'CAS SSO', @@ -14,36 +15,36 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( - - ), + 'dependencies' => [ + + ], 'mandatory' => true, 'visible' => true, // Components // - 'datamodel' => array( + 'datamodel' => [ 'vendor/autoload.php', 'src/CASLoginExtension.php', - ), - 'webservice' => array( - - ), - 'data.struct' => array( + ], + 'webservice' => [ + + ], + 'data.struct' => [ // add your 'structure' definition XML files here, - ), - 'data.sample' => array( + ], + 'data.sample' => [ // add your sample data XML files here, - ), - + ], + // Documentation // 'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any - 'doc.more_information' => '', // hyperlink to more information, if any + 'doc.more_information' => '', // hyperlink to more information, if any // Default settings // - 'settings' => array( + 'settings' => [ // Authentication 'cas_debug' => false, 'cas_host' => '', @@ -51,6 +52,6 @@ SetupWebPage::AddModule( 'cas_context' => '', 'cas_version' => '', 'service_base_url' => '', - ), - ) + ], + ] ); diff --git a/datamodels/2.x/authent-external/module.authent-external.php b/datamodels/2.x/authent-external/module.authent-external.php index cd74ddbb2..d8046f28e 100755 --- a/datamodels/2.x/authent-external/module.authent-external.php +++ b/datamodels/2.x/authent-external/module.authent-external.php @@ -1,9 +1,10 @@ - /** * Authent External * Module definition file for the "External Authentication" module @@ -28,7 +28,7 @@ SetupWebPage::AddModule( __FILE__, // Path to the current file, all other file names are relative to the directory containing this file 'authent-external/3.3.0', - array( + [ // Identification // 'label' => 'External user authentication', @@ -36,23 +36,23 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( - ), + 'dependencies' => [ + ], 'mandatory' => false, 'visible' => true, // Components // - 'datamodel' => array( + 'datamodel' => [ 'model.authent-external.php', - ), - 'data.struct' => array( + ], + 'data.struct' => [ //'data.struct.authent-ldap.xml', - ), - 'data.sample' => array( + ], + 'data.sample' => [ //'data.sample.authent-ldap.xml', - ), - + ], + // Documentation // 'doc.manual_setup' => '', @@ -60,6 +60,6 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array(), - ) + 'settings' => [], + ] ); diff --git a/datamodels/2.x/authent-ldap/module.authent-ldap.php b/datamodels/2.x/authent-ldap/module.authent-ldap.php index d1f7cf715..7e66a72b7 100755 --- a/datamodels/2.x/authent-ldap/module.authent-ldap.php +++ b/datamodels/2.x/authent-ldap/module.authent-ldap.php @@ -1,100 +1,98 @@ 'User authentication based on LDAP', - 'category' => 'authentication', + SetupWebPage::AddModule( + __FILE__, // Path to the current file, all other file names are relative to the directory containing this file + 'authent-ldap/3.3.0', + [ + // Identification + // + 'label' => 'User authentication based on LDAP', + 'category' => 'authentication', - // Setup - // - 'dependencies' => array( - ), - 'mandatory' => false, - 'visible' => true, - 'installer' => 'AuthentLDAPInstaller', + // Setup + // + 'dependencies' => [ + ], + 'mandatory' => false, + 'visible' => true, + 'installer' => 'AuthentLDAPInstaller', - // Components - // - 'datamodel' => array( - ), - 'data.struct' => array( - //'data.struct.authent-ldap.xml', - ), - 'data.sample' => array( - //'data.sample.authent-ldap.xml', - ), - - // Documentation - // - 'doc.manual_setup' => '', - 'doc.more_information' => '', + // Components + // + 'datamodel' => [ + ], + 'data.struct' => [ + //'data.struct.authent-ldap.xml', + ], + 'data.sample' => [ + //'data.sample.authent-ldap.xml', + ], - // Default settings - // - 'settings' => array( - 'uri' => 'ldap://localhost', // URI with host or IP address of your LDAP server - 'default_user' => '', // User and password used for initial "Anonymous" bind to LDAP - 'default_pwd' => '', // Leave both blank, if anonymous (read-only) bind is allowed - 'base_dn' => 'dc=yourcompany,dc=com', // Base DN for User queries, adjust it to your LDAP schema - 'user_query' => '(&(uid=%1$s)(inetuserstatus=ACTIVE))', // Query used to retrieve each user %1$s => iTop login - // For Windows AD use (samaccountname=%1$s) or (userprincipalname=%1$s) - - // Some extra LDAP options, refer to: http://www.php.net/manual/en/function.ldap-set-option.php for more info - 'options' => array( - LDAP_OPT_PROTOCOL_VERSION => 3, - LDAP_OPT_REFERRALS => 0, - ), - 'start_tls' => false, - 'debug' => false, - 'servers' => array(), - ), - ) -); + // Documentation + // + 'doc.manual_setup' => '', + 'doc.more_information' => '', -// Module installation handler -// -class AuthentLDAPInstaller extends ModuleInstallerAPI -{ - public static function AfterDataLoad(Config $oConfiguration, $sPreviousVersion, $sCurrentVersion) + // Default settings + // + 'settings' => [ + 'uri' => 'ldap://localhost', // URI with host or IP address of your LDAP server + 'default_user' => '', // User and password used for initial "Anonymous" bind to LDAP + 'default_pwd' => '', // Leave both blank, if anonymous (read-only) bind is allowed + 'base_dn' => 'dc=yourcompany,dc=com', // Base DN for User queries, adjust it to your LDAP schema + 'user_query' => '(&(uid=%1$s)(inetuserstatus=ACTIVE))', // Query used to retrieve each user %1$s => iTop login + // For Windows AD use (samaccountname=%1$s) or (userprincipalname=%1$s) + + // Some extra LDAP options, refer to: http://www.php.net/manual/en/function.ldap-set-option.php for more info + 'options' => [ + LDAP_OPT_PROTOCOL_VERSION => 3, + LDAP_OPT_REFERRALS => 0, + ], + 'start_tls' => false, + 'debug' => false, + 'servers' => [], + ], + ] + ); + + // Module installation handler + // + class AuthentLDAPInstaller extends ModuleInstallerAPI { - // Create missing table entries - $sUserLDAPTable = MetaModel::DBGetTable('UserLDAP'); - $sUserTable = MetaModel::DBGetTable('User'); - $sSQL = "insert into $sUserLDAPTable (id) select U.id from $sUserTable as U left join $sUserLDAPTable as L on U.id = L.id where U.finalclass='UserLDAP' and isnull(L.id);"; - CMDBSource::Query($sSQL); - } - - public static function BeforeWritingConfig(Config $oConfiguration) - { - $sURI = $oConfiguration->GetModuleSetting('authent-ldap', 'uri'); - if (empty($sURI)) { - $sLDAPHost = MetaModel::GetModuleSetting('authent-ldap', 'host', 'localhost'); - $iLDAPPort = MetaModel::GetModuleSetting('authent-ldap', 'port', 389); - $sURI = preg_match('#^ldaps?://#i', $sLDAPHost) ? $sLDAPHost : 'ldap://'.$sLDAPHost.':'.$iLDAPPort; - $oConfiguration->SetModuleSetting('authent-ldap', 'uri', $sURI); + public static function AfterDataLoad(Config $oConfiguration, $sPreviousVersion, $sCurrentVersion) + { + // Create missing table entries + $sUserLDAPTable = MetaModel::DBGetTable('UserLDAP'); + $sUserTable = MetaModel::DBGetTable('User'); + $sSQL = "insert into $sUserLDAPTable (id) select U.id from $sUserTable as U left join $sUserLDAPTable as L on U.id = L.id where U.finalclass='UserLDAP' and isnull(L.id);"; + CMDBSource::Query($sSQL); } - $aServers = $oConfiguration->GetModuleSetting('authent-ldap', 'servers', []); - foreach ($aServers as &$aServer) { - if (!array_key_exists($aServer, 'uri')) { - $sLDAPHost = $aServerParams['host'] ?? 'localhost'; - $iLDAPPort = $aServerParams['port'] ?? 389; - $aServer['uri'] = preg_match('#^ldaps?://#i', $sLDAPHost) ? $sLDAPHost : 'ldap://'.$sLDAPHost.':'.$iLDAPPort; + public static function BeforeWritingConfig(Config $oConfiguration) + { + $sURI = $oConfiguration->GetModuleSetting('authent-ldap', 'uri'); + if (empty($sURI)) { + $sLDAPHost = MetaModel::GetModuleSetting('authent-ldap', 'host', 'localhost'); + $iLDAPPort = MetaModel::GetModuleSetting('authent-ldap', 'port', 389); + $sURI = preg_match('#^ldaps?://#i', $sLDAPHost) ? $sLDAPHost : 'ldap://'.$sLDAPHost.':'.$iLDAPPort; + $oConfiguration->SetModuleSetting('authent-ldap', 'uri', $sURI); } + + $aServers = $oConfiguration->GetModuleSetting('authent-ldap', 'servers', []); + foreach ($aServers as &$aServer) { + if (!array_key_exists($aServer, 'uri')) { + $sLDAPHost = $aServerParams['host'] ?? 'localhost'; + $iLDAPPort = $aServerParams['port'] ?? 389; + $aServer['uri'] = preg_match('#^ldaps?://#i', $sLDAPHost) ? $sLDAPHost : 'ldap://'.$sLDAPHost.':'.$iLDAPPort; + } + } + $oConfiguration->SetModuleSetting('authent-ldap', 'servers', $aServers); } - $oConfiguration->SetModuleSetting('authent-ldap', 'servers', $aServers); } -} } // if (function_exists('ldap_connect')) diff --git a/datamodels/2.x/authent-local/module.authent-local.php b/datamodels/2.x/authent-local/module.authent-local.php index c1f008f39..19eb5e854 100755 --- a/datamodels/2.x/authent-local/module.authent-local.php +++ b/datamodels/2.x/authent-local/module.authent-local.php @@ -1,10 +1,9 @@ 'User authentication based on the local DB', @@ -12,23 +11,23 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( - ), + 'dependencies' => [ + ], 'mandatory' => true, 'visible' => true, // Components // - 'datamodel' => array( + 'datamodel' => [ 'model.authent-local.php', - ), - 'data.struct' => array( + ], + 'data.struct' => [ //'data.struct.authent-local.xml', - ), - 'data.sample' => array( + ], + 'data.sample' => [ //'data.sample.authent-local.xml', - ), - + ], + // Documentation // 'doc.manual_setup' => '', @@ -37,8 +36,8 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array( + 'settings' => [ // see the './datamodel.authent-local.xml' for the default settings! - ), - ) + ], + ] ); diff --git a/datamodels/2.x/combodo-backoffice-darkmoon-theme/module.combodo-backoffice-darkmoon-theme.php b/datamodels/2.x/combodo-backoffice-darkmoon-theme/module.combodo-backoffice-darkmoon-theme.php index abda98f5e..9175680f0 100644 --- a/datamodels/2.x/combodo-backoffice-darkmoon-theme/module.combodo-backoffice-darkmoon-theme.php +++ b/datamodels/2.x/combodo-backoffice-darkmoon-theme/module.combodo-backoffice-darkmoon-theme.php @@ -1,4 +1,5 @@ 'Backoffice: Darkmoon theme', @@ -14,38 +15,35 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( - - ), + 'dependencies' => [ + + ], 'mandatory' => true, 'visible' => false, // Components // - 'datamodel' => array( - ), - 'webservice' => array( - - ), - 'data.struct' => array( + 'datamodel' => [ + ], + 'webservice' => [ + + ], + 'data.struct' => [ // add your 'structure' definition XML files here, - ), - 'data.sample' => array( + ], + 'data.sample' => [ // add your sample data XML files here, - ), - + ], + // Documentation // 'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any - 'doc.more_information' => '', // hyperlink to more information, if any + 'doc.more_information' => '', // hyperlink to more information, if any // Default settings // - 'settings' => array( + 'settings' => [ // Module specific settings go here, if any - ), - ) + ], + ] ); - - -?> diff --git a/datamodels/2.x/combodo-backoffice-fullmoon-high-contrast-theme/module.combodo-backoffice-fullmoon-high-contrast-theme.php b/datamodels/2.x/combodo-backoffice-fullmoon-high-contrast-theme/module.combodo-backoffice-fullmoon-high-contrast-theme.php index d9567881f..87d38fa5a 100644 --- a/datamodels/2.x/combodo-backoffice-fullmoon-high-contrast-theme/module.combodo-backoffice-fullmoon-high-contrast-theme.php +++ b/datamodels/2.x/combodo-backoffice-fullmoon-high-contrast-theme/module.combodo-backoffice-fullmoon-high-contrast-theme.php @@ -1,4 +1,5 @@ 'Backoffice: Fullmoon with high contrast accessibility theme', @@ -14,38 +15,35 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( - - ), + 'dependencies' => [ + + ], 'mandatory' => true, 'visible' => false, // Components // - 'datamodel' => array( - ), - 'webservice' => array( - - ), - 'data.struct' => array( + 'datamodel' => [ + ], + 'webservice' => [ + + ], + 'data.struct' => [ // add your 'structure' definition XML files here, - ), - 'data.sample' => array( + ], + 'data.sample' => [ // add your sample data XML files here, - ), - + ], + // Documentation // 'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any - 'doc.more_information' => '', // hyperlink to more information, if any + 'doc.more_information' => '', // hyperlink to more information, if any // Default settings // - 'settings' => array( + 'settings' => [ // Module specific settings go here, if any - ), - ) + ], + ] ); - - -?> diff --git a/datamodels/2.x/combodo-backoffice-fullmoon-protanopia-deuteranopia-theme/module.combodo-backoffice-fullmoon-protanopia-deuteranopia-theme.php b/datamodels/2.x/combodo-backoffice-fullmoon-protanopia-deuteranopia-theme/module.combodo-backoffice-fullmoon-protanopia-deuteranopia-theme.php index a058c5690..1f4fd1016 100644 --- a/datamodels/2.x/combodo-backoffice-fullmoon-protanopia-deuteranopia-theme/module.combodo-backoffice-fullmoon-protanopia-deuteranopia-theme.php +++ b/datamodels/2.x/combodo-backoffice-fullmoon-protanopia-deuteranopia-theme/module.combodo-backoffice-fullmoon-protanopia-deuteranopia-theme.php @@ -1,4 +1,5 @@ 'Backoffice: Fullmoon with protonopia & deuteranopia accessibility theme', @@ -14,38 +15,35 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( - - ), + 'dependencies' => [ + + ], 'mandatory' => true, 'visible' => false, // Components // - 'datamodel' => array( - ), - 'webservice' => array( - - ), - 'data.struct' => array( + 'datamodel' => [ + ], + 'webservice' => [ + + ], + 'data.struct' => [ // add your 'structure' definition XML files here, - ), - 'data.sample' => array( + ], + 'data.sample' => [ // add your sample data XML files here, - ), - + ], + // Documentation // 'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any - 'doc.more_information' => '', // hyperlink to more information, if any + 'doc.more_information' => '', // hyperlink to more information, if any // Default settings // - 'settings' => array( + 'settings' => [ // Module specific settings go here, if any - ), - ) + ], + ] ); - - -?> diff --git a/datamodels/2.x/combodo-backoffice-fullmoon-tritanopia-theme/module.combodo-backoffice-fullmoon-tritanopia-theme.php b/datamodels/2.x/combodo-backoffice-fullmoon-tritanopia-theme/module.combodo-backoffice-fullmoon-tritanopia-theme.php index ed02d278a..d4d818f38 100644 --- a/datamodels/2.x/combodo-backoffice-fullmoon-tritanopia-theme/module.combodo-backoffice-fullmoon-tritanopia-theme.php +++ b/datamodels/2.x/combodo-backoffice-fullmoon-tritanopia-theme/module.combodo-backoffice-fullmoon-tritanopia-theme.php @@ -1,4 +1,5 @@ 'Backoffice: Fullmoon with tritanopia accessibility theme', @@ -14,38 +15,35 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( - - ), + 'dependencies' => [ + + ], 'mandatory' => true, 'visible' => false, // Components // - 'datamodel' => array( - ), - 'webservice' => array( - - ), - 'data.struct' => array( + 'datamodel' => [ + ], + 'webservice' => [ + + ], + 'data.struct' => [ // add your 'structure' definition XML files here, - ), - 'data.sample' => array( + ], + 'data.sample' => [ // add your sample data XML files here, - ), - + ], + // Documentation // 'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any - 'doc.more_information' => '', // hyperlink to more information, if any + 'doc.more_information' => '', // hyperlink to more information, if any // Default settings // - 'settings' => array( + 'settings' => [ // Module specific settings go here, if any - ), - ) + ], + ] ); - - -?> diff --git a/datamodels/2.x/combodo-db-tools/module.combodo-db-tools.php b/datamodels/2.x/combodo-db-tools/module.combodo-db-tools.php index 5c48fe12b..a2a33fd89 100644 --- a/datamodels/2.x/combodo-db-tools/module.combodo-db-tools.php +++ b/datamodels/2.x/combodo-db-tools/module.combodo-db-tools.php @@ -1,4 +1,5 @@ 'Database maintenance tools', @@ -33,21 +34,21 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( + 'dependencies' => [ 'itop-structure/3.0.0', - ), + ], 'mandatory' => false, 'visible' => true, // Components // - 'datamodel' => array( + 'datamodel' => [ 'src/Service/DBToolsUtils.php', - 'src/Service/DBAnalyzerUtils.php', - ), - 'webservice' => array(), - 'data.struct' => array(), - 'data.sample' => array(), + 'src/Service/DBAnalyzerUtils.php', + ], + 'webservice' => [], + 'data.struct' => [], + 'data.sample' => [], // Documentation // @@ -56,6 +57,6 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array(), - ) + 'settings' => [], + ] ); diff --git a/datamodels/2.x/itop-attachments/dictionaries/cs.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/cs.dict.itop-attachments.php index 7d72ab48b..bf417ccc8 100644 --- a/datamodels/2.x/itop-attachments/dictionaries/cs.dict.itop-attachments.php +++ b/datamodels/2.x/itop-attachments/dictionaries/cs.dict.itop-attachments.php @@ -1,17 +1,18 @@ * @author Daniel Rokos * */ -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Attachments:TabTitle_Count' => 'Přílohy (%1$d)', 'Attachments:EmptyTabTitle' => 'Přílohy', 'Attachments:FieldsetTitle' => 'Přílohy', @@ -32,13 +33,13 @@ nebe se zeptejte'.ITOP_APPLICATION_SHORT.' správce '.ITOP_APPLICATION_SHORT.' z 'Attachments:Render:Icons' => 'Zobrazit jako ikony', 'Attachments:Render:Table' => 'Zobrazit jako seznam', 'UI:Attachments:DropYourFileHint' => 'Drop files anywhere in this area~~', -)); +]); // // Class: Attachment // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:Attachment' => 'Příloha', 'Class:Attachment+' => '~~', 'Class:Attachment/Attribute:expire' => 'Exspirace', @@ -53,10 +54,9 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Class:Attachment/Attribute:item_org_id+' => '~~', 'Class:Attachment/Attribute:contents' => 'Obsah', 'Class:Attachment/Attribute:contents+' => '~~', -)); +]); - -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Attachments:File:Thumbnail' => 'Ikona', 'Attachments:File:Name' => 'Jméno souboru', 'Attachments:File:Date' => 'Datum nahrání', @@ -64,25 +64,25 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Attachments:File:Size' => 'Velikost', 'Attachments:File:MimeType' => 'Typ', 'Attachments:File:DownloadsCount' => 'Staženo', -)); +]); // // Class: Attachment // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:Attachment/Attribute:creation_date' => 'Datum vytvoření', 'Class:Attachment/Attribute:creation_date+' => '~~', 'Class:Attachment/Attribute:user_id' => 'Jméno uživatele', 'Class:Attachment/Attribute:user_id+' => '~~', 'Class:Attachment/Attribute:contact_id' => 'Kontakt', 'Class:Attachment/Attribute:contact_id+' => '~~', -)); +]); // // Class: TriggerOnAttachmentDownload // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:TriggerOnAttachmentDownload' => 'Trigger (on object\'s attachment download)~~', 'Class:TriggerOnAttachmentDownload+' => 'Trigger on object\'s attachment download of [a child class of] the given class~~', 'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~', @@ -91,5 +91,5 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~', 'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~', 'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~', - 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', -)); + 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', +]); diff --git a/datamodels/2.x/itop-attachments/dictionaries/da.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/da.dict.itop-attachments.php index c570511bf..6fbbe5f2a 100644 --- a/datamodels/2.x/itop-attachments/dictionaries/da.dict.itop-attachments.php +++ b/datamodels/2.x/itop-attachments/dictionaries/da.dict.itop-attachments.php @@ -1,16 +1,17 @@ * */ -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Attachments:TabTitle_Count' => 'Vedhæftninger (%1$d)', 'Attachments:EmptyTabTitle' => 'Vedhæftninger', 'Attachments:FieldsetTitle' => 'Vedhæftninger', @@ -31,13 +32,13 @@ or ask your '.ITOP_APPLICATION_SHORT.' administrator if the '.ITOP_APPLICATION_S 'Attachments:Render:Icons' => 'Display as icons~~', 'Attachments:Render:Table' => 'Display as list~~', 'UI:Attachments:DropYourFileHint' => 'Drop files anywhere in this area~~', -)); +]); // // Class: Attachment // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:Attachment' => 'Attachment~~', 'Class:Attachment+' => '~~', 'Class:Attachment/Attribute:expire' => 'Expire~~', @@ -52,10 +53,9 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Class:Attachment/Attribute:item_org_id+' => '~~', 'Class:Attachment/Attribute:contents' => 'Contents~~', 'Class:Attachment/Attribute:contents+' => '~~', -)); +]); - -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Attachments:File:Thumbnail' => 'Icon~~', 'Attachments:File:Name' => 'File name~~', 'Attachments:File:Date' => 'Upload date~~', @@ -63,25 +63,25 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Attachments:File:Size' => 'Size~~', 'Attachments:File:MimeType' => 'Type~~', 'Attachments:File:DownloadsCount' => 'Downloads~~', -)); +]); // // Class: Attachment // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:Attachment/Attribute:creation_date' => 'Creation date~~', 'Class:Attachment/Attribute:creation_date+' => '~~', 'Class:Attachment/Attribute:user_id' => 'User id~~', 'Class:Attachment/Attribute:user_id+' => '~~', 'Class:Attachment/Attribute:contact_id' => 'Contact id~~', 'Class:Attachment/Attribute:contact_id+' => '~~', -)); +]); // // Class: TriggerOnAttachmentDownload // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:TriggerOnAttachmentDownload' => 'Trigger (on object\'s attachment download)~~', 'Class:TriggerOnAttachmentDownload+' => 'Trigger on object\'s attachment download of [a child class of] the given class~~', 'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~', @@ -90,5 +90,5 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~', 'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~', 'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~', - 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', -)); + 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', +]); diff --git a/datamodels/2.x/itop-attachments/dictionaries/de.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/de.dict.itop-attachments.php index 40d74d363..5749f92b9 100644 --- a/datamodels/2.x/itop-attachments/dictionaries/de.dict.itop-attachments.php +++ b/datamodels/2.x/itop-attachments/dictionaries/de.dict.itop-attachments.php @@ -1,16 +1,17 @@ * */ -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Attachments:TabTitle_Count' => 'Attachments (%1$d)', 'Attachments:EmptyTabTitle' => 'Attachments', 'Attachments:FieldsetTitle' => 'Attachments', @@ -31,13 +32,13 @@ oder melden Sie dem '.ITOP_APPLICATION_SHORT.' Administrator diesen Fehler, weil 'Attachments:Render:Icons' => 'Als Icons anzeigen', 'Attachments:Render:Table' => 'Als Liste anzeigen', 'UI:Attachments:DropYourFileHint' => 'Dateien in diesem Bereich ablegen...', -)); +]); // // Class: Attachment // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:Attachment' => 'Attachment', 'Class:Attachment+' => '', 'Class:Attachment/Attribute:expire' => 'Läuft ab', @@ -52,10 +53,9 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Class:Attachment/Attribute:item_org_id+' => '', 'Class:Attachment/Attribute:contents' => 'Inhalt', 'Class:Attachment/Attribute:contents+' => '', -)); +]); - -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Attachments:File:Thumbnail' => 'Icon', 'Attachments:File:Name' => 'Dateiname', 'Attachments:File:Date' => 'Upload-Datum', @@ -63,25 +63,25 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Attachments:File:Size' => 'Größe', 'Attachments:File:MimeType' => 'Typ', 'Attachments:File:DownloadsCount' => 'Downloads', -)); +]); // // Class: Attachment // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:Attachment/Attribute:creation_date' => 'Erstellungsdatum', 'Class:Attachment/Attribute:creation_date+' => '', 'Class:Attachment/Attribute:user_id' => 'Benutzer ID', 'Class:Attachment/Attribute:user_id+' => '', 'Class:Attachment/Attribute:contact_id' => 'Kontakt ID', 'Class:Attachment/Attribute:contact_id+' => '', -)); +]); // // Class: TriggerOnAttachmentDownload // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:TriggerOnAttachmentDownload' => 'Trigger (beim Herunterladen eines Attachment eines Objekts)', 'Class:TriggerOnAttachmentDownload+' => 'Trigger für das Herunterladen des Attachments der angegebenen Klasse oder einer Unterklasse', 'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~', @@ -90,5 +90,5 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~', 'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~', 'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~', - 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', -)); + 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', +]); diff --git a/datamodels/2.x/itop-attachments/dictionaries/en.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/en.dict.itop-attachments.php index f334994eb..3263ab53c 100644 --- a/datamodels/2.x/itop-attachments/dictionaries/en.dict.itop-attachments.php +++ b/datamodels/2.x/itop-attachments/dictionaries/en.dict.itop-attachments.php @@ -1,4 +1,5 @@ 'Attachments (%1$d)', 'Attachments:EmptyTabTitle' => 'Attachments', 'Attachments:FieldsetTitle' => 'Attachments', @@ -38,13 +39,13 @@ or ask your '.ITOP_APPLICATION_SHORT.' administrator if the '.ITOP_APPLICATION_S 'Attachments:Render:Icons' => 'Display as icons', 'Attachments:Render:Table' => 'Display as list', 'UI:Attachments:DropYourFileHint' => 'Drop files anywhere in this area', -)); +]); // // Class: Attachment // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:Attachment' => 'Attachment', 'Class:Attachment+' => '', 'Class:Attachment/Attribute:expire' => 'Expire', @@ -59,10 +60,9 @@ Dict::Add('EN US', 'English', 'English', array( 'Class:Attachment/Attribute:item_org_id+' => '', 'Class:Attachment/Attribute:contents' => 'Contents', 'Class:Attachment/Attribute:contents+' => '', -)); +]); - -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Attachments:File:Thumbnail' => 'Icon', 'Attachments:File:Name' => 'File name', 'Attachments:File:Date' => 'Upload date', @@ -70,25 +70,25 @@ Dict::Add('EN US', 'English', 'English', array( 'Attachments:File:Size' => 'Size', 'Attachments:File:MimeType' => 'Type', 'Attachments:File:DownloadsCount' => 'Downloads', -)); +]); // // Class: Attachment // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:Attachment/Attribute:creation_date' => 'Creation date', 'Class:Attachment/Attribute:creation_date+' => '', 'Class:Attachment/Attribute:user_id' => 'User id', 'Class:Attachment/Attribute:user_id+' => '', 'Class:Attachment/Attribute:contact_id' => 'Contact id', 'Class:Attachment/Attribute:contact_id+' => '', -)); +]); // // Class: TriggerOnAttachmentDownload // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:TriggerOnAttachmentDownload' => 'Trigger (on object\'s attachment download)', 'Class:TriggerOnAttachmentDownload+' => 'Trigger on object\'s attachment download of [a child class of] the given class', 'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)', @@ -97,5 +97,5 @@ Dict::Add('EN US', 'English', 'English', array( 'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete', 'Class:TriggerOnAttachmentCreate/Attribute:file_in_email' => 'Add file in email', 'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered', - 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger', -)); + 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger', +]); diff --git a/datamodels/2.x/itop-attachments/dictionaries/es_cr.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/es_cr.dict.itop-attachments.php index 3f0e7d721..522fec5b2 100644 --- a/datamodels/2.x/itop-attachments/dictionaries/es_cr.dict.itop-attachments.php +++ b/datamodels/2.x/itop-attachments/dictionaries/es_cr.dict.itop-attachments.php @@ -1,13 +1,14 @@ - * @notas Utilizar codificación UTF-8 para mostrar acentos y otros caracteres especiales + * @notas Utilizar codificación UTF-8 para mostrar acentos y otros caracteres especiales */ -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Attachments:TabTitle_Count' => 'Anexos (%1$d)', 'Attachments:EmptyTabTitle' => 'Anexos', 'Attachments:FieldsetTitle' => 'Anexos', @@ -28,13 +29,13 @@ o pregunte al administador de iTop si el servidor que ha quedado sin espacio en 'Attachments:Render:Icons' => 'Desplegar como icono', 'Attachments:Render:Table' => 'Desplegar como lista', 'UI:Attachments:DropYourFileHint' => 'Arrastre los archivos en cualquier lugar de esta área', -)); +]); // // Class: Attachment // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:Attachment' => 'Anexo', 'Class:Attachment+' => 'Anexo', 'Class:Attachment/Attribute:expire' => 'Expira', @@ -49,10 +50,9 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Class:Attachment/Attribute:item_org_id+' => '', 'Class:Attachment/Attribute:contents' => 'Contenido', 'Class:Attachment/Attribute:contents+' => '', -)); +]); - -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Attachments:File:Thumbnail' => 'Ícono', 'Attachments:File:Name' => 'Nombre de Archivo', 'Attachments:File:Date' => 'Fecha de Carga', @@ -60,25 +60,25 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Attachments:File:Size' => 'Tamaño', 'Attachments:File:MimeType' => 'Tipo', 'Attachments:File:DownloadsCount' => 'Descargas', -)); +]); // // Class: Attachment // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:Attachment/Attribute:creation_date' => 'Fecha de Creación', 'Class:Attachment/Attribute:creation_date+' => '', 'Class:Attachment/Attribute:user_id' => 'Id del Usuario', 'Class:Attachment/Attribute:user_id+' => '', 'Class:Attachment/Attribute:contact_id' => 'Id del Contacto', 'Class:Attachment/Attribute:contact_id+' => '', -)); +]); // // Class: TriggerOnAttachmentDownload // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:TriggerOnAttachmentDownload' => 'Disparador (al descargar el archivo adjunto del objeto)', 'Class:TriggerOnAttachmentDownload+' => 'Disparador al descargar el archivo adjunto del objeto de [una clase secundaria de] la clase dada', 'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~', @@ -87,5 +87,5 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~', 'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~', 'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~', - 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', -)); + 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', +]); diff --git a/datamodels/2.x/itop-attachments/dictionaries/fr.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/fr.dict.itop-attachments.php index cc3c012dc..016362763 100644 --- a/datamodels/2.x/itop-attachments/dictionaries/fr.dict.itop-attachments.php +++ b/datamodels/2.x/itop-attachments/dictionaries/fr.dict.itop-attachments.php @@ -1,15 +1,16 @@ 'Pièces jointes (%1$d)', 'Attachments:EmptyTabTitle' => 'Pièces jointes', 'Attachments:FieldsetTitle' => 'Pièces jointes', @@ -30,13 +31,13 @@ Soit demandez à votre administrateur système s\'il reste de la place disque di 'Attachments:Render:Icons' => 'Affichage en icônes', 'Attachments:Render:Table' => 'Affichage en liste', 'UI:Attachments:DropYourFileHint' => 'Déposez vos fichiers dans cet espace', -)); +]); // // Class: Attachment // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:Attachment' => 'Attachement', 'Class:Attachment+' => '', 'Class:Attachment/Attribute:expire' => 'Expire', @@ -51,10 +52,9 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Class:Attachment/Attribute:item_org_id+' => '', 'Class:Attachment/Attribute:contents' => 'Contenu', 'Class:Attachment/Attribute:contents+' => '', -)); +]); - -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Attachments:File:Thumbnail' => 'Icône', 'Attachments:File:Name' => 'Nom du fichier', 'Attachments:File:Date' => 'Date de chargement', @@ -62,25 +62,25 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Attachments:File:Size' => 'Taille', 'Attachments:File:MimeType' => 'Type', 'Attachments:File:DownloadsCount' => 'Téléchargements', -)); +]); // // Class: Attachment // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:Attachment/Attribute:creation_date' => 'Date de création', 'Class:Attachment/Attribute:creation_date+' => '', 'Class:Attachment/Attribute:user_id' => 'Utilisateur', 'Class:Attachment/Attribute:user_id+' => '', 'Class:Attachment/Attribute:contact_id' => 'Contact', 'Class:Attachment/Attribute:contact_id+' => '', -)); +]); // // Class: TriggerOnAttachmentDownload // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:TriggerOnAttachmentDownload' => 'Déclencheur sur le téléchargement d\'une pièce jointe d\'un objet', 'Class:TriggerOnAttachmentDownload+' => '', 'Class:TriggerOnAttachmentCreate' => 'Déclencheur sur la création d\'une pièce jointe', @@ -89,5 +89,5 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'Si coché, le fichier sera automatiquement attaché à l\'email quand l\'action email est lancée', 'Class:TriggerOnAttachmentDelete' => 'Déclencheur sur la suppression d\'une pièce jointe', 'Class:TriggerOnAttachmentDelete+' => '', - 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Les Triggers sur les objets ne sont pas autorisés sur la classe Attachement. Veuillez utiliser les triggers spécifiques pour cette classe', -)); + 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Les Triggers sur les objets ne sont pas autorisés sur la classe Attachement. Veuillez utiliser les triggers spécifiques pour cette classe', +]); diff --git a/datamodels/2.x/itop-attachments/dictionaries/hu.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/hu.dict.itop-attachments.php index d3db4276b..14f6ba869 100644 --- a/datamodels/2.x/itop-attachments/dictionaries/hu.dict.itop-attachments.php +++ b/datamodels/2.x/itop-attachments/dictionaries/hu.dict.itop-attachments.php @@ -1,15 +1,16 @@ 'Mellékletek (%1$d)', 'Attachments:EmptyTabTitle' => 'Mellékletek', 'Attachments:FieldsetTitle' => 'Mellékletek', @@ -28,13 +29,13 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Attachments:Render:Icons' => 'Mutassa ikonként', 'Attachments:Render:Table' => 'Mutassa listaként', 'UI:Attachments:DropYourFileHint' => 'Húzza a fájlokat erre a területre', -)); +]); // // Class: Attachment // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:Attachment' => 'Mellékletek', 'Class:Attachment+' => '~~', 'Class:Attachment/Attribute:expire' => 'Lejárat', @@ -49,10 +50,9 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Class:Attachment/Attribute:item_org_id+' => '~~', 'Class:Attachment/Attribute:contents' => 'Tartalom', 'Class:Attachment/Attribute:contents+' => '~~', -)); +]); - -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Attachments:File:Thumbnail' => 'Ikon', 'Attachments:File:Name' => 'Fájlnév', 'Attachments:File:Date' => 'Feltöltés dátuma', @@ -60,25 +60,25 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Attachments:File:Size' => 'Méret', 'Attachments:File:MimeType' => 'Típus', 'Attachments:File:DownloadsCount' => 'Downloads~~', -)); +]); // // Class: Attachment // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:Attachment/Attribute:creation_date' => 'Létrehozás dátuma', 'Class:Attachment/Attribute:creation_date+' => '~~', 'Class:Attachment/Attribute:user_id' => 'Felhasználó', 'Class:Attachment/Attribute:user_id+' => '~~', 'Class:Attachment/Attribute:contact_id' => 'Kapcsolattartó', 'Class:Attachment/Attribute:contact_id+' => '~~', -)); +]); // // Class: TriggerOnAttachmentDownload // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:TriggerOnAttachmentDownload' => 'Trigger (on object\'s attachment download)~~', 'Class:TriggerOnAttachmentDownload+' => 'Trigger on object\'s attachment download of [a child class of] the given class~~', 'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~', @@ -87,5 +87,5 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~', 'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~', 'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~', - 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', -)); + 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', +]); diff --git a/datamodels/2.x/itop-attachments/dictionaries/it.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/it.dict.itop-attachments.php index bba364b74..d766a1864 100644 --- a/datamodels/2.x/itop-attachments/dictionaries/it.dict.itop-attachments.php +++ b/datamodels/2.x/itop-attachments/dictionaries/it.dict.itop-attachments.php @@ -1,15 +1,16 @@ 'Allegati (%1$d)', 'Attachments:EmptyTabTitle' => 'Allegati', 'Attachments:FieldsetTitle' => 'Allegati', @@ -30,13 +31,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Attachments:Render:Icons' => 'Visualizza come icone', 'Attachments:Render:Table' => 'Visualizza come lista', 'UI:Attachments:DropYourFileHint' => 'Rilascia i file ovunque in quest\'area', -)); +]); // // Class: Attachment // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:Attachment' => 'Allegato', 'Class:Attachment+' => '~~', 'Class:Attachment/Attribute:expire' => 'Scadenza', @@ -51,10 +52,9 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:Attachment/Attribute:item_org_id+' => '~~', 'Class:Attachment/Attribute:contents' => 'Contenuti', 'Class:Attachment/Attribute:contents+' => '~~', -)); +]); - -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Attachments:File:Thumbnail' => 'Icona', 'Attachments:File:Name' => 'Nome del file', 'Attachments:File:Date' => 'Data di caricamento', @@ -62,32 +62,32 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Attachments:File:Size' => 'Dimensione', 'Attachments:File:MimeType' => 'Tipo', 'Attachments:File:DownloadsCount' => 'Download', -)); +]); // // Class: Attachment // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:Attachment/Attribute:creation_date' => 'Data di creazione', 'Class:Attachment/Attribute:creation_date+' => '~~', 'Class:Attachment/Attribute:user_id' => 'ID utente', 'Class:Attachment/Attribute:user_id+' => '~~', 'Class:Attachment/Attribute:contact_id' => 'ID contatto', 'Class:Attachment/Attribute:contact_id+' => '~~', -)); +]); // // Class: TriggerOnAttachmentDownload // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:TriggerOnAttachmentDownload' => 'Trigger (al download di un allegato dell\'oggetto)', 'Class:TriggerOnAttachmentDownload+' => 'Trigger al download di un allegato di un oggetto di [una sottoclasse di] la classe data', - 'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~', - 'Class:TriggerOnAttachmentCreate+' => 'Trigger on object\'s attachment create~~', + 'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~', + 'Class:TriggerOnAttachmentCreate+' => 'Trigger on object\'s attachment create~~', 'Class:TriggerOnAttachmentCreate/Attribute:file_in_email' => 'Add file in email~~', 'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~', 'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~', 'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~', - 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', -)); + 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', +]); diff --git a/datamodels/2.x/itop-attachments/dictionaries/ja.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/ja.dict.itop-attachments.php index fb5d450d2..45f88c3d2 100644 --- a/datamodels/2.x/itop-attachments/dictionaries/ja.dict.itop-attachments.php +++ b/datamodels/2.x/itop-attachments/dictionaries/ja.dict.itop-attachments.php @@ -1,15 +1,16 @@ '添付 (%1$d)', 'Attachments:EmptyTabTitle' => '添付', 'Attachments:FieldsetTitle' => '添付', @@ -30,13 +31,13 @@ or ask your '.ITOP_APPLICATION_SHORT.' administrator if the '.ITOP_APPLICATION_S 'Attachments:Render:Icons' => 'Display as icons~~', 'Attachments:Render:Table' => 'Display as list~~', 'UI:Attachments:DropYourFileHint' => 'Drop files anywhere in this area~~', -)); +]); // // Class: Attachment // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:Attachment' => 'Attachment~~', 'Class:Attachment+' => '~~', 'Class:Attachment/Attribute:expire' => 'Expire~~', @@ -51,10 +52,9 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Class:Attachment/Attribute:item_org_id+' => '~~', 'Class:Attachment/Attribute:contents' => 'Contents~~', 'Class:Attachment/Attribute:contents+' => '~~', -)); +]); - -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Attachments:File:Thumbnail' => 'Icon~~', 'Attachments:File:Name' => 'File name~~', 'Attachments:File:Date' => 'Upload date~~', @@ -62,25 +62,25 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Attachments:File:Size' => 'Size~~', 'Attachments:File:MimeType' => 'Type~~', 'Attachments:File:DownloadsCount' => 'Downloads~~', -)); +]); // // Class: Attachment // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:Attachment/Attribute:creation_date' => 'Creation date~~', 'Class:Attachment/Attribute:creation_date+' => '~~', 'Class:Attachment/Attribute:user_id' => 'User id~~', 'Class:Attachment/Attribute:user_id+' => '~~', 'Class:Attachment/Attribute:contact_id' => 'Contact id~~', 'Class:Attachment/Attribute:contact_id+' => '~~', -)); +]); // // Class: TriggerOnAttachmentDownload // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:TriggerOnAttachmentDownload' => 'Trigger (on object\'s attachment download)~~', 'Class:TriggerOnAttachmentDownload+' => 'Trigger on object\'s attachment download of [a child class of] the given class~~', 'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~', @@ -89,5 +89,5 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~', 'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~', 'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~', - 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', -)); + 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', +]); diff --git a/datamodels/2.x/itop-attachments/dictionaries/nl.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/nl.dict.itop-attachments.php index 682be462b..0d00101d3 100644 --- a/datamodels/2.x/itop-attachments/dictionaries/nl.dict.itop-attachments.php +++ b/datamodels/2.x/itop-attachments/dictionaries/nl.dict.itop-attachments.php @@ -1,17 +1,18 @@ * @author Jeffrey Bostoen (2018 - 2022) * @author Thomas Casteleyn */ -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Attachments:TabTitle_Count' => 'Bijlagen (%1$d)', 'Attachments:EmptyTabTitle' => 'Bijlagen', 'Attachments:FieldsetTitle' => 'Bijlagen', @@ -32,13 +33,13 @@ of vraag de iTop administrator om de opslagruimte van de iTop-server na te kijke 'Attachments:Render:Icons' => 'Toon als pictogram', 'Attachments:Render:Table' => 'Toon als lijst', 'UI:Attachments:DropYourFileHint' => 'Sleep bestanden in dit gebied', -)); +]); // // Class: Attachment // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:Attachment' => 'Bijlage', 'Class:Attachment+' => '', 'Class:Attachment/Attribute:expire' => 'Vervalt', @@ -53,10 +54,9 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Class:Attachment/Attribute:item_org_id+' => '', 'Class:Attachment/Attribute:contents' => 'Inhoud', 'Class:Attachment/Attribute:contents+' => '', -)); +]); - -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Attachments:File:Thumbnail' => 'Pictogram', 'Attachments:File:Name' => 'Bestandsnaam', 'Attachments:File:Date' => 'Geüpload op', @@ -64,32 +64,32 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Attachments:File:Size' => 'Grootte', 'Attachments:File:MimeType' => 'Type', 'Attachments:File:DownloadsCount' => 'Downloads', -)); +]); // // Class: Attachment // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:Attachment/Attribute:creation_date' => 'Datum creatie', 'Class:Attachment/Attribute:creation_date+' => '', 'Class:Attachment/Attribute:user_id' => 'ID Gebruiker', 'Class:Attachment/Attribute:user_id+' => '', 'Class:Attachment/Attribute:contact_id' => 'ID Contact', 'Class:Attachment/Attribute:contact_id+' => '', -)); +]); // // Class: TriggerOnAttachmentDownload // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:TriggerOnAttachmentDownload' => 'Trigger (Bij het downloaden van een bijlage)', 'Class:TriggerOnAttachmentDownload+' => 'Trigger bij het downloaden van een bijlage van een object van de opgegeven klasse (of subklasse ervan)', - 'Class:TriggerOnAttachmentCreate' => 'Trigger (Bij het toevoegen van een bijlage)', - 'Class:TriggerOnAttachmentCreate+' => 'Trigger bij het toevoegen van een bijlage aan een object van de opgegeven klasse (of subklasse ervan)', + 'Class:TriggerOnAttachmentCreate' => 'Trigger (Bij het toevoegen van een bijlage)', + 'Class:TriggerOnAttachmentCreate+' => 'Trigger bij het toevoegen van een bijlage aan een object van de opgegeven klasse (of subklasse ervan)', 'Class:TriggerOnAttachmentCreate/Attribute:file_in_email' => 'Bestand toevoegen in e-mail', - 'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+'=> 'If checked, the file will be automatically attached to the email when an email action is triggered~~', + 'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~', 'Class:TriggerOnAttachmentDelete' => 'Trigger (Bij het verwijderen van een bijlage)', 'Class:TriggerOnAttachmentDelete+' => 'Trigger bij het verwijderen van een bijlage van een object van de opgegeven klasse (of subklasse ervan)', - 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', -)); + 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', +]); diff --git a/datamodels/2.x/itop-attachments/dictionaries/pl.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/pl.dict.itop-attachments.php index abba580e0..67a1dc9f8 100644 --- a/datamodels/2.x/itop-attachments/dictionaries/pl.dict.itop-attachments.php +++ b/datamodels/2.x/itop-attachments/dictionaries/pl.dict.itop-attachments.php @@ -1,15 +1,16 @@ 'Załączniki (%1$d)', 'Attachments:EmptyTabTitle' => 'Załączniki', 'Attachments:FieldsetTitle' => 'Załączniki', @@ -30,13 +31,13 @@ lub zapytaj administratora '.ITOP_APPLICATION_SHORT.', czy dysk serwera '.ITOP_A 'Attachments:Render:Icons' => 'Wyświetlaj jako ikony', 'Attachments:Render:Table' => 'Wyświetl jako listę', 'UI:Attachments:DropYourFileHint' => 'Upuść pliki w dowolnym miejscu w tym obszarze', -)); +]); // // Class: Attachment // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:Attachment' => 'Załącznik', 'Class:Attachment+' => '', 'Class:Attachment/Attribute:expire' => 'Wygasa', @@ -51,10 +52,9 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Class:Attachment/Attribute:item_org_id+' => '', 'Class:Attachment/Attribute:contents' => 'Zawartość', 'Class:Attachment/Attribute:contents+' => '', -)); +]); - -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Attachments:File:Thumbnail' => 'Ikona', 'Attachments:File:Name' => 'Nazwa pliku', 'Attachments:File:Date' => 'Data przesłania', @@ -62,32 +62,32 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Attachments:File:Size' => 'Rozmiar', 'Attachments:File:MimeType' => 'Typ', 'Attachments:File:DownloadsCount' => 'Pobrano', -)); +]); // // Class: Attachment // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:Attachment/Attribute:creation_date' => 'Data utworzenia', 'Class:Attachment/Attribute:creation_date+' => '', 'Class:Attachment/Attribute:user_id' => 'Id użytkownika', 'Class:Attachment/Attribute:user_id+' => '', 'Class:Attachment/Attribute:contact_id' => 'Id kontaktu', 'Class:Attachment/Attribute:contact_id+' => '', -)); +]); // // Class: TriggerOnAttachmentDownload // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:TriggerOnAttachmentDownload' => 'Wyzwalacz (po pobraniu załącznika obiektu)', 'Class:TriggerOnAttachmentDownload+' => 'Wyzwalacz po pobraniu załącznika obiektu [klasy podrzędnej] danej klasy', - 'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~', - 'Class:TriggerOnAttachmentCreate+' => 'Trigger on object\'s attachment create~~', + 'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~', + 'Class:TriggerOnAttachmentCreate+' => 'Trigger on object\'s attachment create~~', 'Class:TriggerOnAttachmentCreate/Attribute:file_in_email' => 'Add file in email~~', 'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~', 'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~', 'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~', - 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', -)); + 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', +]); diff --git a/datamodels/2.x/itop-attachments/dictionaries/pt_br.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/pt_br.dict.itop-attachments.php index 744e159f2..5afa8f22d 100644 --- a/datamodels/2.x/itop-attachments/dictionaries/pt_br.dict.itop-attachments.php +++ b/datamodels/2.x/itop-attachments/dictionaries/pt_br.dict.itop-attachments.php @@ -1,15 +1,16 @@ 'Anexos (%1$d)', 'Attachments:EmptyTabTitle' => 'Anexos', 'Attachments:FieldsetTitle' => 'Anexos', @@ -30,13 +31,13 @@ ou entre em contato com o seu administrador do '.ITOP_APPLICATION_SHORT.' pois o 'Attachments:Render:Icons' => 'Exibir como ícones', 'Attachments:Render:Table' => 'Exibir como lista', 'UI:Attachments:DropYourFileHint' => 'Solte arquivos em qualquer lugar nesta área', -)); +]); // // Class: Attachment // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Attachment' => 'Anexo', 'Class:Attachment+' => '', 'Class:Attachment/Attribute:expire' => 'Expira', @@ -51,10 +52,9 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Attachment/Attribute:item_org_id+' => '', 'Class:Attachment/Attribute:contents' => 'Conteúdo', 'Class:Attachment/Attribute:contents+' => '', -)); +]); - -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Attachments:File:Thumbnail' => 'Ícone', 'Attachments:File:Name' => 'Nome do arquivo', 'Attachments:File:Date' => 'Data de envio', @@ -62,25 +62,25 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Attachments:File:Size' => 'Tamanho', 'Attachments:File:MimeType' => 'Tipo', 'Attachments:File:DownloadsCount' => 'Downloads~~', -)); +]); // // Class: Attachment // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Attachment/Attribute:creation_date' => 'Data de criação', 'Class:Attachment/Attribute:creation_date+' => '', 'Class:Attachment/Attribute:user_id' => 'Identificador do usuário', 'Class:Attachment/Attribute:user_id+' => '', 'Class:Attachment/Attribute:contact_id' => 'Identificador do contato', 'Class:Attachment/Attribute:contact_id+' => '', -)); +]); // // Class: TriggerOnAttachmentDownload // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:TriggerOnAttachmentDownload' => 'Trigger (on object\'s attachment download)~~', 'Class:TriggerOnAttachmentDownload+' => 'Trigger on object\'s attachment download of [a child class of] the given class~~', 'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~', @@ -89,5 +89,5 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~', 'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~', 'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~', - 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', -)); + 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', +]); diff --git a/datamodels/2.x/itop-attachments/dictionaries/ru.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/ru.dict.itop-attachments.php index 9e314c412..666492848 100644 --- a/datamodels/2.x/itop-attachments/dictionaries/ru.dict.itop-attachments.php +++ b/datamodels/2.x/itop-attachments/dictionaries/ru.dict.itop-attachments.php @@ -1,16 +1,17 @@ * */ -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Attachments:TabTitle_Count' => 'Вложения (%1$d)', 'Attachments:EmptyTabTitle' => 'Вложения', 'Attachments:FieldsetTitle' => 'Вложения', @@ -31,13 +32,13 @@ or ask your '.ITOP_APPLICATION_SHORT.' administrator if the '.ITOP_APPLICATION_S 'Attachments:Render:Icons' => 'Display as icons~~', 'Attachments:Render:Table' => 'Display as list~~', 'UI:Attachments:DropYourFileHint' => 'Drop files anywhere in this area~~', -)); +]); // // Class: Attachment // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:Attachment' => 'Вложение', 'Class:Attachment+' => '', 'Class:Attachment/Attribute:expire' => 'Истекает', @@ -52,10 +53,9 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Class:Attachment/Attribute:item_org_id+' => '', 'Class:Attachment/Attribute:contents' => 'Содержимое', 'Class:Attachment/Attribute:contents+' => '', -)); +]); - -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Attachments:File:Thumbnail' => 'Предпросмотр', 'Attachments:File:Name' => 'Имя файла', 'Attachments:File:Date' => 'Дата', @@ -63,25 +63,25 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Attachments:File:Size' => 'Размер', 'Attachments:File:MimeType' => 'Тип', 'Attachments:File:DownloadsCount' => 'Downloads~~', -)); +]); // // Class: Attachment // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:Attachment/Attribute:creation_date' => 'Дата создания', 'Class:Attachment/Attribute:creation_date+' => '', 'Class:Attachment/Attribute:user_id' => 'Пользователь', 'Class:Attachment/Attribute:user_id+' => '', 'Class:Attachment/Attribute:contact_id' => 'Контакт', 'Class:Attachment/Attribute:contact_id+' => '', -)); +]); // // Class: TriggerOnAttachmentDownload // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:TriggerOnAttachmentDownload' => 'Trigger (on object\'s attachment download)~~', 'Class:TriggerOnAttachmentDownload+' => 'Trigger on object\'s attachment download of [a child class of] the given class~~', 'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~', @@ -90,5 +90,5 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~', 'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~', 'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~', - 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', -)); + 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', +]); diff --git a/datamodels/2.x/itop-attachments/dictionaries/sk.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/sk.dict.itop-attachments.php index d27b9ec93..fafea2013 100644 --- a/datamodels/2.x/itop-attachments/dictionaries/sk.dict.itop-attachments.php +++ b/datamodels/2.x/itop-attachments/dictionaries/sk.dict.itop-attachments.php @@ -1,15 +1,16 @@ 'Prílohy (%1$d)', 'Attachments:EmptyTabTitle' => 'Prílohy', 'Attachments:FieldsetTitle' => 'Prílohy', @@ -30,13 +31,13 @@ or ask your '.ITOP_APPLICATION_SHORT.' administrator if the '.ITOP_APPLICATION_S 'Attachments:Render:Icons' => 'Display as icons~~', 'Attachments:Render:Table' => 'Display as list~~', 'UI:Attachments:DropYourFileHint' => 'Drop files anywhere in this area~~', -)); +]); // // Class: Attachment // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:Attachment' => 'Attachment~~', 'Class:Attachment+' => '~~', 'Class:Attachment/Attribute:expire' => 'Expire~~', @@ -51,10 +52,9 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Class:Attachment/Attribute:item_org_id+' => '~~', 'Class:Attachment/Attribute:contents' => 'Contents~~', 'Class:Attachment/Attribute:contents+' => '~~', -)); +]); - -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Attachments:File:Thumbnail' => 'Icon~~', 'Attachments:File:Name' => 'File name~~', 'Attachments:File:Date' => 'Upload date~~', @@ -62,25 +62,25 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Attachments:File:Size' => 'Size~~', 'Attachments:File:MimeType' => 'Type~~', 'Attachments:File:DownloadsCount' => 'Downloads~~', -)); +]); // // Class: Attachment // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:Attachment/Attribute:creation_date' => 'Creation date~~', 'Class:Attachment/Attribute:creation_date+' => '~~', 'Class:Attachment/Attribute:user_id' => 'User id~~', 'Class:Attachment/Attribute:user_id+' => '~~', 'Class:Attachment/Attribute:contact_id' => 'Contact id~~', 'Class:Attachment/Attribute:contact_id+' => '~~', -)); +]); // // Class: TriggerOnAttachmentDownload // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:TriggerOnAttachmentDownload' => 'Trigger (on object\'s attachment download)~~', 'Class:TriggerOnAttachmentDownload+' => 'Trigger on object\'s attachment download of [a child class of] the given class~~', 'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~', @@ -89,5 +89,5 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~', 'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~', 'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~', - 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', -)); + 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', +]); diff --git a/datamodels/2.x/itop-attachments/dictionaries/tr.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/tr.dict.itop-attachments.php index 67e311d0e..9c361fe06 100644 --- a/datamodels/2.x/itop-attachments/dictionaries/tr.dict.itop-attachments.php +++ b/datamodels/2.x/itop-attachments/dictionaries/tr.dict.itop-attachments.php @@ -1,15 +1,16 @@ 'Attachments (%1$d)~~', 'Attachments:EmptyTabTitle' => 'Attachments~~', 'Attachments:FieldsetTitle' => 'Attachments~~', @@ -30,13 +31,13 @@ or ask your '.ITOP_APPLICATION_SHORT.' administrator if the '.ITOP_APPLICATION_S 'Attachments:Render:Icons' => 'Display as icons~~', 'Attachments:Render:Table' => 'Display as list~~', 'UI:Attachments:DropYourFileHint' => 'Drop files anywhere in this area~~', -)); +]); // // Class: Attachment // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:Attachment' => 'Attachment~~', 'Class:Attachment+' => '~~', 'Class:Attachment/Attribute:expire' => 'Expire~~', @@ -51,10 +52,9 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Class:Attachment/Attribute:item_org_id+' => '~~', 'Class:Attachment/Attribute:contents' => 'Contents~~', 'Class:Attachment/Attribute:contents+' => '~~', -)); +]); - -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Attachments:File:Thumbnail' => 'Icon~~', 'Attachments:File:Name' => 'File name~~', 'Attachments:File:Date' => 'Upload date~~', @@ -62,25 +62,25 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Attachments:File:Size' => 'Size~~', 'Attachments:File:MimeType' => 'Type~~', 'Attachments:File:DownloadsCount' => 'Downloads~~', -)); +]); // // Class: Attachment // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:Attachment/Attribute:creation_date' => 'Creation date~~', 'Class:Attachment/Attribute:creation_date+' => '~~', 'Class:Attachment/Attribute:user_id' => 'User id~~', 'Class:Attachment/Attribute:user_id+' => '~~', 'Class:Attachment/Attribute:contact_id' => 'Contact id~~', 'Class:Attachment/Attribute:contact_id+' => '~~', -)); +]); // // Class: TriggerOnAttachmentDownload // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:TriggerOnAttachmentDownload' => 'Trigger (on object\'s attachment download)~~', 'Class:TriggerOnAttachmentDownload+' => 'Trigger on object\'s attachment download of [a child class of] the given class~~', 'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~', @@ -89,5 +89,5 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~', 'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~', 'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~', - 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', -)); + 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', +]); diff --git a/datamodels/2.x/itop-attachments/dictionaries/zh_cn.dict.itop-attachments.php b/datamodels/2.x/itop-attachments/dictionaries/zh_cn.dict.itop-attachments.php index 2756f8190..ebf9b4a82 100644 --- a/datamodels/2.x/itop-attachments/dictionaries/zh_cn.dict.itop-attachments.php +++ b/datamodels/2.x/itop-attachments/dictionaries/zh_cn.dict.itop-attachments.php @@ -1,4 +1,5 @@ '附件 (%1$d)', 'Attachments:EmptyTabTitle' => '附件', 'Attachments:FieldsetTitle' => '附件', @@ -30,13 +31,13 @@ Dict::Add('ZH CN', 'Chinese', '简体中文', array( 'Attachments:Render:Icons' => '显示为图标', 'Attachments:Render:Table' => '显示为列表', 'UI:Attachments:DropYourFileHint' => '将文件拖放到此区域的任意位置', -)); +]); // // Class: Attachment // -Dict::Add('ZH CN', 'Chinese', '简体中文', array( +Dict::Add('ZH CN', 'Chinese', '简体中文', [ 'Class:Attachment' => '附件', 'Class:Attachment+' => '', 'Class:Attachment/Attribute:expire' => '过期', @@ -51,10 +52,9 @@ Dict::Add('ZH CN', 'Chinese', '简体中文', array( 'Class:Attachment/Attribute:item_org_id+' => '', 'Class:Attachment/Attribute:contents' => '内容', 'Class:Attachment/Attribute:contents+' => '', -)); +]); - -Dict::Add('ZH CN', 'Chinese', '简体中文', array( +Dict::Add('ZH CN', 'Chinese', '简体中文', [ 'Attachments:File:Thumbnail' => '图标', 'Attachments:File:Name' => '文件名', 'Attachments:File:Date' => '上传日期', @@ -62,32 +62,32 @@ Dict::Add('ZH CN', 'Chinese', '简体中文', array( 'Attachments:File:Size' => '大小', 'Attachments:File:MimeType' => '类型', 'Attachments:File:DownloadsCount' => '下载', -)); +]); // // Class: Attachment // -Dict::Add('ZH CN', 'Chinese', '简体中文', array( +Dict::Add('ZH CN', 'Chinese', '简体中文', [ 'Class:Attachment/Attribute:creation_date' => '创建日期', 'Class:Attachment/Attribute:creation_date+' => '~~', 'Class:Attachment/Attribute:user_id' => '用户编号', 'Class:Attachment/Attribute:user_id+' => '~~', 'Class:Attachment/Attribute:contact_id' => '联系人编号', 'Class:Attachment/Attribute:contact_id+' => '~~', -)); +]); // // Class: TriggerOnAttachmentDownload // -Dict::Add('ZH CN', 'Chinese', '简体中文', array( +Dict::Add('ZH CN', 'Chinese', '简体中文', [ 'Class:TriggerOnAttachmentDownload' => '触发器 (于对象附件下载时)', 'Class:TriggerOnAttachmentDownload+' => '触发器于指定类型 [子类型] 对象附件下载时', 'Class:TriggerOnAttachmentCreate' => 'Trigger (on object\'s attachment create)~~', - 'Class:TriggerOnAttachmentCreate+' => 'Trigger on object\'s attachment create~~', + 'Class:TriggerOnAttachmentCreate+' => 'Trigger on object\'s attachment create~~', 'Class:TriggerOnAttachmentCreate/Attribute:file_in_email' => 'Add file in email~~', 'Class:TriggerOnAttachmentCreate/Attribute:file_in_email+' => 'If checked, the file will be automatically attached to the email when an email action is triggered~~', 'Class:TriggerOnAttachmentDelete' => 'Trigger (on object\'s attachment delete)~~', 'Class:TriggerOnAttachmentDelete+' => 'Trigger on object\'s attachment delete~~', - 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', -)); + 'Class:TriggerOnObject:TriggerClassAttachment/ReadOnlyMessage' => 'Trigger on object is not allowed on class Attachment. Please use specific trigger~~', +]); diff --git a/datamodels/2.x/itop-attachments/main.itop-attachments.php b/datamodels/2.x/itop-attachments/main.itop-attachments.php index d7ee5d17d..e2025e731 100644 --- a/datamodels/2.x/itop-attachments/main.itop-attachments.php +++ b/datamodels/2.x/itop-attachments/main.itop-attachments.php @@ -1,4 +1,5 @@ GetAttachmentsPosition() == 'properties') - { + if ($this->GetAttachmentsPosition() == 'properties') { $this->DisplayAttachments($oObject, $oPage, $bEditMode); } } public function OnDisplayRelations($oObject, WebPage $oPage, $bEditMode = false) { - if ($this->GetAttachmentsPosition() == 'relations') - { + if ($this->GetAttachmentsPosition() == 'relations') { $this->DisplayAttachments($oObject, $oPage, $bEditMode); } } public function OnFormSubmit($oObject, $sFormPrefix = '') { - if ($this->IsTargetObject($oObject)) - { + if ($this->IsTargetObject($oObject)) { // For new objects attachments are processed in OnDBInsert - if (!$oObject->IsNew()) - { + if (!$oObject->IsNew()) { self::UpdateAttachments($oObject); } } @@ -53,12 +50,9 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup public static function GetMaxUploadSize() { $sMaxUpload = ini_get('upload_max_filesize'); - if (!$sMaxUpload) - { + if (!$sMaxUpload) { $result = false; - } - else - { + } else { $result = utils::ConvertToBytes($sMaxUpload); } @@ -71,13 +65,11 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup * @return bool * @since 3.2.1 N°7534 */ - public static function IsAttachmentAllowedForObject(cmdbAbstractObject $oObject) : bool + public static function IsAttachmentAllowedForObject(cmdbAbstractObject $oObject): bool { - $aAllowedClasses = MetaModel::GetModuleSetting('itop-attachments', 'allowed_classes', array('Ticket')); - foreach ($aAllowedClasses as $sAllowedClass) - { - if ($oObject instanceof $sAllowedClass) - { + $aAllowedClasses = MetaModel::GetModuleSetting('itop-attachments', 'allowed_classes', ['Ticket']); + foreach ($aAllowedClasses as $sAllowedClass) { + if ($oObject instanceof $sAllowedClass) { return true; } } @@ -92,24 +84,15 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup public static function GetMaxUpload() { $iMaxUpload = static::GetMaxUploadSize(); - if (!$iMaxUpload) - { + if (!$iMaxUpload) { $sRet = Dict::S('Attachments:UploadNotAllowedOnThisSystem'); - } - else - { - if ($iMaxUpload > 1024 * 1024 * 1024) - { + } else { + if ($iMaxUpload > 1024 * 1024 * 1024) { $sRet = Dict::Format('Attachment:Max_Go', sprintf('%0.2f', $iMaxUpload / (1024 * 1024 * 1024))); - } - else - { - if ($iMaxUpload > 1024 * 1024) - { + } else { + if ($iMaxUpload > 1024 * 1024) { $sRet = Dict::Format('Attachment:Max_Mo', sprintf('%0.2f', $iMaxUpload / (1024 * 1024))); - } - else - { + } else { $sRet = Dict::Format('Attachment:Max_Ko', sprintf('%0.2f', $iMaxUpload / (1024))); } } @@ -128,9 +111,8 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup // Delete all "pending" attachments for this form $sOQL = 'SELECT Attachment WHERE temp_id = :temp_id'; $oSearch = DBObjectSearch::FromOQL($sOQL); - $oSet = new DBObjectSet($oSearch, array(), array('temp_id' => $sTempId)); - while ($oAttachment = $oSet->Fetch()) - { + $oSet = new DBObjectSet($oSearch, [], ['temp_id' => $sTempId]); + while ($oAttachment = $oSet->Fetch()) { $oAttachment->DBDelete(); // Pending attachment, don't mention it in the history } @@ -138,7 +120,7 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup public function EnumUsedAttributes($oObject) { - return array(); + return []; } public function GetIcon($oObject) @@ -149,17 +131,17 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup public function GetHilightClass($oObject) { // Possible return values are: - // HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE + // HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE return HILIGHT_CLASS_NONE; } public function EnumAllowedActions(DBObjectSet $oSet) { // No action - return array(); + return []; } - public function RegisterEventsAndListeners() : void + public function RegisterEventsAndListeners(): void { EventService::RegisterListener(EVENT_DB_AFTER_WRITE, [$this, 'OnDBAfterWrite']); EventService::RegisterListener(EVENT_DB_AFTER_DELETE, [$this, 'OnDBAfterDelete']); @@ -171,17 +153,14 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup $oCMDBChange = $oEventData->Get('cmdb_change'); $bIsNew = $oEventData->Get('is_new'); - if ($this->IsTargetObject($oObject)) - { - if($bIsNew){ + if ($this->IsTargetObject($oObject)) { + if ($bIsNew) { self::UpdateAttachments($oObject, $oCMDBChange); - } - else{ + } else { // Get all current attachments $oSearch = DBObjectSearch::FromOQL("SELECT Attachment WHERE item_class = :class AND item_id = :item_id"); - $oSet = new DBObjectSet($oSearch, array(), array('class' => get_class($oObject), 'item_id' => $oObject->GetKey())); - while ($oAttachment = $oSet->Fetch()) - { + $oSet = new DBObjectSet($oSearch, [], ['class' => get_class($oObject), 'item_id' => $oObject->GetKey()]); + while ($oAttachment = $oSet->Fetch()) { $oAttachment->SetItem($oObject, true /*updateonchange*/); } } @@ -192,12 +171,10 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup { $oObject = $oEventData->Get('object'); - if ($this->IsTargetObject($oObject)) - { + if ($this->IsTargetObject($oObject)) { $oSearch = DBObjectSearch::FromOQL("SELECT Attachment WHERE item_class = :class AND item_id = :item_id"); - $oSet = new DBObjectSet($oSearch, array(), array('class' => get_class($oObject), 'item_id' => $oObject->GetKey())); - while ($oAttachment = $oSet->Fetch()) - { + $oSet = new DBObjectSet($oSearch, [], ['class' => get_class($oObject), 'item_id' => $oObject->GetKey()]); + while ($oAttachment = $oSet->Fetch()) { $oAttachment->DBDelete(); } } @@ -211,11 +188,9 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup protected function IsTargetObject($oObject) { - $aAllowedClasses = MetaModel::GetModuleSetting('itop-attachments', 'allowed_classes', array('Ticket')); - foreach ($aAllowedClasses as $sAllowedClass) - { - if ($oObject instanceof $sAllowedClass) - { + $aAllowedClasses = MetaModel::GetModuleSetting('itop-attachments', 'allowed_classes', ['Ticket']); + foreach ($aAllowedClasses as $sAllowedClass) { + if ($oObject instanceof $sAllowedClass) { return true; } } @@ -228,7 +203,7 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup return MetaModel::GetModuleSetting('itop-attachments', 'position', 'relations'); } - var $m_bDeleteEnabled = true; + public $m_bDeleteEnabled = true; public function EnableDelete($bEnabled) { @@ -249,34 +224,28 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup public function DisplayAttachments(DBObject $oObject, WebPage $oPage, $bEditMode = false) { // Exit here if the class is not allowed - if (!$this->IsTargetObject($oObject)) - { + if (!$this->IsTargetObject($oObject)) { return; } $sObjClass = get_class($oObject); $iObjKey = $oObject->GetKey(); $sTransactionId = $oPage->GetTransactionId(); - if ($bEditMode && empty($sTransactionId)) - { + if ($bEditMode && empty($sTransactionId)) { throw new InvalidParameterException('Attachments renderer : invalid transaction id'); } $oAttachmentsRenderer = AttachmentsRendererFactory::GetInstance($oPage, $sObjClass, $iObjKey, $sTransactionId); - if ($this->GetAttachmentsPosition() === 'relations') - { + if ($this->GetAttachmentsPosition() === 'relations') { $iCount = $oAttachmentsRenderer->GetAttachmentsSet()->Count() + $oAttachmentsRenderer->GetTempAttachmentsSet()->Count(); $sTitle = ($iCount > 0) ? Dict::Format('Attachments:TabTitle_Count', $iCount) : Dict::S('Attachments:EmptyTabTitle'); $oPage->SetCurrentTab('Attachments:Tab', $sTitle); } - + $bIsReadOnlyState = self::IsReadonlyState($oObject, $oObject->GetState(), AttachmentPlugIn::ENUM_GUI_BACKOFFICE); - if ($bEditMode && !$bIsReadOnlyState) - { + if ($bEditMode && !$bIsReadOnlyState) { $oAttachmentsRenderer->RenderEditAttachmentsList(); - } - else - { + } else { $oAttachmentsRenderer->RenderViewAttachmentsList(); } } @@ -300,27 +269,23 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup */ protected static function UpdateAttachments($oObject, $oCMDBChange = null) { - if (utils::ReadParam('attachment_plugin', 'not-in-form') == 'not-in-form') - { + if (utils::ReadParam('attachment_plugin', 'not-in-form') == 'not-in-form') { // Workaround to an issue in iTop < 2.0 // Leave silently if there is no trace of the attachment form return; } $sTransactionId = utils::ReadParam('transaction_id', null, false, 'transaction_id'); - if (!is_null($sTransactionId)) - { - $aActions = array(); - $aRemovedAttachmentIds = utils::ReadParam('removed_attachments', array()); + if (!is_null($sTransactionId)) { + $aActions = []; + $aRemovedAttachmentIds = utils::ReadParam('removed_attachments', []); // Get all current attachments $oSearch = DBObjectSearch::FromOQL("SELECT Attachment WHERE item_class = :class AND item_id = :item_id"); $oSearch->AllowAllData(); - $oSet = new DBObjectSet($oSearch, array(), array('class' => get_class($oObject), 'item_id' => $oObject->GetKey())); - while ($oAttachment = $oSet->Fetch()) - { + $oSet = new DBObjectSet($oSearch, [], ['class' => get_class($oObject), 'item_id' => $oObject->GetKey()]); + while ($oAttachment = $oSet->Fetch()) { // Remove attachments that are no longer attached to the current object - if (in_array($oAttachment->GetKey(), $aRemovedAttachmentIds)) - { + if (in_array($oAttachment->GetKey(), $aRemovedAttachmentIds)) { $aData = ['attachment' => $oAttachment]; $oObject->FireEvent(EVENT_REMOVE_ATTACHMENT_FROM_OBJECT, $aData); $oAttachment->DBDelete(); @@ -335,11 +300,9 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup $sOQL = 'SELECT Attachment WHERE temp_id = :temp_id'; $oSearch = DBObjectSearch::FromOQL($sOQL); $oSearch->AllowAllData(); - $oSet = new DBObjectSet($oSearch, array(), array('temp_id' => $sTempId)); - while ($oAttachment = $oSet->Fetch()) - { - if (in_array($oAttachment->GetKey(), $aRemovedAttachmentIds)) - { + $oSet = new DBObjectSet($oSearch, [], ['temp_id' => $sTempId]); + while ($oAttachment = $oSet->Fetch()) { + if (in_array($oAttachment->GetKey(), $aRemovedAttachmentIds)) { $oAttachment->DBDelete(); // temporary attachment removed, don't even mention it in the history } else { @@ -352,10 +315,8 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup $oObject->FireEvent(EVENT_ADD_ATTACHMENT_TO_OBJECT, $aData); } } - if (count($aActions) > 0) - { - foreach ($aActions as $oChangeOp) - { + if (count($aActions) > 0) { + foreach ($aActions as $oChangeOp) { self::RecordHistory($oCMDBChange, $oObject, $oChangeOp); } @@ -367,11 +328,10 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup public static function CopyAttachments($oObject, $sTransactionId) { $oSearch = DBObjectSearch::FromOQL("SELECT Attachment WHERE item_class = :class AND item_id = :item_id"); - $oSet = new DBObjectSet($oSearch, array(), array('class' => get_class($oObject), 'item_id' => $oObject->GetKey())); + $oSet = new DBObjectSet($oSearch, [], ['class' => get_class($oObject), 'item_id' => $oObject->GetKey()]); // Attach new (temporary) attachments $sTempId = utils::GetUploadTempId($sTransactionId); - while ($oAttachment = $oSet->Fetch()) - { + while ($oAttachment = $oSet->Fetch()) { $oTempAttachment = clone $oAttachment; $oTempAttachment->Set('expire', time() + utils::GetConfig()->Get('draft_attachments_lifetime')); $oTempAttachment->Set('item_id', null); @@ -384,15 +344,11 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup public static function GetFileIcon($sFileName) { $aPathParts = pathinfo($sFileName); - if (!array_key_exists('extension', $aPathParts)) - { + if (!array_key_exists('extension', $aPathParts)) { // No extension: use the default icon $sIcon = 'icons8-file.svg'; - } - else - { - switch (strtolower($aPathParts['extension'])) - { + } else { + switch (strtolower($aPathParts['extension'])) { case 'doc': case 'docx': $sIcon = 'icons8-word.svg'; @@ -425,7 +381,7 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup case 'vb': $sIcon = 'icons8-code-file.svg'; break; - + case 'pdf': $sIcon = 'icons8-pdf.svg'; break; @@ -478,7 +434,7 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup case 'ai': $sIcon = 'icons8-image-file.svg'; break; - + case 'zip': case 'gz': case 'tgz': @@ -512,34 +468,34 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup case 'wma': $sIcon = 'icons8-audio-file.svg'; break; - + case 'csv': $sIcon = 'icons8-csv.svg'; break; - + case 'log': $sIcon = 'icons8-event-log.svg'; break; - + case 'sql': $sIcon = 'icons8-sql.svg'; break; - + case 'xml': $sIcon = 'icons8-xml-file.svg'; - break; - + break; + case 'email': case 'eml': case 'emlx': case 'msg': $sIcon = 'icons8-mail.svg'; break; - + case 'patch': $sIcon = 'icons8-bandage.svg'; break; - + default: $sIcon = 'icons8-file.svg'; break; @@ -552,8 +508,7 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup ///////////////////////////////////////////////////////////////////////// private static function RecordHistory($oCMDBChange, $oTargetObject, $oMyChangeOp) { - if (!is_null($oCMDBChange)) - { + if (!is_null($oCMDBChange)) { $oMyChangeOp->Set("change", $oCMDBChange->GetKey()); } $oMyChangeOp->Set("objclass", get_class($oTargetObject)); @@ -566,14 +521,11 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup { $oBlob = $oAttachment->Get('contents'); $sFileName = $oBlob->GetFileName(); - if ($bCreate) - { + if ($bCreate) { $oChangeOp = new CMDBChangeOpAttachmentAdded(); $oChangeOp->Set('attachment_id', $oAttachment->GetKey()); $oChangeOp->Set('filename', $sFileName); - } - else - { + } else { $oChangeOp = new CMDBChangeOpAttachmentRemoved(); $oChangeOp->Set('filename', $sFileName); } @@ -595,44 +547,36 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup */ public static function IsReadonlyState(DBObject $oObject, $sState, $sGUI = self::ENUM_GUI_ALL) { - $aParamDefaultValue = array( - static::ENUM_GUI_ALL => array( - 'Ticket' => array('closed'), - ), - ); + $aParamDefaultValue = [ + static::ENUM_GUI_ALL => [ + 'Ticket' => ['closed'], + ], + ]; $bReadonly = false; $sClass = get_class($oObject); $aReadonlyStatus = MetaModel::GetModuleSetting('itop-attachments', 'readonly_states', $aParamDefaultValue); - if (!empty($aReadonlyStatus)) - { + if (!empty($aReadonlyStatus)) { // Merging GUIs entries - $aEntries = array(); + $aEntries = []; // - All - if (array_key_exists(static::ENUM_GUI_ALL, $aReadonlyStatus)) - { + if (array_key_exists(static::ENUM_GUI_ALL, $aReadonlyStatus)) { $aEntries = array_merge_recursive($aEntries, $aReadonlyStatus[static::ENUM_GUI_ALL]); } // - Backoffice & Portals - foreach (array(static::ENUM_GUI_BACKOFFICE, static::ENUM_GUI_PORTALS) as $sEnumGUI) - { - if (in_array($sGUI, array(static::ENUM_GUI_ALL, $sEnumGUI))) - { - if (array_key_exists($sEnumGUI, $aReadonlyStatus)) - { + foreach ([static::ENUM_GUI_BACKOFFICE, static::ENUM_GUI_PORTALS] as $sEnumGUI) { + if (in_array($sGUI, [static::ENUM_GUI_ALL, $sEnumGUI])) { + if (array_key_exists($sEnumGUI, $aReadonlyStatus)) { $aEntries = array_merge_recursive($aEntries, $aReadonlyStatus[$sEnumGUI]); } } } $aParentClasses = array_reverse(MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL)); - foreach ($aParentClasses as $sParentClass) - { - if (array_key_exists($sParentClass, $aEntries)) - { + foreach ($aParentClasses as $sParentClass) { + if (array_key_exists($sParentClass, $aEntries)) { // If we found an ancestor of the object's class, we stop looking event if the current state is not specified - if (in_array($oObject->GetState(), $aEntries[$sParentClass])) - { + if (in_array($oObject->GetState(), $aEntries[$sParentClass])) { $bReadonly = true; } break; @@ -643,7 +587,6 @@ class AttachmentPlugIn implements iApplicationUIExtension, iEventServiceSetup return $bReadonly; } - } /** @@ -658,38 +601,38 @@ class CMDBChangeOpAttachmentAdded extends CMDBChangeOp { public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "core/cmdb, grant_by_profile", "key_type" => "", "name_attcode" => "change", "state_attcode" => "", - "reconc_keys" => array(), + "reconc_keys" => [], "db_table" => "priv_changeop_attachment_added", "db_key_field" => "id", "db_finalclass_field" => "", - ); + ]; MetaModel::Init_Params($aParams); MetaModel::Init_InheritAttributes(); - MetaModel::Init_AddAttribute(new AttributeExternalKey("attachment_id", array( + MetaModel::Init_AddAttribute(new AttributeExternalKey("attachment_id", [ "targetclass" => "Attachment", "allowed_values" => null, "sql" => "attachment_id", "is_null_allowed" => true, "on_target_delete" => DEL_SILENT, - "depends_on" => array(), - ))); - MetaModel::Init_AddAttribute(new AttributeString("filename", array( + "depends_on" => [], + ])); + MetaModel::Init_AddAttribute(new AttributeString("filename", [ "allowed_values" => null, "sql" => "filename", "default_value" => "", "is_null_allowed" => false, - "depends_on" => array(), - ))); + "depends_on" => [], + ])); // Display lists - MetaModel::Init_SetZListItems('details', array('attachment_id')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('attachment_id')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['attachment_id']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['attachment_id']); // Attributes to be displayed for a list } /** @@ -709,12 +652,15 @@ class CMDBChangeOpAttachmentAdded extends CMDBChangeOp $oAttachment = $oMonoObjectSet->Fetch(); $oDoc = $oAttachment->Get('contents'); $sPreview = $oDoc->IsPreviewAvailable() ? 'data-preview="true"' : ''; - $sResult = Dict::Format('Attachments:History_File_Added', - ''.$sFilename.''); - } - else - { + $sResult = Dict::Format( + 'Attachments:History_File_Added', + ''.$sFilename.'' + ); + } else { $sResult = Dict::Format('Attachments:History_File_Added', ''.$sFilename.''); } @@ -726,30 +672,30 @@ class CMDBChangeOpAttachmentRemoved extends CMDBChangeOp { public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "core/cmdb, grant_by_profile", "key_type" => "", "name_attcode" => "change", "state_attcode" => "", - "reconc_keys" => array(), + "reconc_keys" => [], "db_table" => "priv_changeop_attachment_removed", "db_key_field" => "id", "db_finalclass_field" => "", - ); + ]; MetaModel::Init_Params($aParams); MetaModel::Init_InheritAttributes(); - MetaModel::Init_AddAttribute(new AttributeString("filename", array( + MetaModel::Init_AddAttribute(new AttributeString("filename", [ "allowed_values" => null, "sql" => "filename", "default_value" => "", "is_null_allowed" => false, - "depends_on" => array(), - ))); + "depends_on" => [], + ])); // Display lists - MetaModel::Init_SetZListItems('details', array('filename')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('filename')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['filename']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['filename']); // Attributes to be displayed for a list } /** @@ -758,8 +704,10 @@ class CMDBChangeOpAttachmentRemoved extends CMDBChangeOp public function GetDescription() { // Temporary, until we change the options of GetDescription() -needs a more global revision - $sResult = Dict::Format('Attachments:History_File_Removed', - ''.utils::EscapeHtml($this->Get('filename')).''); + $sResult = Dict::Format( + 'Attachments:History_File_Removed', + ''.utils::EscapeHtml($this->Get('filename')).'' + ); return $sResult; } @@ -776,29 +724,22 @@ class AttachmentsHelper public static function GetAttachmentsDateAddedFromDb($sObjClass, $iObjKey) { $sQuery = "SELECT CMDBChangeOpAttachmentAdded WHERE objclass='$sObjClass' AND objkey=$iObjKey"; - try - { + try { $oSearch = DBObjectSearch::FromOQL($sQuery); - } - catch (OQLException $e) - { - return array(); + } catch (OQLException $e) { + return []; } $oSet = new DBObjectSet($oSearch); - try - { - $aAttachmentDates = array(); - while ($oChangeOpAttAdded = $oSet->Fetch()) - { + try { + $aAttachmentDates = []; + while ($oChangeOpAttAdded = $oSet->Fetch()) { $iAttachmentId = $oChangeOpAttAdded->Get('attachment_id'); $sAttachmentDate = $oChangeOpAttAdded->Get('date'); $aAttachmentDates[$iAttachmentId] = $sAttachmentDate; } - } - catch (Exception $e) - { - return array(); + } catch (Exception $e) { + return []; } return $aAttachmentDates; diff --git a/datamodels/2.x/itop-attachments/module.itop-attachments.php b/datamodels/2.x/itop-attachments/module.itop-attachments.php index b383836b4..cf2291758 100644 --- a/datamodels/2.x/itop-attachments/module.itop-attachments.php +++ b/datamodels/2.x/itop-attachments/module.itop-attachments.php @@ -1,9 +1,10 @@ - SetupWebPage::AddModule( __FILE__, // Path to the current file, all other file names are relative to the directory containing this file 'itop-attachments/3.3.0', - array( + [ // Identification // 'label' => 'Tickets Attachments', @@ -28,52 +28,51 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array(), + 'dependencies' => [], 'mandatory' => false, 'visible' => true, 'installer' => 'AttachmentInstaller', // Components // - 'datamodel' => array( + 'datamodel' => [ 'vendor/autoload.php', 'main.itop-attachments.php', 'src/Trigger/TriggerOnAttachmentCreate.php', 'src/Trigger/TriggerOnAttachmentDelete.php', 'src/Trigger/TriggerOnAttachmentDownload.php', 'renderers.itop-attachments.php', - ), - 'webservice' => array( - - ), - 'dictionary' => array( + ], + 'webservice' => [ - ), - 'data.struct' => array( + ], + 'dictionary' => [ + + ], + 'data.struct' => [ // add your 'structure' definition XML files here, - ), - 'data.sample' => array( + ], + 'data.sample' => [ // add your sample data XML files here, - ), - + ], + // Documentation // 'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any - 'doc.more_information' => '', // hyperlink to more information, if any + 'doc.more_information' => '', // hyperlink to more information, if any // Default settings // - 'settings' => array( - 'allowed_classes' => array('Ticket'), // List of classes for which to manage "Attachments" + 'settings' => [ + 'allowed_classes' => ['Ticket'], // List of classes for which to manage "Attachments" 'position' => 'relations', // Where to display the attachments: relations | properties 'preview_max_width' => 290, 'icon_preview_max_size' => 500000, // Maximum size for attachment preview to be displayed as an icon. In bits - ), - ) + ], + ] ); -if (!class_exists('AttachmentInstaller')) -{ +if (!class_exists('AttachmentInstaller')) { // Module installation handler // class AttachmentInstaller extends ModuleInstallerAPI @@ -94,7 +93,8 @@ if (!class_exists('AttachmentInstaller')) * @throws \MySQLException * @throws \MySQLHasGoneAwayException */ - public static function GetOrphanAttachmentIds($sTableName, $iBulkSize){ + public static function GetOrphanAttachmentIds($sTableName, $iBulkSize) + { $sSqlQuery = <<fetch_array()){ + while ($aRow = $oQueryResult->fetch_array()) { $aIds[] = $aRow['attachment_id']; } @@ -117,15 +117,13 @@ SQL; */ public static function BeforeDatabaseCreation(Config $oConfiguration, $sPreviousVersion, $sCurrentVersion) { - if ($sPreviousVersion != '') - { + if ($sPreviousVersion != '') { // Migrating from a previous version // Check for records where item_id = '', since they are not attached to any object and cannot be migrated to the objkey schema $sTableName = MetaModel::DBGetTable('Attachment'); $sCountQuery = "SELECT COUNT(*) FROM `$sTableName` WHERE (`item_id`='' OR `item_id` IS NULL)"; $iCount = CMDBSource::QueryToScalar($sCountQuery); - if ($iCount > 0) - { + if ($iCount > 0) { SetupLog::Info("Cleanup of orphan attachments that cannot be migrated to the new ObjKey model: $iCount record(s) must be deleted."); $iBulkSize = 100; @@ -141,7 +139,7 @@ SQL; $iDeletedCount += count($aIds); $fElapsed = microtime(true) - $fStartTime; - if ($fElapsed > $iMaxDuration){ + if ($fElapsed > $iMaxDuration) { SetupLog::Info(sprintf("Cleanup of orphan attachments interrupted after %.3f s. $iDeletedCount records were deleted among $iCount.", $fElapsed)); break; } @@ -149,12 +147,10 @@ SQL; $aIds = self::GetOrphanAttachmentIds($sTableName, $iBulkSize); } - if (count($aIds) === 0){ + if (count($aIds) === 0) { SetupLog::Info("Cleanup of orphan attachments successfully completed."); } - } - else - { + } else { SetupLog::Info("No orphan attachment found."); } } @@ -169,7 +165,7 @@ SQL; public static function AfterDatabaseCreation(Config $oConfiguration, $sPreviousVersion, $sCurrentVersion) { // For each record having item_org_id unset, - // get the org_id from the container object + // get the org_id from the container object // // Prerequisite: change null into 0 (workaround to the fact that we cannot use IS NULL in OQL) SetupLog::Info("Initializing attachment/item_org_id - null to zero"); @@ -185,11 +181,10 @@ SQL; 'Attachment' => [ 'item_class', 'item_id', - ] + ], ]); $iUpdated = 0; - while ($oAttachment = $oSet->Fetch()) - { + while ($oAttachment = $oSet->Fetch()) { if (empty($oAttachment->Get('item_class'))) { //do not treat orphan attachment continue; diff --git a/datamodels/2.x/itop-attachments/src/Hook/EventListener.php b/datamodels/2.x/itop-attachments/src/Hook/EventListener.php index eb23cd5f6..47723b063 100644 --- a/datamodels/2.x/itop-attachments/src/Hook/EventListener.php +++ b/datamodels/2.x/itop-attachments/src/Hook/EventListener.php @@ -40,14 +40,14 @@ class EventListener implements iEventServiceSetup [$this, 'OnAttachmentDownloadActivateTriggers'], 'Attachment' ); - EventService::RegisterListener( - \EVENT_ADD_ATTACHMENT_TO_OBJECT, - [$this, 'OnAttachmentAddedActivateTriggers'] - ); - EventService::RegisterListener( - \EVENT_REMOVE_ATTACHMENT_FROM_OBJECT, - [$this, 'OnAttachmentRemovedActivateTriggers'] - ); + EventService::RegisterListener( + \EVENT_ADD_ATTACHMENT_TO_OBJECT, + [$this, 'OnAttachmentAddedActivateTriggers'] + ); + EventService::RegisterListener( + \EVENT_REMOVE_ATTACHMENT_FROM_OBJECT, + [$this, 'OnAttachmentRemovedActivateTriggers'] + ); } /** @@ -70,77 +70,77 @@ class EventListener implements iEventServiceSetup /** @var \ormDocument $oDocument */ $oDocument = $oEventData->Get('document'); - $this->OnAttachmentActivateTriggers( - $oHostObj, - $oAttachment, - $oDocument, - TriggerOnAttachmentDownload::class - ); - } + $this->OnAttachmentActivateTriggers( + $oHostObj, + $oAttachment, + $oDocument, + TriggerOnAttachmentDownload::class + ); + } - /** - * Callback when an Attachment is added: Activate corresponding triggers - * - * @param \Combodo\iTop\Service\Events\EventData $oEventData - * - * @return void - * @throws \CoreException - */ - public function OnAttachmentAddedActivateTriggers(EventData $oEventData): void - { - /** @var DBObject $oAttachment */ - $oAttachment = $oEventData->Get('attachment'); - /** @var DBObject $oHostObj */ - $oHostObj = $oEventData->Get('object'); - /** @var ormDocument $oDocument */ - $oDocument = $oAttachment->Get('contents'); + /** + * Callback when an Attachment is added: Activate corresponding triggers + * + * @param \Combodo\iTop\Service\Events\EventData $oEventData + * + * @return void + * @throws \CoreException + */ + public function OnAttachmentAddedActivateTriggers(EventData $oEventData): void + { + /** @var DBObject $oAttachment */ + $oAttachment = $oEventData->Get('attachment'); + /** @var DBObject $oHostObj */ + $oHostObj = $oEventData->Get('object'); + /** @var ormDocument $oDocument */ + $oDocument = $oAttachment->Get('contents'); - $this->OnAttachmentActivateTriggers( - $oHostObj, - $oAttachment, - $oDocument, - \TriggerOnAttachmentCreate::class - ); - } + $this->OnAttachmentActivateTriggers( + $oHostObj, + $oAttachment, + $oDocument, + \TriggerOnAttachmentCreate::class + ); + } - /** - * Callback when an Attachment is removed: Activate corresponding triggers - * - * @param \Combodo\iTop\Service\Events\EventData $oEventData - * - * @return void - * @throws \CoreException - */ - public function OnAttachmentRemovedActivateTriggers(EventData $oEventData): void - { - /** @var DBObject $oAttachment */ - $oAttachment = $oEventData->Get('attachment'); - /** @var DBObject $oHostObj */ - $oHostObj = $oEventData->Get('object'); - /** @var ormDocument $oDocument */ - $oDocument = $oAttachment->Get('contents'); + /** + * Callback when an Attachment is removed: Activate corresponding triggers + * + * @param \Combodo\iTop\Service\Events\EventData $oEventData + * + * @return void + * @throws \CoreException + */ + public function OnAttachmentRemovedActivateTriggers(EventData $oEventData): void + { + /** @var DBObject $oAttachment */ + $oAttachment = $oEventData->Get('attachment'); + /** @var DBObject $oHostObj */ + $oHostObj = $oEventData->Get('object'); + /** @var ormDocument $oDocument */ + $oDocument = $oAttachment->Get('contents'); - $this->OnAttachmentActivateTriggers( - $oHostObj, - $oAttachment, - $oDocument, - \TriggerOnAttachmentDelete::class - ); - } + $this->OnAttachmentActivateTriggers( + $oHostObj, + $oAttachment, + $oDocument, + \TriggerOnAttachmentDelete::class + ); + } - /** - * Callback when an Attachment downloaded, added or removed: Activate corresponding triggers - * - * @param DBObject $oHostObj - * @param DBObject $oAttachment - * @param ormDocument $oDocument - * @param string $sTriggerClass - * - * @return void - * @throws \CoreException - */ - protected function OnAttachmentActivateTriggers(DBObject $oHostObj, DBObject $oAttachment, ormDocument $oDocument, string $sTriggerClass): void - { + /** + * Callback when an Attachment downloaded, added or removed: Activate corresponding triggers + * + * @param DBObject $oHostObj + * @param DBObject $oAttachment + * @param ormDocument $oDocument + * @param string $sTriggerClass + * + * @return void + * @throws \CoreException + */ + protected function OnAttachmentActivateTriggers(DBObject $oHostObj, DBObject $oAttachment, ormDocument $oDocument, string $sTriggerClass): void + { $aTriggerContextArgs = [ 'this->object()' => $oHostObj, 'attachment->object()' => $oAttachment, diff --git a/datamodels/2.x/itop-attachments/src/Trigger/TriggerOnAttachmentCreate.php b/datamodels/2.x/itop-attachments/src/Trigger/TriggerOnAttachmentCreate.php index 8e755598e..2931de448 100644 --- a/datamodels/2.x/itop-attachments/src/Trigger/TriggerOnAttachmentCreate.php +++ b/datamodels/2.x/itop-attachments/src/Trigger/TriggerOnAttachmentCreate.php @@ -5,7 +5,6 @@ * @license http://opensource.org/licenses/AGPL-3.0 */ - /** * Class TriggerOnAttachmentCreate * @@ -20,29 +19,28 @@ class TriggerOnAttachmentCreate extends TriggerOnObject */ public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "grant_by_profile,core/cmdb,application", "key_type" => "autoincrement", "name_attcode" => "description", - "complementary_name_attcode" => ['finalclass', 'complement'], + "complementary_name_attcode" => ['finalclass', 'complement'], "state_attcode" => "", "reconc_keys" => ['description'], "db_table" => "priv_trigger_onattcreate", "db_key_field" => "id", "db_finalclass_field" => "", "display_template" => "", - ); + ]; MetaModel::Init_Params($aParams); MetaModel::Init_InheritAttributes(); - MetaModel::Init_AddAttribute(new AttributeBoolean("file_in_email", array("sql"=>'file_in_email', "is_null_allowed"=>false, "default_value"=>'true', "allowed_values"=>null, "depends_on"=>array(), "always_load_in_tables"=>false))); - + MetaModel::Init_AddAttribute(new AttributeBoolean("file_in_email", ["sql" => 'file_in_email', "is_null_allowed" => false, "default_value" => 'true', "allowed_values" => null, "depends_on" => [], "always_load_in_tables" => false])); // Display lists - MetaModel::Init_SetZListItems('details', array('description', 'context', 'filter', 'action_list', 'target_class', 'file_in_email')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('finalclass', 'target_class')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['description', 'context', 'filter', 'action_list', 'target_class', 'file_in_email']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['finalclass', 'target_class']); // Attributes to be displayed for a list // Search criteria - MetaModel::Init_SetZListItems('standard_search', array('description', 'target_class')); // Criteria of the std search form + MetaModel::Init_SetZListItems('standard_search', ['description', 'target_class']); // Criteria of the std search form } -} \ No newline at end of file +} diff --git a/datamodels/2.x/itop-attachments/src/Trigger/TriggerOnAttachmentDelete.php b/datamodels/2.x/itop-attachments/src/Trigger/TriggerOnAttachmentDelete.php index 8e7798a7c..a9c8ac7c6 100644 --- a/datamodels/2.x/itop-attachments/src/Trigger/TriggerOnAttachmentDelete.php +++ b/datamodels/2.x/itop-attachments/src/Trigger/TriggerOnAttachmentDelete.php @@ -5,7 +5,6 @@ * @license http://opensource.org/licenses/AGPL-3.0 */ - /** * Class TriggerOnAttachmentCreate * @@ -20,28 +19,28 @@ class TriggerOnAttachmentDelete extends TriggerOnObject */ public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "grant_by_profile,core/cmdb,application", "key_type" => "autoincrement", "name_attcode" => "description", - "complementary_name_attcode" => ['finalclass', 'complement'], + "complementary_name_attcode" => ['finalclass', 'complement'], "state_attcode" => "", "reconc_keys" => ['description'], "db_table" => "priv_trigger_onattdelete", "db_key_field" => "id", "db_finalclass_field" => "", "display_template" => "", - ); + ]; MetaModel::Init_Params($aParams); MetaModel::Init_InheritAttributes(); // Display lists - MetaModel::Init_SetZListItems('details', array('description', 'context', 'filter', 'action_list', 'target_class')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('finalclass', 'target_class')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['description', 'context', 'filter', 'action_list', 'target_class']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['finalclass', 'target_class']); // Attributes to be displayed for a list // Search criteria - MetaModel::Init_SetZListItems('standard_search', array('description', 'target_class')); // Criteria of the std search form + MetaModel::Init_SetZListItems('standard_search', ['description', 'target_class']); // Criteria of the std search form } -} \ No newline at end of file +} diff --git a/datamodels/2.x/itop-attachments/src/Trigger/TriggerOnAttachmentDownload.php b/datamodels/2.x/itop-attachments/src/Trigger/TriggerOnAttachmentDownload.php index 51088d72c..ceb9d3988 100644 --- a/datamodels/2.x/itop-attachments/src/Trigger/TriggerOnAttachmentDownload.php +++ b/datamodels/2.x/itop-attachments/src/Trigger/TriggerOnAttachmentDownload.php @@ -7,27 +7,27 @@ */ class TriggerOnAttachmentDownload extends TriggerOnAttributeBlobDownload { - /** - * @inheritDoc - * @throws \CoreException - * @throws \Exception - */ - public static function Init() - { - $aParams = array - ( - "category" => "grant_by_profile,core/cmdb,application", - "key_type" => "autoincrement", - "name_attcode" => "description", - "complementary_name_attcode" => ['finalclass', 'complement'], - "state_attcode" => "", - "reconc_keys" => ['description'], - "db_table" => "priv_trigger_onattdownload", - "db_key_field" => "id", - "db_finalclass_field" => "", - "display_template" => "", - ); - MetaModel::Init_Params($aParams); - MetaModel::Init_InheritAttributes(); - } -} \ No newline at end of file + /** + * @inheritDoc + * @throws \CoreException + * @throws \Exception + */ + public static function Init() + { + $aParams = + [ + "category" => "grant_by_profile,core/cmdb,application", + "key_type" => "autoincrement", + "name_attcode" => "description", + "complementary_name_attcode" => ['finalclass', 'complement'], + "state_attcode" => "", + "reconc_keys" => ['description'], + "db_table" => "priv_trigger_onattdownload", + "db_key_field" => "id", + "db_finalclass_field" => "", + "display_template" => "", + ]; + MetaModel::Init_Params($aParams); + MetaModel::Init_InheritAttributes(); + } +} diff --git a/datamodels/2.x/itop-backup/dbrestore.class.inc.php b/datamodels/2.x/itop-backup/dbrestore.class.inc.php index 8a0ccc014..5873145a9 100644 --- a/datamodels/2.x/itop-backup/dbrestore.class.inc.php +++ b/datamodels/2.x/itop-backup/dbrestore.class.inc.php @@ -1,4 +1,5 @@ - class DBRestore extends DBBackup { /** @var string */ @@ -54,12 +54,9 @@ class DBRestore extends DBBackup $sPwd = self::EscapeShellArg($this->sDBPwd); $sDBName = self::EscapeShellArg($this->sDBName); $sMySQLExe = DBBackup::MakeSafeMySQLCommand($this->sMySQLBinDir, 'mysql'); - if (is_null($this->iDBPort)) - { + if (is_null($this->iDBPort)) { $sPortOption = ''; - } - else - { + } else { $sPortOption = '--port='.$this->iDBPort.' '; } $sTlsOptions = self::GetMysqlCliTlsOptions($this->oConfig); @@ -70,26 +67,20 @@ class DBRestore extends DBBackup // Now run the command for real $this->LogInfo("Executing command: $sCommandDisplay"); - $aOutput = array(); + $aOutput = []; $iRetCode = 0; exec($sCommand, $aOutput, $iRetCode); - foreach($aOutput as $sLine) - { + foreach ($aOutput as $sLine) { $this->LogInfo("mysql said: $sLine"); } - if ($iRetCode != 0) - { + if ($iRetCode != 0) { $this->LogError("Failed to execute: $sCommandDisplay. The command returned:$iRetCode"); - foreach($aOutput as $sLine) - { + foreach ($aOutput as $sLine) { $this->LogError("mysql said: $sLine"); } - if (count($aOutput) == 1) - { + if (count($aOutput) == 1) { $sMoreInfo = trim($aOutput[0]); - } - else - { + } else { $sMoreInfo = "Check the log file '".realpath(APPROOT.'/log/error.log')."' for more information."; } throw new BackupException("Failed to execute mysql: ".$sMoreInfo); @@ -120,7 +111,6 @@ class DBRestore extends DBBackup //safe zone for db backup => cron is stopped/ itop in readonly $this->LogInfo("Starting restore of ".basename($sFile)); - $sNormalizedFile = strtolower(basename($sFile)); if (substr($sNormalizedFile, -4) == '.zip') { $this->LogInfo('zip file detected'); @@ -170,7 +160,7 @@ class DBRestore extends DBBackup @chmod($sConfigFile, 0440); // Read-only $aExtraFiles = $this->ListExtraFiles($sDataDir); - foreach($aExtraFiles as $sSourceFilePath => $sDestinationFilePath) { + foreach ($aExtraFiles as $sSourceFilePath => $sDestinationFilePath) { SetupUtils::builddir(dirname($sDestinationFilePath)); rename($sSourceFilePath, $sDestinationFilePath); } @@ -191,9 +181,7 @@ class DBRestore extends DBBackup $this->LogInfo("Keep maintenance mode after restore"); } } - } - finally - { + } finally { IssueLog::Info('Backup Restore - LOCK released.'); $oRestoreMutex->Unlock(); } @@ -209,10 +197,9 @@ class DBRestore extends DBBackup { $aExtraFiles = []; $aStandardFiles = ['config-itop.php', 'itop-dump.sql', 'production-modules', 'delta.xml']; - $oDirectoryIterator = new RecursiveDirectoryIterator($sDataDir, FilesystemIterator::CURRENT_AS_FILEINFO|FilesystemIterator::SKIP_DOTS); + $oDirectoryIterator = new RecursiveDirectoryIterator($sDataDir, FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS); $oIterator = new RecursiveIteratorIterator($oDirectoryIterator); - foreach ($oIterator as $oFileInfo) - { + foreach ($oIterator as $oFileInfo) { if (in_array($oFileInfo->getFilename(), $aStandardFiles)) { continue; } diff --git a/datamodels/2.x/itop-backup/main.itop-backup.php b/datamodels/2.x/itop-backup/main.itop-backup.php index 9f7d326e7..9481e29ec 100644 --- a/datamodels/2.x/itop-backup/main.itop-backup.php +++ b/datamodels/2.x/itop-backup/main.itop-backup.php @@ -1,4 +1,5 @@ IsLocked()) - { + if ($oRestoreMutex->IsLocked()) { IssueLog::Info(__class__.'::'.__function__.' A user is trying to use iTop while a restore is running. The requested page is in read-only mode.'); MetaModel::GetConfig()->Set('access_mode', ACCESS_READONLY, 'itop-backup'); MetaModel::GetConfig()->Set('access_message', ' - '.dict::S('bkp-restore-running'), 'itop-backup'); } - } - catch(Exception $e) - { + } catch (Exception $e) { IssueLog::Error(__class__.'::'.__function__.' Failed to check if a backup/restore is running: '.$e->getMessage()); } } @@ -65,22 +60,20 @@ class DBBackupScheduled extends DBBackup */ public function ListFiles($sBackupDir) { - $aFiles = array(); - $aTimes = array(); + $aFiles = []; + $aTimes = []; // Legacy format -limited to 4 Gb - foreach(glob($sBackupDir.'*.zip') as $sFilePath) - { + foreach (glob($sBackupDir.'*.zip') as $sFilePath) { $aFiles[] = $sFilePath; $aTimes[] = filemtime($sFilePath); // unix time } // Modern format - foreach(glob($sBackupDir.'*.tar.gz') as $sFilePath) - { + foreach (glob($sBackupDir.'*.tar.gz') as $sFilePath) { $aFiles[] = $sFilePath; $aTimes[] = filemtime($sFilePath); // unix time } array_multisort($aTimes, $aFiles); - + return $aFiles; } } @@ -107,20 +100,14 @@ class BackupExec extends AbstractWeeklyScheduledProcess */ public function __construct($sBackupDir = null, $iRetentionCount = null) { - if (is_null($sBackupDir)) - { + if (is_null($sBackupDir)) { $this->sBackupDir = utils::GetDataPath().'backups/auto/'; - } - else - { + } else { $this->sBackupDir = $sBackupDir; } - if (is_null($iRetentionCount)) - { + if (is_null($iRetentionCount)) { $this->iRetentionCount = MetaModel::GetConfig()->GetModuleSetting($this->GetModuleName(), 'retention_count', 5); - } - else - { + } else { $this->iRetentionCount = $iRetentionCount; } } @@ -135,53 +122,43 @@ class BackupExec extends AbstractWeeklyScheduledProcess $oMutex = new iTopMutex('backup.'.utils::GetCurrentEnvironment()); $oMutex->Lock(); - try - { + try { // Make sure the target directory exists SetupUtils::builddir($this->sBackupDir); - + $oBackup = new DBBackupScheduled(); // Eliminate files exceeding the retention setting // - if ($this->iRetentionCount > 0) - { + if ($this->iRetentionCount > 0) { $aFiles = $oBackup->ListFiles($this->sBackupDir); - while (count($aFiles) >= $this->iRetentionCount) - { + while (count($aFiles) >= $this->iRetentionCount) { $sFileToDelete = array_shift($aFiles); unlink($sFileToDelete); - if (file_exists($sFileToDelete)) - { + if (file_exists($sFileToDelete)) { // Ok, do not loop indefinitely on this break; } } } - + // Do execute the backup // $oBackup->SetMySQLBinDir(MetaModel::GetConfig()->GetModuleSetting($this->GetModuleName(), 'mysql_bindir', '')); $sBackupFileFormat = MetaModel::GetConfig()->GetModuleSetting($this->GetModuleName(), 'file_name_format', '__DB__-%Y-%m-%d_%H_%M'); $sName = $oBackup->MakeName($sBackupFileFormat); - if ($sName == '') - { + if ($sName == '') { $sName = $oBackup->MakeName(BACKUP_DEFAULT_FORMAT); } $sBackupFile = $this->sBackupDir.$sName; $sSourceConfigFile = APPCONF.utils::GetCurrentEnvironment().'/'.ITOP_CONFIG_FILE; - try - { + try { $oBackup->CreateCompressedBackup($sBackupFile, $sSourceConfigFile); - } - catch (BackupException $e) - { + } catch (BackupException $e) { throw new ProcessFatalException($e->getMessage()); } - } - catch (Exception $e) - { + } catch (Exception $e) { $oMutex->Unlock(); throw $e; } diff --git a/datamodels/2.x/itop-backup/module.itop-backup.php b/datamodels/2.x/itop-backup/module.itop-backup.php index 7cc0972da..35fd85f0b 100644 --- a/datamodels/2.x/itop-backup/module.itop-backup.php +++ b/datamodels/2.x/itop-backup/module.itop-backup.php @@ -1,10 +1,9 @@ 'Backup utilities', @@ -12,31 +11,31 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( - ), + 'dependencies' => [ + ], 'mandatory' => true, 'visible' => false, // Components // - 'datamodel' => array( + 'datamodel' => [ 'main.itop-backup.php', - ), - 'webservice' => array( + ], + 'webservice' => [ //'webservices.itop-backup.php', - ), - 'dictionary' => array( + ], + 'dictionary' => [ 'en.dict.itop-backup.php', 'fr.dict.itop-backup.php', //'de.dict.itop-backup.php', - ), - 'data.struct' => array( + ], + 'data.struct' => [ //'data.struct.itop-backup.xml', - ), - 'data.sample' => array( + ], + 'data.sample' => [ //'data.sample.itop-backup.xml', - ), - + ], + // Documentation // 'doc.manual_setup' => '', @@ -44,14 +43,14 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array( + 'settings' => [ 'mysql_bindir' => '', 'week_days' => 'monday, tuesday, wednesday, thursday, friday', 'time' => '23:30', //'file_name_format' => '__DB__-%Y-%m-%d_%H_%M', - 'retention_count' => 5, + 'retention_count' => 5, 'enabled' => true, 'itop_backup_incident' => '', - ), - ) + ], + ] ); diff --git a/datamodels/2.x/itop-bridge-cmdb-services/module.itop-bridge-cmdb-services.php b/datamodels/2.x/itop-bridge-cmdb-services/module.itop-bridge-cmdb-services.php index 1e1a35161..57c31ad22 100644 --- a/datamodels/2.x/itop-bridge-cmdb-services/module.itop-bridge-cmdb-services.php +++ b/datamodels/2.x/itop-bridge-cmdb-services/module.itop-bridge-cmdb-services.php @@ -1,4 +1,5 @@ 'Bridge for CMDB and Services', @@ -14,40 +15,37 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( + 'dependencies' => [ 'itop-config-mgmt/2.7.1', 'itop-service-mgmt/2.7.1 || itop-service-mgmt-provider/2.7.1', - ), + ], 'mandatory' => false, 'visible' => false, 'auto_select' => 'SetupInfo::ModuleIsSelected("itop-config-mgmt") && (SetupInfo::ModuleIsSelected("itop-service-mgmt") || SetupInfo::ModuleIsSelected("itop-service-mgmt-provider")) ', // Components // - 'datamodel' => array( - ), - 'webservice' => array( - - ), - 'data.struct' => array( + 'datamodel' => [ + ], + 'webservice' => [ + + ], + 'data.struct' => [ // add your 'structure' definition XML files here, - ), - 'data.sample' => array( + ], + 'data.sample' => [ // add your sample data XML files here, - ), - + ], + // Documentation // 'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any - 'doc.more_information' => '', // hyperlink to more information, if any + 'doc.more_information' => '', // hyperlink to more information, if any // Default settings // - 'settings' => array( + 'settings' => [ // Module specific settings go here, if any - ), - ) + ], + ] ); - - -?> diff --git a/datamodels/2.x/itop-bridge-cmdb-ticket/dictionaries/pt_br.dict.itop-bridge-cmdb-ticket.php b/datamodels/2.x/itop-bridge-cmdb-ticket/dictionaries/pt_br.dict.itop-bridge-cmdb-ticket.php index bd78f198d..1ee91b821 100644 --- a/datamodels/2.x/itop-bridge-cmdb-ticket/dictionaries/pt_br.dict.itop-bridge-cmdb-ticket.php +++ b/datamodels/2.x/itop-bridge-cmdb-ticket/dictionaries/pt_br.dict.itop-bridge-cmdb-ticket.php @@ -1,16 +1,17 @@ * */ -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkFunctionalCIToTicket' => 'Relação entre IC / Solicitação', 'Class:lnkFunctionalCIToTicket+' => '', 'Class:lnkFunctionalCIToTicket/Name' => '%1$s / %2$s~~', @@ -30,12 +31,12 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkFunctionalCIToTicket/Attribute:impact_code/Value:manual' => 'Adicionado manualmente', 'Class:lnkFunctionalCIToTicket/Attribute:impact_code/Value:computed' => 'Computado', 'Class:lnkFunctionalCIToTicket/Attribute:impact_code/Value:not_impacted' => 'Não impactado', -)); +]); // // Class: FunctionalCI // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:FunctionalCI/Attribute:tickets_list' => 'Solicitações', 'Class:FunctionalCI/Attribute:tickets_list+' => 'Todas as Solicitações associadas à este Item de Configuração (IC)', -)); +]); diff --git a/datamodels/2.x/itop-bridge-cmdb-ticket/module.itop-bridge-cmdb-ticket.php b/datamodels/2.x/itop-bridge-cmdb-ticket/module.itop-bridge-cmdb-ticket.php index 53ec4ed5c..399d46632 100644 --- a/datamodels/2.x/itop-bridge-cmdb-ticket/module.itop-bridge-cmdb-ticket.php +++ b/datamodels/2.x/itop-bridge-cmdb-ticket/module.itop-bridge-cmdb-ticket.php @@ -1,4 +1,5 @@ 'Bridge for CMDB and Ticket', @@ -14,40 +15,37 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( + 'dependencies' => [ 'itop-config-mgmt/2.7.1', 'itop-tickets/2.7.0', - ), + ], 'mandatory' => false, 'visible' => false, 'auto_select' => 'SetupInfo::ModuleIsSelected("itop-config-mgmt") && SetupInfo::ModuleIsSelected("itop-tickets") ', // Components // - 'datamodel' => array( - ), - 'webservice' => array( - - ), - 'data.struct' => array( + 'datamodel' => [ + ], + 'webservice' => [ + + ], + 'data.struct' => [ // add your 'structure' definition XML files here, - ), - 'data.sample' => array( + ], + 'data.sample' => [ // add your sample data XML files here, - ), - + ], + // Documentation // 'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any - 'doc.more_information' => '', // hyperlink to more information, if any + 'doc.more_information' => '', // hyperlink to more information, if any // Default settings // - 'settings' => array( + 'settings' => [ // Module specific settings go here, if any - ), - ) + ], + ] ); - - -?> diff --git a/datamodels/2.x/itop-bridge-datacenter-mgmt-services/module.itop-bridge-datacenter-mgmt-services.php b/datamodels/2.x/itop-bridge-datacenter-mgmt-services/module.itop-bridge-datacenter-mgmt-services.php index 0666211da..84f239890 100644 --- a/datamodels/2.x/itop-bridge-datacenter-mgmt-services/module.itop-bridge-datacenter-mgmt-services.php +++ b/datamodels/2.x/itop-bridge-datacenter-mgmt-services/module.itop-bridge-datacenter-mgmt-services.php @@ -1,4 +1,5 @@ 'Bridge for CMDB Virtualization objects and Services', @@ -14,28 +15,28 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( + 'dependencies' => [ 'itop-config-mgmt/2.7.1', 'itop-service-mgmt/2.7.1 || itop-service-mgmt-provider/2.7.1', 'itop-datacenter-mgmt/3.1.0', - ), + ], 'mandatory' => false, 'visible' => false, 'auto_select' => 'SetupInfo::ModuleIsSelected("itop-datacenter-mgmt") && (SetupInfo::ModuleIsSelected("itop-service-mgmt") || SetupInfo::ModuleIsSelected("itop-service-mgmt-provider")) ', // Components // - 'datamodel' => array( - ), - 'webservice' => array( + 'datamodel' => [ + ], + 'webservice' => [ - ), - 'data.struct' => array( + ], + 'data.struct' => [ // add your 'structure' definition XML files here, - ), - 'data.sample' => array( + ], + 'data.sample' => [ // add your sample data XML files here, - ), + ], // Documentation // @@ -44,11 +45,8 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array( + 'settings' => [ // Module specific settings go here, if any - ), - ) + ], + ] ); - - -?> diff --git a/datamodels/2.x/itop-bridge-endusers-devices-services/module.itop-bridge-endusers-devices-services.php b/datamodels/2.x/itop-bridge-endusers-devices-services/module.itop-bridge-endusers-devices-services.php index 81fecaaec..f02e4e978 100644 --- a/datamodels/2.x/itop-bridge-endusers-devices-services/module.itop-bridge-endusers-devices-services.php +++ b/datamodels/2.x/itop-bridge-endusers-devices-services/module.itop-bridge-endusers-devices-services.php @@ -1,4 +1,5 @@ 'Bridge for CMDB endusers objects and Services', @@ -14,29 +15,29 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( + 'dependencies' => [ 'itop-config-mgmt/2.7.1', 'itop-service-mgmt/2.7.1 || itop-service-mgmt-provider/2.7.1', 'itop-endusers-devices/3.1.0', - ), + ], 'mandatory' => false, 'visible' => false, 'auto_select' => 'SetupInfo::ModuleIsSelected("itop-endusers-devices") && (SetupInfo::ModuleIsSelected("itop-service-mgmt") || SetupInfo::ModuleIsSelected("itop-service-mgmt-provider")) ', // Components // - 'datamodel' => array( - ), - 'webservice' => array( + 'datamodel' => [ + ], + 'webservice' => [ - ), - 'data.struct' => array( + ], + 'data.struct' => [ // add your 'structure' definition XML files here, - ), - 'data.sample' => array( + ], + 'data.sample' => [ // add your sample data XML files here, - ), + ], // Documentation // @@ -45,11 +46,8 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array( + 'settings' => [ // Module specific settings go here, if any - ), - ) + ], + ] ); - - -?> diff --git a/datamodels/2.x/itop-bridge-storage-mgmt-services/module.itop-bridge-storage-mgmt-services.php b/datamodels/2.x/itop-bridge-storage-mgmt-services/module.itop-bridge-storage-mgmt-services.php index 6fec063d1..5d0f1b1f9 100644 --- a/datamodels/2.x/itop-bridge-storage-mgmt-services/module.itop-bridge-storage-mgmt-services.php +++ b/datamodels/2.x/itop-bridge-storage-mgmt-services/module.itop-bridge-storage-mgmt-services.php @@ -1,4 +1,5 @@ 'Bridge for CMDB Virtualization objects and Services', @@ -14,28 +15,28 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( + 'dependencies' => [ 'itop-config-mgmt/2.7.1', 'itop-service-mgmt/2.7.1 || itop-service-mgmt-provider/2.7.1', 'itop-storage-mgmt/3.1.0', - ), + ], 'mandatory' => false, 'visible' => false, 'auto_select' => 'SetupInfo::ModuleIsSelected("itop-storage-mgmt") && (SetupInfo::ModuleIsSelected("itop-service-mgmt") || SetupInfo::ModuleIsSelected("itop-service-mgmt-provider")) ', // Components // - 'datamodel' => array( - ), - 'webservice' => array( + 'datamodel' => [ + ], + 'webservice' => [ - ), - 'data.struct' => array( + ], + 'data.struct' => [ // add your 'structure' definition XML files here, - ), - 'data.sample' => array( + ], + 'data.sample' => [ // add your sample data XML files here, - ), + ], // Documentation // @@ -44,11 +45,8 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array( + 'settings' => [ // Module specific settings go here, if any - ), - ) + ], + ] ); - - -?> diff --git a/datamodels/2.x/itop-bridge-virtualization-mgmt-services/module.itop-bridge-virtualization-mgmt-services.php b/datamodels/2.x/itop-bridge-virtualization-mgmt-services/module.itop-bridge-virtualization-mgmt-services.php index cfe7a4f96..f1e92326f 100644 --- a/datamodels/2.x/itop-bridge-virtualization-mgmt-services/module.itop-bridge-virtualization-mgmt-services.php +++ b/datamodels/2.x/itop-bridge-virtualization-mgmt-services/module.itop-bridge-virtualization-mgmt-services.php @@ -1,4 +1,5 @@ 'Bridge for CMDB Virtualization objects and Services', @@ -14,28 +15,28 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( + 'dependencies' => [ 'itop-config-mgmt/2.7.1', 'itop-service-mgmt/2.7.1 || itop-service-mgmt-provider/2.7.1', 'itop-virtualization-mgmt/3.1.0', - ), + ], 'mandatory' => false, 'visible' => false, 'auto_select' => 'SetupInfo::ModuleIsSelected("itop-virtualization-mgmt") && (SetupInfo::ModuleIsSelected("itop-service-mgmt") || SetupInfo::ModuleIsSelected("itop-service-mgmt-provider")) ', // Components // - 'datamodel' => array( - ), - 'webservice' => array( + 'datamodel' => [ + ], + 'webservice' => [ - ), - 'data.struct' => array( + ], + 'data.struct' => [ // add your 'structure' definition XML files here, - ), - 'data.sample' => array( + ], + 'data.sample' => [ // add your sample data XML files here, - ), + ], // Documentation // @@ -44,11 +45,8 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array( + 'settings' => [ // Module specific settings go here, if any - ), - ) + ], + ] ); - - -?> diff --git a/datamodels/2.x/itop-bridge-virtualization-storage/module.itop-bridge-virtualization-storage.php b/datamodels/2.x/itop-bridge-virtualization-storage/module.itop-bridge-virtualization-storage.php index 90dbd55a2..6fcb67b75 100644 --- a/datamodels/2.x/itop-bridge-virtualization-storage/module.itop-bridge-virtualization-storage.php +++ b/datamodels/2.x/itop-bridge-virtualization-storage/module.itop-bridge-virtualization-storage.php @@ -1,10 +1,9 @@ 'Links between virtualization and storage', @@ -12,25 +11,25 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( + 'dependencies' => [ 'itop-storage-mgmt/2.2.0', 'itop-virtualization-mgmt/2.2.0', - ), + ], 'mandatory' => false, 'visible' => false, 'auto_select' => 'SetupInfo::ModuleIsSelected("itop-storage-mgmt") && SetupInfo::ModuleIsSelected("itop-virtualization-mgmt")', // Components // - 'datamodel' => array( - ), - 'data.struct' => array( + 'datamodel' => [ + ], + 'data.struct' => [ //'data.struct.itop-change-mgmt.xml', - ), - 'data.sample' => array( + ], + 'data.sample' => [ //'data.sample.itop-change-mgmt.xml', - ), - + ], + // Documentation // 'doc.manual_setup' => '', @@ -38,7 +37,7 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array( - ), - ) + 'settings' => [ + ], + ] ); diff --git a/datamodels/2.x/itop-change-mgmt-itil/module.itop-change-mgmt-itil.php b/datamodels/2.x/itop-change-mgmt-itil/module.itop-change-mgmt-itil.php index ae5e63e41..5158d5294 100755 --- a/datamodels/2.x/itop-change-mgmt-itil/module.itop-change-mgmt-itil.php +++ b/datamodels/2.x/itop-change-mgmt-itil/module.itop-change-mgmt-itil.php @@ -1,10 +1,9 @@ 'Change Management ITIL', @@ -12,24 +11,24 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( + 'dependencies' => [ 'itop-config-mgmt/2.2.0', 'itop-tickets/2.0.0', - ), + ], 'mandatory' => false, 'visible' => true, // Components // - 'datamodel' => array( - ), - 'data.struct' => array( + 'datamodel' => [ + ], + 'data.struct' => [ //'data.struct.itop-change-mgmt.xml', - ), - 'data.sample' => array( + ], + 'data.sample' => [ //'data.sample.itop-change-mgmt.xml', - ), - + ], + // Documentation // 'doc.manual_setup' => '', @@ -37,7 +36,7 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array( - ), - ) + 'settings' => [ + ], + ] ); diff --git a/datamodels/2.x/itop-change-mgmt/module.itop-change-mgmt.php b/datamodels/2.x/itop-change-mgmt/module.itop-change-mgmt.php index 5790d730d..7489e2ed6 100755 --- a/datamodels/2.x/itop-change-mgmt/module.itop-change-mgmt.php +++ b/datamodels/2.x/itop-change-mgmt/module.itop-change-mgmt.php @@ -1,10 +1,9 @@ 'Change Management', @@ -12,25 +11,25 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( + 'dependencies' => [ 'itop-config-mgmt/2.2.0', 'itop-tickets/2.0.0', - ), + ], 'mandatory' => false, 'visible' => true, 'installer' => 'ChangeManagementInstaller', // Components // - 'datamodel' => array( - ), - 'data.struct' => array( + 'datamodel' => [ + ], + 'data.struct' => [ //'data.struct.itop-change-mgmt.xml', - ), - 'data.sample' => array( + ], + 'data.sample' => [ //'data.sample.itop-change-mgmt.xml', - ), - + ], + // Documentation // 'doc.manual_setup' => '', @@ -38,9 +37,9 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array( - ), - ) + 'settings' => [ + ], + ] ); // Module installation handler @@ -63,7 +62,7 @@ class ChangeManagementInstaller extends ModuleInstallerAPI { // If you want to migrate data from one format to another, do it here } - + /** * Handler called after the creation/update of the database schema * @param $oConfiguration Config The new configuration of the application @@ -82,8 +81,7 @@ class ChangeManagementInstaller extends ModuleInstallerAPI $sField = 'start_date'; - if (CMDBSource::IsField($sSourceTable, $sField) && CMDBSource::IsField($sTargetTable, $sField) && CMDBSource::IsField($sSourceTable, $sSourceKeyField) && CMDBSource::IsField($sTargetTable, $sTargetKeyField)) - { + if (CMDBSource::IsField($sSourceTable, $sField) && CMDBSource::IsField($sTargetTable, $sField) && CMDBSource::IsField($sSourceTable, $sSourceKeyField) && CMDBSource::IsField($sTargetTable, $sTargetKeyField)) { SetupLog::Info("Issue #464 - Copying change/start_date into ticket/start_date"); $sRepair = "UPDATE `$sTargetTable`, `$sSourceTable` SET `$sTargetTable`.`$sField` = `$sSourceTable`.`$sField` WHERE `$sTargetTable`.`$sField` IS NULL AND`$sTargetTable`.`$sTargetKeyField` = `$sSourceTable`.`$sSourceKeyField`"; CMDBSource::Query($sRepair); diff --git a/datamodels/2.x/itop-config-mgmt/dictionaries/it.dict.itop-config-mgmt.php b/datamodels/2.x/itop-config-mgmt/dictionaries/it.dict.itop-config-mgmt.php index 02eaa125d..b691acb80 100644 --- a/datamodels/2.x/itop-config-mgmt/dictionaries/it.dict.itop-config-mgmt.php +++ b/datamodels/2.x/itop-config-mgmt/dictionaries/it.dict.itop-config-mgmt.php @@ -1,15 +1,16 @@ 'Elementi impattati da...', 'Relation:impacts/DownStream' => 'Impatto...', 'Relation:impacts/DownStream+' => 'Elementi impattati da...', @@ -21,8 +22,7 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Relation:impacts/LoadData' => 'Carica dati', 'Relation:impacts/NoFilteredData' => 'seleziona oggetti e carica dati', 'Relation:impacts/FilteredData' => 'Dati filtrati', -)); - +]); // Dictionnay conventions // Class: @@ -65,7 +65,7 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( // Class: lnkContactToFunctionalCI // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:lnkContactToFunctionalCI' => 'Link Contact / FunctionalCI', 'Class:lnkContactToFunctionalCI+' => '~~', 'Class:lnkContactToFunctionalCI/Name' => '%1$s / %2$s', @@ -77,13 +77,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:lnkContactToFunctionalCI/Attribute:contact_id+' => '~~', 'Class:lnkContactToFunctionalCI/Attribute:contact_name' => 'Nome Contatto', 'Class:lnkContactToFunctionalCI/Attribute:contact_name+' => '~~', -)); +]); // // Class: FunctionalCI // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:FunctionalCI' => 'CI Funzionale', 'Class:FunctionalCI+' => '', 'Class:FunctionalCI/Attribute:name' => 'Nome', @@ -116,13 +116,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:FunctionalCI/Attribute:finalclass+' => '', 'Class:FunctionalCI/Tab:OpenedTickets' => 'Ticket attivi', 'Class:FunctionalCI/Tab:OpenedTickets+' => 'Ticket attivi che stanno influenzando questa CI funzionale', -)); +]); // // Class: PhysicalDevice // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:PhysicalDevice' => 'Dispositivo Fisico', 'Class:PhysicalDevice+' => '~~', 'Class:PhysicalDevice/ComplementaryName' => '%1$s - %2$s', @@ -156,13 +156,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:PhysicalDevice/Attribute:purchase_date+' => '~~', 'Class:PhysicalDevice/Attribute:end_of_warranty' => 'Scadenza garanzia', 'Class:PhysicalDevice/Attribute:end_of_warranty+' => '~~', -)); +]); // // Class: Rack // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:Rack' => 'Rack', 'Class:Rack+' => '~~', 'Class:Rack/ComplementaryName' => '%1$s - %2$s', @@ -172,64 +172,64 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:Rack/Attribute:device_list+' => 'Tutti i dispositivi fisici installati in questo rack', 'Class:Rack/Attribute:enclosure_list' => 'Contenitori', 'Class:Rack/Attribute:enclosure_list+' => 'Tutti i contenitori in questo rack', -)); +]); // // Class: TelephonyCI // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:TelephonyCI' => 'CI Telefoni', 'Class:TelephonyCI+' => '~~', 'Class:TelephonyCI/Attribute:phonenumber' => 'Numero di telefono', 'Class:TelephonyCI/Attribute:phonenumber+' => '~~', -)); +]); // // Class: Phone // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:Phone' => 'Telefono fisso', 'Class:Phone+' => '~~', -)); +]); // // Class: MobilePhone // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:MobilePhone' => 'Cellulari', 'Class:MobilePhone+' => '', 'Class:MobilePhone/Attribute:imei' => 'IMEI', 'Class:MobilePhone/Attribute:imei+' => '', 'Class:MobilePhone/Attribute:hw_pin' => 'Hardware PIN', 'Class:MobilePhone/Attribute:hw_pin+' => '', -)); +]); // // Class: IPPhone // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:IPPhone' => 'Telefoni IP / VoIP', 'Class:IPPhone+' => '~~', -)); +]); // // Class: Tablet // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:Tablet' => 'Tablet', 'Class:Tablet+' => '~~', -)); +]); // // Class: ConnectableCI // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:ConnectableCI' => 'CI collegabile', 'Class:ConnectableCI+' => 'CI fisico', 'Class:ConnectableCI/ComplementaryName' => '%1$s - %2$s', @@ -237,13 +237,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:ConnectableCI/Attribute:networkdevice_list+' => 'Tutti i dispositivi di rete collegati a questo dispositivo', 'Class:ConnectableCI/Attribute:physicalinterface_list' => 'Interfacce di rete', 'Class:ConnectableCI/Attribute:physicalinterface_list+' => 'Tutte le interfacce di rete fisiche', -)); +]); // // Class: DatacenterDevice // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:DatacenterDevice' => 'Datacenter Device', 'Class:DatacenterDevice+' => '~~', 'Class:DatacenterDevice/ComplementaryName' => '%1$s - %2$s', @@ -275,13 +275,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:DatacenterDevice/Attribute:redundancy/count' => 'Il dispositivo è operativo se almeno una connessione elettrica (A o B) è attiva', 'Class:DatacenterDevice/Attribute:redundancy/disabled' => 'Il dispositivo è operativo se tutte le sue connessioni elettriche sono attive', 'Class:DatacenterDevice/Attribute:redundancy/percent' => 'Il dispositivo è operativo se almeno il %1$s %% delle sue connessioni elettriche sono attive', -)); +]); // // Class: NetworkDevice // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:NetworkDevice' => 'Dispositivi di rete', 'Class:NetworkDevice+' => '', 'Class:NetworkDevice/ComplementaryName' => '%1$s - %2$s', @@ -297,13 +297,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:NetworkDevice/Attribute:iosversion_name+' => '~~', 'Class:NetworkDevice/Attribute:ram' => 'RAM', 'Class:NetworkDevice/Attribute:ram+' => '', -)); +]); // // Class: Server // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:Server' => 'Server', 'Class:Server+' => '', 'Class:Server/ComplementaryName' => '%1$s - %2$s', @@ -325,61 +325,61 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:Server/Attribute:ram+' => '', 'Class:Server/Attribute:logicalvolumes_list' => 'Volumi Logici', 'Class:Server/Attribute:logicalvolumes_list+' => 'Tutti i volumi logici collegati a questo server', -)); +]); // // Class: StorageSystem // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:StorageSystem' => 'Sistema di Archiviazione', 'Class:StorageSystem+' => '~~', 'Class:StorageSystem/ComplementaryName' => '%1$s - %2$s', 'Class:StorageSystem/Attribute:logicalvolume_list' => 'Volumi Logici', 'Class:StorageSystem/Attribute:logicalvolume_list+' => 'Tutti i volumi logici in questo sistema di archiviazione', -)); +]); // // Class: SANSwitch // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:SANSwitch' => 'SAN Switch', 'Class:SANSwitch+' => '~~', 'Class:SANSwitch/ComplementaryName' => '%1$s - %2$s', 'Class:SANSwitch/Attribute:datacenterdevice_list' => 'Dispositivi', 'Class:SANSwitch/Attribute:datacenterdevice_list+' => 'Tutti i dispositivi collegati a questo switch SAN', -)); +]); // // Class: TapeLibrary // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:TapeLibrary' => 'Libreria di nastri', 'Class:TapeLibrary+' => '~~', 'Class:TapeLibrary/ComplementaryName' => '%1$s - %2$s', 'Class:TapeLibrary/Attribute:tapes_list' => 'Nastri', 'Class:TapeLibrary/Attribute:tapes_list+' => 'Tutti i nastri nella libreria di nastri', -)); +]); // // Class: NAS // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:NAS' => 'NAS', 'Class:NAS+' => '~~', 'Class:NAS/ComplementaryName' => '%1$s - %2$s', 'Class:NAS/Attribute:nasfilesystem_list' => 'File system', 'Class:NAS/Attribute:nasfilesystem_list+' => 'Tutti i file system in questo NAS', -)); +]); // // Class: PC // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:PC' => 'PC', 'Class:PC+' => '', 'Class:PC/ComplementaryName' => '%1$s - %2$s', @@ -401,45 +401,45 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:PC/Attribute:type/Value:desktop+' => 'desktop~~', 'Class:PC/Attribute:type/Value:laptop' => 'laptop~~', 'Class:PC/Attribute:type/Value:laptop+' => 'laptop~~', -)); +]); // // Class: Printer // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:Printer' => 'Stampante', 'Class:Printer+' => '', 'Class:Printer/ComplementaryName' => '%1$s - %2$s', -)); +]); // // Class: PowerConnection // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:PowerConnection' => 'Connessione di Alimentazione', 'Class:PowerConnection+' => '~~', 'Class:PowerConnection/ComplementaryName' => '%1$s - %2$s', -)); +]); // // Class: PowerSource // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:PowerSource' => 'Sorgente di Alimentazione', 'Class:PowerSource+' => '~~', 'Class:PowerSource/ComplementaryName' => '%1$s - %2$s', 'Class:PowerSource/Attribute:pdus_list' => 'PDU', 'Class:PowerSource/Attribute:pdus_list+' => 'Tutte le PDU che utilizzano questa sorgente di alimentazione', -)); +]); // // Class: PDU // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:PDU' => 'PDU', 'Class:PDU+' => '~~', 'Class:PDU/ComplementaryName' => '%1$s - %2$s - %3$s - %4$s', @@ -451,23 +451,23 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:PDU/Attribute:powerstart_id+' => '~~', 'Class:PDU/Attribute:powerstart_name' => 'Nome Avvio Alimentazione', 'Class:PDU/Attribute:powerstart_name+' => '~~', -)); +]); // // Class: Peripheral // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:Peripheral' => 'Periferica', 'Class:Peripheral+' => '~~', 'Class:Peripheral/ComplementaryName' => '%1$s - %2$s', -)); +]); // // Class: Enclosure // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:Enclosure' => 'Contenitore', 'Class:Enclosure+' => '~~', 'Class:Enclosure/ComplementaryName' => '%1$s - %2$s - %3$s', @@ -479,13 +479,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:Enclosure/Attribute:nb_u+' => '~~', 'Class:Enclosure/Attribute:device_list' => 'Dispositivi', 'Class:Enclosure/Attribute:device_list+' => 'Tutti i dispositivi in questo contenitore', -)); +]); // // Class: ApplicationSolution // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:ApplicationSolution' => 'Soluzione Applicativa', 'Class:ApplicationSolution+' => '', 'Class:ApplicationSolution/Attribute:functionalcis_list' => 'CIs', @@ -502,13 +502,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:ApplicationSolution/Attribute:redundancy/disabled' => 'La soluzione è attiva se tutti gli elementi di configurazione sono attivi', 'Class:ApplicationSolution/Attribute:redundancy/count' => 'La soluzione è attiva se almeno %1$s elemento(i) di configurazione sono attivi', 'Class:ApplicationSolution/Attribute:redundancy/percent' => 'La soluzione è attiva se almeno il %1$s %% degli elementi di configurazione sono attivi', -)); +]); // // Class: BusinessProcess // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:BusinessProcess' => 'Processi aziendali', 'Class:BusinessProcess+' => '', 'Class:BusinessProcess/Attribute:applicationsolutions_list' => 'Soluzioni applicative', @@ -519,13 +519,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:BusinessProcess/Attribute:status/Value:active+' => 'attivo', 'Class:BusinessProcess/Attribute:status/Value:inactive' => 'inattivo', 'Class:BusinessProcess/Attribute:status/Value:inactive+' => 'inattivo', -)); +]); // // Class: SoftwareInstance // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:SoftwareInstance' => 'Istanza Software', 'Class:SoftwareInstance+' => '', 'Class:SoftwareInstance/Attribute:system_id' => 'Sistema', @@ -548,64 +548,64 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:SoftwareInstance/Attribute:status/Value:active+' => 'attivo', 'Class:SoftwareInstance/Attribute:status/Value:inactive' => 'inattivo', 'Class:SoftwareInstance/Attribute:status/Value:inactive+' => 'inattivo', -)); +]); // // Class: Middleware // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:Middleware' => 'Middleware', 'Class:Middleware+' => '~~', 'Class:Middleware/Attribute:middlewareinstance_list' => 'Istanze Middleware', 'Class:Middleware/Attribute:middlewareinstance_list+' => 'Tutte le istanze del middleware fornite da questo middleware', -)); +]); // // Class: DBServer // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:DBServer' => 'Database', 'Class:DBServer+' => 'Database server SW', 'Class:DBServer/Attribute:dbschema_list' => 'Schema Database', 'Class:DBServer/Attribute:dbschema_list+' => 'Tutti gli schemi del database per questo server di database', -)); +]); // // Class: WebServer // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:WebServer' => 'Web server', 'Class:WebServer+' => '~~', 'Class:WebServer/Attribute:webapp_list' => 'Applicazioni web', 'Class:WebServer/Attribute:webapp_list+' => 'Tutte le applicazioni web disponibili su questo server web', -)); +]); // // Class: PCSoftware // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:PCSoftware' => 'Software PC', 'Class:PCSoftware+' => '~~', -)); +]); // // Class: OtherSoftware // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:OtherSoftware' => 'Altro Software', 'Class:OtherSoftware+' => '~~', -)); +]); // // Class: MiddlewareInstance // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:MiddlewareInstance' => 'Istanza Middleware', 'Class:MiddlewareInstance+' => '~~', 'Class:MiddlewareInstance/ComplementaryName' => '%1$s - %2$s', @@ -613,13 +613,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:MiddlewareInstance/Attribute:middleware_id+' => '~~', 'Class:MiddlewareInstance/Attribute:middleware_name' => 'Nome Middleware', 'Class:MiddlewareInstance/Attribute:middleware_name+' => '~~', -)); +]); // // Class: DatabaseSchema // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:DatabaseSchema' => 'Schema del Database', 'Class:DatabaseSchema+' => '~~', 'Class:DatabaseSchema/ComplementaryName' => '%1$s - %2$s', @@ -627,13 +627,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:DatabaseSchema/Attribute:dbserver_id+' => '~~', 'Class:DatabaseSchema/Attribute:dbserver_name' => 'Nome Server del Database', 'Class:DatabaseSchema/Attribute:dbserver_name+' => '~~', -)); +]); // // Class: WebApplication // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:WebApplication' => 'Web Application', 'Class:WebApplication+' => '~~', 'Class:WebApplication/ComplementaryName' => '%1$s - %2$s', @@ -643,14 +643,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:WebApplication/Attribute:webserver_name+' => '~~', 'Class:WebApplication/Attribute:url' => 'URL', 'Class:WebApplication/Attribute:url+' => '~~', -)); - +]); // // Class: VirtualDevice // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:VirtualDevice' => 'Dispositivo virtuale', 'Class:VirtualDevice+' => '~~', 'Class:VirtualDevice/Attribute:status' => 'Stato', @@ -665,24 +664,24 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:VirtualDevice/Attribute:status/Value:stock+' => 'In Stock', 'Class:VirtualDevice/Attribute:logicalvolumes_list' => 'Volumi Logici', 'Class:VirtualDevice/Attribute:logicalvolumes_list+' => 'Tutti i volumi logici utilizzati da questo dispositivo', -)); +]); // // Class: VirtualHost // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:VirtualHost' => 'Host Virtuale', 'Class:VirtualHost+' => '~~', 'Class:VirtualHost/Attribute:virtualmachine_list' => 'Macchine virtuali', 'Class:VirtualHost/Attribute:virtualmachine_list+' => 'Tutte le macchine virtuali ospitate da questo host', -)); +]); // // Class: Hypervisor // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:Hypervisor' => 'Hypervisor', 'Class:Hypervisor+' => '~~', 'Class:Hypervisor/Attribute:farm_id' => 'Farm', @@ -693,13 +692,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:Hypervisor/Attribute:server_id+' => '~~', 'Class:Hypervisor/Attribute:server_name' => 'Nome Server', 'Class:Hypervisor/Attribute:server_name+' => '~~', -)); +]); // // Class: Farm // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:Farm' => 'Farm', 'Class:Farm+' => '~~', 'Class:Farm/Attribute:hypervisor_list' => 'Hypervisor', @@ -708,13 +707,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:Farm/Attribute:redundancy/disabled' => 'La farm è attiva se tutti gli hypervisor sono attivi', 'Class:Farm/Attribute:redundancy/count' => 'La farm è attiva se almeno %1$s hypervisor è(sono) attivo(i)', 'Class:Farm/Attribute:redundancy/percent' => 'La farm è attiva se almeno %1$s %% degli hypervisor è attivo', -)); +]); // // Class: VirtualMachine // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:VirtualMachine' => 'Macchina virtuale', 'Class:VirtualMachine+' => '~~', 'Class:VirtualMachine/ComplementaryName' => '%1$s - %2$s', @@ -742,13 +741,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:VirtualMachine/Attribute:managementip+' => '~~', 'Class:VirtualMachine/Attribute:logicalinterface_list' => 'Interfacce di rete logiche', 'Class:VirtualMachine/Attribute:logicalinterface_list+' => 'Tutte le interfacce di rete logiche', -)); +]); // // Class: LogicalVolume // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:LogicalVolume' => 'Volume Logico', 'Class:LogicalVolume+' => '~~', 'Class:LogicalVolume/Attribute:name' => 'Nome', @@ -769,13 +768,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:LogicalVolume/Attribute:servers_list+' => 'Tutti i server che utilizzano questo volume', 'Class:LogicalVolume/Attribute:virtualdevices_list' => 'Dispositivi Virtuali', 'Class:LogicalVolume/Attribute:virtualdevices_list+' => 'Tutti i dispositivi virtuali che utilizzano questo volume', -)); +]); // // Class: lnkServerToVolume // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:lnkServerToVolume' => 'Collegamento Server / Volume', 'Class:lnkServerToVolume+' => '~~', 'Class:lnkServerToVolume/Name' => '%1$s / %2$s', @@ -789,13 +788,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:lnkServerToVolume/Attribute:server_name+' => '~~', 'Class:lnkServerToVolume/Attribute:size_used' => 'Dimensione utilizzata', 'Class:lnkServerToVolume/Attribute:size_used+' => '~~', -)); +]); // // Class: lnkVirtualDeviceToVolume // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:lnkVirtualDeviceToVolume' => 'Collegamento dispositivo virtuale / volume', 'Class:lnkVirtualDeviceToVolume+' => '~~', 'Class:lnkVirtualDeviceToVolume/Name' => '%1$s / %2$s', @@ -809,13 +808,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:lnkVirtualDeviceToVolume/Attribute:virtualdevice_name+' => '~~', 'Class:lnkVirtualDeviceToVolume/Attribute:size_used' => 'Dimensione utilizzata', 'Class:lnkVirtualDeviceToVolume/Attribute:size_used+' => '~~', -)); +]); // // Class: lnkSanToDatacenterDevice // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:lnkSanToDatacenterDevice' => 'Collegamento SAN / Dispositivo Datacenter', 'Class:lnkSanToDatacenterDevice+' => '~~', 'Class:lnkSanToDatacenterDevice/Name' => '%1$s / %2$s', @@ -831,13 +830,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:lnkSanToDatacenterDevice/Attribute:san_port+' => '~~', 'Class:lnkSanToDatacenterDevice/Attribute:datacenterdevice_port' => 'Porta dispositivo FC', 'Class:lnkSanToDatacenterDevice/Attribute:datacenterdevice_port+' => '~~', -)); +]); // // Class: Tape // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:Tape' => 'Nastro', 'Class:Tape+' => '~~', 'Class:Tape/Attribute:name' => 'Nome', @@ -850,13 +849,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:Tape/Attribute:tapelibrary_id+' => '~~', 'Class:Tape/Attribute:tapelibrary_name' => 'Nome della libreria di nastri', 'Class:Tape/Attribute:tapelibrary_name+' => '~~', -)); +]); // // Class: NASFileSystem // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:NASFileSystem' => 'File System NAS', 'Class:NASFileSystem+' => '~~', 'Class:NASFileSystem/Attribute:name' => 'Nome', @@ -871,13 +870,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:NASFileSystem/Attribute:nas_id+' => '~~', 'Class:NASFileSystem/Attribute:nas_name' => 'Nome del NAS', 'Class:NASFileSystem/Attribute:nas_name+' => '~~', -)); +]); // // Class: Software // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:Software' => 'Software', 'Class:Software+' => '', 'Class:Software/ComplementaryName' => '%1$s - %2$s', @@ -907,13 +906,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:Software/Attribute:softwarepatch_list+' => 'Tutte le patch per questo software', 'Class:Software/Attribute:softwarelicence_list' => 'Licenze Software', 'Class:Software/Attribute:softwarelicence_list+' => 'Tutte le licenze per questo software', -)); +]); // // Class: Patch // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:Patch' => 'Patch', 'Class:Patch+' => '', 'Class:Patch/Attribute:name' => 'Nome', @@ -924,13 +923,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:Patch/Attribute:description+' => '', 'Class:Patch/Attribute:finalclass' => 'Tipo', 'Class:Patch/Attribute:finalclass+' => 'Nome della classe finale', -)); +]); // // Class: OSPatch // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:OSPatch' => 'Patch del Sistema Operativo', 'Class:OSPatch+' => '~~', 'Class:OSPatch/Attribute:functionalcis_list' => 'Dispositivi', @@ -939,13 +938,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:OSPatch/Attribute:osversion_id+' => '~~', 'Class:OSPatch/Attribute:osversion_name' => 'Nome della Versione del Sistema Operativo', 'Class:OSPatch/Attribute:osversion_name+' => '~~', -)); +]); // // Class: SoftwarePatch // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:SoftwarePatch' => 'Patch del Software', 'Class:SoftwarePatch+' => '~~', 'Class:SoftwarePatch/Attribute:software_id' => 'Software', @@ -954,13 +953,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:SoftwarePatch/Attribute:software_name+' => '~~', 'Class:SoftwarePatch/Attribute:softwareinstances_list' => 'Istanze del Software', 'Class:SoftwarePatch/Attribute:softwareinstances_list+' => 'Tutti i sistemi in cui questa patch del software è installata', -)); +]); // // Class: Licence // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:Licence' => 'Licenza', 'Class:Licence+' => '', 'Class:Licence/Attribute:name' => 'Nome', @@ -989,13 +988,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:Licence/Attribute:perpetual/Value:yes+' => 'sì', 'Class:Licence/Attribute:finalclass' => 'Tipo', 'Class:Licence/Attribute:finalclass+' => 'Nome della classe finale', -)); +]); // // Class: OSLicence // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:OSLicence' => 'Licenza OS', 'Class:OSLicence+' => '~~', 'Class:OSLicence/ComplementaryName' => '%1$s - %2$s', @@ -1007,13 +1006,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:OSLicence/Attribute:virtualmachines_list+' => 'Tutte le macchine virtuali in cui questa licenza è utilizzata', 'Class:OSLicence/Attribute:servers_list' => 'Server', 'Class:OSLicence/Attribute:servers_list+' => 'Tutti i server in cui questa licenza è utilizzata', -)); +]); // // Class: SoftwareLicence // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:SoftwareLicence' => 'Licenza software', 'Class:SoftwareLicence+' => '~~', 'Class:SoftwareLicence/ComplementaryName' => '%1$s - %2$s', @@ -1023,13 +1022,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:SoftwareLicence/Attribute:software_name+' => '~~', 'Class:SoftwareLicence/Attribute:softwareinstance_list' => 'Istanze software', 'Class:SoftwareLicence/Attribute:softwareinstance_list+' => 'Tutti i sistemi in cui questa licenza è utilizzata', -)); +]); // // Class: lnkDocumentToLicence // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:lnkDocumentToLicence' => 'Link Documento/Licenza', 'Class:lnkDocumentToLicence+' => '~~', 'Class:lnkDocumentToLicence/Name' => '%1$s / %2$s', @@ -1041,48 +1040,48 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:lnkDocumentToLicence/Attribute:document_id+' => '~~', 'Class:lnkDocumentToLicence/Attribute:document_name' => 'Nome documento', 'Class:lnkDocumentToLicence/Attribute:document_name+' => '~~', -)); +]); // // Class: OSVersion // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:OSVersion' => 'Versione del Sistema Operativo', 'Class:OSVersion+' => '~~', 'Class:OSVersion/Attribute:osfamily_id' => 'Famiglia del Sistema Operativo', 'Class:OSVersion/Attribute:osfamily_id+' => '~~', 'Class:OSVersion/Attribute:osfamily_name' => 'Nome della Famiglia del Sistema Operativo', 'Class:OSVersion/Attribute:osfamily_name+' => '~~', -)); +]); // // Class: OSFamily // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:OSFamily' => 'Famiglia del Sistema Operativo', 'Class:OSFamily+' => '~~', -)); +]); // // Class: Brand // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:Brand' => 'Marca', 'Class:Brand+' => '~~', 'Class:Brand/Attribute:physicaldevices_list' => 'Dispositivi fisici', 'Class:Brand/Attribute:physicaldevices_list+' => 'Tutti i dispositivi fisici corrispondenti a questa marca', 'Class:Brand/UniquenessRule:name+' => 'Il nome deve essere univoco', 'Class:Brand/UniquenessRule:name' => 'Questa marca esiste già', -)); +]); // // Class: Model // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:Model' => 'Modello', 'Class:Model+' => '~~', 'Class:Model/Attribute/type/Value:NAS+' => 'NAS', @@ -1157,37 +1156,37 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:Model/Attribute:physicaldevices_list+' => 'Tutti i dispositivi fisici corrispondenti a questo modello', 'Class:Model/UniquenessRule:name_brand+' => 'Il nome deve essere univoco nella marca', 'Class:Model/UniquenessRule:name_brand' => 'Questo modello esiste già per questa marca', -)); +]); // // Class: NetworkDeviceType // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:NetworkDeviceType' => 'Tipo di Dispositivo di Rete', 'Class:NetworkDeviceType+' => '~~', 'Class:NetworkDeviceType/Attribute:networkdevicesdevices_list' => 'Dispositivi di Rete', 'Class:NetworkDeviceType/Attribute:networkdevicesdevices_list+' => 'Tutti i dispositivi di rete corrispondenti a questo tipo', -)); +]); // // Class: IOSVersion // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:IOSVersion' => 'Versione IOS', 'Class:IOSVersion+' => '~~', 'Class:IOSVersion/Attribute:brand_id' => 'Marca', 'Class:IOSVersion/Attribute:brand_id+' => '~~', 'Class:IOSVersion/Attribute:brand_name' => 'Nome della marca', 'Class:IOSVersion/Attribute:brand_name+' => '~~', -)); +]); // // Class: lnkDocumentToPatch // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:lnkDocumentToPatch' => 'Collegamento documento / patch', 'Class:lnkDocumentToPatch+' => '~~', 'Class:lnkDocumentToPatch/Name' => '%1$s / %2$s', @@ -1199,13 +1198,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:lnkDocumentToPatch/Attribute:document_id+' => '~~', 'Class:lnkDocumentToPatch/Attribute:document_name' => 'Nome del documento', 'Class:lnkDocumentToPatch/Attribute:document_name+' => '~~', -)); +]); // // Class: lnkSoftwareInstanceToSoftwarePatch // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:lnkSoftwareInstanceToSoftwarePatch' => 'Collegamento istanza software / patch software', 'Class:lnkSoftwareInstanceToSoftwarePatch+' => '~~', 'Class:lnkSoftwareInstanceToSoftwarePatch/Name' => '%1$s / %2$s', @@ -1217,13 +1216,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:lnkSoftwareInstanceToSoftwarePatch/Attribute:softwareinstance_id+' => '~~', 'Class:lnkSoftwareInstanceToSoftwarePatch/Attribute:softwareinstance_name' => 'Nome dell\'istanza software', 'Class:lnkSoftwareInstanceToSoftwarePatch/Attribute:softwareinstance_name+' => '~~', -)); +]); // // Class: lnkFunctionalCIToOSPatch // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:lnkFunctionalCIToOSPatch' => 'Collegamento CI funzionale / patch OS', 'Class:lnkFunctionalCIToOSPatch+' => '~~', 'Class:lnkFunctionalCIToOSPatch/Name' => '%1$s / %2$s', @@ -1235,13 +1234,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:lnkFunctionalCIToOSPatch/Attribute:functionalci_id+' => '~~', 'Class:lnkFunctionalCIToOSPatch/Attribute:functionalci_name' => 'Nome del CI funzionale', 'Class:lnkFunctionalCIToOSPatch/Attribute:functionalci_name+' => '~~', -)); +]); // // Class: lnkDocumentToSoftware // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:lnkDocumentToSoftware' => 'Collegamento documento / software', 'Class:lnkDocumentToSoftware+' => '~~', 'Class:lnkDocumentToSoftware/Name' => '%1$s / %2$s', @@ -1253,13 +1252,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:lnkDocumentToSoftware/Attribute:document_id+' => '~~', 'Class:lnkDocumentToSoftware/Attribute:document_name' => 'Nome del documento', 'Class:lnkDocumentToSoftware/Attribute:document_name+' => '~~', -)); +]); // // Class: Subnet // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:Subnet' => 'Subnet', 'Class:Subnet+' => '', 'Class:Subnet/Name' => '%1$s/%2$s', @@ -1278,13 +1277,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:Subnet/Attribute:ip_mask+' => '', 'Class:Subnet/Attribute:vlans_list' => 'VLANs', 'Class:Subnet/Attribute:vlans_list+' => '~~', -)); +]); // // Class: VLAN // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:VLAN' => 'VLAN', 'Class:VLAN+' => '~~', 'Class:VLAN/Attribute:vlan_tag' => 'VLAN Tag', @@ -1299,13 +1298,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:VLAN/Attribute:subnets_list+' => '~~', 'Class:VLAN/Attribute:physicalinterfaces_list' => 'Interfacce di rete fisiche', 'Class:VLAN/Attribute:physicalinterfaces_list+' => '~~', -)); +]); // // Class: lnkSubnetToVLAN // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:lnkSubnetToVLAN' => 'Link Subnet / VLAN', 'Class:lnkSubnetToVLAN+' => '~~', 'Class:lnkSubnetToVLAN/Name' => '%1$s / %2$s', @@ -1319,26 +1318,26 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:lnkSubnetToVLAN/Attribute:vlan_id+' => '~~', 'Class:lnkSubnetToVLAN/Attribute:vlan_tag' => 'VLAN tag', 'Class:lnkSubnetToVLAN/Attribute:vlan_tag+' => '~~', -)); +]); // // Class: NetworkInterface // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:NetworkInterface' => 'Interfaccia di Rete', 'Class:NetworkInterface+' => '', 'Class:NetworkInterface/Attribute:name' => 'Nome', 'Class:NetworkInterface/Attribute:name+' => '~~', 'Class:NetworkInterface/Attribute:finalclass' => 'Tipo', 'Class:NetworkInterface/Attribute:finalclass+' => 'Nome della classe finale', -)); +]); // // Class: IPInterface // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:IPInterface' => 'Interfaccia IP', 'Class:IPInterface+' => '~~', 'Class:IPInterface/Attribute:ipaddress' => 'Indirizzo IP', @@ -1353,13 +1352,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:IPInterface/Attribute:ipmask+' => '~~', 'Class:IPInterface/Attribute:speed' => 'Velocità', 'Class:IPInterface/Attribute:speed+' => '~~', -)); +]); // // Class: PhysicalInterface // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:PhysicalInterface' => 'Interfaccia fisica', 'Class:PhysicalInterface+' => '~~', 'Class:PhysicalInterface/Name' => '%2$s %1$s', @@ -1369,13 +1368,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:PhysicalInterface/Attribute:connectableci_name+' => '~~', 'Class:PhysicalInterface/Attribute:vlans_list' => 'VLAN', 'Class:PhysicalInterface/Attribute:vlans_list+' => '~~', -)); +]); // // Class: lnkPhysicalInterfaceToVLAN // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:lnkPhysicalInterfaceToVLAN' => 'Collegamento interfaccia fisica / VLAN', 'Class:lnkPhysicalInterfaceToVLAN+' => '~~', 'Class:lnkPhysicalInterfaceToVLAN/Name' => '%1$s %2$s / %3$s', @@ -1391,27 +1390,26 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:lnkPhysicalInterfaceToVLAN/Attribute:vlan_id+' => '~~', 'Class:lnkPhysicalInterfaceToVLAN/Attribute:vlan_tag' => 'Tag VLAN', 'Class:lnkPhysicalInterfaceToVLAN/Attribute:vlan_tag+' => '~~', -)); - +]); // // Class: LogicalInterface // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:LogicalInterface' => 'Interfaccia logica', 'Class:LogicalInterface+' => '~~', 'Class:LogicalInterface/Attribute:virtualmachine_id' => 'Macchina Virtuale', 'Class:LogicalInterface/Attribute:virtualmachine_id+' => '~~', 'Class:LogicalInterface/Attribute:virtualmachine_name' => 'Nome Macchina Virtuale', 'Class:LogicalInterface/Attribute:virtualmachine_name+' => '~~', -)); +]); // // Class: FiberChannelInterface // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:FiberChannelInterface' => 'Interfaccia Fibre Channel', 'Class:FiberChannelInterface+' => '~~', 'Class:FiberChannelInterface/Attribute:speed' => 'Velocità', @@ -1424,13 +1422,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:FiberChannelInterface/Attribute:datacenterdevice_id+' => '~~', 'Class:FiberChannelInterface/Attribute:datacenterdevice_name' => 'Nome Dispositivo', 'Class:FiberChannelInterface/Attribute:datacenterdevice_name+' => '~~', -)); +]); // // Class: lnkConnectableCIToNetworkDevice // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:lnkConnectableCIToNetworkDevice' => 'Collega CI collegabile / Dispositivo di rete', 'Class:lnkConnectableCIToNetworkDevice+' => '~~', 'Class:lnkConnectableCIToNetworkDevice/Name' => '%1$s / %2$s', @@ -1452,13 +1450,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:lnkConnectableCIToNetworkDevice/Attribute:connection_type/Value:downlink+' => 'Collegamento verso il basso', 'Class:lnkConnectableCIToNetworkDevice/Attribute:connection_type/Value:uplink' => 'Collegamento verso l\'alto', 'Class:lnkConnectableCIToNetworkDevice/Attribute:connection_type/Value:uplink+' => 'Collegamento verso l\'alto', -)); +]); // // Class: lnkApplicationSolutionToFunctionalCI // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:lnkApplicationSolutionToFunctionalCI' => 'Collega soluzione applicativa / CI funzionale', 'Class:lnkApplicationSolutionToFunctionalCI+' => '~~', 'Class:lnkApplicationSolutionToFunctionalCI/Name' => '%1$s / %2$s', @@ -1470,13 +1468,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:lnkApplicationSolutionToFunctionalCI/Attribute:functionalci_id+' => '~~', 'Class:lnkApplicationSolutionToFunctionalCI/Attribute:functionalci_name' => 'Nome CI funzionale', 'Class:lnkApplicationSolutionToFunctionalCI/Attribute:functionalci_name+' => '~~', -)); +]); // // Class: lnkApplicationSolutionToBusinessProcess // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:lnkApplicationSolutionToBusinessProcess' => 'Collega Soluzione Applicativa / Processo Aziendale', 'Class:lnkApplicationSolutionToBusinessProcess+' => '~~', 'Class:lnkApplicationSolutionToBusinessProcess/Name' => '%1$s / %2$s', @@ -1488,13 +1486,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:lnkApplicationSolutionToBusinessProcess/Attribute:applicationsolution_id+' => '~~', 'Class:lnkApplicationSolutionToBusinessProcess/Attribute:applicationsolution_name' => 'Nome Soluzione Applicativa', 'Class:lnkApplicationSolutionToBusinessProcess/Attribute:applicationsolution_name+' => '~~', -)); +]); // // Class: Group // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:Group' => 'Gruppo', 'Class:Group+' => '', 'Class:Group/ComplementaryName' => '%1$s - %2$s', @@ -1524,13 +1522,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:Group/Attribute:ci_list+' => 'Tutti gli elementi di configurazione collegati a questo gruppo', 'Class:Group/Attribute:parent_id_friendlyname' => 'Nome del gruppo padre', 'Class:Group/Attribute:parent_id_friendlyname+' => '~~', -)); +]); // // Class: lnkGroupToCI // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:lnkGroupToCI' => 'Gruppo / CI', 'Class:lnkGroupToCI+' => '', 'Class:lnkGroupToCI/Name' => '%1$s / %2$s', @@ -1544,11 +1542,11 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:lnkGroupToCI/Attribute:ci_name+' => '', 'Class:lnkGroupToCI/Attribute:reason' => 'Motivo', 'Class:lnkGroupToCI/Attribute:reason+' => '', -)); +]); // Add translation for Fieldsets -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Server:baseinfo' => 'Informazioni generali', 'Server:Date' => 'Date', 'Server:moreinfo' => 'Ulteriori informazioni', @@ -1561,14 +1559,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:Subnet/Tab:FreeIPs-count' => 'IP liberi: %1$s', 'Class:Subnet/Tab:FreeIPs-explain' => 'Ecco un estratto di 10 indirizzi IP liberi', 'Class:Document:PreviewTab' => 'Anteprima', -)); - +]); // // Class: lnkDocumentToFunctionalCI // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:lnkDocumentToFunctionalCI' => 'Collegamento Documento / FunctionalCI', 'Class:lnkDocumentToFunctionalCI+' => '~~', 'Class:lnkDocumentToFunctionalCI/Name' => '%1$s / %2$s', @@ -1580,13 +1577,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:lnkDocumentToFunctionalCI/Attribute:document_id+' => '~~', 'Class:lnkDocumentToFunctionalCI/Attribute:document_name' => 'Nome documento', 'Class:lnkDocumentToFunctionalCI/Attribute:document_name+' => '~~', -)); +]); // // Application Menu // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Menu:Application' => 'Applicazioni', 'Menu:Application+' => 'Tutte le applicazioni', 'Menu:DBServer' => 'Server di Database', @@ -1631,5 +1628,4 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Menu:OSVersion+' => '~~', 'Menu:Software' => 'Catalogo software', 'Menu:Software+' => 'Catalogo software', -)); - +]); diff --git a/datamodels/2.x/itop-config-mgmt/dictionaries/pt_br.dict.itop-config-mgmt.php b/datamodels/2.x/itop-config-mgmt/dictionaries/pt_br.dict.itop-config-mgmt.php index 4bd11a1c3..cbb232a58 100644 --- a/datamodels/2.x/itop-config-mgmt/dictionaries/pt_br.dict.itop-config-mgmt.php +++ b/datamodels/2.x/itop-config-mgmt/dictionaries/pt_br.dict.itop-config-mgmt.php @@ -1,15 +1,16 @@ 'Elementos impactados por', 'Relation:impacts/DownStream' => 'Impacto...', 'Relation:impacts/DownStream+' => 'Elementos impactados por', @@ -21,8 +22,7 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Relation:impacts/LoadData' => 'Carregando dados', 'Relation:impacts/NoFilteredData' => 'Por favor, selecione os objetos na tag de visualização Gráfica', 'Relation:impacts/FilteredData' => 'Filtered data~~', -)); - +]); // Dictionnay conventions // Class: @@ -65,7 +65,7 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( // Class: lnkContactToFunctionalCI // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkContactToFunctionalCI' => 'Relação entre Contato / IC', 'Class:lnkContactToFunctionalCI+' => '', 'Class:lnkContactToFunctionalCI/Name' => '%1$s / %2$s~~', @@ -77,13 +77,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkContactToFunctionalCI/Attribute:contact_id+' => '', 'Class:lnkContactToFunctionalCI/Attribute:contact_name' => 'Nome do contato', 'Class:lnkContactToFunctionalCI/Attribute:contact_name+' => '', -)); +]); // // Class: FunctionalCI // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:FunctionalCI' => 'Item de Configuração', 'Class:FunctionalCI+' => '', 'Class:FunctionalCI/Attribute:name' => 'Nome', @@ -116,13 +116,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:FunctionalCI/Attribute:finalclass+' => '', 'Class:FunctionalCI/Tab:OpenedTickets' => 'Solicitações ativas', 'Class:FunctionalCI/Tab:OpenedTickets+' => 'Active Tickets which are impacting this functional CI~~', -)); +]); // // Class: PhysicalDevice // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:PhysicalDevice' => 'Dispositivo físico', 'Class:PhysicalDevice+' => 'Lista de Dispositivos Físicos', 'Class:PhysicalDevice/ComplementaryName' => '%1$s - %2$s~~', @@ -156,13 +156,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:PhysicalDevice/Attribute:purchase_date+' => '', 'Class:PhysicalDevice/Attribute:end_of_warranty' => 'Fim da garantia', 'Class:PhysicalDevice/Attribute:end_of_warranty+' => '', -)); +]); // // Class: Rack // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Rack' => 'Rack', 'Class:Rack+' => '', 'Class:Rack/ComplementaryName' => '%1$s - %2$s~~', @@ -172,64 +172,64 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Rack/Attribute:device_list+' => 'Todos os Dispositivos físicos empilhados neste Rack', 'Class:Rack/Attribute:enclosure_list' => 'Gavetas', 'Class:Rack/Attribute:enclosure_list+' => 'Todas as Gavetas neste Rack', -)); +]); // // Class: TelephonyCI // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:TelephonyCI' => 'Telefonia', 'Class:TelephonyCI+' => '', 'Class:TelephonyCI/Attribute:phonenumber' => 'Número de telefone', 'Class:TelephonyCI/Attribute:phonenumber+' => '', -)); +]); // // Class: Phone // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Phone' => 'Telefone', 'Class:Phone+' => '', -)); +]); // // Class: MobilePhone // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:MobilePhone' => 'Telefone Celular', 'Class:MobilePhone+' => '', 'Class:MobilePhone/Attribute:imei' => 'IMEI', 'Class:MobilePhone/Attribute:imei+' => '', 'Class:MobilePhone/Attribute:hw_pin' => 'Hardware PIN', 'Class:MobilePhone/Attribute:hw_pin+' => '', -)); +]); // // Class: IPPhone // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:IPPhone' => 'Telefone IP', 'Class:IPPhone+' => '', -)); +]); // // Class: Tablet // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Tablet' => 'Tablet', 'Class:Tablet+' => '', -)); +]); // // Class: ConnectableCI // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:ConnectableCI' => 'Conectividade', 'Class:ConnectableCI+' => 'Físico', 'Class:ConnectableCI/ComplementaryName' => '%1$s - %2$s~~', @@ -237,13 +237,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:ConnectableCI/Attribute:networkdevice_list+' => 'Todos os Dispositivos de rede conectados neste dispositivo', 'Class:ConnectableCI/Attribute:physicalinterface_list' => 'Interface de rede', 'Class:ConnectableCI/Attribute:physicalinterface_list+' => 'Todas as Interfaces de rede presentes neste dispositivo', -)); +]); // // Class: DatacenterDevice // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:DatacenterDevice' => 'Dispositivo de Datacenter', 'Class:DatacenterDevice+' => '', 'Class:DatacenterDevice/ComplementaryName' => '%1$s - %2$s~~', @@ -275,13 +275,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:DatacenterDevice/Attribute:redundancy/count' => 'O dispositivo está ativo se pelo menos uma conexão de energia (A ou B) estiver ativa', 'Class:DatacenterDevice/Attribute:redundancy/disabled' => 'O dispositivo está ativo se todas as conexões de energia estiverem ativadas', 'Class:DatacenterDevice/Attribute:redundancy/percent' => 'O dispositivo está ativo se pelo menos %1$s %% de suas conexões de energia estiverem funcionando', -)); +]); // // Class: NetworkDevice // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:NetworkDevice' => 'Dispositivo de Rede', 'Class:NetworkDevice+' => '', 'Class:NetworkDevice/ComplementaryName' => '%1$s - %2$s~~', @@ -297,13 +297,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:NetworkDevice/Attribute:iosversion_name+' => '', 'Class:NetworkDevice/Attribute:ram' => 'RAM', 'Class:NetworkDevice/Attribute:ram+' => '', -)); +]); // // Class: Server // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Server' => 'Servidor', 'Class:Server+' => '', 'Class:Server/ComplementaryName' => '%1$s - %2$s~~', @@ -325,61 +325,61 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Server/Attribute:ram+' => '', 'Class:Server/Attribute:logicalvolumes_list' => 'Volumes lógicos', 'Class:Server/Attribute:logicalvolumes_list+' => 'Todos os Volumes lógicos associados à este Servidor', -)); +]); // // Class: StorageSystem // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:StorageSystem' => 'Sistema de Storage', 'Class:StorageSystem+' => '', 'Class:StorageSystem/ComplementaryName' => '%1$s - %2$s~~', 'Class:StorageSystem/Attribute:logicalvolume_list' => 'Volumes lógicos', 'Class:StorageSystem/Attribute:logicalvolume_list+' => 'Todos os Volumes lógicos neste Sistema de storage', -)); +]); // // Class: SANSwitch // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:SANSwitch' => 'Switch SAN', 'Class:SANSwitch+' => '', 'Class:SANSwitch/ComplementaryName' => '%1$s - %2$s~~', 'Class:SANSwitch/Attribute:datacenterdevice_list' => 'Dispositivos', 'Class:SANSwitch/Attribute:datacenterdevice_list+' => 'Todos os Dispositivos associados à este Switch SAN', -)); +]); // // Class: TapeLibrary // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:TapeLibrary' => 'Biblioteca de Fitas', 'Class:TapeLibrary+' => '', 'Class:TapeLibrary/ComplementaryName' => '%1$s - %2$s~~', 'Class:TapeLibrary/Attribute:tapes_list' => 'Fitas', 'Class:TapeLibrary/Attribute:tapes_list+' => 'Todas as Fitas associadas à esta Biblioteca de fitas', -)); +]); // // Class: NAS // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:NAS' => 'NAS', 'Class:NAS+' => '', 'Class:NAS/ComplementaryName' => '%1$s - %2$s~~', 'Class:NAS/Attribute:nasfilesystem_list' => 'Sistemas de arquivos', 'Class:NAS/Attribute:nasfilesystem_list+' => 'Todos os Sistemas de arquivos para este NAS', -)); +]); // // Class: PC // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:PC' => 'PC', 'Class:PC+' => '', 'Class:PC/ComplementaryName' => '%1$s - %2$s~~', @@ -401,45 +401,45 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:PC/Attribute:type/Value:desktop+' => '', 'Class:PC/Attribute:type/Value:laptop' => 'Laptop', 'Class:PC/Attribute:type/Value:laptop+' => '', -)); +]); // // Class: Printer // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Printer' => 'Impressora', 'Class:Printer+' => '', 'Class:Printer/ComplementaryName' => '%1$s - %2$s~~', -)); +]); // // Class: PowerConnection // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:PowerConnection' => 'Conexão de Energia', 'Class:PowerConnection+' => '', 'Class:PowerConnection/ComplementaryName' => '%1$s - %2$s~~', -)); +]); // // Class: PowerSource // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:PowerSource' => 'Fonte de Energia', 'Class:PowerSource+' => '', 'Class:PowerSource/ComplementaryName' => '%1$s - %2$s~~', 'Class:PowerSource/Attribute:pdus_list' => 'PDUs', 'Class:PowerSource/Attribute:pdus_list+' => 'Todos os PDUs utilizando esta Fonte de energia', -)); +]); // // Class: PDU // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:PDU' => 'PDU', 'Class:PDU+' => '', 'Class:PDU/ComplementaryName' => '%1$s - %2$s - %3$s - %4$s~~', @@ -451,23 +451,23 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:PDU/Attribute:powerstart_id+' => '', 'Class:PDU/Attribute:powerstart_name' => 'Nome da fonte de energia', 'Class:PDU/Attribute:powerstart_name+' => '', -)); +]); // // Class: Peripheral // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Peripheral' => 'Periférico', 'Class:Peripheral+' => '', 'Class:Peripheral/ComplementaryName' => '%1$s - %2$s~~', -)); +]); // // Class: Enclosure // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Enclosure' => 'Gaveta', 'Class:Enclosure+' => '', 'Class:Enclosure/ComplementaryName' => '%1$s - %2$s - %3$s~~', @@ -479,13 +479,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Enclosure/Attribute:nb_u+' => '', 'Class:Enclosure/Attribute:device_list' => 'Dispositivos', 'Class:Enclosure/Attribute:device_list+' => 'Todos os Dispositivos presentes nesta Gaveta', -)); +]); // // Class: ApplicationSolution // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:ApplicationSolution' => 'Solução de Aplicação', 'Class:ApplicationSolution+' => '', 'Class:ApplicationSolution/Attribute:functionalcis_list' => 'ICs', @@ -502,13 +502,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:ApplicationSolution/Attribute:redundancy/disabled' => 'A Solução de aplicação está funcionando se todos os Itens de configuração (ICs) estiverem funcionando', 'Class:ApplicationSolution/Attribute:redundancy/count' => 'A Solução de aplicação está funcionando se no mínimo %1$s Item(ns) de configuração (IC(s)) estiver(em) funcionando', 'Class:ApplicationSolution/Attribute:redundancy/percent' => 'A Solução de aplicação está funcionando se no mínimo %1$s %% dos Itens de configuração (ICs) estiverem funcionando', -)); +]); // // Class: BusinessProcess // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:BusinessProcess' => 'Processo de Negócio', 'Class:BusinessProcess+' => '', 'Class:BusinessProcess/Attribute:applicationsolutions_list' => 'Soluções de aplicação', @@ -519,13 +519,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:BusinessProcess/Attribute:status/Value:active+' => '', 'Class:BusinessProcess/Attribute:status/Value:inactive' => 'Inativo', 'Class:BusinessProcess/Attribute:status/Value:inactive+' => '', -)); +]); // // Class: SoftwareInstance // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:SoftwareInstance' => 'Instância de Software', 'Class:SoftwareInstance+' => '', 'Class:SoftwareInstance/Attribute:system_id' => 'Sistema', @@ -548,64 +548,64 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:SoftwareInstance/Attribute:status/Value:active+' => 'Ativo', 'Class:SoftwareInstance/Attribute:status/Value:inactive' => 'Inativo', 'Class:SoftwareInstance/Attribute:status/Value:inactive+' => 'Inativo', -)); +]); // // Class: Middleware // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Middleware' => 'Middleware', 'Class:Middleware+' => '', 'Class:Middleware/Attribute:middlewareinstance_list' => 'Instância Middleware', 'Class:Middleware/Attribute:middlewareinstance_list+' => 'Todos as instância middleware fornecida por essa middleware', -)); +]); // // Class: DBServer // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:DBServer' => 'Servidor de DB', 'Class:DBServer+' => '', 'Class:DBServer/Attribute:dbschema_list' => 'Esquemas de BD', 'Class:DBServer/Attribute:dbschema_list+' => 'Todos os Esquemas de BD para este Servidor de Banco de Dados (BD)', -)); +]); // // Class: WebServer // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:WebServer' => 'Servidor Web', 'Class:WebServer+' => '', 'Class:WebServer/Attribute:webapp_list' => 'Aplicações Web', 'Class:WebServer/Attribute:webapp_list+' => 'Todas as Aplicações Web disponíveis para este Servidor Web', -)); +]); // // Class: PCSoftware // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:PCSoftware' => 'Software de PC', 'Class:PCSoftware+' => '', -)); +]); // // Class: OtherSoftware // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:OtherSoftware' => 'Outro Software', 'Class:OtherSoftware+' => '', -)); +]); // // Class: MiddlewareInstance // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:MiddlewareInstance' => 'Instância Middleware', 'Class:MiddlewareInstance+' => '', 'Class:MiddlewareInstance/ComplementaryName' => '%1$s - %2$s~~', @@ -613,13 +613,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:MiddlewareInstance/Attribute:middleware_id+' => '', 'Class:MiddlewareInstance/Attribute:middleware_name' => 'Nome do middleware', 'Class:MiddlewareInstance/Attribute:middleware_name+' => '', -)); +]); // // Class: DatabaseSchema // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:DatabaseSchema' => 'Esquema de Banco de Dados (BD)', 'Class:DatabaseSchema+' => '', 'Class:DatabaseSchema/ComplementaryName' => '%1$s - %2$s~~', @@ -627,13 +627,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:DatabaseSchema/Attribute:dbserver_id+' => '', 'Class:DatabaseSchema/Attribute:dbserver_name' => 'Nome do servidor de DB', 'Class:DatabaseSchema/Attribute:dbserver_name+' => '', -)); +]); // // Class: WebApplication // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:WebApplication' => 'Aplicação Web', 'Class:WebApplication+' => '', 'Class:WebApplication/ComplementaryName' => '%1$s - %2$s~~', @@ -643,14 +643,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:WebApplication/Attribute:webserver_name+' => '', 'Class:WebApplication/Attribute:url' => 'URL', 'Class:WebApplication/Attribute:url+' => '', -)); - +]); // // Class: VirtualDevice // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:VirtualDevice' => 'Dispositivo Virtual', 'Class:VirtualDevice+' => '', 'Class:VirtualDevice/Attribute:status' => 'Status', @@ -665,24 +664,24 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:VirtualDevice/Attribute:status/Value:stock+' => 'Suporte', 'Class:VirtualDevice/Attribute:logicalvolumes_list' => 'Volume lógico', 'Class:VirtualDevice/Attribute:logicalvolumes_list+' => 'Todos os Volumes lógicos associados à este Dispositivo virtual', -)); +]); // // Class: VirtualHost // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:VirtualHost' => 'Host Virtual', 'Class:VirtualHost+' => '', 'Class:VirtualHost/Attribute:virtualmachine_list' => 'Máquinas virtuais (VMs)', 'Class:VirtualHost/Attribute:virtualmachine_list+' => 'Todas as Máquinas virtuais (VMs) hospedadas neste Host virtual', -)); +]); // // Class: Hypervisor // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Hypervisor' => 'Hypervisor', 'Class:Hypervisor+' => '', 'Class:Hypervisor/Attribute:farm_id' => 'Cluster/HA', @@ -693,13 +692,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Hypervisor/Attribute:server_id+' => '', 'Class:Hypervisor/Attribute:server_name' => 'Nome do servidor', 'Class:Hypervisor/Attribute:server_name+' => '', -)); +]); // // Class: Farm // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Farm' => 'Cluster/HA', 'Class:Farm+' => '', 'Class:Farm/Attribute:hypervisor_list' => 'Hypervisors', @@ -708,13 +707,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Farm/Attribute:redundancy/disabled' => 'O farm está ativo se todos os hypervisors estiverem disponíveis', 'Class:Farm/Attribute:redundancy/count' => 'O farm está ativo se pelo menos %1$s hypervisor(s) estiver(em) disponíveis', 'Class:Farm/Attribute:redundancy/percent' => 'O farm está ativo se pelo menos %1$s %% dos hypervisors estiverem disponíveis', -)); +]); // // Class: VirtualMachine // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:VirtualMachine' => 'Máquina Virtual', 'Class:VirtualMachine+' => '', 'Class:VirtualMachine/ComplementaryName' => '%1$s - %2$s~~', @@ -742,13 +741,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:VirtualMachine/Attribute:managementip+' => '', 'Class:VirtualMachine/Attribute:logicalinterface_list' => 'Interfaces de rede', 'Class:VirtualMachine/Attribute:logicalinterface_list+' => 'Todas as interfaces de rede', -)); +]); // // Class: LogicalVolume // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:LogicalVolume' => 'Volume Lógico', 'Class:LogicalVolume+' => '', 'Class:LogicalVolume/Attribute:name' => 'Nome', @@ -769,13 +768,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:LogicalVolume/Attribute:servers_list+' => 'Todos os Servidores usando este Volume lógico', 'Class:LogicalVolume/Attribute:virtualdevices_list' => 'Dispositivos virtuais', 'Class:LogicalVolume/Attribute:virtualdevices_list+' => 'Todos os Dispositivos virtuais usando este Volume lógico', -)); +]); // // Class: lnkServerToVolume // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkServerToVolume' => 'Relação entre Servidor / Volume', 'Class:lnkServerToVolume+' => '', 'Class:lnkServerToVolume/Name' => '%1$s / %2$s~~', @@ -789,13 +788,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkServerToVolume/Attribute:server_name+' => '', 'Class:lnkServerToVolume/Attribute:size_used' => 'Tamanho utilizado', 'Class:lnkServerToVolume/Attribute:size_used+' => '', -)); +]); // // Class: lnkVirtualDeviceToVolume // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkVirtualDeviceToVolume' => 'Relação entre Dispositivo virtual / Volume', 'Class:lnkVirtualDeviceToVolume+' => '', 'Class:lnkVirtualDeviceToVolume/Name' => '%1$s / %2$s~~', @@ -809,13 +808,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkVirtualDeviceToVolume/Attribute:virtualdevice_name+' => '', 'Class:lnkVirtualDeviceToVolume/Attribute:size_used' => 'Tamanho utilizado', 'Class:lnkVirtualDeviceToVolume/Attribute:size_used+' => '', -)); +]); // // Class: lnkSanToDatacenterDevice // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkSanToDatacenterDevice' => 'Relação entre Switch SAN / Dispositivo de datacenter', 'Class:lnkSanToDatacenterDevice+' => '', 'Class:lnkSanToDatacenterDevice/Name' => '%1$s / %2$s~~', @@ -831,13 +830,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkSanToDatacenterDevice/Attribute:san_port+' => '', 'Class:lnkSanToDatacenterDevice/Attribute:datacenterdevice_port' => 'FC do dispositivo', 'Class:lnkSanToDatacenterDevice/Attribute:datacenterdevice_port+' => '', -)); +]); // // Class: Tape // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Tape' => 'Fita', 'Class:Tape+' => '', 'Class:Tape/Attribute:name' => 'Nome', @@ -850,13 +849,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Tape/Attribute:tapelibrary_id+' => '', 'Class:Tape/Attribute:tapelibrary_name' => 'Nome da biblioteca de fitas', 'Class:Tape/Attribute:tapelibrary_name+' => '', -)); +]); // // Class: NASFileSystem // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:NASFileSystem' => 'Sistema de arquivos NAS', 'Class:NASFileSystem+' => '', 'Class:NASFileSystem/Attribute:name' => 'Nome', @@ -871,13 +870,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:NASFileSystem/Attribute:nas_id+' => '', 'Class:NASFileSystem/Attribute:nas_name' => 'Nome do NAS', 'Class:NASFileSystem/Attribute:nas_name+' => '', -)); +]); // // Class: Software // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Software' => 'Software', 'Class:Software+' => '', 'Class:Software/ComplementaryName' => '%1$s - %2$s~~', @@ -907,13 +906,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Software/Attribute:softwarepatch_list+' => 'Todas as Atualizações para este Software', 'Class:Software/Attribute:softwarelicence_list' => 'Licenças de software', 'Class:Software/Attribute:softwarelicence_list+' => 'Todas as Licenças de software para este Software', -)); +]); // // Class: Patch // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Patch' => 'Atualização', 'Class:Patch+' => '', 'Class:Patch/Attribute:name' => 'Nome', @@ -924,13 +923,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Patch/Attribute:description+' => '', 'Class:Patch/Attribute:finalclass' => 'Tipo', 'Class:Patch/Attribute:finalclass+' => '', -)); +]); // // Class: OSPatch // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:OSPatch' => 'Atualização de SO', 'Class:OSPatch+' => '', 'Class:OSPatch/Attribute:functionalcis_list' => 'Dispositivos', @@ -939,13 +938,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:OSPatch/Attribute:osversion_id+' => '', 'Class:OSPatch/Attribute:osversion_name' => 'Nome da versão do SO', 'Class:OSPatch/Attribute:osversion_name+' => '', -)); +]); // // Class: SoftwarePatch // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:SoftwarePatch' => 'Atualização de Software', 'Class:SoftwarePatch+' => '', 'Class:SoftwarePatch/Attribute:software_id' => 'Software', @@ -954,13 +953,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:SoftwarePatch/Attribute:software_name+' => '', 'Class:SoftwarePatch/Attribute:softwareinstances_list' => 'Instâncias de software', 'Class:SoftwarePatch/Attribute:softwareinstances_list+' => 'Todos os sistemas onde essa Atualização de software está instalada', -)); +]); // // Class: Licence // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Licence' => 'Licença', 'Class:Licence+' => '', 'Class:Licence/Attribute:name' => 'Nome', @@ -989,13 +988,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Licence/Attribute:perpetual/Value:yes+' => 'Sim', 'Class:Licence/Attribute:finalclass' => 'Tipo', 'Class:Licence/Attribute:finalclass+' => '', -)); +]); // // Class: OSLicence // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:OSLicence' => 'Licença de SO', 'Class:OSLicence+' => '', 'Class:OSLicence/ComplementaryName' => '%1$s - %2$s~~', @@ -1007,13 +1006,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:OSLicence/Attribute:virtualmachines_list+' => 'Todas as Máquinas virtuais (VMs) onde essa Licença é utilizada', 'Class:OSLicence/Attribute:servers_list' => 'Servidores', 'Class:OSLicence/Attribute:servers_list+' => 'Todos os Servidores onde essa Licença é utilizada', -)); +]); // // Class: SoftwareLicence // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:SoftwareLicence' => 'Licença de Software', 'Class:SoftwareLicence+' => '', 'Class:SoftwareLicence/ComplementaryName' => '%1$s - %2$s~~', @@ -1023,13 +1022,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:SoftwareLicence/Attribute:software_name+' => '', 'Class:SoftwareLicence/Attribute:softwareinstance_list' => 'Instâncias de software', 'Class:SoftwareLicence/Attribute:softwareinstance_list+' => 'Todos os sistemas onde esta Licença é utilizada', -)); +]); // // Class: lnkDocumentToLicence // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkDocumentToLicence' => 'Relação entre Documento / Licença', 'Class:lnkDocumentToLicence+' => '', 'Class:lnkDocumentToLicence/Name' => '%1$s / %2$s~~', @@ -1041,35 +1040,35 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkDocumentToLicence/Attribute:document_id+' => '', 'Class:lnkDocumentToLicence/Attribute:document_name' => 'Nome do documento', 'Class:lnkDocumentToLicence/Attribute:document_name+' => '', -)); +]); // // Class: OSVersion // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:OSVersion' => 'Versão do OS', 'Class:OSVersion+' => '', 'Class:OSVersion/Attribute:osfamily_id' => 'Família do SO', 'Class:OSVersion/Attribute:osfamily_id+' => '', 'Class:OSVersion/Attribute:osfamily_name' => 'Nome da família do SO', 'Class:OSVersion/Attribute:osfamily_name+' => '', -)); +]); // // Class: OSFamily // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:OSFamily' => 'Família do OS', 'Class:OSFamily+' => '', -)); +]); // // Class: Brand // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Brand' => 'Fabricante', 'Class:Brand+' => '', 'Class:Brand/Attribute:logo' => 'Logo~~', @@ -1078,13 +1077,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Brand/Attribute:physicaldevices_list+' => 'Todos os Dispositivos físicos correspondentes a esse(a) Fabricante', 'Class:Brand/UniquenessRule:name+' => 'O nome do(a) fabricante deve ser único', 'Class:Brand/UniquenessRule:name' => 'Esse(a) fabricante já existe', -)); +]); // // Class: Model // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Model' => 'Modelo', 'Class:Model+' => '', 'Class:Model/ComplementaryName' => '%1$s - %2$s~~', @@ -1136,37 +1135,37 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Model/Attribute:physicaldevices_list+' => 'Todos os Dispositivos físicos correspondentes à este Modelo', 'Class:Model/UniquenessRule:name_brand+' => 'O nome do modelo deve ser único', 'Class:Model/UniquenessRule:name_brand' => 'Este modelo já existe', -)); +]); // // Class: NetworkDeviceType // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:NetworkDeviceType' => 'Tipo de dispositivo de rede', 'Class:NetworkDeviceType+' => '', 'Class:NetworkDeviceType/Attribute:networkdevicesdevices_list' => 'Dispositivos de rede', 'Class:NetworkDeviceType/Attribute:networkdevicesdevices_list+' => 'Todos os Dispositivos de rede correspondentes a este Tipo', -)); +]); // // Class: IOSVersion // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:IOSVersion' => 'Versão do SO', 'Class:IOSVersion+' => '', 'Class:IOSVersion/Attribute:brand_id' => 'Fabricante', 'Class:IOSVersion/Attribute:brand_id+' => '', 'Class:IOSVersion/Attribute:brand_name' => 'Nome do fabricante', 'Class:IOSVersion/Attribute:brand_name+' => '', -)); +]); // // Class: lnkDocumentToPatch // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkDocumentToPatch' => 'Relação entre Documento / Atualização', 'Class:lnkDocumentToPatch+' => '', 'Class:lnkDocumentToPatch/Name' => '%1$s / %2$s~~', @@ -1178,13 +1177,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkDocumentToPatch/Attribute:document_id+' => '', 'Class:lnkDocumentToPatch/Attribute:document_name' => 'Nome do documento', 'Class:lnkDocumentToPatch/Attribute:document_name+' => '', -)); +]); // // Class: lnkSoftwareInstanceToSoftwarePatch // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkSoftwareInstanceToSoftwarePatch' => 'Relação entre Instância de software / Atualização de software', 'Class:lnkSoftwareInstanceToSoftwarePatch+' => '', 'Class:lnkSoftwareInstanceToSoftwarePatch/Name' => '%1$s / %2$s~~', @@ -1196,13 +1195,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkSoftwareInstanceToSoftwarePatch/Attribute:softwareinstance_id+' => '', 'Class:lnkSoftwareInstanceToSoftwarePatch/Attribute:softwareinstance_name' => 'Nome da instância de software', 'Class:lnkSoftwareInstanceToSoftwarePatch/Attribute:softwareinstance_name+' => '', -)); +]); // // Class: lnkFunctionalCIToOSPatch // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkFunctionalCIToOSPatch' => 'Relação entre IC / Atualização de SO', 'Class:lnkFunctionalCIToOSPatch+' => '', 'Class:lnkFunctionalCIToOSPatch/Name' => '%1$s / %2$s~~', @@ -1214,13 +1213,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkFunctionalCIToOSPatch/Attribute:functionalci_id+' => '', 'Class:lnkFunctionalCIToOSPatch/Attribute:functionalci_name' => 'Nome do IC', 'Class:lnkFunctionalCIToOSPatch/Attribute:functionalci_name+' => '', -)); +]); // // Class: lnkDocumentToSoftware // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkDocumentToSoftware' => 'Relação entre Documento / Software', 'Class:lnkDocumentToSoftware+' => '', 'Class:lnkDocumentToSoftware/Name' => '%1$s / %2$s~~', @@ -1232,13 +1231,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkDocumentToSoftware/Attribute:document_id+' => '', 'Class:lnkDocumentToSoftware/Attribute:document_name' => 'Nome do documento', 'Class:lnkDocumentToSoftware/Attribute:document_name+' => '', -)); +]); // // Class: Subnet // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Subnet' => 'Sub-rede', 'Class:Subnet+' => '', 'Class:Subnet/Name' => '%1$s/%2$s~~', @@ -1257,13 +1256,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Subnet/Attribute:ip_mask+' => '', 'Class:Subnet/Attribute:vlans_list' => 'VLANs', 'Class:Subnet/Attribute:vlans_list+' => '', -)); +]); // // Class: VLAN // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:VLAN' => 'VLAN', 'Class:VLAN+' => '', 'Class:VLAN/Attribute:vlan_tag' => 'Nome da VLAN', @@ -1278,13 +1277,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:VLAN/Attribute:subnets_list+' => '', 'Class:VLAN/Attribute:physicalinterfaces_list' => 'Interfaces de rede física', 'Class:VLAN/Attribute:physicalinterfaces_list+' => '', -)); +]); // // Class: lnkSubnetToVLAN // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkSubnetToVLAN' => 'Relação entre Sub-rede / VLAN', 'Class:lnkSubnetToVLAN+' => '', 'Class:lnkSubnetToVLAN/Name' => '%1$s / %2$s~~', @@ -1298,26 +1297,26 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkSubnetToVLAN/Attribute:vlan_id+' => '', 'Class:lnkSubnetToVLAN/Attribute:vlan_tag' => 'Nome da VLAN', 'Class:lnkSubnetToVLAN/Attribute:vlan_tag+' => '', -)); +]); // // Class: NetworkInterface // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:NetworkInterface' => 'Adaptador de Rede', 'Class:NetworkInterface+' => '', 'Class:NetworkInterface/Attribute:name' => 'Nome', 'Class:NetworkInterface/Attribute:name+' => '', 'Class:NetworkInterface/Attribute:finalclass' => 'Tipo', 'Class:NetworkInterface/Attribute:finalclass+' => '', -)); +]); // // Class: IPInterface // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:IPInterface' => 'Endereço IP', 'Class:IPInterface+' => '', 'Class:IPInterface/Attribute:ipaddress' => 'Endereço IP', @@ -1332,13 +1331,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:IPInterface/Attribute:ipmask+' => '', 'Class:IPInterface/Attribute:speed' => 'Velocidade', 'Class:IPInterface/Attribute:speed+' => '', -)); +]); // // Class: PhysicalInterface // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:PhysicalInterface' => 'Placa física', 'Class:PhysicalInterface+' => '', 'Class:PhysicalInterface/Name' => '%2$s %1$s~~', @@ -1348,13 +1347,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:PhysicalInterface/Attribute:connectableci_name+' => '', 'Class:PhysicalInterface/Attribute:vlans_list' => 'VLANs', 'Class:PhysicalInterface/Attribute:vlans_list+' => '', -)); +]); // // Class: lnkPhysicalInterfaceToVLAN // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkPhysicalInterfaceToVLAN' => 'Relação entre Interface física / VLAN', 'Class:lnkPhysicalInterfaceToVLAN+' => '', 'Class:lnkPhysicalInterfaceToVLAN/Name' => '%1$s %2$s / %3$s~~', @@ -1370,27 +1369,26 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkPhysicalInterfaceToVLAN/Attribute:vlan_id+' => '', 'Class:lnkPhysicalInterfaceToVLAN/Attribute:vlan_tag' => 'Nome da VLAN', 'Class:lnkPhysicalInterfaceToVLAN/Attribute:vlan_tag+' => '', -)); - +]); // // Class: LogicalInterface // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:LogicalInterface' => 'Placa lógica', 'Class:LogicalInterface+' => '', 'Class:LogicalInterface/Attribute:virtualmachine_id' => 'Máquina virtual', 'Class:LogicalInterface/Attribute:virtualmachine_id+' => '', 'Class:LogicalInterface/Attribute:virtualmachine_name' => 'Nome da máquina virtual', 'Class:LogicalInterface/Attribute:virtualmachine_name+' => '', -)); +]); // // Class: FiberChannelInterface // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:FiberChannelInterface' => 'Placa Fiber Channel', 'Class:FiberChannelInterface+' => '', 'Class:FiberChannelInterface/Attribute:speed' => 'Velocidade', @@ -1403,13 +1401,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:FiberChannelInterface/Attribute:datacenterdevice_id+' => '', 'Class:FiberChannelInterface/Attribute:datacenterdevice_name' => 'Nome do dispositivo', 'Class:FiberChannelInterface/Attribute:datacenterdevice_name+' => '', -)); +]); // // Class: lnkConnectableCIToNetworkDevice // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkConnectableCIToNetworkDevice' => 'Relação entre Dispositivo conectado / Dispositivo de rede', 'Class:lnkConnectableCIToNetworkDevice+' => '', 'Class:lnkConnectableCIToNetworkDevice/Name' => '%1$s / %2$s~~', @@ -1431,13 +1429,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkConnectableCIToNetworkDevice/Attribute:connection_type/Value:downlink+' => 'Link down', 'Class:lnkConnectableCIToNetworkDevice/Attribute:connection_type/Value:uplink' => 'Link up', 'Class:lnkConnectableCIToNetworkDevice/Attribute:connection_type/Value:uplink+' => 'Link up', -)); +]); // // Class: lnkApplicationSolutionToFunctionalCI // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkApplicationSolutionToFunctionalCI' => 'Relação entre Solução de aplicação / IC', 'Class:lnkApplicationSolutionToFunctionalCI+' => '', 'Class:lnkApplicationSolutionToFunctionalCI/Name' => '%1$s / %2$s~~', @@ -1449,13 +1447,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkApplicationSolutionToFunctionalCI/Attribute:functionalci_id+' => '', 'Class:lnkApplicationSolutionToFunctionalCI/Attribute:functionalci_name' => 'Nome do IC', 'Class:lnkApplicationSolutionToFunctionalCI/Attribute:functionalci_name+' => '', -)); +]); // // Class: lnkApplicationSolutionToBusinessProcess // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkApplicationSolutionToBusinessProcess' => 'Relação entre Solução de aplicação / Processo de negócio', 'Class:lnkApplicationSolutionToBusinessProcess+' => '', 'Class:lnkApplicationSolutionToBusinessProcess/Name' => '%1$s / %2$s~~', @@ -1467,13 +1465,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkApplicationSolutionToBusinessProcess/Attribute:applicationsolution_id+' => '', 'Class:lnkApplicationSolutionToBusinessProcess/Attribute:applicationsolution_name' => 'Nome da solução de aplicação', 'Class:lnkApplicationSolutionToBusinessProcess/Attribute:applicationsolution_name+' => '', -)); +]); // // Class: Group // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Group' => 'Grupo', 'Class:Group+' => '', 'Class:Group/ComplementaryName' => '%1$s - %2$s~~', @@ -1503,13 +1501,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Group/Attribute:ci_list+' => 'Todos os Itens de configuração (IC) associados à este Grupo', 'Class:Group/Attribute:parent_id_friendlyname' => 'Grupo pai', 'Class:Group/Attribute:parent_id_friendlyname+' => '', -)); +]); // // Class: lnkGroupToCI // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkGroupToCI' => 'Relação entre Grupo / IC', 'Class:lnkGroupToCI+' => '', 'Class:lnkGroupToCI/Name' => '%1$s / %2$s~~', @@ -1523,11 +1521,11 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkGroupToCI/Attribute:ci_name+' => '', 'Class:lnkGroupToCI/Attribute:reason' => 'Motivo do link', 'Class:lnkGroupToCI/Attribute:reason+' => '', -)); +]); // Add translation for Fieldsets -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Server:baseinfo' => 'Informações gerais', 'Server:Date' => 'Data', 'Server:moreinfo' => 'Mais informações', @@ -1540,14 +1538,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Subnet/Tab:FreeIPs-count' => 'IPs livres: %1$s', 'Class:Subnet/Tab:FreeIPs-explain' => 'Aqui uma faixa de 10 endereços IPs livres', 'Class:Document:PreviewTab' => 'Visualização', -)); - +]); // // Class: lnkDocumentToFunctionalCI // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkDocumentToFunctionalCI' => 'Relação entre Documento / IC', 'Class:lnkDocumentToFunctionalCI+' => '', 'Class:lnkDocumentToFunctionalCI/Name' => '%1$s / %2$s~~', @@ -1559,13 +1556,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkDocumentToFunctionalCI/Attribute:document_id+' => '', 'Class:lnkDocumentToFunctionalCI/Attribute:document_name' => 'Nome do documento', 'Class:lnkDocumentToFunctionalCI/Attribute:document_name+' => '', -)); +]); // // Application Menu // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Menu:Application' => 'Aplicações', 'Menu:Application+' => 'Lista de Aplicações', 'Menu:DBServer' => 'Servidores de Banco de Dados', @@ -1610,15 +1607,15 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Menu:OSVersion+' => 'Lista de Versões do SO', 'Menu:Software' => 'Catálogo de Software', 'Menu:Software+' => '', -)); +]); // // Class: PhysicalInterface // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:PhysicalInterface/Attribute:org_id' => 'Org id~~', 'Class:PhysicalInterface/Attribute:org_id+' => '~~', 'Class:PhysicalInterface/Attribute:location_id' => 'Location id~~', 'Class:PhysicalInterface/Attribute:location_id+' => '~~', -)); +]); diff --git a/datamodels/2.x/itop-config-mgmt/module.itop-config-mgmt.php b/datamodels/2.x/itop-config-mgmt/module.itop-config-mgmt.php index c9b87ee0c..9632bafae 100755 --- a/datamodels/2.x/itop-config-mgmt/module.itop-config-mgmt.php +++ b/datamodels/2.x/itop-config-mgmt/module.itop-config-mgmt.php @@ -1,10 +1,9 @@ 'Configuration Management (CMDB)', @@ -12,25 +11,25 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( + 'dependencies' => [ 'itop-structure/2.7.1', - ), + ], 'mandatory' => false, 'visible' => true, 'installer' => 'ConfigMgmtInstaller', // Components // - 'datamodel' => array( + 'datamodel' => [ 'model.itop-config-mgmt.php', 'main.itop-config-mgmt.php', - ), - 'data.struct' => array( + ], + 'data.struct' => [ 'data/en_us.data.itop-brand.xml', 'data/en_us.data.itop-osfamily.xml', 'data/en_us.data.itop-osversion.xml', - ), - 'data.sample' => array( + ], + 'data.sample' => [ 'data.sample.model.xml', 'data.sample.networkdevicetype.xml', 'data.sample.servers.xml', @@ -42,8 +41,8 @@ SetupWebPage::AddModule( 'data.sample.webapp.xml', 'data.sample.applications.xml', 'data.sample.applicationsolutionci.xml', - ), - + ], + // Documentation // 'doc.manual_setup' => '', @@ -51,13 +50,12 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array( - ), - ) + 'settings' => [ + ], + ] ); -if (!class_exists('ConfigMgmtInstaller')) -{ +if (!class_exists('ConfigMgmtInstaller')) { // Module installation handler // class ConfigMgmtInstaller extends ModuleInstallerAPI @@ -76,8 +74,7 @@ if (!class_exists('ConfigMgmtInstaller')) */ public static function BeforeDatabaseCreation(Config $oConfiguration, $sPreviousVersion, $sCurrentVersion) { - if (strlen($sPreviousVersion) > 0) - { + if (strlen($sPreviousVersion) > 0) { // If you want to migrate data from one format to another, do it here self::RenameEnumValueInDB('Software', 'type', 'DBserver', 'DBServer'); self::RenameEnumValueInDB('Software', 'type', 'Webserver', 'WebServer'); @@ -95,7 +92,7 @@ if (!class_exists('ConfigMgmtInstaller')) self::RenameClassInDB('IPinterface', 'IPInterface'); } } - + /** * Handler called after the creation/update of the database schema * @param $oConfiguration Config The new configuration of the application diff --git a/datamodels/2.x/itop-config/config.php b/datamodels/2.x/itop-config/config.php index 5b8f2c4b3..5372d6d72 100644 --- a/datamodels/2.x/itop-config/config.php +++ b/datamodels/2.x/itop-config/config.php @@ -1,4 +1,5 @@ SetDefaultOperation('Edit'); $oConfigEditorController->HandleOperation(); - diff --git a/datamodels/2.x/itop-config/dictionaries/it.dict.itop-config.php b/datamodels/2.x/itop-config/dictionaries/it.dict.itop-config.php index 6145516c9..ba2ac0097 100644 --- a/datamodels/2.x/itop-config/dictionaries/it.dict.itop-config.php +++ b/datamodels/2.x/itop-config/dictionaries/it.dict.itop-config.php @@ -1,15 +1,16 @@ 'Modifica file di configurazione', 'config-edit-intro' => 'Prestare molta attenzione durante la modifica del file di configurazione.', 'Menu:ConfigEditor' => 'Configurazione', @@ -27,4 +28,4 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'config-error-file-changed' => 'Errore: il file di configurazione è stato modificato da quando lo hai aperto e non può essere salvato. Aggiorna e applica nuovamente le tue modifiche.', 'config-not-allowed-in-demo' => 'Spiacente, '.ITOP_APPLICATION_SHORT.' è in modalità dimostrativa: il file di configurazione non può essere modificato.', 'config-interactive-not-allowed' => 'La modifica interattiva della configurazione di '.ITOP_APPLICATION_SHORT.' è stata disabilitata. Vedere \'config_editor\' => \'disabled\' nel file di configurazione.', -)); +]); diff --git a/datamodels/2.x/itop-config/dictionaries/pt_br.dict.itop-config.php b/datamodels/2.x/itop-config/dictionaries/pt_br.dict.itop-config.php index 9625de2a7..3c4d38b79 100644 --- a/datamodels/2.x/itop-config/dictionaries/pt_br.dict.itop-config.php +++ b/datamodels/2.x/itop-config/dictionaries/pt_br.dict.itop-config.php @@ -1,15 +1,16 @@ 'Configurações', 'itop-config/Operation:Edit/Title' => 'Editor do arquivo de configuração', 'config-edit-intro' => 'Tenha cuidado ao editar o arquivo de configuração', @@ -28,4 +29,4 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'config-error-file-changed' => 'Error: The Configuration file has changed since you opened it and cannot be saved. Refresh and apply your changes again.~~', 'config-not-allowed-in-demo' => 'Sorry, '.ITOP_APPLICATION_SHORT.' is in demonstration mode: the configuration file cannot be edited.~~', 'config-interactive-not-allowed' => ITOP_APPLICATION_SHORT.' interactive edition of the configuration as been disabled. See \'config_editor\' => \'disabled\' in the configuration file.~~', -)); +]); diff --git a/datamodels/2.x/itop-config/module.itop-config.php b/datamodels/2.x/itop-config/module.itop-config.php index 70c2882a6..941a6b0e1 100644 --- a/datamodels/2.x/itop-config/module.itop-config.php +++ b/datamodels/2.x/itop-config/module.itop-config.php @@ -1,10 +1,9 @@ 'Configuration editor', @@ -12,27 +11,27 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array(), + 'dependencies' => [], 'mandatory' => true, 'visible' => false, // Components // - 'datamodel' => array( + 'datamodel' => [ 'src/Validator/ConfigNodesVisitor.php', 'src/Validator/iTopConfigAstValidator.php', 'src/Validator/iTopConfigSyntaxValidator.php', 'src/Validator/iTopConfigValidator.php', 'src/Controller/ConfigEditorController.php', -), - 'webservice' => array(), - 'dictionary' => array( +], + 'webservice' => [], + 'dictionary' => [ 'en.dict.itop-config.php', 'fr.dict.itop-config.php', - ), - 'data.struct' => array(), - 'data.sample' => array(), - + ], + 'data.struct' => [], + 'data.sample' => [], + // Documentation // 'doc.manual_setup' => '', @@ -40,6 +39,6 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array(), - ) + 'settings' => [], + ] ); diff --git a/datamodels/2.x/itop-config/src/Controller/ConfigEditorController.php b/datamodels/2.x/itop-config/src/Controller/ConfigEditorController.php index 48405d694..c45c4f015 100644 --- a/datamodels/2.x/itop-config/src/Controller/ConfigEditorController.php +++ b/datamodels/2.x/itop-config/src/Controller/ConfigEditorController.php @@ -1,4 +1,5 @@ Get('demo_mode')) { throw new Exception(Dict::S('config-not-allowed-in-demo'), iTopConfigValidator::CONFIG_INFO); @@ -52,8 +54,7 @@ class ConfigEditorController extends Controller try { if ($sOperation == 'revert') { $this->AddAlert(Dict::S('config-reverted'), iTopConfigValidator::CONFIG_WARNING); - } - else if ($sOperation == 'save') { + } elseif ($sOperation == 'save') { $sTransactionId = utils::ReadParam('transaction_id', '', false, 'transaction_id'); if (!utils::IsTransactionValid($sTransactionId)) { throw new Exception(Dict::S('config-error-transaction'), iTopConfigValidator::CONFIG_ERROR); @@ -99,24 +100,21 @@ class ConfigEditorController extends Controller $this->AddAlert($oValidator->CheckAsyncTasksRetryConfig($oTempConfig), iTopConfigValidator::CONFIG_WARNING); - // Read the config from disk after save $sCurrentConfig = file_get_contents($sConfigFile); $sConfigChecksum = md5($sCurrentConfig); } - } - catch (Exception $e) { + } catch (Exception $e) { $this->AddAlertFromException($e); } $this->AddAceScripts(); - } - catch (Exception $e) { + } catch (Exception $e) { $bShowEditor = false; $this->AddAlertFromException($e); } - // display page + // display page $this->DisplayPage([ 'aErrors' => $this->aErrors, 'aWarnings' => $this->aWarnings, @@ -127,7 +125,7 @@ class ConfigEditorController extends Controller 'sChecksum' => $sConfigChecksum, 'sPrevConfig' => $sCurrentConfig, 'sNewConfig' => $sCurrentConfig, - ]); + ]); } /** @@ -143,7 +141,6 @@ class ConfigEditorController extends Controller $this->AddLinkedScript(utils::GetAbsoluteUrlAppRoot().$sAceDir.'ext-searchbox.js'); } - public function AddAlertFromException(Exception $e): void { $this->AddAlert($e->getMessage(), $e->getCode()); @@ -158,18 +155,18 @@ class ConfigEditorController extends Controller return; } switch ($iLevel) { - case iTopConfigValidator::CONFIG_SUCCESS : + case iTopConfigValidator::CONFIG_SUCCESS: $this->aSuccesses[] = $sMessage; break; - case iTopConfigValidator::CONFIG_WARNING : + case iTopConfigValidator::CONFIG_WARNING: $this->aWarnings[] = $sMessage; break; - case iTopConfigValidator::CONFIG_INFO : + case iTopConfigValidator::CONFIG_INFO: $this->aInfo[] = $sMessage; break; - default : + default: $this->aErrors[] = $sMessage; } } -} \ No newline at end of file +} diff --git a/datamodels/2.x/itop-config/src/Validator/iTopConfigAstValidator.php b/datamodels/2.x/itop-config/src/Validator/iTopConfigAstValidator.php index 6d0fcf2fb..03400edc3 100644 --- a/datamodels/2.x/itop-config/src/Validator/iTopConfigAstValidator.php +++ b/datamodels/2.x/itop-config/src/Validator/iTopConfigAstValidator.php @@ -1,4 +1,5 @@ createForNewestSupportedVersion(); + $oParser = (new ParserFactory())->createForNewestSupportedVersion(); $oNodeVisitor = new ConfigNodesVisitor(); try { $aInitialNodes = $oParser->parse($sConfig); } catch (\Error $e) { - $sMessage = 'Invalid configuration: '. \Dict::Format('config-parse-error', $e->getMessage(), $e->getLine()); + $sMessage = 'Invalid configuration: '.\Dict::Format('config-parse-error', $e->getMessage(), $e->getLine()); throw new \Exception($sMessage, iTopConfigValidator::CONFIG_ERROR, $e); - }catch (\Exception $e) { - $sMessage = 'Invalid configuration: '. \Dict::Format('config-parse-error', $e->getMessage(), $e->getLine()); + } catch (\Exception $e) { + $sMessage = 'Invalid configuration: '.\Dict::Format('config-parse-error', $e->getMessage(), $e->getLine()); throw new \Exception($sMessage, iTopConfigValidator::CONFIG_ERROR, $e); } @@ -41,4 +41,4 @@ class iTopConfigAstValidator $oTraverser->addVisitor($oNodeVisitor); $oTraverser->traverse($aInitialNodes); } -} \ No newline at end of file +} diff --git a/datamodels/2.x/itop-config/src/Validator/iTopConfigSyntaxValidator.php b/datamodels/2.x/itop-config/src/Validator/iTopConfigSyntaxValidator.php index 4ecbed82e..0d61b284f 100644 --- a/datamodels/2.x/itop-config/src/Validator/iTopConfigSyntaxValidator.php +++ b/datamodels/2.x/itop-config/src/Validator/iTopConfigSyntaxValidator.php @@ -1,4 +1,5 @@ = 7.0.0 syntax errors are thrown as Error - $sConfig = preg_replace(array('#^\s*<\?php#', '#\?>\s*$#'), '', $sRawConfig); + $sConfig = preg_replace(['#^\s*<\?php#', '#\?>\s*$#'], '', $sRawConfig); eval('if(0){'.trim($sConfig).'}'); $sNoise = trim(ob_get_contents()); - } - catch (\Error $e) { + } catch (\Error $e) { // ParseError only thrown in PHP7 throw new \Exception('Error in configuration: '.$e->getMessage().' at line '.$e->getLine(), iTopConfigValidator::CONFIG_ERROR); - } - finally { + } finally { ob_end_clean(); } @@ -40,11 +38,10 @@ class iTopConfigSyntaxValidator $sLine = $aMatches[3]; $sMessage = \Dict::Format('config-parse-error', $sMessage, $sLine); throw new \Exception($sMessage, iTopConfigValidator::CONFIG_ERROR); - } - else { + } else { // Note: sNoise is an html output, but so far it was ok for me (e.g. showing the entire call stack) throw new \Exception('Syntax error in configuration file: '.$sNoise.'', iTopConfigValidator::CONFIG_ERROR); } } } -} \ No newline at end of file +} diff --git a/datamodels/2.x/itop-config/src/Validator/iTopConfigValidator.php b/datamodels/2.x/itop-config/src/Validator/iTopConfigValidator.php index 3c5faa84a..7d83d84af 100644 --- a/datamodels/2.x/itop-config/src/Validator/iTopConfigValidator.php +++ b/datamodels/2.x/itop-config/src/Validator/iTopConfigValidator.php @@ -5,18 +5,19 @@ namespace Combodo\iTop\Config\Validator; use AsyncTask; use ReflectionClass; -class iTopConfigValidator { - const CONFIG_ERROR = 0; - const CONFIG_WARNING = 1; - const CONFIG_INFO = 2; - const CONFIG_SUCCESS = 3; +class iTopConfigValidator +{ + public const CONFIG_ERROR = 0; + public const CONFIG_WARNING = 1; + public const CONFIG_INFO = 2; + public const CONFIG_SUCCESS = 3; /** * @param $sRawConfig * * @throws \Exception */ - public function Validate($sRawConfig):void + public function Validate($sRawConfig): void { $oiTopConfigValidator = new iTopConfigAstValidator(); $oiTopConfigValidator->Validate($sRawConfig); @@ -26,7 +27,7 @@ class iTopConfigValidator { $oiTopConfigValidator->Validate($sRawConfig); } - function DBPasswordIsOk($sPassword):bool + public function DBPasswordIsOk($sPassword): bool { $bIsWindows = (array_key_exists('WINDIR', $_SERVER) || array_key_exists('windir', $_SERVER)); @@ -37,7 +38,6 @@ class iTopConfigValidator { return true; } - public function CheckAsyncTasksRetryConfig(\Config $oTempConfig): array { $aWarnings = []; @@ -56,4 +56,4 @@ class iTopConfigValidator { return $aWarnings; } -} \ No newline at end of file +} diff --git a/datamodels/2.x/itop-core-update/dictionaries/pt_br.dict.itop-core-update.php b/datamodels/2.x/itop-core-update/dictionaries/pt_br.dict.itop-core-update.php index 056b32700..e8bbcd378 100644 --- a/datamodels/2.x/itop-core-update/dictionaries/pt_br.dict.itop-core-update.php +++ b/datamodels/2.x/itop-core-update/dictionaries/pt_br.dict.itop-core-update.php @@ -1,15 +1,16 @@ 'Atualização do '.ITOP_APPLICATION_SHORT, 'itop-core-update:UI:SelectUpdateFile' => 'Atualização do '.ITOP_APPLICATION_SHORT, 'itop-core-update:UI:ConfirmUpdate' => 'Atualização do '.ITOP_APPLICATION_SHORT, @@ -95,7 +96,5 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:ModuleInstallation/Attribute:installed' => 'Instalado em', 'Class:ModuleInstallation/Attribute:name' => 'Nome', 'Class:ModuleInstallation/Attribute:version' => 'Versão', - 'Class:ModuleInstallation/Attribute:comment' => 'Comentário' -)); - - + 'Class:ModuleInstallation/Attribute:comment' => 'Comentário', +]); diff --git a/datamodels/2.x/itop-datacenter-mgmt/module.itop-datacenter-mgmt.php b/datamodels/2.x/itop-datacenter-mgmt/module.itop-datacenter-mgmt.php index f3bd85bfe..30d29a8c9 100755 --- a/datamodels/2.x/itop-datacenter-mgmt/module.itop-datacenter-mgmt.php +++ b/datamodels/2.x/itop-datacenter-mgmt/module.itop-datacenter-mgmt.php @@ -1,9 +1,10 @@ 'Datacenter Management', @@ -27,36 +28,35 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( - 'itop-config-mgmt/2.2.0' - ), + 'dependencies' => [ + 'itop-config-mgmt/2.2.0', + ], 'mandatory' => false, 'visible' => true, // Components // - 'datamodel' => array(), - 'webservice' => array( - - ), - 'data.struct' => array( + 'datamodel' => [], + 'webservice' => [ + + ], + 'data.struct' => [ // add your 'structure' definition XML files here, - ), - 'data.sample' => array( + ], + 'data.sample' => [ // add your sample data XML files here, 'data.sample.racks.xml', - ), - + ], + // Documentation // 'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any - 'doc.more_information' => '', // hyperlink to more information, if any + 'doc.more_information' => '', // hyperlink to more information, if any // Default settings // - 'settings' => array( + 'settings' => [ // Module specific settings go here, if any - ), - ) + ], + ] ); - diff --git a/datamodels/2.x/itop-endusers-devices/module.itop-endusers-devices.php b/datamodels/2.x/itop-endusers-devices/module.itop-endusers-devices.php index 6afc623a6..162a46aed 100644 --- a/datamodels/2.x/itop-endusers-devices/module.itop-endusers-devices.php +++ b/datamodels/2.x/itop-endusers-devices/module.itop-endusers-devices.php @@ -1,4 +1,5 @@ 'End-user Devices Management', @@ -34,42 +35,41 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( - 'itop-config-mgmt/2.2.0' - ), + 'dependencies' => [ + 'itop-config-mgmt/2.2.0', + ], 'mandatory' => false, 'visible' => true, 'installer' => 'EndUserMgmtInstaller', // Components // - 'datamodel' => array( - ), - 'webservice' => array( - - ), - 'data.struct' => array( + 'datamodel' => [ + ], + 'webservice' => [ + + ], + 'data.struct' => [ // add your 'structure' definition XML files here, - ), - 'data.sample' => array( + ], + 'data.sample' => [ // add your sample data XML files here, - ), - + ], + // Documentation // 'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any - 'doc.more_information' => '', // hyperlink to more information, if any + 'doc.more_information' => '', // hyperlink to more information, if any // Default settings // - 'settings' => array( + 'settings' => [ // Module specific settings go here, if any - ), - ) + ], + ] ); -if (!class_exists('EndUserMgmtInstaller')) -{ +if (!class_exists('EndUserMgmtInstaller')) { // Module installation handler // class EndUserMgmtInstaller extends ModuleInstallerAPI @@ -88,13 +88,12 @@ if (!class_exists('EndUserMgmtInstaller')) */ public static function BeforeDatabaseCreation(Config $oConfiguration, $sPreviousVersion, $sCurrentVersion) { - if (strlen($sPreviousVersion) > 0) - { + if (strlen($sPreviousVersion) > 0) { // If you want to migrate data from one format to another, do it here self::RenameClassInDB('IpPhone', 'IPPhone'); } } - + /** * Handler called after the creation/update of the database schema * @param $oConfiguration Config The new configuration of the application @@ -106,4 +105,3 @@ if (!class_exists('EndUserMgmtInstaller')) } } } - diff --git a/datamodels/2.x/itop-faq-light/module.itop-faq-light.php b/datamodels/2.x/itop-faq-light/module.itop-faq-light.php index d599034b2..476a797f3 100755 --- a/datamodels/2.x/itop-faq-light/module.itop-faq-light.php +++ b/datamodels/2.x/itop-faq-light/module.itop-faq-light.php @@ -1,10 +1,9 @@ 'Frequently Asked Questions Database', @@ -12,24 +11,24 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( + 'dependencies' => [ 'itop-structure/3.0.0 || itop-portal/3.0.0', - ), + ], 'mandatory' => false, 'visible' => true, 'installer' => 'FAQLightInstaller', // Components // - 'datamodel' => array( - ), - 'data.struct' => array( + 'datamodel' => [ + ], + 'data.struct' => [ //'data.struct.itop-knownerror-mgmt.xml', - ), - 'data.sample' => array( + ], + 'data.sample' => [ 'data.sample.faq-domains.xml', - ), - + ], + // Documentation // 'doc.manual_setup' => '', // No manual installation instructions @@ -37,13 +36,12 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array( - ), - ) + 'settings' => [ + ], + ] ); -if (!class_exists('FAQLightInstaller')) -{ +if (!class_exists('FAQLightInstaller')) { // Module installation handler // class FAQLightInstaller extends ModuleInstallerAPI @@ -62,13 +60,12 @@ if (!class_exists('FAQLightInstaller')) */ public static function BeforeDatabaseCreation(Config $oConfiguration, $sPreviousVersion, $sCurrentVersion) { - if (strlen($sPreviousVersion) > 0) - { + if (strlen($sPreviousVersion) > 0) { // If you want to migrate data from one format to another, do it here self::RenameClassInDB('FAQcategory', 'FAQCategory'); } } - + /** * Handler called after the creation/update of the database schema * @param $oConfiguration Config The new configuration of the application diff --git a/datamodels/2.x/itop-files-information/module.itop-files-information.php b/datamodels/2.x/itop-files-information/module.itop-files-information.php index 188b35aba..05d1b03c2 100644 --- a/datamodels/2.x/itop-files-information/module.itop-files-information.php +++ b/datamodels/2.x/itop-files-information/module.itop-files-information.php @@ -1,4 +1,5 @@ 'iTop files information', @@ -33,22 +34,22 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( - ), + 'dependencies' => [ + ], 'mandatory' => false, 'visible' => false, // Components // - 'datamodel' => array( - 'src/Service/FilesInformation.php', - 'src/Service/FilesInformationException.php', + 'datamodel' => [ + 'src/Service/FilesInformation.php', + 'src/Service/FilesInformationException.php', 'src/Service/FilesInformationUtils.php', 'src/Service/FilesIntegrity.php', - ), - 'webservice' => array(), - 'data.struct' => array(), - 'data.sample' => array(), + ], + 'webservice' => [], + 'data.struct' => [], + 'data.sample' => [], // Documentation // @@ -57,6 +58,6 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array(), - ) + 'settings' => [], + ] ); diff --git a/datamodels/2.x/itop-full-itil/module.itop-full-itil.php b/datamodels/2.x/itop-full-itil/module.itop-full-itil.php index daa46e691..c69f0a01e 100644 --- a/datamodels/2.x/itop-full-itil/module.itop-full-itil.php +++ b/datamodels/2.x/itop-full-itil/module.itop-full-itil.php @@ -7,35 +7,35 @@ SetupWebPage::AddModule( __FILE__, // Path to the current file, all other file names are relative to the directory containing this file 'itop-full-itil/3.3.0', - array( + [ // Identification // 'label' => 'Bridge - Request management ITIL + Incident management ITIL', 'category' => 'business', // Setup // - 'dependencies' => array( + 'dependencies' => [ 'itop-request-mgmt-itil/2.3.0', 'itop-incident-mgmt-itil/2.3.0', - ), + ], 'mandatory' => false, 'visible' => false, 'auto_select' => 'SetupInfo::ModuleIsSelected("itop-request-mgmt-itil") && SetupInfo::ModuleIsSelected("itop-incident-mgmt-itil")', // Components // - 'datamodel' => array(), - 'webservice' => array(), - 'data.struct' => array(// add your 'structure' definition XML files here, - ), - 'data.sample' => array(// add your sample data XML files here, - ), + 'datamodel' => [], + 'webservice' => [], + 'data.struct' => [// add your 'structure' definition XML files here, + ], + 'data.sample' => [// add your sample data XML files here, + ], // Documentation // 'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any 'doc.more_information' => '', // hyperlink to more information, if any // Default settings // - 'settings' => array(// Module specific settings go here, if any - ), - ) + 'settings' => [// Module specific settings go here, if any + ], + ] ); diff --git a/datamodels/2.x/itop-hub-connector/ajax.php b/datamodels/2.x/itop-hub-connector/ajax.php index ba9ad6507..33ac5940b 100644 --- a/datamodels/2.x/itop-hub-connector/ajax.php +++ b/datamodels/2.x/itop-hub-connector/ajax.php @@ -1,4 +1,5 @@ SetMySQLBinDir(MetaModel::GetConfig()->GetModuleSetting('itop-backup', 'mysql_bindir', '')); $sSourceConfigFile = APPCONF.utils::GetCurrentEnvironment().'/'.ITOP_CONFIG_FILE; - + $oMutex = new iTopMutex('backup.'.utils::GetCurrentEnvironment()); $oMutex->Lock(); - try - { + try { $oBackup->CreateCompressedBackup($sTargetFile, $sSourceConfigFile); - } - catch (Exception $e) - { + } catch (Exception $e) { $oMutex->Unlock(); throw $e; } @@ -101,22 +98,22 @@ function DoBackup($sTargetFile) /** * Outputs the status of the current ajax execution (as a JSON structure) - * + * * @param string $sMessage * @param bool $bSuccess * @param number $iErrorCode * @param array $aMoreFields * Extra fields to pass to the caller, if needed */ -function ReportStatus($sMessage, $bSuccess, $iErrorCode = 0, $aMoreFields = array()) +function ReportStatus($sMessage, $bSuccess, $iErrorCode = 0, $aMoreFields = []) { // Do not use AjaxPage during setup phases, because it uses InterfaceDiscovery in Twig compilation $oPage = new JsonPage(); - $aResult = array( + $aResult = [ 'code' => $iErrorCode, 'message' => $sMessage, - 'fields' => $aMoreFields - ); + 'fields' => $aMoreFields, + ]; $oPage->SetData($aResult); $oPage->SetOutputDataOnly(true); $oPage->output(); @@ -124,154 +121,137 @@ function ReportStatus($sMessage, $bSuccess, $iErrorCode = 0, $aMoreFields = arra /** * Helper to output the status of a successful execution - * + * * @param string $sMessage * @param array $aMoreFields * Extra fields to pass to the caller, if needed */ -function ReportSuccess($sMessage, $aMoreFields = array()) +function ReportSuccess($sMessage, $aMoreFields = []) { ReportStatus($sMessage, true, 0, $aMoreFields); } /** * Helper to output the status of a failed execution - * + * * @param string $sMessage * @param number $iErrorCode * @param array $aMoreFields * Extra fields to pass to the caller, if needed */ -function ReportError($sMessage, $iErrorCode, $aMoreFields = array()) +function ReportError($sMessage, $iErrorCode, $aMoreFields = []) { - if ($iErrorCode==0) - { + if ($iErrorCode == 0) { // 0 means no error, so change it if no meaningful error code is supplied $iErrorCode = -1; } ReportStatus($sMessage, false, $iErrorCode, $aMoreFields); } -try -{ +try { SetupUtils::ExitMaintenanceMode(false); // Reset maintenance mode in case of problem utils::PushArchiveMode(false); - + ini_set('max_execution_time', max(3600, ini_get('max_execution_time'))); // Under Windows SQL/backup operations are part of the PHP timeout and require extra time ini_set('display_errors', 1); // Make sure that fatal errors remain visible from the end-user - + // Most of the ajax calls are done without the MetaModel being loaded - // Therefore, the language must be passed as an argument, - // and the dictionnaries be loaded here + // Therefore, the language must be passed as an argument, + // and the dictionnaries be loaded here $sLanguage = utils::ReadParam('language', ''); - if ($sLanguage!='') - { - foreach (glob(APPROOT.'env-production/dictionaries/*.dict.php') as $sFilePath) - { - require_once ($sFilePath); + if ($sLanguage != '') { + foreach (glob(APPROOT.'env-production/dictionaries/*.dict.php') as $sFilePath) { + require_once($sFilePath); } - + $aLanguages = Dict::GetLanguages(); - if (array_key_exists($sLanguage, $aLanguages)) - { + if (array_key_exists($sLanguage, $aLanguages)) { Dict::SetUserLanguage($sLanguage); } } $sOperation = utils::ReadParam('operation', ''); - switch ($sOperation) - { + switch ($sOperation) { case 'check_before_backup': - require_once (APPROOT.'/application/startup.inc.php'); - require_once (APPROOT.'/application/loginwebpage.class.inc.php'); + require_once(APPROOT.'/application/startup.inc.php'); + require_once(APPROOT.'/application/loginwebpage.class.inc.php'); LoginWebPage::DoLogin(true); // Check user rights and prompt if needed (must be admin) $sDBBackupPath = utils::GetDataPath().'backups/manual'; $aChecks = SetupUtils::CheckBackupPrerequisites($sDBBackupPath); $bFailed = false; - foreach ($aChecks as $oCheckResult) - { - if ($oCheckResult->iSeverity==CheckResult::ERROR) - { + foreach ($aChecks as $oCheckResult) { + if ($oCheckResult->iSeverity == CheckResult::ERROR) { $bFailed = true; ReportError($oCheckResult->sLabel, -2); } } - if (!$bFailed) - { + if (!$bFailed) { // Continue the checks $fFreeSpace = SetupUtils::CheckDiskSpace($sDBBackupPath); - if ($fFreeSpace!==false) - { + if ($fFreeSpace !== false) { $sMessage = Dict::Format('iTopHub:BackupFreeDiskSpaceIn', SetupUtils::HumanReadableSize($fFreeSpace), dirname($sDBBackupPath)); ReportSuccess($sMessage); - } - else - { + } else { ReportError(Dict::S('iTopHub:FailedToCheckFreeDiskSpace'), -1); } } - break; - + break; + case 'do_backup': - require_once (APPROOT.'/application/startup.inc.php'); - require_once (APPROOT.'/application/loginwebpage.class.inc.php'); + require_once(APPROOT.'/application/startup.inc.php'); + require_once(APPROOT.'/application/loginwebpage.class.inc.php'); LoginWebPage::DoLogin(true); // Check user rights and prompt if needed (must be admin) - try - { - if (MetaModel::GetConfig()->Get('demo_mode')) throw new Exception('Sorry the installation of extensions is not allowed in demo mode'); + try { + if (MetaModel::GetConfig()->Get('demo_mode')) { + throw new Exception('Sorry the installation of extensions is not allowed in demo mode'); + } SetupLog::Info('Backup starts...'); set_time_limit(0); $sBackupPath = APPROOT.'/data/backups/manual/backup-'; $iSuffix = 1; $sSuffix = ''; // Generate a unique name... - do - { + do { $sBackupFile = $sBackupPath.date('Y-m-d-His').$sSuffix; $sSuffix = '-'.$iSuffix; $iSuffix++ ; - } - while (file_exists($sBackupFile)); + } while (file_exists($sBackupFile)); $oBackup = DoBackup($sBackupFile); $aErrors = $oBackup->GetErrors(); - if (count($aErrors)>0) - { + if (count($aErrors) > 0) { SetupLog::Error('Backup failed.'); SetupLog::Error(implode("\n", $aErrors)); - ReportError(Dict::S('iTopHub:BackupFailed'), -1, $aErrors); - } - else - { + ReportError(Dict::S('iTopHub:BackupFailed'), -1, $aErrors); + } else { SetupLog::Info('Backup successfully completed.'); ReportSuccess(Dict::S('iTopHub:BackupOk')); } - } - catch (Exception $e) - { + } catch (Exception $e) { SetupLog::Error($e->getMessage()); ReportError($e->getMessage(), $e->getCode()); } - break; - + break; + case 'compile': SetupLog::Info('Deployment starts...'); $sAuthent = utils::ReadParam('authent', '', false, 'raw_data'); - if (!file_exists(utils::GetDataPath().'hub/compile_authent') || $sAuthent !== file_get_contents(utils::GetDataPath().'hub/compile_authent')) - { - throw new SecurityException(Dict::S('iTopHub:FailAuthent')); + if (!file_exists(utils::GetDataPath().'hub/compile_authent') || $sAuthent !== file_get_contents(utils::GetDataPath().'hub/compile_authent')) { + throw new SecurityException(Dict::S('iTopHub:FailAuthent')); } // First step: prepare the datamodel, if it fails, roll-back - $aSelectedExtensionCodes = utils::ReadParam('extension_codes', array()); - $aSelectedExtensionDirs = utils::ReadParam('extension_dirs', array()); + $aSelectedExtensionCodes = utils::ReadParam('extension_codes', []); + $aSelectedExtensionDirs = utils::ReadParam('extension_dirs', []); $oRuntimeEnv = new HubRunTimeEnvironment('production', false); // use a temp environment: production-build $oRuntimeEnv->MoveSelectedExtensions(APPROOT.'/data/downloaded-extensions/', $aSelectedExtensionDirs); $oConfig = new Config(APPCONF.'production/'.ITOP_CONFIG_FILE); - if ($oConfig->Get('demo_mode')) throw new Exception('Sorry the installation of extensions is not allowed in demo mode'); + if ($oConfig->Get('demo_mode')) { + throw new Exception('Sorry the installation of extensions is not allowed in demo mode'); + } $aSelectModules = $oRuntimeEnv->CompileFrom('production', false); // WARNING symlinks does not seem to be compatible with manual Commit @@ -289,21 +269,19 @@ try $oRuntimeEnv->Commit(); // Report the success in a way that will be detected by the ajax caller - SetupLog::Info('Compilation completed...'); + SetupLog::Info('Compilation completed...'); ReportSuccess('Ok'); // No access to Dict::S here - break; - + break; + case 'move_to_production': // Second step: update the schema and the data // Everything happening below is based on env-production $oRuntimeEnv = new RunTimeEnvironment('production', true); - try - { + try { SetupLog::Info('Move to production starts...'); - $sAuthent = utils::ReadParam('authent', '', false, 'raw_data'); - if (!file_exists(utils::GetDataPath().'hub/compile_authent') || $sAuthent !== file_get_contents(utils::GetDataPath().'hub/compile_authent')) - { + $sAuthent = utils::ReadParam('authent', '', false, 'raw_data'); + if (!file_exists(utils::GetDataPath().'hub/compile_authent') || $sAuthent !== file_get_contents(utils::GetDataPath().'hub/compile_authent')) { throw new SecurityException(Dict::S('iTopHub:FailAuthent')); } unlink(utils::GetDataPath().'hub/compile_authent'); @@ -315,15 +293,11 @@ try $aAvailableModules = $oRuntimeEnv->AnalyzeInstallation($oConfig, $oRuntimeEnv->GetBuildDir(), true); - $aSelectedModules = array(); - foreach ($aAvailableModules as $sModuleId => $aModule) - { - if (($sModuleId == ROOT_MODULE) || ($sModuleId == DATAMODEL_MODULE)) - { + $aSelectedModules = []; + foreach ($aAvailableModules as $sModuleId => $aModule) { + if (($sModuleId == ROOT_MODULE) || ($sModuleId == DATAMODEL_MODULE)) { continue; - } - else - { + } else { $aSelectedModules[] = $sModuleId; } } @@ -349,17 +323,14 @@ try // Default choices = as before $oExtensionsMap->LoadChoicesFromDatabase($oConfig); - foreach ($oExtensionsMap->GetAllExtensions() as $oExtension) - { + foreach ($oExtensionsMap->GetAllExtensions() as $oExtension) { // Plus all "remote" extensions - if ($oExtension->sSource==iTopExtension::SOURCE_REMOTE) - { + if ($oExtension->sSource == iTopExtension::SOURCE_REMOTE) { $oExtensionsMap->MarkAsChosen($oExtension->sCode); } } - $aSelectedExtensionCodes = array(); - foreach ($oExtensionsMap->GetChoices() as $oExtension) - { + $aSelectedExtensionCodes = []; + foreach ($oExtensionsMap->GetChoices() as $oExtension) { $aSelectedExtensionCodes[] = $oExtension->sCode; } $aSelectedExtensions = $oExtensionsMap->GetChoices(); @@ -368,34 +339,27 @@ try // Report the success in a way that will be detected by the ajax caller SetupLog::Info('Deployment successfully completed.'); ReportSuccess(Dict::S('iTopHub:CompiledOK')); - } - catch (Exception $e) - { - if(file_exists(utils::GetDataPath().'hub/compile_authent')) - { + } catch (Exception $e) { + if (file_exists(utils::GetDataPath().'hub/compile_authent')) { unlink(utils::GetDataPath().'hub/compile_authent'); } // Note: at this point, the dictionnary is not necessarily loaded SetupLog::Error(get_class($e).': '.Dict::S('iTopHub:ConfigurationSafelyReverted')."\n".$e->getMessage()); SetupLog::Error('Debug trace: '.$e->getTraceAsString()); ReportError($e->getMessage(), $e->getCode()); - } - finally - { + } finally { SetupUtils::ExitReadOnlyMode(); } - break; - + break; + default: ReportError("Invalid operation: '$sOperation'", -1); } -} -catch (Exception $e) -{ +} catch (Exception $e) { SetupLog::Error(get_class($e).': '.Dict::S('iTopHub:ConfigurationSafelyReverted')."\n".$e->getMessage()); SetupLog::Error('Debug trace: '.$e->getTraceAsString()); - + utils::PopArchiveMode(); - + ReportError($e->getMessage(), $e->getCode()); } diff --git a/datamodels/2.x/itop-hub-connector/dictionaries/pt_br.dict.itop-hub-connector.php b/datamodels/2.x/itop-hub-connector/dictionaries/pt_br.dict.itop-hub-connector.php index 419c534a6..cc5596bd7 100644 --- a/datamodels/2.x/itop-hub-connector/dictionaries/pt_br.dict.itop-hub-connector.php +++ b/datamodels/2.x/itop-hub-connector/dictionaries/pt_br.dict.itop-hub-connector.php @@ -1,15 +1,16 @@ 'iTop Hub', 'Menu:iTopHub:Register' => 'Conectar ao iTop Hub', 'Menu:iTopHub:Register+' => 'Vá para o iTop Hub para atualizar sua instância '.ITOP_APPLICATION_SHORT, @@ -64,4 +65,4 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'iTopHub:InstallationStatus:Installed_Version' => '%1$s versão: %2$s', 'iTopHub:InstallationStatus:Installed' => 'Instalado', 'iTopHub:InstallationStatus:Version_NotInstalled' => 'Versão %1$s NÃO instalada', -)); +]); diff --git a/datamodels/2.x/itop-hub-connector/land.php b/datamodels/2.x/itop-hub-connector/land.php index 1d55e431f..2e6760c60 100644 --- a/datamodels/2.x/itop-hub-connector/land.php +++ b/datamodels/2.x/itop-hub-connector/land.php @@ -16,7 +16,7 @@ function DisplayStatus(WebPage $oPage) $oPage->add('
'); // Now scan the extensions and display a report of the extensions brought by the hub $sPath = utils::GetDataPath().'downloaded-extensions/'; - $aExtraDirs = array(); + $aExtraDirs = []; if (is_dir($sPath)) { $aExtraDirs[] = $sPath; // Also read the extra downloaded-modules directory } @@ -25,7 +25,7 @@ function DisplayStatus(WebPage $oPage) foreach ($oExtensionsMap->GetAllExtensions() as $oExtension) { if ($oExtension->sSource == iTopExtension::SOURCE_REMOTE) { - $aCSSClasses = array('landing-extension'); + $aCSSClasses = ['landing-extension']; if ($oExtension->sInstalledVersion === '') { $aCSSClasses[] = 'landing-installation'; $sInstallation = Dict::Format('iTopHub:InstallationStatus:Version_NotInstalled', $oExtension->sVersion); @@ -68,12 +68,11 @@ function DoLanding(WebPage $oPage) $oPage->add('

'.Dict::S('iTopHub:Uncompressing').'

'); - $sProduct = utils::ReadParam('applicationName', '', false, 'raw_data'); $sVersion = utils::ReadParam('applicationVersion', '', false, 'raw_data'); $sInstanceUUID = utils::ReadParam('uuidFile', '', false, 'raw_data'); $sDatabaseUUID = utils::ReadParam('uuidBdd', '', false, 'raw_data'); - $aExtensions = utils::ReadParam('extensions', array(), false, 'raw_data'); + $aExtensions = utils::ReadParam('extensions', [], false, 'raw_data'); // Basic consistency validation if ($sProduct != ITOP_APPLICATION) { @@ -128,7 +127,7 @@ function DoLanding(WebPage $oPage) } // Now scan the extensions and display a report of the extensions brought by the hub - $sNextPage = utils::GetAbsoluteUrlModulePage('itop-hub-connector', 'land.php', array('operation' => 'install')); + $sNextPage = utils::GetAbsoluteUrlModulePage('itop-hub-connector', 'land.php', ['operation' => 'install']); $oPage->add_ready_script("window.location.href='$sNextPage'"); } @@ -148,11 +147,10 @@ function DoInstall(WebPage $oPage) $oPage->set_title(Dict::S('iTopHub:Landing:Install')); $oPage->add('
'); - // Now scan the extensions and display a report of the extensions brought by the hub // Now scan the extensions and display a report of the extensions brought by the hub $sPath = utils::GetDataPath().'downloaded-extensions/'; - $aExtraDirs = array(); + $aExtraDirs = []; if (is_dir($sPath)) { $aExtraDirs[] = $sPath; // Also read the extra downloaded-modules directory } @@ -175,14 +173,14 @@ function DoInstall(WebPage $oPage) $oPage->add('
'); $oPage->add('
'); } else { - $aCSSClasses = array('landing-extension'); + $aCSSClasses = ['landing-extension']; if ($oExtension->sInstalledVersion === '') { $aCSSClasses[] = 'landing-installation'; $sInstallation = Dict::Format('iTopHub:InstallationEffect:Install', $oExtension->sVersion); - } else if ($oExtension->sInstalledVersion == $oExtension->sVersion) { + } elseif ($oExtension->sInstalledVersion == $oExtension->sVersion) { $aCSSClasses[] = 'landing-no-change'; $sInstallation = Dict::Format('iTopHub:InstallationEffect:NoChange', $oExtension->sVersion); - } else if (version_compare($oExtension->sInstalledVersion, $oExtension->sVersion, '<')) { + } elseif (version_compare($oExtension->sInstalledVersion, $oExtension->sVersion, '<')) { $aCSSClasses[] = 'landing-upgrade'; $sInstallation = Dict::Format('iTopHub:InstallationEffect:Upgrade', $oExtension->sInstalledVersion, $oExtension->sVersion); } else { @@ -213,10 +211,8 @@ function DoInstall(WebPage $oPage) $oPage->add(''); // module-selection-body - $oPage->LinkStylesheetFromAppRoot('css/font-awesome/css/all.min.css'); - $oPage->add('
'); $oPage->add('
'.Dict::S('iTopHub:DBBackupLabel').''); $oPage->add('
'); @@ -224,22 +220,22 @@ function DoInstall(WebPage $oPage) $oPage->add('
'); $oPage->add('

'); - $sIframeUrl = utils::GetAbsoluteUrlModulePage('itop-hub-connector', 'launch.php', array('target' => 'inform_after_setup')); - $sStatusPageUrl = utils::GetAbsoluteUrlModulePage('itop-hub-connector', 'land.php', array('operation' => 'done')); + $sIframeUrl = utils::GetAbsoluteUrlModulePage('itop-hub-connector', 'launch.php', ['target' => 'inform_after_setup']); + $sStatusPageUrl = utils::GetAbsoluteUrlModulePage('itop-hub-connector', 'land.php', ['operation' => 'done']); - $aWidgetParams = array( - 'self_url' => utils::GetAbsoluteUrlModulePage('itop-hub-connector', 'ajax.php', array('maintenance' => true)), + $aWidgetParams = [ + 'self_url' => utils::GetAbsoluteUrlModulePage('itop-hub-connector', 'ajax.php', ['maintenance' => true]), 'iframe_url' => $sIframeUrl, 'redirect_after_completion_url' => $sStatusPageUrl, 'mysql_bindir' => MetaModel::GetConfig()->GetModuleSetting('itop-backup', 'mysql_bindir', ''), - 'labels' => array( + 'labels' => [ 'database_backup' => Dict::S('iTopHub:InstallationProgress:DatabaseBackup'), 'extensions_installation' => Dict::S('iTopHub:InstallationProgress:ExtensionsInstallation'), 'installation_successful' => Dict::S('iTopHub:InstallationProgress:InstallationSuccessful'), 'rollback' => Dict::S('iTopHub:ConfigurationSafelyReverted'), - ), + ], 'authent' => $sUID, - ); + ]; $sWidgetParams = json_encode($aWidgetParams); @@ -249,7 +245,6 @@ function DoInstall(WebPage $oPage) $oPage->add('
'); } - try { require_once(APPROOT.'/application/application.inc.php'); require_once(APPROOT.'/setup/setuppage.class.inc.php'); @@ -266,7 +261,8 @@ try { $oPage->LinkScriptFromModule('itop-hub-connector/js/hub.js'); $oPage->LinkStylesheetFromAppRoot('css/font-combodo/font-combodo.css'); - $oPage->add_style(<<add_style( + <<output(); -} -catch (Exception $e) { +} catch (Exception $e) { require_once(APPROOT.'/setup/setuppage.class.inc.php'); $oP = new ErrorPage(Dict::S('UI:PageTitle:FatalError')); $oP->add("

".Dict::S('UI:FatalErrorMessage')."

\n"); @@ -312,7 +307,7 @@ catch (Exception $e) { $oLog->Set('issue', 'PHP Exception'); $oLog->Set('impact', 'Page could not be displayed'); $oLog->Set('callstack', $e->getTrace()); - $oLog->Set('data', array()); + $oLog->Set('data', []); $oLog->DBInsertNoReload(); } diff --git a/datamodels/2.x/itop-hub-connector/launch.php b/datamodels/2.x/itop-hub-connector/launch.php index 32c542f44..8797cf38f 100644 --- a/datamodels/2.x/itop-hub-connector/launch.php +++ b/datamodels/2.x/itop-hub-connector/launch.php @@ -114,7 +114,7 @@ use Combodo\iTop\Application\WebPage\NiceWebPage; */ function CleanVersionNumber($sString) { - $aMatches = array(); + $aMatches = []; if (preg_match("|^([0-9\\.]+)-|", $sString, $aMatches)) { return $aMatches[1]; } @@ -124,11 +124,11 @@ function CleanVersionNumber($sString) function collect_configuration() { - $aConfiguration = array( - 'php' => array(), - 'mysql' => array(), - 'apache' => array(), - ); + $aConfiguration = [ + 'php' => [], + 'mysql' => [], + 'apache' => [], + ]; // Database information $m_oMysqli = CMDBSource::GetMysqli(); @@ -170,7 +170,7 @@ function collect_configuration() // PHP extensions if (!MetaModel::GetConfig()->GetModuleSetting('itop-hub-connector', 'php_extensions_enable', true)) { - $aConfiguration['php_extensions'] = array(); + $aConfiguration['php_extensions'] = []; } else { foreach (get_loaded_extensions() as $extension) { $aConfiguration['php_extensions'][$extension] = $extension; @@ -178,8 +178,8 @@ function collect_configuration() } // Collect some PHP settings having a known impact on iTop - $aIniGet = MetaModel::GetConfig()->GetModuleSetting('itop-hub-connector', 'php_settings_array', array()); // by default, on the time of the writting, it values are : array('post_max_size', 'upload_max_filesize', 'apc.enabled', 'timezone', 'memory_limit', 'max_execution_time'); - $aConfiguration['php_settings'] = array(); + $aIniGet = MetaModel::GetConfig()->GetModuleSetting('itop-hub-connector', 'php_settings_array', []); // by default, on the time of the writting, it values are : array('post_max_size', 'upload_max_filesize', 'apc.enabled', 'timezone', 'memory_limit', 'max_execution_time'); + $aConfiguration['php_settings'] = []; foreach ($aIniGet as $iniGet) { $aConfiguration['php_settings'][$iniGet] = (string)ini_get($iniGet); } @@ -197,22 +197,22 @@ function collect_configuration() // iTop Installation Options, i.e. "Extensions" $oExtensionMap = new iTopExtensionsMap(); $oExtensionMap->LoadChoicesFromDatabase($oConfig); - $aConfiguration['itop_extensions'] = array(); + $aConfiguration['itop_extensions'] = []; foreach ($oExtensionMap->GetChoices() as $oExtension) { switch ($oExtension->sSource) { case iTopExtension::SOURCE_MANUAL: case iTopExtension::SOURCE_REMOTE: - $aConfiguration['itop_extensions'][$oExtension->sCode] = array( + $aConfiguration['itop_extensions'][$oExtension->sCode] = [ 'label' => $oExtension->sLabel, 'value' => $oExtension->sInstalledVersion, - ); + ]; break; default: - $aConfiguration['itop_installation_options'][$oExtension->sCode] = array( + $aConfiguration['itop_installation_options'][$oExtension->sCode] = [ 'label' => $oExtension->sLabel, 'value' => true, - ); + ]; } } @@ -223,13 +223,13 @@ function MakeDataToPost($sTargetRoute) { if (MetaModel::GetConfig()->Get('demo_mode')) { // Don't expose such information in demo mode - $aDataToPost = array('disabled' => true, 'reason' => 'demo_mode'); + $aDataToPost = ['disabled' => true, 'reason' => 'demo_mode']; } else { $aConfiguration = collect_configuration(); - $aDataToPost = array( + $aDataToPost = [ 'itop_hub_target_route' => $sTargetRoute, - 'itop_stack' => array( + 'itop_stack' => [ "uuidBdd" => (string)trim(DBProperty::GetProperty('database_uuid', ''), '{}'), // TODO check if empty and... regenerate a new UUID ?? "uuidFile" => (string)trim(@file_get_contents(utils::GetDataPath()."instance.txt"), "{} \n"), // TODO check if empty and... regenerate a new UUID ?? 'instance_friendly_name' => (string)$_SERVER['SERVER_NAME'], @@ -242,8 +242,8 @@ function MakeDataToPost($sTargetRoute) 'itop_modules' => (object)$aConfiguration['itop_modules'], 'itop_extensions' => (object)$aConfiguration['itop_extensions'], 'itop_installation_options' => (object)$aConfiguration['itop_installation_options'], - ), - 'server_stack' => array( + ], + 'server_stack' => [ 'os_name' => (string)PHP_OS, 'web_server_name' => (string)$aConfiguration['web_server_name'], 'web_server_version' => (string)$aConfiguration['web_server_version'], @@ -253,8 +253,8 @@ function MakeDataToPost($sTargetRoute) 'php_version' => (string)CleanVersionNumber(phpversion()), 'php_settings' => (object)$aConfiguration['php_settings'], 'php_extensions' => (object)$aConfiguration['php_extensions'], - ), - ); + ], + ]; } return $aDataToPost; @@ -282,21 +282,21 @@ try { switch ($sTargetRoute) { case 'inform_after_setup': - // Hidden IFRAME at the end of the setup - $sParamToken = utils::ReadParam('setup_token'); - $oTokenValidation = new TokenValidation(); - $bIsTokenValid = $oTokenValidation->isSetupTokenValid($sParamToken); - if (UserRights::IsAdministrator() || $bIsTokenValid) { - $oPage = new NiceWebPage(''); - $aDataToPost = MakeDataToPost($sTargetRoute); - $oPage->add('
'); - $oPage->add(''); - $oPage->add_ready_script('$("#hub_launch_form").trigger(\'submit\');'); - } else { - IssueLog::Error('TokenValidation failed on inform_after_setup page'); - throw new Exception("Not allowed"); - } - break; + // Hidden IFRAME at the end of the setup + $sParamToken = utils::ReadParam('setup_token'); + $oTokenValidation = new TokenValidation(); + $bIsTokenValid = $oTokenValidation->isSetupTokenValid($sParamToken); + if (UserRights::IsAdministrator() || $bIsTokenValid) { + $oPage = new NiceWebPage(''); + $aDataToPost = MakeDataToPost($sTargetRoute); + $oPage->add(''); + $oPage->add(''); + $oPage->add_ready_script('$("#hub_launch_form").trigger(\'submit\');'); + } else { + IssueLog::Error('TokenValidation failed on inform_after_setup page'); + throw new Exception("Not allowed"); + } + break; default: // All other cases, special "Hub like" web page @@ -335,7 +335,8 @@ try { $sButtonLabelClose = Dict::S('iTopHub:CloseBtn'); $sButtonLabelGo = Dict::S('iTopHub:GoBtn'); $sButtonLabelTooltip = Dict::S('iTopHub:GoBtn:Tooltip'); - $oPage->add(<<add( + << @@ -403,8 +404,7 @@ JS } $oPage->output(); -} -catch (CoreException $e) { +} catch (CoreException $e) { require_once(APPROOT.'/setup/setuppage.class.inc.php'); $oP = new ErrorPage(Dict::S('UI:PageTitle:FatalError')); $oP->add("

".Dict::S('UI:FatalErrorMessage')."

\n"); @@ -429,8 +429,7 @@ catch (CoreException $e) { // For debugging only // throw $e; -} -catch (Exception $e) { +} catch (Exception $e) { require_once(APPROOT.'/setup/setuppage.class.inc.php'); $oP = new ErrorPage(Dict::S('UI:PageTitle:FatalError')); $oP->add("

".Dict::S('UI:FatalErrorMessage')."

\n"); @@ -446,11 +445,10 @@ catch (Exception $e) { $oLog->Set('issue', 'PHP Exception'); $oLog->Set('impact', 'Page could not be displayed'); $oLog->Set('callstack', $e->getTrace()); - $oLog->Set('data', array()); + $oLog->Set('data', []); $oLog->DBInsertNoReload(); } IssueLog::Error($e->getMessage()); } } - diff --git a/datamodels/2.x/itop-hub-connector/module.itop-hub-connector.php b/datamodels/2.x/itop-hub-connector/module.itop-hub-connector.php index b2d64dda1..70521511c 100644 --- a/datamodels/2.x/itop-hub-connector/module.itop-hub-connector.php +++ b/datamodels/2.x/itop-hub-connector/module.itop-hub-connector.php @@ -1,4 +1,5 @@ 'iTop Hub Connector', @@ -14,31 +15,31 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( + 'dependencies' => [ 'itop-config-mgmt/2.4.0', // Actually this module requires iTop 2.4.1 minimum - ), + ], 'mandatory' => false, 'visible' => true, // Components // - 'datamodel' => array( + 'datamodel' => [ 'menus.php', - 'hubnewsroomprovider.class.inc.php', - ), - 'webservice' => array( - - ), - 'data.struct' => array( + 'hubnewsroomprovider.class.inc.php', + ], + 'webservice' => [ + + ], + 'data.struct' => [ // add your 'structure' definition XML files here, - ), - 'data.sample' => array( + ], + 'data.sample' => [ // add your sample data XML files here, - ), - + ], + // Documentation // 'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any - 'doc.more_information' => '', // hyperlink to more information, if any - ) + 'doc.more_information' => '', // hyperlink to more information, if any + ] ); diff --git a/datamodels/2.x/itop-incident-mgmt-itil/dictionaries/it.dict.itop-incident-mgmt-itil.php b/datamodels/2.x/itop-incident-mgmt-itil/dictionaries/it.dict.itop-incident-mgmt-itil.php index 474317008..1d85a4677 100644 --- a/datamodels/2.x/itop-incident-mgmt-itil/dictionaries/it.dict.itop-incident-mgmt-itil.php +++ b/datamodels/2.x/itop-incident-mgmt-itil/dictionaries/it.dict.itop-incident-mgmt-itil.php @@ -1,15 +1,16 @@ 'Gestione incidente', 'Menu:IncidentManagement+' => 'Gestione incidente', 'Menu:Incident:Overview' => 'Overview', @@ -31,8 +32,7 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'UI-IncidentManagementOverview-OpenIncidentByStatus' => 'Incidenti aperti per stato', 'UI-IncidentManagementOverview-OpenIncidentByAgent' => 'Incidenti aperti per agente', 'UI-IncidentManagementOverview-OpenIncidentByCustomer' => 'Incidenti aperti per cliente', -)); - +]); // Dictionnay conventions // Class: @@ -48,7 +48,7 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( // Class: Incident // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:Incident' => 'Incidente', 'Class:Incident+' => '~~', 'Class:Incident/Attribute:status' => 'Stato', @@ -227,4 +227,4 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:Incident/Method:ResolveChildTickets' => 'ResolveChildTickets~~', 'Class:Incident/Method:ResolveChildTickets+' => 'Risoluzione a cascata delle richieste figlie (ev_autoresolve), e allineare le seguenti caratteristiche: servizio, team, agente e risoluzione', 'Tickets:Related:OpenIncidents' => 'Incidenti aperti', -)); +]); diff --git a/datamodels/2.x/itop-incident-mgmt-itil/module.itop-incident-mgmt-itil.php b/datamodels/2.x/itop-incident-mgmt-itil/module.itop-incident-mgmt-itil.php index 9fee1f7d3..fa0902fd3 100755 --- a/datamodels/2.x/itop-incident-mgmt-itil/module.itop-incident-mgmt-itil.php +++ b/datamodels/2.x/itop-incident-mgmt-itil/module.itop-incident-mgmt-itil.php @@ -1,10 +1,9 @@ 'Incident Management ITIL', @@ -12,25 +11,25 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( + 'dependencies' => [ 'itop-config-mgmt/2.4.0', 'itop-tickets/2.4.0', 'itop-profiles-itil/2.3.0', - ), + ], 'mandatory' => false, 'visible' => true, // Components // - 'datamodel' => array( - ), - 'data.struct' => array( + 'datamodel' => [ + ], + 'data.struct' => [ - ), - 'data.sample' => array( + ], + 'data.sample' => [ //'data.sample.itop-request-mgmt.xml', - ), - + ], + // Documentation // 'doc.manual_setup' => '', @@ -38,7 +37,7 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array( - ), - ) + 'settings' => [ + ], + ] ); diff --git a/datamodels/2.x/itop-knownerror-mgmt/dictionaries/it.dict.itop-knownerror-mgmt.php b/datamodels/2.x/itop-knownerror-mgmt/dictionaries/it.dict.itop-knownerror-mgmt.php index 6babd13d9..01d9c155c 100644 --- a/datamodels/2.x/itop-knownerror-mgmt/dictionaries/it.dict.itop-knownerror-mgmt.php +++ b/datamodels/2.x/itop-knownerror-mgmt/dictionaries/it.dict.itop-knownerror-mgmt.php @@ -1,15 +1,16 @@ 'Errori conosciuti', 'Class:KnownError+' => 'Errori documentati per problemi noti', 'Class:KnownError/Attribute:name' => 'Nome', @@ -52,13 +53,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:KnownError/Attribute:ci_list+' => 'All the configuration items that are related to this known error~~', 'Class:KnownError/Attribute:document_list' => 'Documenti', 'Class:KnownError/Attribute:document_list+' => 'All the documents linked to this known error~~', -)); +]); // // Class: lnkErrorToFunctionalCI // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:lnkErrorToFunctionalCI' => 'Link Errore /CIFunzionale', 'Class:lnkErrorToFunctionalCI+' => 'Infra impattata dall\'errore conosciuto', 'Class:lnkErrorToFunctionalCI/Name' => '%1$s / %2$s~~', @@ -72,13 +73,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:lnkErrorToFunctionalCI/Attribute:error_name+' => '~~', 'Class:lnkErrorToFunctionalCI/Attribute:reason' => 'Ragione', 'Class:lnkErrorToFunctionalCI/Attribute:reason+' => '~~', -)); +]); // // Class: lnkDocumentToError // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:lnkDocumentToError' => 'Link Documento / Errore', 'Class:lnkDocumentToError+' => 'Link tra il documento e l\'errore conosciuto', 'Class:lnkDocumentToError/Name' => '%1$s / %2$s~~', @@ -92,9 +93,9 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:lnkDocumentToError/Attribute:error_name+' => '~~', 'Class:lnkDocumentToError/Attribute:link_type' => 'link_type', 'Class:lnkDocumentToError/Attribute:link_type+' => '~~', -)); +]); -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Menu:ProblemManagement' => 'Gestione dei problemi', 'Menu:ProblemManagement+' => 'Gestione dei problemi', 'Menu:Problem:Shortcuts' => 'Scorciatoia', @@ -104,4 +105,4 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Menu:SearchError+' => 'Ricerca per errori conosciuti', 'Menu:Problem:KnownErrors' => 'Tutti gli errori conosciuti', 'Menu:Problem:KnownErrors+' => 'Tutti gli errori conosciuti', -)); +]); diff --git a/datamodels/2.x/itop-knownerror-mgmt/dictionaries/pt_br.dict.itop-knownerror-mgmt.php b/datamodels/2.x/itop-knownerror-mgmt/dictionaries/pt_br.dict.itop-knownerror-mgmt.php index 9d6d74cfc..b187c1198 100644 --- a/datamodels/2.x/itop-knownerror-mgmt/dictionaries/pt_br.dict.itop-knownerror-mgmt.php +++ b/datamodels/2.x/itop-knownerror-mgmt/dictionaries/pt_br.dict.itop-knownerror-mgmt.php @@ -1,15 +1,16 @@ 'Erro Conhecido', 'Class:KnownError+' => 'Erro documentado de um problema conhecido', 'Class:KnownError/Attribute:name' => 'Nome', @@ -52,13 +53,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:KnownError/Attribute:ci_list+' => 'Todos os Itens de Configuração (ICs) associados à este Erro conhecido', 'Class:KnownError/Attribute:document_list' => 'Documentos', 'Class:KnownError/Attribute:document_list+' => 'Todos os Documentos associados à este Erro conhecido', -)); +]); // // Class: lnkErrorToFunctionalCI // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkErrorToFunctionalCI' => 'Relação entre Erro conhecido / IC', 'Class:lnkErrorToFunctionalCI+' => 'Itens de configuração (IC) associados à este Erro conhecido', 'Class:lnkErrorToFunctionalCI/Name' => '%1$s / %2$s~~', @@ -72,13 +73,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkErrorToFunctionalCI/Attribute:error_name+' => '', 'Class:lnkErrorToFunctionalCI/Attribute:reason' => 'Motivo do link', 'Class:lnkErrorToFunctionalCI/Attribute:reason+' => '', -)); +]); // // Class: lnkDocumentToError // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkDocumentToError' => 'Relação entre Documento / Erro', 'Class:lnkDocumentToError+' => 'Uma ligação entre um documento e um erro conhecido', 'Class:lnkDocumentToError/Name' => '%1$s / %2$s~~', @@ -92,9 +93,9 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkDocumentToError/Attribute:error_name+' => '', 'Class:lnkDocumentToError/Attribute:link_type' => 'Tipo de link', 'Class:lnkDocumentToError/Attribute:link_type+' => '', -)); +]); -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Menu:ProblemManagement' => 'Gerenciamento de Problemas', 'Menu:ProblemManagement+' => 'Lista de Gerenciamento de Problemas', 'Menu:Problem:Shortcuts' => 'Atalhos', @@ -104,4 +105,4 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Menu:SearchError+' => '', 'Menu:Problem:KnownErrors' => 'Erros Conhecidos', 'Menu:Problem:KnownErrors+' => 'Erro documentado de um problema conhecido', -)); +]); diff --git a/datamodels/2.x/itop-knownerror-mgmt/module.itop-knownerror-mgmt.php b/datamodels/2.x/itop-knownerror-mgmt/module.itop-knownerror-mgmt.php index 2d09d3a19..81d65d58b 100755 --- a/datamodels/2.x/itop-knownerror-mgmt/module.itop-knownerror-mgmt.php +++ b/datamodels/2.x/itop-knownerror-mgmt/module.itop-knownerror-mgmt.php @@ -1,10 +1,9 @@ 'Known Errors Database', @@ -12,22 +11,22 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( + 'dependencies' => [ 'itop-config-mgmt/2.2.0', - ), + ], 'mandatory' => false, 'visible' => true, // Components // - 'datamodel' => array( - ), - 'data.struct' => array( + 'datamodel' => [ + ], + 'data.struct' => [ //'data.struct.itop-knownerror-mgmt.xml', - ), - 'data.sample' => array( - ), - + ], + 'data.sample' => [ + ], + // Documentation // 'doc.manual_setup' => '', // No manual installation instructions @@ -35,7 +34,7 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array( - ), - ) + 'settings' => [ + ], + ] ); diff --git a/datamodels/2.x/itop-oauth-client/module.itop-oauth-client.php b/datamodels/2.x/itop-oauth-client/module.itop-oauth-client.php index e8e692e57..d1a1631d7 100644 --- a/datamodels/2.x/itop-oauth-client/module.itop-oauth-client.php +++ b/datamodels/2.x/itop-oauth-client/module.itop-oauth-client.php @@ -1,4 +1,5 @@ 'OAuth 2.0 client', @@ -14,39 +15,38 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( + 'dependencies' => [ 'itop-welcome-itil/3.1.0,', - ), + ], 'mandatory' => false, 'visible' => true, // Components // - 'datamodel' => array( + 'datamodel' => [ 'vendor/autoload.php', 'src/Service/PopupMenuExtension.php', 'src/Service/ApplicationUIExtension.php', - ), - 'webservice' => array( - - ), - 'data.struct' => array( + ], + 'webservice' => [ + + ], + 'data.struct' => [ // add your 'structure' definition XML files here, - ), - 'data.sample' => array( + ], + 'data.sample' => [ // add your sample data XML files here, - ), - + ], + // Documentation // 'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any - 'doc.more_information' => '', // hyperlink to more information, if any + 'doc.more_information' => '', // hyperlink to more information, if any // Default settings // - 'settings' => array( + 'settings' => [ // Module specific settings go here, if any - ), - ) + ], + ] ); - diff --git a/datamodels/2.x/itop-portal-base/dictionaries/cs.dict.itop-portal-base.php b/datamodels/2.x/itop-portal-base/dictionaries/cs.dict.itop-portal-base.php index 1f41b3dd8..4f80d018d 100644 --- a/datamodels/2.x/itop-portal-base/dictionaries/cs.dict.itop-portal-base.php +++ b/datamodels/2.x/itop-portal-base/dictionaries/cs.dict.itop-portal-base.php @@ -1,15 +1,16 @@ 'Uživatelský portál %1$s', 'Page:PleaseWait' => 'Počkejte prosím', 'Page:Home' => 'Domů', @@ -53,19 +54,19 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Portal:File:DisplayInfo' => '%1$s', 'Portal:File:DisplayInfo+' => '%1$s (%2$s) Otevřít / Stáhnout', 'Portal:Calendar-FirstDayOfWeek' => 'cs', //work with moment.js locales -)); +]); // Object form -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Portal:Form:Caselog:Entry:Close:Tooltip' => 'Zavřít tento vstup', 'Portal:Form:Close:Warning' => 'Opravdu chcete opustit tento formulář? Data vložená do formuláře budou ztracena ', 'Portal:Error:ObjectCannotBeCreated' => 'Chyba: objekt nelze vytvořit. Před opětovným odesláním tohoto formuláře zkontrolujte související objekty a přílohy.', 'Portal:Error:ObjectCannotBeUpdated' => 'Chyba: objekt nelze vytvořit. Před opětovným odesláním tohoto formuláře zkontrolujte související objekty a přílohy.', - 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', -)); + 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', +]); // UserProfile brick -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Brick:Portal:UserProfile:Name' => 'Uživatelský profil', 'Brick:Portal:UserProfile:Navigation:Dropdown:MyProfil' => 'Můj profil', 'Brick:Portal:UserProfile:Navigation:Dropdown:Logout' => 'Odhlásit', @@ -76,15 +77,15 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Brick:Portal:UserProfile:Password:CantChangeForUnknownReason' => 'Nepodařilo se změnit heslo, kontaktujte prosím administrátora', 'Brick:Portal:UserProfile:PersonalInformations:Title' => 'Osobní informace', 'Brick:Portal:UserProfile:Photo:Title' => 'Foto', -)); +]); // AggregatePageBrick -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Brick:Portal:AggregatePage:DefaultTitle' => 'Nástěnka', -)); +]); // BrowseBrick brick -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Brick:Portal:Browse:Name' => 'Procházet položky', 'Brick:Portal:Browse:Mode:List' => 'Seznam', 'Brick:Portal:Browse:Mode:Tree' => 'Strom', @@ -98,10 +99,10 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Brick:Portal:Browse:Tree:CollapseAll' => 'Sbalit vše', 'Brick:Portal:Browse:Filter:NoData' => 'Žádná položka', 'Brick:Portal:Browse:Mosaic:Back' => 'Zpět', -)); +]); // ManageBrick brick -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Brick:Portal:Manage:Name' => 'Spravovat položky', 'Brick:Portal:Manage:Table:NoData' => 'Žádná položka', 'Brick:Portal:Manage:Table:ItemActions' => 'Akce', @@ -116,10 +117,10 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Brick:Portal:Manage:fct:avg' => 'Průměr', 'Brick:Portal:Manage:fct:min' => 'Min', 'Brick:Portal:Manage:fct:max' => 'Max', -)); +]); // ObjectBrick brick -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Brick:Portal:Object:Name' => 'Objekt', 'Brick:Portal:Object:Form:Create:Title' => 'Nový %1$s', 'Brick:Portal:Object:Form:Edit:Title' => 'Aktualizace %1$s', @@ -131,18 +132,18 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Brick:Portal:Object:Search:Hierarchy:Title' => 'Vybrat %1$s', 'Brick:Portal:Object:Copy:TextToCopy' => '%1$s: %2$s', 'Brick:Portal:Object:Copy:Tooltip' => 'Zkopíruj odkaz na objekt', - 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Zkopírováno' -)); + 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Zkopírováno', +]); // CreateBrick brick -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Brick:Portal:Create:Name' => 'Rychlé vytvoření', 'Brick:Portal:Create:ChooseType' => 'Vyberte typ', -)); +]); // Filter brick -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Brick:Portal:Filter:Name' => 'Předfiltrování dlaždice', 'Brick:Portal:Filter:SearchInput:Placeholder' => 'např. připojení k wifi', 'Brick:Portal:Filter:SearchInput:Submit' => 'Vyhledat', -)); +]); diff --git a/datamodels/2.x/itop-portal-base/dictionaries/da.dict.itop-portal-base.php b/datamodels/2.x/itop-portal-base/dictionaries/da.dict.itop-portal-base.php index 2e1dc286c..3cd9473b8 100644 --- a/datamodels/2.x/itop-portal-base/dictionaries/da.dict.itop-portal-base.php +++ b/datamodels/2.x/itop-portal-base/dictionaries/da.dict.itop-portal-base.php @@ -1,15 +1,16 @@ '%1$s User portal~~', 'Page:PleaseWait' => 'Please wait...~~', 'Page:Home' => 'Home~~', @@ -53,19 +54,19 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Portal:File:DisplayInfo' => '%1$s~~', 'Portal:File:DisplayInfo+' => '%1$s (%2$s) Open / Download~~', 'Portal:Calendar-FirstDayOfWeek' => 'da', //work with moment.js locales -)); +]); // Object form -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Portal:Form:Caselog:Entry:Close:Tooltip' => 'Close this entry~~', 'Portal:Form:Close:Warning' => 'Do you want to leave this form? Data entered may be lost~~', 'Portal:Error:ObjectCannotBeCreated' => 'Error: object cannot be created. Check associated objects and attachments before submitting this form again.~~', 'Portal:Error:ObjectCannotBeUpdated' => 'Error: object cannot be updated. Check associated objects and attachments before submitting this form again.~~', - 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', -)); + 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', +]); // UserProfile brick -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Brick:Portal:UserProfile:Name' => 'User profile~~', 'Brick:Portal:UserProfile:Navigation:Dropdown:MyProfil' => 'My profile~~', 'Brick:Portal:UserProfile:Navigation:Dropdown:Logout' => 'Logoff~~', @@ -76,15 +77,15 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Brick:Portal:UserProfile:Password:CantChangeForUnknownReason' => 'Can\'t change password, please contact your %1$s administrator~~', 'Brick:Portal:UserProfile:PersonalInformations:Title' => 'Personal information~~', 'Brick:Portal:UserProfile:Photo:Title' => 'Photo~~', -)); +]); // AggregatePageBrick -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Brick:Portal:AggregatePage:DefaultTitle' => 'Dashboard~~', -)); +]); // BrowseBrick brick -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Brick:Portal:Browse:Name' => 'Browse throught items~~', 'Brick:Portal:Browse:Mode:List' => 'List~~', 'Brick:Portal:Browse:Mode:Tree' => 'Tree~~', @@ -98,10 +99,10 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Brick:Portal:Browse:Tree:CollapseAll' => 'Collapse all~~', 'Brick:Portal:Browse:Filter:NoData' => 'No item~~', 'Brick:Portal:Browse:Mosaic:Back' => 'Back~~', -)); +]); // ManageBrick brick -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Brick:Portal:Manage:Name' => 'Manage items~~', 'Brick:Portal:Manage:Table:NoData' => 'No item.~~', 'Brick:Portal:Manage:Table:ItemActions' => 'Actions~~', @@ -116,10 +117,10 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Brick:Portal:Manage:fct:avg' => 'Average~~', 'Brick:Portal:Manage:fct:min' => 'Min~~', 'Brick:Portal:Manage:fct:max' => 'Max~~', -)); +]); // ObjectBrick brick -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Brick:Portal:Object:Name' => 'Object~~', 'Brick:Portal:Object:Form:Create:Title' => 'New %1$s~~', 'Brick:Portal:Object:Form:Edit:Title' => 'Updating %1$s~~', @@ -131,18 +132,18 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Brick:Portal:Object:Search:Hierarchy:Title' => 'Select %1$s~~', 'Brick:Portal:Object:Copy:TextToCopy' => '%2$s', 'Brick:Portal:Object:Copy:Tooltip' => 'Copy object link~~', - 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Copied~~' -)); + 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Copied~~', +]); // CreateBrick brick -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Brick:Portal:Create:Name' => 'Quick creation~~', 'Brick:Portal:Create:ChooseType' => 'Please, choose a type~~', -)); +]); // Filter brick -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Brick:Portal:Filter:Name' => 'Prefilter a brick~~', 'Brick:Portal:Filter:SearchInput:Placeholder' => 'eg. connect wifi~~', 'Brick:Portal:Filter:SearchInput:Submit' => 'Search~~', -)); +]); diff --git a/datamodels/2.x/itop-portal-base/dictionaries/de.dict.itop-portal-base.php b/datamodels/2.x/itop-portal-base/dictionaries/de.dict.itop-portal-base.php index b972bcd2a..fc82655ce 100644 --- a/datamodels/2.x/itop-portal-base/dictionaries/de.dict.itop-portal-base.php +++ b/datamodels/2.x/itop-portal-base/dictionaries/de.dict.itop-portal-base.php @@ -1,15 +1,16 @@ '%1$s - Benutzer Portal', 'Page:PleaseWait' => 'Bitte warten...', 'Page:Home' => 'Start', @@ -53,19 +54,19 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Portal:File:DisplayInfo' => '%1$s', 'Portal:File:DisplayInfo+' => '%1$s (%2$s) Öffnen / Download', 'Portal:Calendar-FirstDayOfWeek' => 'de', //work with moment.js locales -)); +]); // Object form -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Portal:Form:Caselog:Entry:Close:Tooltip' => 'Dieses Objekt schließen', 'Portal:Form:Close:Warning' => 'Soll diese Eingabemaske verlassen werden? Eingegebene Daten werden nicht gespeichert.', 'Portal:Error:ObjectCannotBeCreated' => 'Error: Objekt kann nicht erzeugt werden. Prüfen Sie verknüpfte Objekte und Anhänge bevor Sie dieses Formular erneut abschicken.', 'Portal:Error:ObjectCannotBeUpdated' => 'Error: Objekt kann nicht geupdated werden. Prüfen Sie verknüpfte Objekte und Anhänge bevor Sie dieses Formular erneut abschicken.', - 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', -)); + 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', +]); // UserProfile brick -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Brick:Portal:UserProfile:Name' => 'Benutzer Profil', 'Brick:Portal:UserProfile:Navigation:Dropdown:MyProfil' => 'Mein Profil', 'Brick:Portal:UserProfile:Navigation:Dropdown:Logout' => 'Abmelden', @@ -76,15 +77,15 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Brick:Portal:UserProfile:Password:CantChangeForUnknownReason' => 'Passwort kann nicht geändert werden - bitte kontaktieren Sie Ihren %1$s Administrator', 'Brick:Portal:UserProfile:PersonalInformations:Title' => 'Persönliche Informationen', 'Brick:Portal:UserProfile:Photo:Title' => 'Foto', -)); +]); // AggregatePageBrick -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Brick:Portal:AggregatePage:DefaultTitle' => 'Dashboard', -)); +]); // BrowseBrick brick -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Brick:Portal:Browse:Name' => 'Liste durchgehen', 'Brick:Portal:Browse:Mode:List' => 'Liste', 'Brick:Portal:Browse:Mode:Tree' => 'Baum', @@ -98,10 +99,10 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Brick:Portal:Browse:Tree:CollapseAll' => 'Alle kollabieren', 'Brick:Portal:Browse:Filter:NoData' => 'Kein Eintrag', 'Brick:Portal:Browse:Mosaic:Back' => 'Zurück', -)); +]); // ManageBrick brick -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Brick:Portal:Manage:Name' => 'Einträge managen', 'Brick:Portal:Manage:Table:NoData' => 'Kein Eintrag.', 'Brick:Portal:Manage:Table:ItemActions' => 'Aktionen', @@ -116,10 +117,10 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Brick:Portal:Manage:fct:avg' => 'Durchschnitt', 'Brick:Portal:Manage:fct:min' => 'Minimum', 'Brick:Portal:Manage:fct:max' => 'Maximum', -)); +]); // ObjectBrick brick -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Brick:Portal:Object:Name' => 'Object', 'Brick:Portal:Object:Form:Create:Title' => 'Neue %1$s', 'Brick:Portal:Object:Form:Edit:Title' => 'Wird aktualisiert %1$s', @@ -131,18 +132,18 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Brick:Portal:Object:Search:Hierarchy:Title' => 'Select %1$s', 'Brick:Portal:Object:Copy:TextToCopy' => '%2$s', 'Brick:Portal:Object:Copy:Tooltip' => 'Objektverknüpfung kopieren', - 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Kopiert' -)); + 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Kopiert', +]); // CreateBrick brick -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Brick:Portal:Create:Name' => 'Schnelles Erstellen', 'Brick:Portal:Create:ChooseType' => 'Bitte wählen Sie einen Typ', -)); +]); // Filter brick -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Brick:Portal:Filter:Name' => 'Brick vorfiltern', 'Brick:Portal:Filter:SearchInput:Placeholder' => 'z.B. connect wifi', 'Brick:Portal:Filter:SearchInput:Submit' => 'Suchen', -)); +]); diff --git a/datamodels/2.x/itop-portal-base/dictionaries/en.dict.itop-portal-base.php b/datamodels/2.x/itop-portal-base/dictionaries/en.dict.itop-portal-base.php index 8d04efa5c..3c4cf29c6 100644 --- a/datamodels/2.x/itop-portal-base/dictionaries/en.dict.itop-portal-base.php +++ b/datamodels/2.x/itop-portal-base/dictionaries/en.dict.itop-portal-base.php @@ -1,4 +1,5 @@ '%1$s User portal', 'Page:PleaseWait' => 'Please wait...', 'Page:Home' => 'Home', @@ -62,19 +63,19 @@ Dict::Add('EN US', 'English', 'English', array( 'Portal:File:DisplayInfo' => '%1$s', 'Portal:File:DisplayInfo+' => '%1$s (%2$s) Open / Download', 'Portal:Calendar-FirstDayOfWeek' => 'en-us', //work with moment.js locales -)); +]); // Object form -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Portal:Form:Caselog:Entry:Close:Tooltip' => 'Close this entry', 'Portal:Form:Close:Warning' => 'Do you want to leave this form? Data entered may be lost', 'Portal:Error:ObjectCannotBeCreated' => 'Error: object cannot be created. Check associated objects and attachments before submitting this form again.', 'Portal:Error:ObjectCannotBeUpdated' => 'Error: object cannot be updated. Check associated objects and attachments before submitting this form again.', - 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s', -)); + 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s', +]); // UserProfile brick -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Brick:Portal:UserProfile:Name' => 'User profile', 'Brick:Portal:UserProfile:Navigation:Dropdown:MyProfil' => 'My profile', 'Brick:Portal:UserProfile:Navigation:Dropdown:Logout' => 'Logoff', @@ -85,15 +86,15 @@ Dict::Add('EN US', 'English', 'English', array( 'Brick:Portal:UserProfile:Password:CantChangeForUnknownReason' => 'Can\'t change password, please contact your %1$s administrator', 'Brick:Portal:UserProfile:PersonalInformations:Title' => 'Personal information', 'Brick:Portal:UserProfile:Photo:Title' => 'Photo', -)); +]); // AggregatePageBrick -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Brick:Portal:AggregatePage:DefaultTitle' => 'Dashboard', -)); +]); // BrowseBrick brick -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Brick:Portal:Browse:Name' => 'Browse throught items', 'Brick:Portal:Browse:Mode:List' => 'List', 'Brick:Portal:Browse:Mode:Tree' => 'Tree', @@ -107,10 +108,10 @@ Dict::Add('EN US', 'English', 'English', array( 'Brick:Portal:Browse:Tree:CollapseAll' => 'Collapse all', 'Brick:Portal:Browse:Filter:NoData' => 'No item', 'Brick:Portal:Browse:Mosaic:Back' => 'Back', -)); +]); // ManageBrick brick -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Brick:Portal:Manage:Name' => 'Manage items', 'Brick:Portal:Manage:Table:NoData' => 'No item.', 'Brick:Portal:Manage:Table:ItemActions' => 'Actions', @@ -125,10 +126,10 @@ Dict::Add('EN US', 'English', 'English', array( 'Brick:Portal:Manage:fct:avg' => 'Average', 'Brick:Portal:Manage:fct:min' => 'Min', 'Brick:Portal:Manage:fct:max' => 'Max', -)); +]); // ObjectBrick brick -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Brick:Portal:Object:Name' => 'Object', 'Brick:Portal:Object:Form:Create:Title' => 'New %1$s', 'Brick:Portal:Object:Form:Edit:Title' => 'Updating %1$s', @@ -140,18 +141,18 @@ Dict::Add('EN US', 'English', 'English', array( 'Brick:Portal:Object:Search:Hierarchy:Title' => 'Select %1$s', 'Brick:Portal:Object:Copy:TextToCopy' => '%2$s', 'Brick:Portal:Object:Copy:Tooltip' => 'Copy object link', - 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Copied' -)); + 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Copied', +]); // CreateBrick brick -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Brick:Portal:Create:Name' => 'Quick creation', 'Brick:Portal:Create:ChooseType' => 'Please, choose a type', -)); +]); // Filter brick -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Brick:Portal:Filter:Name' => 'Prefilter a brick', 'Brick:Portal:Filter:SearchInput:Placeholder' => 'eg. connect wifi', 'Brick:Portal:Filter:SearchInput:Submit' => 'Search', -)); +]); diff --git a/datamodels/2.x/itop-portal-base/dictionaries/en_gb.dict.itop-portal-base.php b/datamodels/2.x/itop-portal-base/dictionaries/en_gb.dict.itop-portal-base.php index fc667fdc3..984c0e8d9 100644 --- a/datamodels/2.x/itop-portal-base/dictionaries/en_gb.dict.itop-portal-base.php +++ b/datamodels/2.x/itop-portal-base/dictionaries/en_gb.dict.itop-portal-base.php @@ -1,11 +1,12 @@ '%1$s User portal', 'Page:PleaseWait' => 'Please wait...', 'Page:Home' => 'Home', @@ -49,19 +50,19 @@ Dict::Add('EN GB', 'British English', 'British English', array( 'Portal:File:DisplayInfo' => '%1$s', 'Portal:File:DisplayInfo+' => '%1$s (%2$s) Open / Download', 'Portal:Calendar-FirstDayOfWeek' => 'en-gb', -)); +]); // Object form -Dict::Add('EN GB', 'British English', 'British English', array( +Dict::Add('EN GB', 'British English', 'British English', [ 'Portal:Form:Caselog:Entry:Close:Tooltip' => 'Close this entry', 'Portal:Form:Close:Warning' => 'Do you want to leave this form? Data entered may be lost', 'Portal:Error:ObjectCannotBeCreated' => 'Error: object cannot be created. Check associated objects and attachments before submitting this form again.', 'Portal:Error:ObjectCannotBeUpdated' => 'Error: object cannot be updated. Check associated objects and attachments before submitting this form again.', - 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s', -)); + 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s', +]); // UserProfile brick -Dict::Add('EN GB', 'British English', 'British English', array( +Dict::Add('EN GB', 'British English', 'British English', [ 'Brick:Portal:UserProfile:Name' => 'User profile', 'Brick:Portal:UserProfile:Navigation:Dropdown:MyProfil' => 'My profile', 'Brick:Portal:UserProfile:Navigation:Dropdown:Logout' => 'Log off', @@ -72,15 +73,15 @@ Dict::Add('EN GB', 'British English', 'British English', array( 'Brick:Portal:UserProfile:Password:CantChangeForUnknownReason' => 'Can\'t change password, please contact your %1$s administrator', 'Brick:Portal:UserProfile:PersonalInformations:Title' => 'Personal information', 'Brick:Portal:UserProfile:Photo:Title' => 'Photo', -)); +]); // AggregatePageBrick -Dict::Add('EN GB', 'British English', 'British English', array( +Dict::Add('EN GB', 'British English', 'British English', [ 'Brick:Portal:AggregatePage:DefaultTitle' => 'Dashboard', -)); +]); // BrowseBrick brick -Dict::Add('EN GB', 'British English', 'British English', array( +Dict::Add('EN GB', 'British English', 'British English', [ 'Brick:Portal:Browse:Name' => 'Browse through items', 'Brick:Portal:Browse:Mode:List' => 'List', 'Brick:Portal:Browse:Mode:Tree' => 'Tree', @@ -94,10 +95,10 @@ Dict::Add('EN GB', 'British English', 'British English', array( 'Brick:Portal:Browse:Tree:CollapseAll' => 'Collapse all', 'Brick:Portal:Browse:Filter:NoData' => 'No item', 'Brick:Portal:Browse:Mosaic:Back' => 'Back', -)); +]); // ManageBrick brick -Dict::Add('EN GB', 'British English', 'British English', array( +Dict::Add('EN GB', 'British English', 'British English', [ 'Brick:Portal:Manage:Name' => 'Manage items', 'Brick:Portal:Manage:Table:NoData' => 'No item.', 'Brick:Portal:Manage:Table:ItemActions' => 'Actions', @@ -112,10 +113,10 @@ Dict::Add('EN GB', 'British English', 'British English', array( 'Brick:Portal:Manage:fct:avg' => 'Average', 'Brick:Portal:Manage:fct:min' => 'Min', 'Brick:Portal:Manage:fct:max' => 'Max', -)); +]); // ObjectBrick brick -Dict::Add('EN GB', 'British English', 'British English', array( +Dict::Add('EN GB', 'British English', 'British English', [ 'Brick:Portal:Object:Name' => 'Object', 'Brick:Portal:Object:Form:Create:Title' => 'New %1$s', 'Brick:Portal:Object:Form:Edit:Title' => 'Updating %1$s', @@ -127,18 +128,18 @@ Dict::Add('EN GB', 'British English', 'British English', array( 'Brick:Portal:Object:Search:Hierarchy:Title' => 'Select %1$s', 'Brick:Portal:Object:Copy:TextToCopy' => '%2$s', 'Brick:Portal:Object:Copy:Tooltip' => 'Copy object link', - 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Copied' -)); + 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Copied', +]); // CreateBrick brick -Dict::Add('EN GB', 'British English', 'British English', array( +Dict::Add('EN GB', 'British English', 'British English', [ 'Brick:Portal:Create:Name' => 'Quick creation', 'Brick:Portal:Create:ChooseType' => 'Please, choose a type', -)); +]); // Filter brick -Dict::Add('EN GB', 'British English', 'British English', array( +Dict::Add('EN GB', 'British English', 'British English', [ 'Brick:Portal:Filter:Name' => 'Prefilter a brick', 'Brick:Portal:Filter:SearchInput:Placeholder' => 'eg. connect wifi', 'Brick:Portal:Filter:SearchInput:Submit' => 'Search', -)); +]); diff --git a/datamodels/2.x/itop-portal-base/dictionaries/es_cr.dict.itop-portal-base.php b/datamodels/2.x/itop-portal-base/dictionaries/es_cr.dict.itop-portal-base.php index 1a8533c4b..90cfa2ace 100644 --- a/datamodels/2.x/itop-portal-base/dictionaries/es_cr.dict.itop-portal-base.php +++ b/datamodels/2.x/itop-portal-base/dictionaries/es_cr.dict.itop-portal-base.php @@ -1,13 +1,14 @@ - * @notas Utilizar codificación UTF-8 para mostrar acentos y otros caracteres especiales + * @notas Utilizar codificación UTF-8 para mostrar acentos y otros caracteres especiales */ -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Page:DefaultTitle' => '%1$s - Portal de Usuario', 'Page:PleaseWait' => 'Por favor espere...', 'Page:Home' => 'Inicio', @@ -51,19 +52,19 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Portal:File:DisplayInfo' => '%1$s', 'Portal:File:DisplayInfo+' => '%1$s (%2$s) Abierto / Descarga', 'Portal:Calendar-FirstDayOfWeek' => 'es', //work with moment.js locales -)); +]); // Object form -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Portal:Form:Caselog:Entry:Close:Tooltip' => 'Cerrar este registro', 'Portal:Form:Close:Warning' => '¿Desea abandorar este formulario? Datos modificados se perderan', 'Portal:Error:ObjectCannotBeCreated' => 'Error: no se puede crear el objeto. Verifique los objetos asociados y archivos adjuntos antes de enviar nuevamente este formulario.', 'Portal:Error:ObjectCannotBeUpdated' => 'Error: no se puede actualizar el objeto. Verifique los objetos asociados y archivos adjuntos antes de enviar nuevamente este formulario.', - 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', -)); + 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', +]); // UserProfile brick -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Brick:Portal:UserProfile:Name' => 'Perfil del usuario', 'Brick:Portal:UserProfile:Navigation:Dropdown:MyProfil' => 'Mi perfil', 'Brick:Portal:UserProfile:Navigation:Dropdown:Logout' => 'Cerrar Sesión', @@ -74,15 +75,15 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Brick:Portal:UserProfile:Password:CantChangeForUnknownReason' => 'No se puede cambiar la contraseña, póngase en contacto con el administrador de %1$s', 'Brick:Portal:UserProfile:PersonalInformations:Title' => 'Información Personal', 'Brick:Portal:UserProfile:Photo:Title' => 'Foto', -)); +]); // AggregatePageBrick -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Brick:Portal:AggregatePage:DefaultTitle' => 'Tablero de Control', -)); +]); // BrowseBrick brick -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Brick:Portal:Browse:Name' => 'Buscar en todos los elementos', 'Brick:Portal:Browse:Mode:List' => 'Lista', 'Brick:Portal:Browse:Mode:Tree' => 'Árbol', @@ -96,10 +97,10 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Brick:Portal:Browse:Tree:CollapseAll' => 'Desplegar todo', 'Brick:Portal:Browse:Filter:NoData' => 'Sin elementos', 'Brick:Portal:Browse:Mosaic:Back' => 'Volver', -)); +]); // ManageBrick brick -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Brick:Portal:Manage:Name' => 'Administrar elementos', 'Brick:Portal:Manage:Table:NoData' => 'Sin elementos', 'Brick:Portal:Manage:Table:ItemActions' => 'Acciones', @@ -114,10 +115,10 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Brick:Portal:Manage:fct:avg' => 'Promedio', 'Brick:Portal:Manage:fct:min' => 'Mínimo', 'Brick:Portal:Manage:fct:max' => 'Máximo', -)); +]); // ObjectBrick brick -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Brick:Portal:Object:Name' => 'Objecto', 'Brick:Portal:Object:Form:Create:Title' => 'Nuevo %1$s', 'Brick:Portal:Object:Form:Edit:Title' => 'Actualizando %1$s', @@ -129,18 +130,18 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Brick:Portal:Object:Search:Hierarchy:Title' => 'Selección %1$s', 'Brick:Portal:Object:Copy:TextToCopy' => '%2$s', 'Brick:Portal:Object:Copy:Tooltip' => 'Copiar liga al objeto', - 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Copiado' -)); + 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Copiado', +]); // CreateBrick brick -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Brick:Portal:Create:Name' => 'Creación rápida', 'Brick:Portal:Create:ChooseType' => 'Por favor, seleccione un tipo', -)); +]); // Filter brick -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Brick:Portal:Filter:Name' => 'Prefiltrar bloque', 'Brick:Portal:Filter:SearchInput:Placeholder' => 'Ej.:. Conectar a WiFi', 'Brick:Portal:Filter:SearchInput:Submit' => 'Buscar', -)); +]); diff --git a/datamodels/2.x/itop-portal-base/dictionaries/fr.dict.itop-portal-base.php b/datamodels/2.x/itop-portal-base/dictionaries/fr.dict.itop-portal-base.php index ee538a13e..c4f306746 100644 --- a/datamodels/2.x/itop-portal-base/dictionaries/fr.dict.itop-portal-base.php +++ b/datamodels/2.x/itop-portal-base/dictionaries/fr.dict.itop-portal-base.php @@ -1,15 +1,16 @@ 'Portail utilisateur %1$s', 'Page:PleaseWait' => 'Veuillez patienter...', 'Page:Home' => 'Accueil', @@ -53,19 +54,19 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Portal:File:DisplayInfo' => '%1$s', 'Portal:File:DisplayInfo+' => '%1$s (%2$s) Ouvrir / Télécharger', 'Portal:Calendar-FirstDayOfWeek' => 'fr', //work with moment.js locales -)); +]); // Object form -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Portal:Form:Caselog:Entry:Close:Tooltip' => 'Fermer cette entrée', 'Portal:Form:Close:Warning' => 'Voulez-vous quitter ce formulaire ? Les données saisies seront perdues', 'Portal:Error:ObjectCannotBeCreated' => 'Erreur: L\'objet n\'a pas été créé. Vérifiez les objets liés et les attachements avant de soumettre à nouveau le formulaire.', 'Portal:Error:ObjectCannotBeUpdated' => 'Erreur: L\'objet n\'a pas été modifié. Vérifiez les objets liés et les attachements avant de soumettre à nouveau le formulaire.', - 'Portal:Error:CheckToWriteFailed' => 'Erreur durant la validation du champ \'%1$s\' : %2$s', -)); + 'Portal:Error:CheckToWriteFailed' => 'Erreur durant la validation du champ \'%1$s\' : %2$s', +]); // UserProfile brick -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Brick:Portal:UserProfile:Name' => 'Profil utilisateur', 'Brick:Portal:UserProfile:Navigation:Dropdown:MyProfil' => 'Mon profil', 'Brick:Portal:UserProfile:Navigation:Dropdown:Logout' => 'Déconnexion', @@ -76,15 +77,15 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Brick:Portal:UserProfile:Password:CantChangeForUnknownReason' => 'Impossible de modifier votre mot de passe, veuillez contacter votre administrateur %1$s', 'Brick:Portal:UserProfile:PersonalInformations:Title' => 'Informations personnelles', 'Brick:Portal:UserProfile:Photo:Title' => 'Photo', -)); +]); // AggregatePageBrick -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Brick:Portal:AggregatePage:DefaultTitle' => 'Tableau de bord', -)); +]); // BrowseBrick brick -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Brick:Portal:Browse:Name' => 'Navigation dans les éléments', 'Brick:Portal:Browse:Mode:List' => 'Liste', 'Brick:Portal:Browse:Mode:Tree' => 'Hiérarchie', @@ -98,10 +99,10 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Brick:Portal:Browse:Tree:CollapseAll' => 'Tout replier', 'Brick:Portal:Browse:Filter:NoData' => 'Aucun élément', 'Brick:Portal:Browse:Mosaic:Back' => 'Retour', -)); +]); // ManageBrick brick -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Brick:Portal:Manage:Name' => 'Gestion d\'éléments', 'Brick:Portal:Manage:Table:NoData' => 'Aucun élément', 'Brick:Portal:Manage:Table:ItemActions' => 'Actions', @@ -116,10 +117,10 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Brick:Portal:Manage:fct:avg' => 'Moyenne', 'Brick:Portal:Manage:fct:min' => 'Min', 'Brick:Portal:Manage:fct:max' => 'Max', -)); +]); // ObjectBrick brick -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Brick:Portal:Object:Name' => 'Objet', 'Brick:Portal:Object:Form:Create:Title' => 'Création de %1$s', 'Brick:Portal:Object:Form:Edit:Title' => 'Modification de %1$s', @@ -131,18 +132,18 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Brick:Portal:Object:Search:Hierarchy:Title' => 'Sélection de %1$s', 'Brick:Portal:Object:Copy:TextToCopy' => '%2$s', 'Brick:Portal:Object:Copy:Tooltip' => 'Copier l\'url de l\'objet', - 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Copié' -)); + 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Copié', +]); // CreateBrick brick -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Brick:Portal:Create:Name' => 'Création rapide', 'Brick:Portal:Create:ChooseType' => 'Veuillez choisir le type', -)); +]); // Filter brick -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Brick:Portal:Filter:Name' => 'Préfiltre une brique', 'Brick:Portal:Filter:SearchInput:Placeholder' => 'ex : connecter wifi', 'Brick:Portal:Filter:SearchInput:Submit' => 'Rechercher', -)); +]); diff --git a/datamodels/2.x/itop-portal-base/dictionaries/hu.dict.itop-portal-base.php b/datamodels/2.x/itop-portal-base/dictionaries/hu.dict.itop-portal-base.php index f3f2d4721..f2ae2cf37 100644 --- a/datamodels/2.x/itop-portal-base/dictionaries/hu.dict.itop-portal-base.php +++ b/datamodels/2.x/itop-portal-base/dictionaries/hu.dict.itop-portal-base.php @@ -1,15 +1,16 @@ '%1$s Felhasználói portál', 'Page:PleaseWait' => 'Kérem várjon...', 'Page:Home' => 'Kezdőlap', @@ -53,19 +54,19 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Portal:File:DisplayInfo' => '%1$s', 'Portal:File:DisplayInfo+' => '%1$s (%2$s) Megnyitás / Letöltés', 'Portal:Calendar-FirstDayOfWeek' => 'hu', //work with moment.js locales -)); +]); // Object form -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Portal:Form:Caselog:Entry:Close:Tooltip' => 'Bejegyzés bezárása', 'Portal:Form:Close:Warning' => 'Szeretné elhagyni ezt az űrlapot? A megadott adatok elveszhetnek', 'Portal:Error:ObjectCannotBeCreated' => 'Hiba: az objektum nem hozható létre. Ellenőrizze a kapcsolódó objektumokat és mellékleteket, mielőtt újra elküldi ezt az űrlapot.', 'Portal:Error:ObjectCannotBeUpdated' => 'Hiba: az objektum nem frissíthető. Ellenőrizze a kapcsolódó objektumokat és mellékleteket, mielőtt újra elküldi ezt az űrlapot.', - 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', -)); + 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', +]); // UserProfile brick -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Brick:Portal:UserProfile:Name' => 'Felhasználói profil', 'Brick:Portal:UserProfile:Navigation:Dropdown:MyProfil' => 'Saját profil', 'Brick:Portal:UserProfile:Navigation:Dropdown:Logout' => 'Kijelentkezés', @@ -76,15 +77,15 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Brick:Portal:UserProfile:Password:CantChangeForUnknownReason' => 'Nem tudja megváltoztatni a jelszót, lépjen kapcsolatba a %1$s rendszergazdával', 'Brick:Portal:UserProfile:PersonalInformations:Title' => 'Személyi adatok', 'Brick:Portal:UserProfile:Photo:Title' => 'Fénykép', -)); +]); // AggregatePageBrick -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Brick:Portal:AggregatePage:DefaultTitle' => 'Műszerfal', -)); +]); // BrowseBrick brick -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Brick:Portal:Browse:Name' => 'Böngésszen az elemek között', 'Brick:Portal:Browse:Mode:List' => 'Lista', 'Brick:Portal:Browse:Mode:Tree' => 'Fa', @@ -98,10 +99,10 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Brick:Portal:Browse:Tree:CollapseAll' => 'Összecsukás', 'Brick:Portal:Browse:Filter:NoData' => 'Nincs elem', 'Brick:Portal:Browse:Mosaic:Back' => 'Vissza', -)); +]); // ManageBrick brick -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Brick:Portal:Manage:Name' => 'Elemek kezelése', 'Brick:Portal:Manage:Table:NoData' => 'Nincs elem', 'Brick:Portal:Manage:Table:ItemActions' => 'Műveletek', @@ -116,10 +117,10 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Brick:Portal:Manage:fct:avg' => 'Átlag', 'Brick:Portal:Manage:fct:min' => 'Minimum', 'Brick:Portal:Manage:fct:max' => 'Maximum', -)); +]); // ObjectBrick brick -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Brick:Portal:Object:Name' => 'Objektum', 'Brick:Portal:Object:Form:Create:Title' => 'Új %1$s', 'Brick:Portal:Object:Form:Edit:Title' => '%1$s frissítése', @@ -131,18 +132,18 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Brick:Portal:Object:Search:Hierarchy:Title' => '%1$s kiválasztása', 'Brick:Portal:Object:Copy:TextToCopy' => '%2$s', 'Brick:Portal:Object:Copy:Tooltip' => 'Objektum hivatkozás másolása', - 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Másolva' -)); + 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Másolva', +]); // CreateBrick brick -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Brick:Portal:Create:Name' => 'Gyors létrehozás', 'Brick:Portal:Create:ChooseType' => 'Válasszon típust', -)); +]); // Filter brick -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Brick:Portal:Filter:Name' => 'Tégla előszűrése', 'Brick:Portal:Filter:SearchInput:Placeholder' => 'pl. wifi kapcsolat', 'Brick:Portal:Filter:SearchInput:Submit' => 'Keresés', -)); +]); diff --git a/datamodels/2.x/itop-portal-base/dictionaries/it.dict.itop-portal-base.php b/datamodels/2.x/itop-portal-base/dictionaries/it.dict.itop-portal-base.php index 21bcff0a4..d5ef20a06 100644 --- a/datamodels/2.x/itop-portal-base/dictionaries/it.dict.itop-portal-base.php +++ b/datamodels/2.x/itop-portal-base/dictionaries/it.dict.itop-portal-base.php @@ -1,15 +1,16 @@ '%1$s Portale Utente', 'Page:PleaseWait' => 'Attendere…', 'Page:Home' => 'Home', @@ -53,19 +54,19 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Portal:File:DisplayInfo' => '%1$s', 'Portal:File:DisplayInfo+' => '%1$s (%2$s) Open / Download~~', 'Portal:Calendar-FirstDayOfWeek' => 'it', //work with moment.js locales -)); +]); // Object form -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Portal:Form:Caselog:Entry:Close:Tooltip' => 'Close this entry~~', 'Portal:Form:Close:Warning' => 'Do you want to leave this form? Data entered may be lost~~', 'Portal:Error:ObjectCannotBeCreated' => 'Error: object cannot be created. Check associated objects and attachments before submitting this form again.~~', 'Portal:Error:ObjectCannotBeUpdated' => 'Error: object cannot be updated. Check associated objects and attachments before submitting this form again.~~', - 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', -)); + 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', +]); // UserProfile brick -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Brick:Portal:UserProfile:Name' => 'User profile~~', 'Brick:Portal:UserProfile:Navigation:Dropdown:MyProfil' => 'My profile~~', 'Brick:Portal:UserProfile:Navigation:Dropdown:Logout' => 'Logoff~~', @@ -76,15 +77,15 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Brick:Portal:UserProfile:Password:CantChangeForUnknownReason' => 'Can\'t change password, please contact your %1$s administrator~~', 'Brick:Portal:UserProfile:PersonalInformations:Title' => 'Personal information~~', 'Brick:Portal:UserProfile:Photo:Title' => 'Photo~~', -)); +]); // AggregatePageBrick -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Brick:Portal:AggregatePage:DefaultTitle' => 'Dashboard~~', -)); +]); // BrowseBrick brick -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Brick:Portal:Browse:Name' => 'Browse throught items~~', 'Brick:Portal:Browse:Mode:List' => 'List~~', 'Brick:Portal:Browse:Mode:Tree' => 'Tree~~', @@ -98,10 +99,10 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Brick:Portal:Browse:Tree:CollapseAll' => 'Collapse all~~', 'Brick:Portal:Browse:Filter:NoData' => 'No item~~', 'Brick:Portal:Browse:Mosaic:Back' => 'Back~~', -)); +]); // ManageBrick brick -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Brick:Portal:Manage:Name' => 'Manage items~~', 'Brick:Portal:Manage:Table:NoData' => 'No item.~~', 'Brick:Portal:Manage:Table:ItemActions' => 'Actions~~', @@ -116,10 +117,10 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Brick:Portal:Manage:fct:avg' => 'Average~~', 'Brick:Portal:Manage:fct:min' => 'Min~~', 'Brick:Portal:Manage:fct:max' => 'Max~~', -)); +]); // ObjectBrick brick -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Brick:Portal:Object:Name' => 'Object~~', 'Brick:Portal:Object:Form:Create:Title' => 'New %1$s~~', 'Brick:Portal:Object:Form:Edit:Title' => 'Updating %1$s~~', @@ -131,18 +132,18 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Brick:Portal:Object:Search:Hierarchy:Title' => 'Select %1$s~~', 'Brick:Portal:Object:Copy:TextToCopy' => '%2$s', 'Brick:Portal:Object:Copy:Tooltip' => 'Copy object link~~', - 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Copied~~' -)); + 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Copied~~', +]); // CreateBrick brick -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Brick:Portal:Create:Name' => 'Quick creation~~', 'Brick:Portal:Create:ChooseType' => 'Please, choose a type~~', -)); +]); // Filter brick -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Brick:Portal:Filter:Name' => 'Prefilter a brick~~', 'Brick:Portal:Filter:SearchInput:Placeholder' => 'eg. connect wifi~~', 'Brick:Portal:Filter:SearchInput:Submit' => 'Search~~', -)); +]); diff --git a/datamodels/2.x/itop-portal-base/dictionaries/ja.dict.itop-portal-base.php b/datamodels/2.x/itop-portal-base/dictionaries/ja.dict.itop-portal-base.php index db8627a7b..a8952a8eb 100644 --- a/datamodels/2.x/itop-portal-base/dictionaries/ja.dict.itop-portal-base.php +++ b/datamodels/2.x/itop-portal-base/dictionaries/ja.dict.itop-portal-base.php @@ -1,15 +1,16 @@ '%1$s User portal~~', 'Page:PleaseWait' => 'Please wait...~~', 'Page:Home' => 'Home~~', @@ -53,19 +54,19 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Portal:File:DisplayInfo' => '%1$s~~', 'Portal:File:DisplayInfo+' => '%1$s (%2$s) Open / Download~~', 'Portal:Calendar-FirstDayOfWeek' => 'ja', //work with moment.js locales -)); +]); // Object form -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Portal:Form:Caselog:Entry:Close:Tooltip' => 'Close this entry~~', 'Portal:Form:Close:Warning' => 'Do you want to leave this form? Data entered may be lost~~', 'Portal:Error:ObjectCannotBeCreated' => 'Error: object cannot be created. Check associated objects and attachments before submitting this form again.~~', 'Portal:Error:ObjectCannotBeUpdated' => 'Error: object cannot be updated. Check associated objects and attachments before submitting this form again.~~', - 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', -)); + 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', +]); // UserProfile brick -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Brick:Portal:UserProfile:Name' => 'User profile~~', 'Brick:Portal:UserProfile:Navigation:Dropdown:MyProfil' => 'My profile~~', 'Brick:Portal:UserProfile:Navigation:Dropdown:Logout' => 'Logoff~~', @@ -76,15 +77,15 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Brick:Portal:UserProfile:Password:CantChangeForUnknownReason' => 'Can\'t change password, please contact your %1$s administrator~~', 'Brick:Portal:UserProfile:PersonalInformations:Title' => 'Personal information~~', 'Brick:Portal:UserProfile:Photo:Title' => 'Photo~~', -)); +]); // AggregatePageBrick -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Brick:Portal:AggregatePage:DefaultTitle' => 'Dashboard~~', -)); +]); // BrowseBrick brick -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Brick:Portal:Browse:Name' => 'Browse throught items~~', 'Brick:Portal:Browse:Mode:List' => 'List~~', 'Brick:Portal:Browse:Mode:Tree' => 'Tree~~', @@ -98,10 +99,10 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Brick:Portal:Browse:Tree:CollapseAll' => 'Collapse all~~', 'Brick:Portal:Browse:Filter:NoData' => 'No item~~', 'Brick:Portal:Browse:Mosaic:Back' => 'Back~~', -)); +]); // ManageBrick brick -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Brick:Portal:Manage:Name' => 'Manage items~~', 'Brick:Portal:Manage:Table:NoData' => 'No item.~~', 'Brick:Portal:Manage:Table:ItemActions' => 'Actions~~', @@ -116,10 +117,10 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Brick:Portal:Manage:fct:avg' => 'Average~~', 'Brick:Portal:Manage:fct:min' => 'Min~~', 'Brick:Portal:Manage:fct:max' => 'Max~~', -)); +]); // ObjectBrick brick -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Brick:Portal:Object:Name' => 'Object~~', 'Brick:Portal:Object:Form:Create:Title' => 'New %1$s~~', 'Brick:Portal:Object:Form:Edit:Title' => 'Updating %1$s~~', @@ -131,18 +132,18 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Brick:Portal:Object:Search:Hierarchy:Title' => 'Select %1$s~~', 'Brick:Portal:Object:Copy:TextToCopy' => '%2$s', 'Brick:Portal:Object:Copy:Tooltip' => 'Copy object link~~', - 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Copied~~' -)); + 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Copied~~', +]); // CreateBrick brick -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Brick:Portal:Create:Name' => 'Quick creation~~', 'Brick:Portal:Create:ChooseType' => 'Please, choose a type~~', -)); +]); // Filter brick -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Brick:Portal:Filter:Name' => 'Prefilter a brick~~', 'Brick:Portal:Filter:SearchInput:Placeholder' => 'eg. connect wifi~~', 'Brick:Portal:Filter:SearchInput:Submit' => 'Search~~', -)); +]); diff --git a/datamodels/2.x/itop-portal-base/dictionaries/nl.dict.itop-portal-base.php b/datamodels/2.x/itop-portal-base/dictionaries/nl.dict.itop-portal-base.php index 9ba61f147..7cc9e8069 100644 --- a/datamodels/2.x/itop-portal-base/dictionaries/nl.dict.itop-portal-base.php +++ b/datamodels/2.x/itop-portal-base/dictionaries/nl.dict.itop-portal-base.php @@ -1,16 +1,17 @@ (2018 - 2022) * */ -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Page:DefaultTitle' => '%1$s Gebruikersportaal', 'Page:PleaseWait' => 'Even geduld...', 'Page:Home' => 'Welkom', @@ -54,19 +55,19 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Portal:File:DisplayInfo' => '%1$s', 'Portal:File:DisplayInfo+' => '%1$s (%2$s) Open / Download', 'Portal:Calendar-FirstDayOfWeek' => 'nl', //work with moment.js locales -)); +]); // Object form -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Portal:Form:Caselog:Entry:Close:Tooltip' => 'Sluit dit item.', 'Portal:Form:Close:Warning' => 'Ben je zeker dat je dit venster wil sluiten? Ingevoerde gegevens kunnen verloren gaan.', 'Portal:Error:ObjectCannotBeCreated' => 'Fout: object kan niet worden aangemaakt. Kijk verwante objecten en bijlagen na vooraleer dit formulier opnieuw te versturen.', 'Portal:Error:ObjectCannotBeUpdated' => 'Fout: object kan niet worden aangepast. Kijk verwante objecten en bijlagen na vooraleer dit formulier opnieuw te versturen.', - 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', -)); + 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', +]); // UserProfile brick -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Brick:Portal:UserProfile:Name' => 'Gebruikersprofiel', 'Brick:Portal:UserProfile:Navigation:Dropdown:MyProfil' => 'Mijn profiel', 'Brick:Portal:UserProfile:Navigation:Dropdown:Logout' => 'Uitloggen', @@ -77,15 +78,15 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Brick:Portal:UserProfile:Password:CantChangeForUnknownReason' => 'Jouw wachtwoord kan niet gewijzigd worden. Neem contact op met de beheerder', 'Brick:Portal:UserProfile:PersonalInformations:Title' => 'Persoonlijke informatie', 'Brick:Portal:UserProfile:Photo:Title' => 'Foto', -)); +]); // AggregatePageBrick -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Brick:Portal:AggregatePage:DefaultTitle' => 'Dashboard', -)); +]); // BrowseBrick brick -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Brick:Portal:Browse:Name' => 'Bladeren', 'Brick:Portal:Browse:Mode:List' => 'Lijst', 'Brick:Portal:Browse:Mode:Tree' => 'Boomstructuur', @@ -99,10 +100,10 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Brick:Portal:Browse:Tree:CollapseAll' => 'Verberg alles', 'Brick:Portal:Browse:Filter:NoData' => 'Geen gegevens', 'Brick:Portal:Browse:Mosaic:Back' => 'Terug', -)); +]); // ManageBrick brick -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Brick:Portal:Manage:Name' => 'Beheer items', 'Brick:Portal:Manage:Table:NoData' => 'Geen gegevens', 'Brick:Portal:Manage:Table:ItemActions' => 'Acties', @@ -117,10 +118,10 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Brick:Portal:Manage:fct:avg' => 'Gemiddelde', 'Brick:Portal:Manage:fct:min' => 'Min', 'Brick:Portal:Manage:fct:max' => 'Max', -)); +]); // ObjectBrick brick -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Brick:Portal:Object:Name' => 'Object', 'Brick:Portal:Object:Form:Create:Title' => 'Nieuw %1$s', 'Brick:Portal:Object:Form:Edit:Title' => 'Verwerken %1$s', @@ -132,18 +133,18 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Brick:Portal:Object:Search:Hierarchy:Title' => 'Selecteer %1$s', 'Brick:Portal:Object:Copy:TextToCopy' => '%2$s', 'Brick:Portal:Object:Copy:Tooltip' => 'Kopieer link naar object', - 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Gekopieerd' -)); + 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Gekopieerd', +]); // CreateBrick brick -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Brick:Portal:Create:Name' => 'Snel aanmaken', 'Brick:Portal:Create:ChooseType' => 'Geef een type op.', -)); +]); // Filter brick -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Brick:Portal:Filter:Name' => 'Voorfilteren van een bouwsteen', 'Brick:Portal:Filter:SearchInput:Placeholder' => 'bv. wifi-verbinding', 'Brick:Portal:Filter:SearchInput:Submit' => 'Zoek', -)); +]); diff --git a/datamodels/2.x/itop-portal-base/dictionaries/pl.dict.itop-portal-base.php b/datamodels/2.x/itop-portal-base/dictionaries/pl.dict.itop-portal-base.php index 512c1a048..faf083d68 100644 --- a/datamodels/2.x/itop-portal-base/dictionaries/pl.dict.itop-portal-base.php +++ b/datamodels/2.x/itop-portal-base/dictionaries/pl.dict.itop-portal-base.php @@ -1,15 +1,16 @@ '%1$s portal użytkownika', 'Page:PleaseWait' => 'Proszę czekać...', 'Page:Home' => 'Start', @@ -53,19 +54,19 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Portal:File:DisplayInfo' => '%1$s', 'Portal:File:DisplayInfo+' => '%1$s (%2$s) Open / Pobierz', 'Portal:Calendar-FirstDayOfWeek' => 'en-us', //work with moment.js locales -)); +]); // Object form -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Portal:Form:Caselog:Entry:Close:Tooltip' => 'Zamknij ten wpis', 'Portal:Form:Close:Warning' => 'Chcesz opuścić ten formularz? Wprowadzone dane mogą zostać utracone', 'Portal:Error:ObjectCannotBeCreated' => 'Błąd: nie można utworzyć obiektu. Sprawdź powiązane obiekty i załączniki przed ponownym przesłaniem tego formularza.', 'Portal:Error:ObjectCannotBeUpdated' => 'Błąd: nie można zaktualizować obiektu. Sprawdź powiązane obiekty i załączniki przed ponownym przesłaniem tego formularza.', - 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', -)); + 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', +]); // UserProfile brick -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Brick:Portal:UserProfile:Name' => 'Profil użytkownika', 'Brick:Portal:UserProfile:Navigation:Dropdown:MyProfil' => 'Mój profil', 'Brick:Portal:UserProfile:Navigation:Dropdown:Logout' => 'Wyloguj', @@ -76,15 +77,15 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Brick:Portal:UserProfile:Password:CantChangeForUnknownReason' => 'Nie można zmienić hasła. Skontaktuj się z administratorem %1$s', 'Brick:Portal:UserProfile:PersonalInformations:Title' => 'Informacje osobiste', 'Brick:Portal:UserProfile:Photo:Title' => 'Zdjęcie', -)); +]); // AggregatePageBrick -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Brick:Portal:AggregatePage:DefaultTitle' => 'Pulpit', -)); +]); // BrowseBrick brick -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Brick:Portal:Browse:Name' => 'Przeglądaj elementy', 'Brick:Portal:Browse:Mode:List' => 'Lista', 'Brick:Portal:Browse:Mode:Tree' => 'Drzewo', @@ -98,10 +99,10 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Brick:Portal:Browse:Tree:CollapseAll' => 'Zwiń wszystkie', 'Brick:Portal:Browse:Filter:NoData' => 'Brak elementu', 'Brick:Portal:Browse:Mosaic:Back' => 'Wstecz', -)); +]); // ManageBrick brick -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Brick:Portal:Manage:Name' => 'Zarządzaj elementami', 'Brick:Portal:Manage:Table:NoData' => 'Brak elementu.', 'Brick:Portal:Manage:Table:ItemActions' => 'Akcje', @@ -116,10 +117,10 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Brick:Portal:Manage:fct:avg' => 'Średnia', 'Brick:Portal:Manage:fct:min' => 'Minimum', 'Brick:Portal:Manage:fct:max' => 'Maksimum', -)); +]); // ObjectBrick brick -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Brick:Portal:Object:Name' => 'Obiekty', 'Brick:Portal:Object:Form:Create:Title' => 'Nowy %1$s', 'Brick:Portal:Object:Form:Edit:Title' => 'Aktualizacja %1$s', @@ -131,18 +132,18 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Brick:Portal:Object:Search:Hierarchy:Title' => 'Wybierz %1$s', 'Brick:Portal:Object:Copy:TextToCopy' => '%2$s', 'Brick:Portal:Object:Copy:Tooltip' => 'Skopiuj obiekt', - 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Skopiowano' -)); + 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Skopiowano', +]); // CreateBrick brick -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Brick:Portal:Create:Name' => 'Szybkie tworzenie', 'Brick:Portal:Create:ChooseType' => 'Proszę wybrać typ', -)); +]); // Filter brick -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Brick:Portal:Filter:Name' => 'Wstępny filtr', 'Brick:Portal:Filter:SearchInput:Placeholder' => 'na przykład. podłącz wifi', 'Brick:Portal:Filter:SearchInput:Submit' => 'Szukaj', -)); +]); diff --git a/datamodels/2.x/itop-portal-base/dictionaries/pt_br.dict.itop-portal-base.php b/datamodels/2.x/itop-portal-base/dictionaries/pt_br.dict.itop-portal-base.php index 630926603..1617a99a8 100644 --- a/datamodels/2.x/itop-portal-base/dictionaries/pt_br.dict.itop-portal-base.php +++ b/datamodels/2.x/itop-portal-base/dictionaries/pt_br.dict.itop-portal-base.php @@ -1,15 +1,16 @@ 'Portal do Usuário do '.ITOP_APPLICATION_SHORT, 'Page:PleaseWait' => 'Aguarde...', 'Page:Home' => 'Página inicial', @@ -53,19 +54,19 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Portal:File:DisplayInfo' => '%1$s', 'Portal:File:DisplayInfo+' => '%1$s (%2$s) Abrir / Download', 'Portal:Calendar-FirstDayOfWeek' => 'pt-br', //work with moment.js locales -)); +]); // Object form -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Portal:Form:Caselog:Entry:Close:Tooltip' => 'Fechar esta solicitação', 'Portal:Form:Close:Warning' => 'Você deseja abandonar esta página? Os dados digitados podem ser perdidos', 'Portal:Error:ObjectCannotBeCreated' => 'Erro: objeto não pode ser criado. Verifique os objetos e anexos associados antes de enviar novamente este formulário', 'Portal:Error:ObjectCannotBeUpdated' => 'Erro: objeto não pode ser atualizado. Verifique os objetos e anexos associados antes de enviar novamente este formulário', - 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', -)); + 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', +]); // UserProfile brick -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Brick:Portal:UserProfile:Name' => 'Perfil de Usuário', 'Brick:Portal:UserProfile:Navigation:Dropdown:MyProfil' => 'Meu Perfil', 'Brick:Portal:UserProfile:Navigation:Dropdown:Logout' => 'Sair', @@ -76,15 +77,15 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Brick:Portal:UserProfile:Password:CantChangeForUnknownReason' => 'Não foi possível alterar sua senha, entre em contato com a T.I.', 'Brick:Portal:UserProfile:PersonalInformations:Title' => 'Informações pessoais', 'Brick:Portal:UserProfile:Photo:Title' => 'Imagem', -)); +]); // AggregatePageBrick -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Brick:Portal:AggregatePage:DefaultTitle' => 'Painel do '.ITOP_APPLICATION_SHORT, -)); +]); // BrowseBrick brick -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Brick:Portal:Browse:Name' => 'Navegar por itens', 'Brick:Portal:Browse:Mode:List' => 'Lista', 'Brick:Portal:Browse:Mode:Tree' => 'Cascata', @@ -98,10 +99,10 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Brick:Portal:Browse:Tree:CollapseAll' => 'Recolher todos', 'Brick:Portal:Browse:Filter:NoData' => 'Sem dados', 'Brick:Portal:Browse:Mosaic:Back' => 'Voltar', -)); +]); // ManageBrick brick -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Brick:Portal:Manage:Name' => 'Gerenciar itens', 'Brick:Portal:Manage:Table:NoData' => 'Sem dados', 'Brick:Portal:Manage:Table:ItemActions' => 'Ações', @@ -116,10 +117,10 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Brick:Portal:Manage:fct:avg' => 'Média', 'Brick:Portal:Manage:fct:min' => 'Min.', 'Brick:Portal:Manage:fct:max' => 'Máx.', -)); +]); // ObjectBrick brick -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Brick:Portal:Object:Name' => 'Objeto', 'Brick:Portal:Object:Form:Create:Title' => 'Novo %1$s', 'Brick:Portal:Object:Form:Edit:Title' => 'Alterar %1$s', @@ -131,18 +132,18 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Brick:Portal:Object:Search:Hierarchy:Title' => 'Selecionar %1$s', 'Brick:Portal:Object:Copy:TextToCopy' => '%2$s', 'Brick:Portal:Object:Copy:Tooltip' => 'Copiar', - 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Copiado' -)); + 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Copiado', +]); // CreateBrick brick -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Brick:Portal:Create:Name' => 'Criação rápida', 'Brick:Portal:Create:ChooseType' => 'Por favor, escolha um tipo:', -)); +]); // Filter brick -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Brick:Portal:Filter:Name' => 'Filtro ativado', 'Brick:Portal:Filter:SearchInput:Placeholder' => 'ex. conectar ao WiFi', 'Brick:Portal:Filter:SearchInput:Submit' => 'Pesquisa', -)); +]); diff --git a/datamodels/2.x/itop-portal-base/dictionaries/ru.dict.itop-portal-base.php b/datamodels/2.x/itop-portal-base/dictionaries/ru.dict.itop-portal-base.php index cc7b677dd..5875b1b0c 100644 --- a/datamodels/2.x/itop-portal-base/dictionaries/ru.dict.itop-portal-base.php +++ b/datamodels/2.x/itop-portal-base/dictionaries/ru.dict.itop-portal-base.php @@ -1,16 +1,17 @@ * */ -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Page:DefaultTitle' => 'Пользовательский портал %1$s', 'Page:PleaseWait' => 'Пожалуйста, подождите...', 'Page:Home' => 'Домашняя страница', @@ -54,19 +55,19 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Portal:File:DisplayInfo' => '%1$s', 'Portal:File:DisplayInfo+' => '%1$s (%2$s) Открыть / Скачать', 'Portal:Calendar-FirstDayOfWeek' => 'ru', //work with moment.js locales -)); +]); // Object form -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Portal:Form:Caselog:Entry:Close:Tooltip' => 'Close this entry~~', 'Portal:Form:Close:Warning' => 'Вы действительно хотите закрыть эту форму? Введённые данные могут быть утеряны.', 'Portal:Error:ObjectCannotBeCreated' => 'Error: object cannot be created. Check associated objects and attachments before submitting this form again.~~', 'Portal:Error:ObjectCannotBeUpdated' => 'Error: object cannot be updated. Check associated objects and attachments before submitting this form again.~~', - 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', -)); + 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', +]); // UserProfile brick -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Brick:Portal:UserProfile:Name' => 'Профиль пользователя', 'Brick:Portal:UserProfile:Navigation:Dropdown:MyProfil' => 'Мой профиль', 'Brick:Portal:UserProfile:Navigation:Dropdown:Logout' => 'Выйти', @@ -77,15 +78,15 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Brick:Portal:UserProfile:Password:CantChangeForUnknownReason' => 'Не удалось изменить пароль, пожалуйста, свяжитесь с вашим администратором %1$s.', 'Brick:Portal:UserProfile:PersonalInformations:Title' => 'Персональная информация', 'Brick:Portal:UserProfile:Photo:Title' => 'Фотография', -)); +]); // AggregatePageBrick -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Brick:Portal:AggregatePage:DefaultTitle' => 'Дашборд', -)); +]); // BrowseBrick brick -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Brick:Portal:Browse:Name' => 'Просмотр элементов', 'Brick:Portal:Browse:Mode:List' => 'Список', 'Brick:Portal:Browse:Mode:Tree' => 'Дерево', @@ -99,10 +100,10 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Brick:Portal:Browse:Tree:CollapseAll' => 'Свернуть все', 'Brick:Portal:Browse:Filter:NoData' => 'Нет элементов', 'Brick:Portal:Browse:Mosaic:Back' => 'Назад', -)); +]); // ManageBrick brick -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Brick:Portal:Manage:Name' => 'Управление элементами', 'Brick:Portal:Manage:Table:NoData' => 'Нет элементов', 'Brick:Portal:Manage:Table:ItemActions' => 'Действия', @@ -117,10 +118,10 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Brick:Portal:Manage:fct:avg' => 'Среднее', 'Brick:Portal:Manage:fct:min' => 'Минимум', 'Brick:Portal:Manage:fct:max' => 'Максимум', -)); +]); // ObjectBrick brick -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Brick:Portal:Object:Name' => 'Object', 'Brick:Portal:Object:Form:Create:Title' => 'Создать %1$s', 'Brick:Portal:Object:Form:Edit:Title' => 'Обновление %1$s', @@ -132,18 +133,18 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Brick:Portal:Object:Search:Hierarchy:Title' => 'Выбрать %1$s', 'Brick:Portal:Object:Copy:TextToCopy' => '%2$s', 'Brick:Portal:Object:Copy:Tooltip' => 'Скопировать ссылку на объект', - 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Ссылка скопирована' -)); + 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Ссылка скопирована', +]); // CreateBrick brick -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Brick:Portal:Create:Name' => 'Быстрое создание', 'Brick:Portal:Create:ChooseType' => 'Пожалуйста, выберите тип', -)); +]); // Filter brick -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Brick:Portal:Filter:Name' => 'Фильтр', 'Brick:Portal:Filter:SearchInput:Placeholder' => 'например, подключить wi-fi', 'Brick:Portal:Filter:SearchInput:Submit' => 'Искать', -)); +]); diff --git a/datamodels/2.x/itop-portal-base/dictionaries/sk.dict.itop-portal-base.php b/datamodels/2.x/itop-portal-base/dictionaries/sk.dict.itop-portal-base.php index b4a0df5be..a03c781b1 100644 --- a/datamodels/2.x/itop-portal-base/dictionaries/sk.dict.itop-portal-base.php +++ b/datamodels/2.x/itop-portal-base/dictionaries/sk.dict.itop-portal-base.php @@ -1,15 +1,16 @@ '%1$s User portal~~', 'Page:PleaseWait' => 'Please wait...~~', 'Page:Home' => 'Home~~', @@ -53,19 +54,19 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Portal:File:DisplayInfo' => '%1$s~~', 'Portal:File:DisplayInfo+' => '%1$s (%2$s) Open / Download~~', 'Portal:Calendar-FirstDayOfWeek' => 'en-us~~', //work with moment.js locales -)); +]); // Object form -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Portal:Form:Caselog:Entry:Close:Tooltip' => 'Close this entry~~', 'Portal:Form:Close:Warning' => 'Do you want to leave this form? Data entered may be lost~~', 'Portal:Error:ObjectCannotBeCreated' => 'Error: object cannot be created. Check associated objects and attachments before submitting this form again.~~', 'Portal:Error:ObjectCannotBeUpdated' => 'Error: object cannot be updated. Check associated objects and attachments before submitting this form again.~~', - 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', -)); + 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', +]); // UserProfile brick -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Brick:Portal:UserProfile:Name' => 'User profile~~', 'Brick:Portal:UserProfile:Navigation:Dropdown:MyProfil' => 'My profile~~', 'Brick:Portal:UserProfile:Navigation:Dropdown:Logout' => 'Logoff~~', @@ -76,15 +77,15 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Brick:Portal:UserProfile:Password:CantChangeForUnknownReason' => 'Can\'t change password, please contact your %1$s administrator~~', 'Brick:Portal:UserProfile:PersonalInformations:Title' => 'Personal information~~', 'Brick:Portal:UserProfile:Photo:Title' => 'Photo~~', -)); +]); // AggregatePageBrick -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Brick:Portal:AggregatePage:DefaultTitle' => 'Dashboard~~', -)); +]); // BrowseBrick brick -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Brick:Portal:Browse:Name' => 'Browse throught items~~', 'Brick:Portal:Browse:Mode:List' => 'List~~', 'Brick:Portal:Browse:Mode:Tree' => 'Tree~~', @@ -98,10 +99,10 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Brick:Portal:Browse:Tree:CollapseAll' => 'Collapse all~~', 'Brick:Portal:Browse:Filter:NoData' => 'No item~~', 'Brick:Portal:Browse:Mosaic:Back' => 'Back~~', -)); +]); // ManageBrick brick -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Brick:Portal:Manage:Name' => 'Manage items~~', 'Brick:Portal:Manage:Table:NoData' => 'No item.~~', 'Brick:Portal:Manage:Table:ItemActions' => 'Actions~~', @@ -116,10 +117,10 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Brick:Portal:Manage:fct:avg' => 'Average~~', 'Brick:Portal:Manage:fct:min' => 'Min~~', 'Brick:Portal:Manage:fct:max' => 'Max~~', -)); +]); // ObjectBrick brick -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Brick:Portal:Object:Name' => 'Object~~', 'Brick:Portal:Object:Form:Create:Title' => 'New %1$s~~', 'Brick:Portal:Object:Form:Edit:Title' => 'Updating %1$s~~', @@ -131,18 +132,18 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Brick:Portal:Object:Search:Hierarchy:Title' => 'Select %1$s~~', 'Brick:Portal:Object:Copy:TextToCopy' => '%2$s', 'Brick:Portal:Object:Copy:Tooltip' => 'Copy object link~~', - 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Copied~~' -)); + 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Copied~~', +]); // CreateBrick brick -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Brick:Portal:Create:Name' => 'Quick creation~~', 'Brick:Portal:Create:ChooseType' => 'Please, choose a type~~', -)); +]); // Filter brick -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Brick:Portal:Filter:Name' => 'Prefilter a brick~~', 'Brick:Portal:Filter:SearchInput:Placeholder' => 'eg. connect wifi~~', 'Brick:Portal:Filter:SearchInput:Submit' => 'Search~~', -)); +]); diff --git a/datamodels/2.x/itop-portal-base/dictionaries/tr.dict.itop-portal-base.php b/datamodels/2.x/itop-portal-base/dictionaries/tr.dict.itop-portal-base.php index a85fd6c81..fca699326 100644 --- a/datamodels/2.x/itop-portal-base/dictionaries/tr.dict.itop-portal-base.php +++ b/datamodels/2.x/itop-portal-base/dictionaries/tr.dict.itop-portal-base.php @@ -1,15 +1,16 @@ '%1$s User portal~~', 'Page:PleaseWait' => 'Please wait...~~', 'Page:Home' => 'Home~~', @@ -53,19 +54,19 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Portal:File:DisplayInfo' => '%1$s~~', 'Portal:File:DisplayInfo+' => '%1$s (%2$s) Open / Download~~', 'Portal:Calendar-FirstDayOfWeek' => 'tr', //work with moment.js locales -)); +]); // Object form -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Portal:Form:Caselog:Entry:Close:Tooltip' => 'Close this entry~~', 'Portal:Form:Close:Warning' => 'Do you want to leave this form? Data entered may be lost~~', 'Portal:Error:ObjectCannotBeCreated' => 'Error: object cannot be created. Check associated objects and attachments before submitting this form again.~~', 'Portal:Error:ObjectCannotBeUpdated' => 'Error: object cannot be updated. Check associated objects and attachments before submitting this form again.~~', - 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', -)); + 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', +]); // UserProfile brick -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Brick:Portal:UserProfile:Name' => 'User profile~~', 'Brick:Portal:UserProfile:Navigation:Dropdown:MyProfil' => 'My profile~~', 'Brick:Portal:UserProfile:Navigation:Dropdown:Logout' => 'Logoff~~', @@ -76,15 +77,15 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Brick:Portal:UserProfile:Password:CantChangeForUnknownReason' => 'Can\'t change password, please contact your %1$s administrator~~', 'Brick:Portal:UserProfile:PersonalInformations:Title' => 'Personal information~~', 'Brick:Portal:UserProfile:Photo:Title' => 'Photo~~', -)); +]); // AggregatePageBrick -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Brick:Portal:AggregatePage:DefaultTitle' => 'Dashboard~~', -)); +]); // BrowseBrick brick -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Brick:Portal:Browse:Name' => 'Browse throught items~~', 'Brick:Portal:Browse:Mode:List' => 'List~~', 'Brick:Portal:Browse:Mode:Tree' => 'Tree~~', @@ -98,10 +99,10 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Brick:Portal:Browse:Tree:CollapseAll' => 'Collapse all~~', 'Brick:Portal:Browse:Filter:NoData' => 'No item~~', 'Brick:Portal:Browse:Mosaic:Back' => 'Back~~', -)); +]); // ManageBrick brick -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Brick:Portal:Manage:Name' => 'Manage items~~', 'Brick:Portal:Manage:Table:NoData' => 'No item.~~', 'Brick:Portal:Manage:Table:ItemActions' => 'Actions~~', @@ -116,10 +117,10 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Brick:Portal:Manage:fct:avg' => 'Average~~', 'Brick:Portal:Manage:fct:min' => 'Min~~', 'Brick:Portal:Manage:fct:max' => 'Max~~', -)); +]); // ObjectBrick brick -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Brick:Portal:Object:Name' => 'Object~~', 'Brick:Portal:Object:Form:Create:Title' => 'New %1$s~~', 'Brick:Portal:Object:Form:Edit:Title' => 'Updating %1$s~~', @@ -131,18 +132,18 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Brick:Portal:Object:Search:Hierarchy:Title' => 'Select %1$s~~', 'Brick:Portal:Object:Copy:TextToCopy' => '%2$s', 'Brick:Portal:Object:Copy:Tooltip' => 'Copy object link~~', - 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Copied~~' -)); + 'Brick:Portal:Object:Copy:CopiedTooltip' => 'Copied~~', +]); // CreateBrick brick -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Brick:Portal:Create:Name' => 'Quick creation~~', 'Brick:Portal:Create:ChooseType' => 'Please, choose a type~~', -)); +]); // Filter brick -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Brick:Portal:Filter:Name' => 'Prefilter a brick~~', 'Brick:Portal:Filter:SearchInput:Placeholder' => 'eg. connect wifi~~', 'Brick:Portal:Filter:SearchInput:Submit' => 'Search~~', -)); +]); diff --git a/datamodels/2.x/itop-portal-base/dictionaries/zh_cn.dict.itop-portal-base.php b/datamodels/2.x/itop-portal-base/dictionaries/zh_cn.dict.itop-portal-base.php index 9f2a05a97..87b44e1b4 100644 --- a/datamodels/2.x/itop-portal-base/dictionaries/zh_cn.dict.itop-portal-base.php +++ b/datamodels/2.x/itop-portal-base/dictionaries/zh_cn.dict.itop-portal-base.php @@ -1,4 +1,5 @@ '%1$s 用户门户', 'Page:PleaseWait' => '请稍候...', 'Page:Home' => '主页', @@ -62,19 +63,19 @@ Dict::Add('ZH CN', 'Chinese', '简体中文', array( 'Portal:File:DisplayInfo' => '%1$s', 'Portal:File:DisplayInfo+' => '%1$s (%2$s) 打开 / 下载', 'Portal:Calendar-FirstDayOfWeek' => 'zh-cn', //work with moment.js locales -)); +]); // Object form -Dict::Add('ZH CN', 'Chinese', '简体中文', array( +Dict::Add('ZH CN', 'Chinese', '简体中文', [ 'Portal:Form:Caselog:Entry:Close:Tooltip' => '关闭此条目', 'Portal:Form:Close:Warning' => '确定要离开表单吗? 已输入数据会丢失', 'Portal:Error:ObjectCannotBeCreated' => '错误: 无法创建对象. 请在再次提交表单前检查相关对象和附件.', 'Portal:Error:ObjectCannotBeUpdated' => '错误: 无法更新对象. 请在再次提交表单前检查相关对象和附件.', - 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', -)); + 'Portal:Error:CheckToWriteFailed' => 'Error during validation of field \'%1$s\': %2$s~~', +]); // UserProfile brick -Dict::Add('ZH CN', 'Chinese', '简体中文', array( +Dict::Add('ZH CN', 'Chinese', '简体中文', [ 'Brick:Portal:UserProfile:Name' => '用户资料', 'Brick:Portal:UserProfile:Navigation:Dropdown:MyProfil' => '我的资料', 'Brick:Portal:UserProfile:Navigation:Dropdown:Logout' => '注销', @@ -85,15 +86,15 @@ Dict::Add('ZH CN', 'Chinese', '简体中文', array( 'Brick:Portal:UserProfile:Password:CantChangeForUnknownReason' => '无法修改密码, 请联系管理员', 'Brick:Portal:UserProfile:PersonalInformations:Title' => '人员信息', 'Brick:Portal:UserProfile:Photo:Title' => '头像', -)); +]); // AggregatePageBrick -Dict::Add('ZH CN', 'Chinese', '简体中文', array( +Dict::Add('ZH CN', 'Chinese', '简体中文', [ 'Brick:Portal:AggregatePage:DefaultTitle' => '仪表盘', -)); +]); // BrowseBrick brick -Dict::Add('ZH CN', 'Chinese', '简体中文', array( +Dict::Add('ZH CN', 'Chinese', '简体中文', [ 'Brick:Portal:Browse:Name' => '浏览项目', 'Brick:Portal:Browse:Mode:List' => '列表', 'Brick:Portal:Browse:Mode:Tree' => '树形', @@ -107,10 +108,10 @@ Dict::Add('ZH CN', 'Chinese', '简体中文', array( 'Brick:Portal:Browse:Tree:CollapseAll' => '全部收起', 'Brick:Portal:Browse:Filter:NoData' => '没有项目', 'Brick:Portal:Browse:Mosaic:Back' => '返回', -)); +]); // ManageBrick brick -Dict::Add('ZH CN', 'Chinese', '简体中文', array( +Dict::Add('ZH CN', 'Chinese', '简体中文', [ 'Brick:Portal:Manage:Name' => '管理项目', 'Brick:Portal:Manage:Table:NoData' => '没有项目.', 'Brick:Portal:Manage:Table:ItemActions' => '操作', @@ -125,10 +126,10 @@ Dict::Add('ZH CN', 'Chinese', '简体中文', array( 'Brick:Portal:Manage:fct:avg' => '平均', 'Brick:Portal:Manage:fct:min' => '最小', 'Brick:Portal:Manage:fct:max' => '最大', -)); +]); // ObjectBrick brick -Dict::Add('ZH CN', 'Chinese', '简体中文', array( +Dict::Add('ZH CN', 'Chinese', '简体中文', [ 'Brick:Portal:Object:Name' => '对象', 'Brick:Portal:Object:Form:Create:Title' => '新建 %1$s', 'Brick:Portal:Object:Form:Edit:Title' => '正在更新 %1$s', @@ -140,18 +141,18 @@ Dict::Add('ZH CN', 'Chinese', '简体中文', array( 'Brick:Portal:Object:Search:Hierarchy:Title' => '选择 %1$s', 'Brick:Portal:Object:Copy:TextToCopy' => '%2$s', 'Brick:Portal:Object:Copy:Tooltip' => '复制对象链接', - 'Brick:Portal:Object:Copy:CopiedTooltip' => '已复制' -)); + 'Brick:Portal:Object:Copy:CopiedTooltip' => '已复制', +]); // CreateBrick brick -Dict::Add('ZH CN', 'Chinese', '简体中文', array( +Dict::Add('ZH CN', 'Chinese', '简体中文', [ 'Brick:Portal:Create:Name' => '快速创建', 'Brick:Portal:Create:ChooseType' => '请选择类型', -)); +]); // Filter brick -Dict::Add('ZH CN', 'Chinese', '简体中文', array( +Dict::Add('ZH CN', 'Chinese', '简体中文', [ 'Brick:Portal:Filter:Name' => '预筛选组件', 'Brick:Portal:Filter:SearchInput:Placeholder' => '例如. 连接wifi', 'Brick:Portal:Filter:SearchInput:Submit' => '搜索', -)); +]); diff --git a/datamodels/2.x/itop-portal-base/module.itop-portal-base.php b/datamodels/2.x/itop-portal-base/module.itop-portal-base.php index 4ce34b1d8..3cb0b401f 100644 --- a/datamodels/2.x/itop-portal-base/module.itop-portal-base.php +++ b/datamodels/2.x/itop-portal-base/module.itop-portal-base.php @@ -1,4 +1,5 @@ 'Portal Development Library', 'category' => 'Portal', // Setup - 'dependencies' => array( - ), + 'dependencies' => [ + ], 'mandatory' => true, 'visible' => false, // Components - 'datamodel' => array( + 'datamodel' => [ // Note: The autoloader is there instead of portal/config/bootstrap.php in order to be available for other modules with a dependency on this one. // eg. If a module has a class extending \Combodo\iTop\Portal\Controller\AbstractController, it needs to find it even if the portal kernel is not loaded. 'portal/vendor/autoload.php', - ), - 'webservice' => array( + ], + 'webservice' => [ //'webservices.itop-portal-base.php', - ), - 'dictionary' => array( - ), - 'data.struct' => array( + ], + 'dictionary' => [ + ], + 'data.struct' => [ //'data.struct.itop-portal-base.xml', - ), - 'data.sample' => array( + ], + 'data.sample' => [ //'data.sample.itop-portal-base.xml', - ), + ], // Documentation 'doc.manual_setup' => '', 'doc.more_information' => '', // Default settings - 'settings' => array( - ), - ) + 'settings' => [ + ], + ] ); - // ____ _ _ _ __ _ _ _ _ _______ // | _ \| | ___ __ _ ___ ___ | |_ __ _| | _____ ___ __ _ _ __ ___ ___ / _| | |_| |__ ___ _ __ ___ _ __| |_ __ _| | / /___ / // | |_) | |/ _ \/ _` / __|/ _ \ | __/ _` | |/ / _ \ / __/ _` | '__/ _ \ / _ \| |_ | __| '_ \ / _ \ | '_ \ / _ \| '__| __/ _` | | / / |_ \ diff --git a/datamodels/2.x/itop-portal-base/portal/config/bootstrap.php b/datamodels/2.x/itop-portal-base/portal/config/bootstrap.php index e888e5b0b..1ec5f140b 100644 --- a/datamodels/2.x/itop-portal-base/portal/config/bootstrap.php +++ b/datamodels/2.x/itop-portal-base/portal/config/bootstrap.php @@ -28,14 +28,10 @@ use Symfony\Component\Dotenv\Dotenv; require_once APPROOT.'/lib/autoload.php'; // Load current environment if necessary (typically from CLI as the app is not started yet) -if (!defined('MODULESROOT')) -{ - if (file_exists(__DIR__.'/../../../../approot.inc.php')) - { +if (!defined('MODULESROOT')) { + if (file_exists(__DIR__.'/../../../../approot.inc.php')) { require_once __DIR__.'/../../../../approot.inc.php'; // When in env-xxxx folder - } - else - { + } else { require_once __DIR__.'/../../../../../approot.inc.php'; // When in datamodels/x.x folder } require_once APPROOT.'/application/startup.inc.php'; @@ -62,7 +58,7 @@ if (!class_exists(Dotenv::class)) { } if (null === $sEnv = (isset($_SERVER['APP_ENV']) ? $_SERVER['APP_ENV'] : (isset($_ENV['APP_ENV']) ? $_ENV['APP_ENV'] : null))) { - $oDotenv->populate(array('APP_ENV' => $sEnv = 'prod')); + $oDotenv->populate(['APP_ENV' => $sEnv = 'prod']); } if ('test' !== $sEnv && file_exists($sPathDist = "$sPath.local")) { @@ -83,31 +79,27 @@ if (!class_exists(Dotenv::class)) { $_SERVER += $_ENV; $_SERVER['APP_ENV'] = $_ENV['APP_ENV'] = (isset($_SERVER['APP_ENV']) ? $_SERVER['APP_ENV'] : (isset($_ENV['APP_ENV']) ? $_ENV['APP_ENV'] : null)) ?: 'prod'; $_SERVER['APP_DEBUG'] = isset($_SERVER['APP_DEBUG']) ? $_SERVER['APP_DEBUG'] : (isset($_ENV['APP_DEBUG']) ? $_ENV['APP_DEBUG'] : ('prod' !== $_SERVER['APP_ENV'])); -$_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = (int)$_SERVER['APP_DEBUG'] || filter_var($_SERVER['APP_DEBUG'], - FILTER_VALIDATE_BOOLEAN) ? '1' : '0'; +$_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = (int)$_SERVER['APP_DEBUG'] || filter_var( + $_SERVER['APP_DEBUG'], + FILTER_VALIDATE_BOOLEAN +) ? '1' : '0'; -if ($_SERVER['APP_DEBUG']) -{ +if ($_SERVER['APP_DEBUG']) { umask(0000); - if (class_exists(Debug::class)) - { + if (class_exists(Debug::class)) { Debug::enable(); } } -if (isset($_ENV['PORTAL_ID'])) -{ +if (isset($_ENV['PORTAL_ID'])) { // Nothing to do } // Note: Default value is set to "false" to differentiate an empty value from a non given parameter -elseif ($sPortalId = utils::ReadParam('portal_id', false, true)) -{ +elseif ($sPortalId = utils::ReadParam('portal_id', false, true)) { $_ENV['PORTAL_ID'] = $sPortalId; -} -elseif (defined('PORTAL_ID')) -{ +} elseif (defined('PORTAL_ID')) { $_ENV['PORTAL_ID'] = PORTAL_ID; @trigger_error( sprintf( @@ -118,16 +110,14 @@ elseif (defined('PORTAL_ID')) ); } -if (empty($_ENV['PORTAL_ID'])) -{ +if (empty($_ENV['PORTAL_ID'])) { echo "Missing argument 'portal_id'"; exit; } // Make sure that the PORTAL_ID constant is also defined // Note: This is widely used in extensions, snippets and all -if (!defined('PORTAL_ID')) -{ +if (!defined('PORTAL_ID')) { define('PORTAL_ID', $_ENV['PORTAL_ID']); } @@ -141,4 +131,4 @@ $_ENV['COMBODO_PORTAL_BASE_ABSOLUTE_URL'] = utils::GetAbsoluteUrlModulesRoot().' $_ENV['COMBODO_PORTAL_BASE_ABSOLUTE_PATH'] = MODULESROOT.'/itop-portal-base/portal/public/'; $_ENV['COMBODO_PORTAL_INSTANCE_ABSOLUTE_URL'] = utils::GetAbsoluteUrlModulesRoot().$_ENV['PORTAL_ID'].'/'; $_ENV['COMBODO_PORTAL_LANGUAGE'] = UserRights::GetUserLanguage(); -$_ENV['COMBODO_PORTAL_METADATA_LANGUAGE'] = strtolower(substr($_ENV['COMBODO_PORTAL_LANGUAGE'], 0, 2));; \ No newline at end of file +$_ENV['COMBODO_PORTAL_METADATA_LANGUAGE'] = strtolower(substr($_ENV['COMBODO_PORTAL_LANGUAGE'], 0, 2));; diff --git a/datamodels/2.x/itop-portal-base/portal/src/Brick/ManageBrick.php b/datamodels/2.x/itop-portal-base/portal/src/Brick/ManageBrick.php index ababa6596..8e9f67257 100644 --- a/datamodels/2.x/itop-portal-base/portal/src/Brick/ManageBrick.php +++ b/datamodels/2.x/itop-portal-base/portal/src/Brick/ManageBrick.php @@ -32,87 +32,87 @@ use ModuleDesign; class ManageBrick extends PortalBrick { /** @var string ENUM_ACTION_VIEW */ - const ENUM_ACTION_VIEW = 'view'; + public const ENUM_ACTION_VIEW = 'view'; /** @var string ENUM_ACTION_EDIT */ - const ENUM_ACTION_EDIT = 'edit'; + public const ENUM_ACTION_EDIT = 'edit'; /** @var string ENUM_TILE_MODE_TEXT */ - const ENUM_TILE_MODE_TEXT = 'text'; + public const ENUM_TILE_MODE_TEXT = 'text'; /** @var string ENUM_TILE_MODE_BADGE */ - const ENUM_TILE_MODE_BADGE = 'badge'; + public const ENUM_TILE_MODE_BADGE = 'badge'; /** @var string ENUM_TILE_MODE_PIE */ - const ENUM_TILE_MODE_PIE = 'pie-chart'; + public const ENUM_TILE_MODE_PIE = 'pie-chart'; /** @var string ENUM_TILE_MODE_BAR */ - const ENUM_TILE_MODE_BAR = 'bar-chart'; + public const ENUM_TILE_MODE_BAR = 'bar-chart'; /** @var string ENUM_TILE_MODE_TOP */ - const ENUM_TILE_MODE_TOP = 'top-list'; + public const ENUM_TILE_MODE_TOP = 'top-list'; /** @var string ENUM_DISPLAY_MODE_LIST */ - const ENUM_DISPLAY_MODE_LIST = 'list'; + public const ENUM_DISPLAY_MODE_LIST = 'list'; /** @var string ENUM_DISPLAY_MODE_PIE */ - const ENUM_DISPLAY_MODE_PIE = 'pie-chart'; + public const ENUM_DISPLAY_MODE_PIE = 'pie-chart'; /** @var string ENUM_DISPLAY_MODE_BAR */ - const ENUM_DISPLAY_MODE_BAR = 'bar-chart'; + public const ENUM_DISPLAY_MODE_BAR = 'bar-chart'; /** @var string ENUM_PAGE_TEMPLATE_PATH_TABLE * @deprecated since 3.2.1 * */ - const ENUM_PAGE_TEMPLATE_PATH_TABLE = 'itop-portal-base/portal/templates/bricks/manage/layout-table.html.twig'; + public const ENUM_PAGE_TEMPLATE_PATH_TABLE = 'itop-portal-base/portal/templates/bricks/manage/layout-table.html.twig'; /** @var string ENUM_PAGE_TEMPLATE_PATH_CHART * @deprecated since 3.2.1 * */ - const ENUM_PAGE_TEMPLATE_PATH_CHART = 'itop-portal-base/portal/templates/bricks/manage/layout-chart.html.twig'; + public const ENUM_PAGE_TEMPLATE_PATH_CHART = 'itop-portal-base/portal/templates/bricks/manage/layout-chart.html.twig'; /** Overloaded constants */ - const DEFAULT_DECORATION_CLASS_HOME = 'fas fa-tag'; - const DEFAULT_DECORATION_CLASS_NAVIGATION_MENU = 'fas fa-tag fa-2x'; + public const DEFAULT_DECORATION_CLASS_HOME = 'fas fa-tag'; + public const DEFAULT_DECORATION_CLASS_NAVIGATION_MENU = 'fas fa-tag fa-2x'; /** * @deprecated 3.2.1 */ - const DEFAULT_PAGE_TEMPLATE_PATH = self::ENUM_PAGE_TEMPLATE_PATH_TABLE; - const DEFAULT_DATA_LOADING = self::ENUM_DATA_LOADING_LAZY; + public const DEFAULT_PAGE_TEMPLATE_PATH = self::ENUM_PAGE_TEMPLATE_PATH_TABLE; + public const DEFAULT_DATA_LOADING = self::ENUM_DATA_LOADING_LAZY; /** * @deprecated 3.2.1 */ - const DEFAULT_TILE_TEMPLATE_PATH = 'itop-portal-base/portal/templates/bricks/manage/tile-default.html.twig'; - const DEFAULT_TILE_CONTROLLER_ACTION = 'Combodo\\iTop\\Portal\\Controller\\ManageBrickController::TileAction'; + public const DEFAULT_TILE_TEMPLATE_PATH = 'itop-portal-base/portal/templates/bricks/manage/tile-default.html.twig'; + public const DEFAULT_TILE_CONTROLLER_ACTION = 'Combodo\\iTop\\Portal\\Controller\\ManageBrickController::TileAction'; /** @var string DEFAULT_OQL */ - const DEFAULT_OQL = ''; + public const DEFAULT_OQL = ''; /** @var string DEFAULT_OPENING_MODE */ - const DEFAULT_OPENING_MODE = self::ENUM_ACTION_EDIT; + public const DEFAULT_OPENING_MODE = self::ENUM_ACTION_EDIT; /** @var int DEFAULT_LIST_LENGTH */ - const DEFAULT_LIST_LENGTH = 20; + public const DEFAULT_LIST_LENGTH = 20; /** @var string DEFAULT_ZLIST_FIELDS */ - const DEFAULT_ZLIST_FIELDS = 'list'; + public const DEFAULT_ZLIST_FIELDS = 'list'; /** @var bool DEFAULT_SHOW_TAB_COUNTS */ - const DEFAULT_SHOW_TAB_COUNTS = false; + public const DEFAULT_SHOW_TAB_COUNTS = false; /** @var string DEFAULT_DISPLAY_MODE */ - const DEFAULT_DISPLAY_MODE = self::ENUM_DISPLAY_MODE_LIST; + public const DEFAULT_DISPLAY_MODE = self::ENUM_DISPLAY_MODE_LIST; /** @var string DEFAULT_TILE_MODE */ - const DEFAULT_TILE_MODE = self::ENUM_TILE_MODE_TEXT; + public const DEFAULT_TILE_MODE = self::ENUM_TILE_MODE_TEXT; /** @var int DEFAULT_GROUP_LIMIT */ - const DEFAULT_GROUP_LIMIT = 0; + public const DEFAULT_GROUP_LIMIT = 0; /** @var bool DEFAULT_GROUP_SHOW_OTHERS */ - const DEFAULT_GROUP_SHOW_OTHERS = true; + public const DEFAULT_GROUP_SHOW_OTHERS = true; /** @var int DEFAULT_WIDTH */ - const DEFAULT_WIDTH = 500; + public const DEFAULT_WIDTH = 500; /** @var array $aDisplayModes */ - public static array $aDisplayModes = array( + public static array $aDisplayModes = [ self::ENUM_DISPLAY_MODE_LIST, self::ENUM_DISPLAY_MODE_PIE, self::ENUM_DISPLAY_MODE_BAR, - ); + ]; /** @var array $aTileModes */ - public static array $aTileModes = array( + public static array $aTileModes = [ self::ENUM_TILE_MODE_TEXT, self::ENUM_TILE_MODE_BADGE, self::ENUM_TILE_MODE_PIE, self::ENUM_TILE_MODE_BAR, self::ENUM_TILE_MODE_TOP, - ); + ]; /** @var array $aDefaultTileData */ private static array $aDefaultTileData = [ @@ -167,7 +167,7 @@ class ManageBrick extends PortalBrick /** @var bool $bShowTabCounts */ protected $bShowTabCounts; /** @var array $aAvailableDisplayModes */ - protected $aAvailableDisplayModes = array(); + protected $aAvailableDisplayModes = []; /** @var string $sDefaultDisplayMode */ protected $sDefaultDisplayMode; /** @var string $sTileMode */ @@ -183,16 +183,17 @@ class ManageBrick extends PortalBrick public static function RegisterTemplates(TemplatesRegister $oTemplatesRegister): void { parent::RegisterTemplates($oTemplatesRegister); - $oTemplatesRegister->RegisterTemplates(self::class, - TemplateDefinitionDto::Create('tile', static::TEMPLATES_BASE_PATH . 'manage/tile-default.html.twig'), - TemplateDefinitionDto::Create('tile_badge', static::TEMPLATES_BASE_PATH. 'manage/tile-badge.html.twig'), - TemplateDefinitionDto::Create('tile_chart', static::TEMPLATES_BASE_PATH . 'manage/tile-chart.html.twig'), - TemplateDefinitionDto::Create('tile_top_list', static::TEMPLATES_BASE_PATH . 'manage/tile-top-list.html.twig'), - TemplateDefinitionDto::Create('page', static::TEMPLATES_BASE_PATH . 'manage/layout.html.twig'), - TemplateDefinitionDto::Create('page_table', static::TEMPLATES_BASE_PATH . 'manage/layout-table.html.twig'), - TemplateDefinitionDto::Create('page_chart', static::TEMPLATES_BASE_PATH . 'manage/layout-chart.html.twig'), - TemplateDefinitionDto::Create('mode_chart_bar', static::TEMPLATES_BASE_PATH . 'manage/mode-bar-chart.html.twig', true, self::ENUM_DISPLAY_MODE_BAR), - TemplateDefinitionDto::Create('mode_chart_pie', static::TEMPLATES_BASE_PATH . 'manage/mode-pie-chart.html.twig', true,self::ENUM_DISPLAY_MODE_PIE), + $oTemplatesRegister->RegisterTemplates( + self::class, + TemplateDefinitionDto::Create('tile', static::TEMPLATES_BASE_PATH.'manage/tile-default.html.twig'), + TemplateDefinitionDto::Create('tile_badge', static::TEMPLATES_BASE_PATH.'manage/tile-badge.html.twig'), + TemplateDefinitionDto::Create('tile_chart', static::TEMPLATES_BASE_PATH.'manage/tile-chart.html.twig'), + TemplateDefinitionDto::Create('tile_top_list', static::TEMPLATES_BASE_PATH.'manage/tile-top-list.html.twig'), + TemplateDefinitionDto::Create('page', static::TEMPLATES_BASE_PATH.'manage/layout.html.twig'), + TemplateDefinitionDto::Create('page_table', static::TEMPLATES_BASE_PATH.'manage/layout-table.html.twig'), + TemplateDefinitionDto::Create('page_chart', static::TEMPLATES_BASE_PATH.'manage/layout-chart.html.twig'), + TemplateDefinitionDto::Create('mode_chart_bar', static::TEMPLATES_BASE_PATH.'manage/mode-bar-chart.html.twig', true, self::ENUM_DISPLAY_MODE_BAR), + TemplateDefinitionDto::Create('mode_chart_pie', static::TEMPLATES_BASE_PATH.'manage/mode-pie-chart.html.twig', true, self::ENUM_DISPLAY_MODE_PIE), ); } @@ -205,9 +206,9 @@ class ManageBrick extends PortalBrick $this->sOql = static::DEFAULT_OQL; $this->sOpeningMode = static::DEFAULT_OPENING_MODE; - $this->aGrouping = array(); - $this->aFields = array(); - $this->aExportFields = array(); + $this->aGrouping = []; + $this->aFields = []; + $this->aExportFields = []; $this->bShowTabCounts = static::DEFAULT_SHOW_TAB_COUNTS; $this->sDefaultDisplayMode = static::DEFAULT_DISPLAY_MODE; @@ -217,7 +218,7 @@ class ManageBrick extends PortalBrick $this->iDefaultListLength = static::DEFAULT_LIST_LENGTH; // This is hardcoded for now, we might allow area grouping on another attribute in the future - $this->AddGrouping('areas', array('attribute' => 'finalclass')); + $this->AddGrouping('areas', ['attribute' => 'finalclass']); } /** @@ -488,7 +489,8 @@ class ManageBrick extends PortalBrick * * @return $this */ - public function SetDefaultListLength($iDefaultListLength) { + public function SetDefaultListLength($iDefaultListLength) + { $this->iDefaultListLength = $iDefaultListLength; return $this; } @@ -508,8 +510,7 @@ class ManageBrick extends PortalBrick $this->aGrouping[$sName] = $aGrouping; // Sorting - if (!$this->IsGroupingByDistinctValues($sName)) - { + if (!$this->IsGroupingByDistinctValues($sName)) { usort($this->aGrouping[$sName]['groups'], function ($a, $b) { if ($a['rank'] === $b['rank']) { return 0; @@ -531,8 +532,7 @@ class ManageBrick extends PortalBrick */ public function RemoveGrouping($sName) { - if (isset($this->aGrouping[$sName])) - { + if (isset($this->aGrouping[$sName])) { unset($this->aGrouping[$sName]); } @@ -548,8 +548,7 @@ class ManageBrick extends PortalBrick */ public function AddField($sAttCode) { - if (!in_array($sAttCode, $this->aFields)) - { + if (!in_array($sAttCode, $this->aFields)) { $this->aFields[] = $sAttCode; } @@ -565,8 +564,7 @@ class ManageBrick extends PortalBrick */ public function RemoveField($sAttCode) { - if (isset($this->aFields[$sAttCode])) - { + if (isset($this->aFields[$sAttCode])) { unset($this->aFields[$sAttCode]); } @@ -575,8 +573,7 @@ class ManageBrick extends PortalBrick public function AddExportField($sAttCode) { - if (!in_array($sAttCode, $this->aExportFields)) - { + if (!in_array($sAttCode, $this->aExportFields)) { $this->aExportFields[] = $sAttCode; } @@ -585,8 +582,7 @@ class ManageBrick extends PortalBrick public function RemoveExportField($sAttCode) { - if (isset($this->aExportFields[$sAttCode])) - { + if (isset($this->aExportFields[$sAttCode])) { unset($this->aExportFields[$sAttCode]); } @@ -642,10 +638,11 @@ class ManageBrick extends PortalBrick */ public function AddAvailableDisplayMode($sModeId) { - if (!in_array($sModeId, static::$aDisplayModes)) - { - throw new Exception('ManageBrick: Display mode "'.$sModeId.'" must be one of the allowed display modes ('.implode(', ', - static::$aDisplayModes).')'); + if (!in_array($sModeId, static::$aDisplayModes)) { + throw new Exception('ManageBrick: Display mode "'.$sModeId.'" must be one of the allowed display modes ('.implode( + ', ', + static::$aDisplayModes + ).')'); } $this->aAvailableDisplayModes[] = $sModeId; @@ -662,8 +659,7 @@ class ManageBrick extends PortalBrick */ public function RemoveAvailableDisplayMode($sModeId) { - if (isset($this->aAvailableDisplayModes[$sModeId])) - { + if (isset($this->aAvailableDisplayModes[$sModeId])) { unset($this->aAvailableDisplayModes[$sModeId]); } @@ -736,16 +732,17 @@ class ManageBrick extends PortalBrick // Checking specific elements /** @var \Combodo\iTop\DesignElement $oBrickSubNode */ - foreach ($oMDElement->GetNodes('./*') as $oBrickSubNode) - { - switch ($oBrickSubNode->nodeName) - { + foreach ($oMDElement->GetNodes('./*') as $oBrickSubNode) { + switch ($oBrickSubNode->nodeName) { case 'class': $sClass = $oBrickSubNode->GetText(); - if ($sClass === '') - { - throw new DOMFormatException('ManageBrick: class tag is empty. Must contain Classname', null, - null, $oBrickSubNode); + if ($sClass === '') { + throw new DOMFormatException( + 'ManageBrick: class tag is empty. Must contain Classname', + null, + null, + $oBrickSubNode + ); } $this->SetOql('SELECT '.$sClass); @@ -753,10 +750,13 @@ class ManageBrick extends PortalBrick case 'oql': $sOql = $oBrickSubNode->GetText(); - if ($sOql === '') - { - throw new DOMFormatException('ManageBrick: oql tag is empty. Must contain OQL statement', null, - null, $oBrickSubNode); + if ($sOql === '') { + throw new DOMFormatException( + 'ManageBrick: oql tag is empty. Must contain OQL statement', + null, + null, + $oBrickSubNode + ); } $this->SetOql($sOql); @@ -764,10 +764,13 @@ class ManageBrick extends PortalBrick case 'opening_mode': $sOpeningMode = $oBrickSubNode->GetText(static::DEFAULT_OPENING_MODE); - if (!in_array($sOpeningMode, array(static::ENUM_ACTION_VIEW, static::ENUM_ACTION_EDIT))) - { - throw new DOMFormatException('ManageBrick: opening_mode tag value must be edit|view ("'.$sOpeningMode.'" given)', - null, null, $oBrickSubNode); + if (!in_array($sOpeningMode, [static::ENUM_ACTION_VIEW, static::ENUM_ACTION_EDIT])) { + throw new DOMFormatException( + 'ManageBrick: opening_mode tag value must be edit|view ("'.$sOpeningMode.'" given)', + null, + null, + $oBrickSubNode + ); } $this->SetOpeningMode($sOpeningMode); @@ -775,26 +778,31 @@ class ManageBrick extends PortalBrick case 'display_modes': /** @var \Combodo\iTop\DesignElement $oDisplayNode */ - foreach ($oBrickSubNode->GetNodes('./*') as $oDisplayNode) - { - switch ($oDisplayNode->nodeName) - { - case 'availables'; + foreach ($oBrickSubNode->GetNodes('./*') as $oDisplayNode) { + switch ($oDisplayNode->nodeName) { + case 'availables': /** @var \Combodo\iTop\DesignElement $oModeNode */ - foreach ($oDisplayNode->GetNodes('*') as $oModeNode) - { - if (!$oModeNode->hasAttribute('id')) - { - throw new DOMFormatException('ManageBrick: Display mode must have a unique ID attribute', - 0, null, $oModeNode); + foreach ($oDisplayNode->GetNodes('*') as $oModeNode) { + if (!$oModeNode->hasAttribute('id')) { + throw new DOMFormatException( + 'ManageBrick: Display mode must have a unique ID attribute', + 0, + null, + $oModeNode + ); } $sModeId = $oModeNode->getAttribute('id'); - if (!in_array($sModeId, static::$aDisplayModes)) - { - throw new DOMFormatException('ManageBrick: Display mode has an invalid value. Expected '.implode('/', - static::$aDisplayModes.', "'.$sModeId.'" given.'), - null, null, $oModeNode); + if (!in_array($sModeId, static::$aDisplayModes)) { + throw new DOMFormatException( + 'ManageBrick: Display mode has an invalid value. Expected '.implode( + '/', + static::$aDisplayModes.', "'.$sModeId.'" given.' + ), + null, + null, + $oModeNode + ); } $this->AddAvailableDisplayMode($sModeId); @@ -805,9 +813,9 @@ class ManageBrick extends PortalBrick $this->SetDefaultDisplayMode($oDisplayNode->GetText(static::DEFAULT_DISPLAY_MODE)); break; - case 'tile'; + case 'tile': $this->SetTileMode($oDisplayNode->GetText(static::DEFAULT_TILE_MODE)); - if($this->sDecorationClassHome === static::DEFAULT_DECORATION_CLASS_HOME){ + if ($this->sDecorationClassHome === static::DEFAULT_DECORATION_CLASS_HOME) { $this->sDecorationClassHome = static::$aDefaultTileData[$this->GetTileMode()]['decorationCssClass']; $this->SetDecorationClassNavigationMenu(static::$aDefaultTileData[$this->GetTileMode()]['decorationCssClass']); $this->SetDecorationClassHome(static::$aDefaultTileData[$this->GetTileMode()]['decorationCssClass']); @@ -820,12 +828,14 @@ class ManageBrick extends PortalBrick case 'fields': /** @var \Combodo\iTop\DesignElement $oFieldNode */ - foreach ($oBrickSubNode->GetNodes('./field') as $oFieldNode) - { - if (!$oFieldNode->hasAttribute('id')) - { - throw new DOMFormatException('ManageBrick : Field must have a unique ID attribute', 0, - null, $oFieldNode); + foreach ($oBrickSubNode->GetNodes('./field') as $oFieldNode) { + if (!$oFieldNode->hasAttribute('id')) { + throw new DOMFormatException( + 'ManageBrick : Field must have a unique ID attribute', + 0, + null, + $oFieldNode + ); } $this->AddField($oFieldNode->getAttribute('id')); } @@ -833,19 +843,18 @@ class ManageBrick extends PortalBrick case 'export': /** @var \Combodo\iTop\DesignElement $oExportNode */ - foreach ($oBrickSubNode->GetNodes('./*') as $oExportNode) - { - switch ($oExportNode->nodeName) - { + foreach ($oBrickSubNode->GetNodes('./*') as $oExportNode) { + switch ($oExportNode->nodeName) { case 'fields': /** @var \Combodo\iTop\DesignElement $oFieldNode */ - foreach ($oExportNode->GetNodes('./field') as $oFieldNode) - { - if (!$oFieldNode->hasAttribute('id')) - { - throw new DOMFormatException('ManageBrick : Field must have a unique ID attribute', + foreach ($oExportNode->GetNodes('./field') as $oFieldNode) { + if (!$oFieldNode->hasAttribute('id')) { + throw new DOMFormatException( + 'ManageBrick : Field must have a unique ID attribute', 0, - null, $oFieldNode); + null, + $oFieldNode + ); } $this->AddExportField($oFieldNode->getAttribute('id')); } @@ -860,12 +869,12 @@ class ManageBrick extends PortalBrick break; case 'default_list_length': $iNodeDefaultListLength = (int)$oBrickSubNode->GetText(static::DEFAULT_LIST_LENGTH); - if(!in_array($iNodeDefaultListLength, array(10, 20, 50, -1),true)) - { + if (!in_array($iNodeDefaultListLength, [10, 20, 50, -1], true)) { throw new DOMFormatException( 'ManageBrick : Default list length must be contained in list length options. Expected -1/10/20/50, '.$iNodeDefaultListLength.' given.', null, - null, $oBrickSubNode + null, + $oBrickSubNode ); } $this->SetDefaultListLength($iNodeDefaultListLength); @@ -873,25 +882,21 @@ class ManageBrick extends PortalBrick case 'grouping': // Tabs grouping /** @var \Combodo\iTop\DesignElement $oGroupingNode */ - foreach ($oBrickSubNode->GetNodes('./tabs/*') as $oGroupingNode) - { - switch ($oGroupingNode->nodeName) - { - case 'show_tab_counts'; + foreach ($oBrickSubNode->GetNodes('./tabs/*') as $oGroupingNode) { + switch ($oGroupingNode->nodeName) { + case 'show_tab_counts': $bShowTabCounts = ($oGroupingNode->GetText(static::DEFAULT_SHOW_TAB_COUNTS) === 'true') ? true : false; $this->SetShowTabCounts($bShowTabCounts); break; case 'attribute': $sAttribute = $oGroupingNode->GetText(); - if ($sAttribute !== '') - { - $this->AddGrouping('tabs', array('attribute' => $sAttribute)); + if ($sAttribute !== '') { + $this->AddGrouping('tabs', ['attribute' => $sAttribute]); } break; case 'limit': $iLimit = $oGroupingNode->GetText(); - if (is_numeric($iLimit)) - { + if (is_numeric($iLimit)) { $this->iGroupLimit = $iLimit; } break; @@ -899,24 +904,24 @@ class ManageBrick extends PortalBrick $this->bGroupShowOthers = ($oGroupingNode->GetText() === 'true') ? true : false; break; case 'groups': - $aGroups = array(); + $aGroups = []; /** @var \Combodo\iTop\DesignElement $oGroupNode */ - foreach ($oGroupingNode->GetNodes('./group') as $oGroupNode) - { - if (!$oGroupNode->hasAttribute('id')) - { - throw new DOMFormatException('ManageBrick : Group must have a unique ID attribute', - 0, null, $oGroupNode); + foreach ($oGroupingNode->GetNodes('./group') as $oGroupNode) { + if (!$oGroupNode->hasAttribute('id')) { + throw new DOMFormatException( + 'ManageBrick : Group must have a unique ID attribute', + 0, + null, + $oGroupNode + ); } $sGroupId = $oGroupNode->getAttribute('id'); - $aGroup = array(); + $aGroup = []; $aGroup['id'] = $sGroupId; // We don't put the group id as the $aGroups key because the array will be sorted later in AddGrouping, which replace array keys by integer ordered keys /** @var \Combodo\iTop\DesignElement $oGroupProperty */ - foreach ($oGroupNode->GetNodes('*') as $oGroupProperty) - { - switch ($oGroupProperty->nodeName) - { + foreach ($oGroupNode->GetNodes('*') as $oGroupProperty) { + switch ($oGroupProperty->nodeName) { case 'rank': $aGroup[$oGroupProperty->nodeName] = (int)$oGroupProperty->GetText(0); break; @@ -929,19 +934,25 @@ class ManageBrick extends PortalBrick } // Checking constitancy - if (!isset($aGroup['title']) || $aGroup['title'] === '') - { - throw new DOMFormatException('ManageBrick : Group must have a title tag and it must not be empty', - 0, null, $oGroupNode); + if (!isset($aGroup['title']) || $aGroup['title'] === '') { + throw new DOMFormatException( + 'ManageBrick : Group must have a title tag and it must not be empty', + 0, + null, + $oGroupNode + ); } - if (!isset($aGroup['condition']) || $aGroup['condition'] === '') - { - throw new DOMFormatException('ManageBrick : Group must have a condition tag and it must not be empty', - 0, null, $oGroupNode); + if (!isset($aGroup['condition']) || $aGroup['condition'] === '') { + throw new DOMFormatException( + 'ManageBrick : Group must have a condition tag and it must not be empty', + 0, + null, + $oGroupNode + ); } $aGroups[] = $aGroup; } - $this->AddGrouping('tabs', array('groups' => $aGroups)); + $this->AddGrouping('tabs', ['groups' => $aGroups]); break; } } @@ -963,62 +974,58 @@ class ManageBrick extends PortalBrick } // Checking if has an oql - if ($this->GetOql() === '') - { + if ($this->GetOql() === '') { throw new DOMFormatException('ManageBrick: must have a valid tag', null, null, $oMDElement); } // Checking that the brick has at least a display mode - if (count($this->GetAvailablesDisplayModes()) === 0) - { + if (count($this->GetAvailablesDisplayModes()) === 0) { $this->AddAvailableDisplayMode(static::DEFAULT_DISPLAY_MODE); } // Checking that default display mode in among the availables - if (!in_array($this->sDefaultDisplayMode, $this->aAvailableDisplayModes)) - { - throw new DOMFormatException('ManageBrick: Default display mode "'.$this->sDefaultDisplayMode.'" must be one of the available display modes ('.implode(', ', - $this->aAvailableDisplayModes).')', null, null, $oMDElement); + if (!in_array($this->sDefaultDisplayMode, $this->aAvailableDisplayModes)) { + throw new DOMFormatException('ManageBrick: Default display mode "'.$this->sDefaultDisplayMode.'" must be one of the available display modes ('.implode( + ', ', + $this->aAvailableDisplayModes + ).')', null, null, $oMDElement); } // Checking that tile mode in among the availables - if (!in_array($this->sTileMode, static::$aTileModes)) - { - throw new DOMFormatException('ManageBrick: Tile mode "'.$this->sTileMode.'" must be one of the allowed tile modes ('.implode(', ', - static::$aTileModes).')', null, null, $oMDElement); + if (!in_array($this->sTileMode, static::$aTileModes)) { + throw new DOMFormatException('ManageBrick: Tile mode "'.$this->sTileMode.'" must be one of the allowed tile modes ('.implode( + ', ', + static::$aTileModes + ).')', null, null, $oMDElement); } // Checking if specified fields, if not we put those from the details zlist - if (empty($this->aFields)) - { + if (empty($this->aFields)) { $sClass = DBSearch::FromOQL($this->GetOql()); - $aFields = MetaModel::FlattenZList(MetaModel::GetZListItems($sClass->GetClass(), - static::DEFAULT_ZLIST_FIELDS)); + $aFields = MetaModel::FlattenZList(MetaModel::GetZListItems( + $sClass->GetClass(), + static::DEFAULT_ZLIST_FIELDS + )); $this->SetFields($aFields); } // Default Export Fields - if ($bUseListFieldsForExport) - { - foreach ($this->GetFields() as $sAttCode) - { + if ($bUseListFieldsForExport) { + foreach ($this->GetFields() as $sAttCode) { $this->AddExportField($sAttCode); } } // Checking the navigation icon $sDecorationClassNavigationMenu = $this->GetDecorationClassNavigationMenu(); - if (empty($sDecorationClassNavigationMenu) && isset(static::$aDefaultTileData[$this->sTileMode])) - { + if (empty($sDecorationClassNavigationMenu) && isset(static::$aDefaultTileData[$this->sTileMode])) { /** @var string $sDecorationClassNavigationMenu */ $sDecorationClassNavigationMenu = static::$aDefaultTileData[$this->sTileMode]['decorationCssClass']; - if (!empty($sDecorationClassNavigationMenu)) - { + if (!empty($sDecorationClassNavigationMenu)) { $this->SetDecorationClassNavigationMenu($sDecorationClassNavigationMenu); } } $sTitle = $this->GetTitleHome(); - if (empty($sTitle)) - { + if (empty($sTitle)) { $sOql = $this->GetOql(); $oSearch = DBSearch::FromOQL($sOql); $sClassName = MetaModel::GetName($oSearch->GetClass()); diff --git a/datamodels/2.x/itop-portal-base/portal/src/Brick/PortalBrick.php b/datamodels/2.x/itop-portal-base/portal/src/Brick/PortalBrick.php index 0c6ba6fdc..42512028e 100644 --- a/datamodels/2.x/itop-portal-base/portal/src/Brick/PortalBrick.php +++ b/datamodels/2.x/itop-portal-base/portal/src/Brick/PortalBrick.php @@ -38,37 +38,37 @@ use ModuleDesign; abstract class PortalBrick extends AbstractBrick { /** @var string ENUM_OPENING_TARGET_MODAL */ - const ENUM_OPENING_TARGET_MODAL = 'modal'; + public const ENUM_OPENING_TARGET_MODAL = 'modal'; /** @var string ENUM_OPENING_TARGET_SELF */ - const ENUM_OPENING_TARGET_SELF = 'self'; + public const ENUM_OPENING_TARGET_SELF = 'self'; /** @var string ENUM_OPENING_TARGET_NEW */ - const ENUM_OPENING_TARGET_NEW = 'new'; + public const ENUM_OPENING_TARGET_NEW = 'new'; /** @var int DEFAULT_WIDTH */ - const DEFAULT_WIDTH = 400; + public const DEFAULT_WIDTH = 400; /** @var int DEFAULT_HEIGHT */ - const DEFAULT_HEIGHT = null; + public const DEFAULT_HEIGHT = null; /** @var bool DEFAULT_MODAL */ - const DEFAULT_MODAL = false; + public const DEFAULT_MODAL = false; /** @var bool DEFAULT_VISIBLE_HOME */ - const DEFAULT_VISIBLE_HOME = true; + public const DEFAULT_VISIBLE_HOME = true; /** @var bool DEFAULT_VISIBLE_NAVIGATION_MENU */ - const DEFAULT_VISIBLE_NAVIGATION_MENU = true; + public const DEFAULT_VISIBLE_NAVIGATION_MENU = true; /** @var string DEFAULT_DECORATION_CLASS_HOME */ - const DEFAULT_DECORATION_CLASS_HOME = ''; + public const DEFAULT_DECORATION_CLASS_HOME = ''; /** @var string DEFAULT_DECORATION_CLASS_NAVIGATION_MENU */ - const DEFAULT_DECORATION_CLASS_NAVIGATION_MENU = ''; + public const DEFAULT_DECORATION_CLASS_NAVIGATION_MENU = ''; /** @var string DEFAULT_TILE_TEMPLATE_PATH */ - const DEFAULT_TILE_TEMPLATE_PATH = 'itop-portal-base/portal/templates/bricks/tile.html.twig'; + public const DEFAULT_TILE_TEMPLATE_PATH = 'itop-portal-base/portal/templates/bricks/tile.html.twig'; /** @var string|null DEFAULT_TILE_CONTROLLER_ACTION */ - const DEFAULT_TILE_CONTROLLER_ACTION = null; + public const DEFAULT_TILE_CONTROLLER_ACTION = null; /** @var string DEFAULT_OPENING_TARGET */ - const DEFAULT_OPENING_TARGET = self::ENUM_OPENING_TARGET_MODAL; + public const DEFAULT_OPENING_TARGET = self::ENUM_OPENING_TARGET_MODAL; /** @var string|null $sRouteName */ - static $sRouteName = null; + public static $sRouteName = null; /** @var array $aOpeningTargets */ - static $aOpeningTargets = array(self::ENUM_OPENING_TARGET_MODAL, self::ENUM_OPENING_TARGET_SELF, self::ENUM_OPENING_TARGET_NEW); + public static $aOpeningTargets = [self::ENUM_OPENING_TARGET_MODAL, self::ENUM_OPENING_TARGET_SELF, self::ENUM_OPENING_TARGET_NEW]; /** @var int $iWidth */ protected $iWidth; @@ -101,14 +101,13 @@ abstract class PortalBrick extends AbstractBrick /** @var string $sTitleNavigationMenu */ protected $sTitleNavigationMenu; - - /** @inheritdoc */ public static function RegisterTemplates(TemplatesRegister $oTemplatesRegister): void { parent::RegisterTemplates($oTemplatesRegister); - $oTemplatesRegister->RegisterTemplates(self::class, - TemplateDefinitionDto::Create('tile', static::TEMPLATES_BASE_PATH . 'tile.html.twig'), + $oTemplatesRegister->RegisterTemplates( + self::class, + TemplateDefinitionDto::Create('tile', static::TEMPLATES_BASE_PATH.'tile.html.twig'), ); } @@ -466,10 +465,8 @@ abstract class PortalBrick extends AbstractBrick // Checking specific elements /** @var \Combodo\iTop\DesignElement $oBrickSubNode */ - foreach ($oMDElement->GetNodes('./*') as $oBrickSubNode) - { - switch ($oBrickSubNode->nodeName) - { + foreach ($oMDElement->GetNodes('./*') as $oBrickSubNode) { + switch ($oBrickSubNode->nodeName) { case 'width': $sWidth = $oBrickSubNode->GetText(static::DEFAULT_WIDTH); $this->bIsWidthPixel = str_contains($sWidth, 'px'); @@ -488,23 +485,20 @@ abstract class PortalBrick extends AbstractBrick case 'visible': // Default value $oOptionalNode = $oBrickSubNode->GetOptionalElement('default'); - if ($oOptionalNode !== null) - { + if ($oOptionalNode !== null) { $optionalNodeValue = ($oOptionalNode->GetText() === 'false') ? false : true; $this->SetVisibleHome($optionalNodeValue); $this->SetVisibleNavigationMenu($optionalNodeValue); } // Home value $oOptionalNode = $oBrickSubNode->GetOptionalElement('home'); - if ($oOptionalNode !== null) - { + if ($oOptionalNode !== null) { $optionalNodeValue = ($oOptionalNode->GetText() === 'false') ? false : true; $this->SetVisibleHome($optionalNodeValue); } // Navigation menu value $oOptionalNode = $oBrickSubNode->GetOptionalElement('navigation_menu'); - if ($oOptionalNode !== null) - { + if ($oOptionalNode !== null) { $optionalNodeValue = ($oOptionalNode->GetText() === 'false') ? false : true; $this->SetVisibleNavigationMenu($optionalNodeValue); } @@ -512,8 +506,7 @@ abstract class PortalBrick extends AbstractBrick case 'templates': $oTemplateNodeList = $oBrickSubNode->GetNodes('template[@id='.ModuleDesign::XPathQuote('tile').']'); - if ($oTemplateNodeList->length > 0) - { + if ($oTemplateNodeList->length > 0) { /** @var \Combodo\iTop\DesignElement $oTemplateNode */ $oTemplateNode = $oTemplateNodeList->item(0); $this->SetTemplatePath('tile', $oTemplateNode->GetText(static::DEFAULT_TILE_TEMPLATE_PATH)); @@ -526,23 +519,20 @@ abstract class PortalBrick extends AbstractBrick $this->SetRankNavigationMenu($this->fRank); // Default value $oOptionalNode = $oBrickSubNode->GetOptionalElement('default'); - if ($oOptionalNode !== null) - { + if ($oOptionalNode !== null) { $optionalNodeValue = $oOptionalNode->GetText(static::DEFAULT_RANK); $this->SetRankHome($optionalNodeValue); $this->SetRankNavigationMenu($optionalNodeValue); } // Home value $oOptionalNode = $oBrickSubNode->GetOptionalElement('home'); - if ($oOptionalNode !== null) - { + if ($oOptionalNode !== null) { $optionalNodeValue = $oOptionalNode->GetText(static::DEFAULT_RANK); $this->SetRankHome($optionalNodeValue); } // Navigation menu value $oOptionalNode = $oBrickSubNode->GetOptionalElement('navigation_menu'); - if ($oOptionalNode !== null) - { + if ($oOptionalNode !== null) { $optionalNodeValue = $oOptionalNode->GetText(static::DEFAULT_RANK); $this->SetRankNavigationMenu($optionalNodeValue); } @@ -554,23 +544,20 @@ abstract class PortalBrick extends AbstractBrick $this->SetTitleNavigationMenu($this->sTitle); // Default value $oOptionalNode = $oBrickSubNode->GetOptionalElement('default'); - if ($oOptionalNode !== null) - { + if ($oOptionalNode !== null) { $optionalNodeValue = $oOptionalNode->GetText(static::DEFAULT_TITLE); $this->SetTitleHome($optionalNodeValue); $this->SetTitleNavigationMenu($optionalNodeValue); } // Home value $oOptionalNode = $oBrickSubNode->GetOptionalElement('home'); - if ($oOptionalNode !== null) - { + if ($oOptionalNode !== null) { $optionalNodeValue = $oOptionalNode->GetText(static::DEFAULT_TITLE); $this->SetTitleHome($optionalNodeValue); } // Navigation menu value $oOptionalNode = $oBrickSubNode->GetOptionalElement('navigation_menu'); - if ($oOptionalNode !== null) - { + if ($oOptionalNode !== null) { $optionalNodeValue = $oOptionalNode->GetText(static::DEFAULT_TITLE); $this->SetTitleNavigationMenu($optionalNodeValue); $this->SetTitle($optionalNodeValue); @@ -583,23 +570,20 @@ abstract class PortalBrick extends AbstractBrick $this->SetDecorationClassNavigationMenu(static::DEFAULT_DECORATION_CLASS_NAVIGATION_MENU); // Default value $oOptionalNode = $oBrickSubNode->GetOptionalElement('default'); - if ($oOptionalNode !== null) - { + if ($oOptionalNode !== null) { $optionalNodeValue = $oOptionalNode->GetText(static::DEFAULT_DECORATION_CLASS_NAVIGATION_MENU); $this->SetDecorationClassHome($optionalNodeValue); $this->SetDecorationClassNavigationMenu($optionalNodeValue); } // Home value $oOptionalNode = $oBrickSubNode->GetOptionalElement('home'); - if ($oOptionalNode !== null) - { + if ($oOptionalNode !== null) { $optionalNodeValue = $oOptionalNode->GetText(static::DEFAULT_DECORATION_CLASS_HOME); $this->SetDecorationClassHome($optionalNodeValue); } // Navigation menu value $oOptionalNode = $oBrickSubNode->GetOptionalElement('navigation_menu'); - if ($oOptionalNode !== null) - { + if ($oOptionalNode !== null) { $optionalNodeValue = $oOptionalNode->GetText(static::DEFAULT_DECORATION_CLASS_NAVIGATION_MENU); $this->SetDecorationClassNavigationMenu($optionalNodeValue); } @@ -611,11 +595,16 @@ abstract class PortalBrick extends AbstractBrick case 'opening_target': $sOpeningTarget = $oBrickSubNode->GetText(static::DEFAULT_OPENING_TARGET); - if (!in_array($sOpeningTarget, - array(static::ENUM_OPENING_TARGET_MODAL, static::ENUM_OPENING_TARGET_NEW, static::ENUM_OPENING_TARGET_SELF))) - { - throw new DOMFormatException('PortalBrick : opening_target tag value must be modal|new|self ("'.$sOpeningTarget.'" given)', - null, null, $oBrickSubNode); + if (!in_array( + $sOpeningTarget, + [static::ENUM_OPENING_TARGET_MODAL, static::ENUM_OPENING_TARGET_NEW, static::ENUM_OPENING_TARGET_SELF] + )) { + throw new DOMFormatException( + 'PortalBrick : opening_target tag value must be modal|new|self ("'.$sOpeningTarget.'" given)', + null, + null, + $oBrickSubNode + ); } $this->SetOpeningTarget($sOpeningTarget); diff --git a/datamodels/2.x/itop-portal-base/portal/src/Brick/UserProfileBrick.php b/datamodels/2.x/itop-portal-base/portal/src/Brick/UserProfileBrick.php index d41350379..95c5d05df 100644 --- a/datamodels/2.x/itop-portal-base/portal/src/Brick/UserProfileBrick.php +++ b/datamodels/2.x/itop-portal-base/portal/src/Brick/UserProfileBrick.php @@ -1,4 +1,5 @@ RegisterTemplates(self::class, - TemplateDefinitionDto::Create('page', static::TEMPLATES_BASE_PATH . 'user-profile/layout.html.twig'), + $oTemplatesRegister->RegisterTemplates( + self::class, + TemplateDefinitionDto::Create('page', static::TEMPLATES_BASE_PATH.'user-profile/layout.html.twig'), TemplateDefinitionDto::Create('user_info', static::TEMPLATES_BASE_PATH.'user-profile/user_info.html.twig'), TemplateDefinitionDto::Create('user_info_ready_js', static::TEMPLATES_BASE_PATH.'user-profile/user_info.ready.js.twig'), ); @@ -76,12 +78,12 @@ class UserProfileBrick extends PortalBrick { parent::__construct(); - $this->aForm = array( + $this->aForm = [ 'id' => 'default-user-profile', 'type' => 'zlist', 'fields' => 'details', 'layout' => null, - ); + ]; $this->bShowPictureForm = static::DEFAULT_SHOW_PICTURE_FORM; $this->bShowPreferencesForm = static::DEFAULT_SHOW_PREFERENCES_FORM; $this->bShowPasswordForm = static::DEFAULT_SHOW_PASSWORD_FORM; @@ -192,13 +194,13 @@ class UserProfileBrick extends PortalBrick // Enumerating fields if ($oBrickSubNode->GetOptionalElement('fields') !== null) { $this->aForm['type'] = 'custom_list'; - $this->aForm['fields'] = array(); + $this->aForm['fields'] = []; /** @var \Combodo\iTop\DesignElement $oFieldNode */ foreach ($oBrickSubNode->GetOptionalElement('fields')->GetNodes('field') as $oFieldNode) { $sFieldId = $oFieldNode->getAttribute('id'); if ($sFieldId !== '') { - $aField = array(); + $aField = []; // Parsing field options like read_only, hidden and mandatory if ($oFieldNode->GetOptionalElement('read_only')) { $aField['readonly'] = ($oFieldNode->GetOptionalElement('read_only')->GetText('true') === 'true') ? true : false; @@ -224,10 +226,10 @@ class UserProfileBrick extends PortalBrick $sXml = preg_replace('/^.+\n/', '', $sXml); $sXml = preg_replace('/\n.+$/', '', $sXml); - $this->aForm['layout'] = array( + $this->aForm['layout'] = [ 'type' => (preg_match('/\{\{|\{\#|\{\%/', $sXml) === 1) ? 'twig' : 'xhtml', 'content' => $sXml, - ); + ]; } break; diff --git a/datamodels/2.x/itop-portal-base/portal/src/Controller/AbstractController.php b/datamodels/2.x/itop-portal-base/portal/src/Controller/AbstractController.php index b0a84a7a4..6ee76faa0 100644 --- a/datamodels/2.x/itop-portal-base/portal/src/Controller/AbstractController.php +++ b/datamodels/2.x/itop-portal-base/portal/src/Controller/AbstractController.php @@ -37,15 +37,16 @@ use Symfony\Contracts\Service\Attribute\Required; */ abstract class AbstractController extends SymfonyAbstractController implements TemplatesProviderInterface { - const TEMPLATES_BASE_PATH = 'itop-portal-base/portal/templates/'; + public const TEMPLATES_BASE_PATH = 'itop-portal-base/portal/templates/'; /** @inheritdoc */ public static function RegisterTemplates(TemplatesRegister $oTemplatesRegister): void { - $oTemplatesRegister->RegisterTemplates(self::class, - TemplateDefinitionDto::Create('page', static::TEMPLATES_BASE_PATH . 'layout.html.twig'), + $oTemplatesRegister->RegisterTemplates( + self::class, + TemplateDefinitionDto::Create('page', static::TEMPLATES_BASE_PATH.'layout.html.twig'), TemplateDefinitionDto::Create('navigation_menu', static::TEMPLATES_BASE_PATH.'/pages/navigation_menu.html.twig'), - TemplateDefinitionDto::Create('modal', static::TEMPLATES_BASE_PATH . 'modal/layout.html.twig'), + TemplateDefinitionDto::Create('modal', static::TEMPLATES_BASE_PATH.'modal/layout.html.twig'), TemplateDefinitionDto::Create('loader', static::TEMPLATES_BASE_PATH.'helpers/loader.html.twig'), TemplateDefinitionDto::Create('tagset_clic_handler_js', static::TEMPLATES_BASE_PATH.'helpers/tagset_clic_handler.js.twig'), TemplateDefinitionDto::Create('session_message', static::TEMPLATES_BASE_PATH.'helpers/session_messages/session_message.html.twig'), diff --git a/datamodels/2.x/itop-portal-base/portal/src/Controller/ObjectController.php b/datamodels/2.x/itop-portal-base/portal/src/Controller/ObjectController.php index 24fd7f901..747530824 100644 --- a/datamodels/2.x/itop-portal-base/portal/src/Controller/ObjectController.php +++ b/datamodels/2.x/itop-portal-base/portal/src/Controller/ObjectController.php @@ -73,16 +73,17 @@ use VariableExpression; */ class ObjectController extends BrickController { - const DEFAULT_PAGE_NUMBER = 1; - const DEFAULT_LIST_LENGTH = 10; + public const DEFAULT_PAGE_NUMBER = 1; + public const DEFAULT_LIST_LENGTH = 10; /** @inheritdoc */ public static function RegisterTemplates(TemplatesRegister $oTemplatesRegister): void { parent::RegisterTemplates($oTemplatesRegister); - $oTemplatesRegister->RegisterTemplates(self::class, - TemplateDefinitionDto::Create('page', static::TEMPLATES_BASE_PATH. 'bricks/object/layout.html.twig'), - TemplateDefinitionDto::Create('modal', static::TEMPLATES_BASE_PATH. 'bricks/object/modal.html.twig'), + $oTemplatesRegister->RegisterTemplates( + self::class, + TemplateDefinitionDto::Create('page', static::TEMPLATES_BASE_PATH.'bricks/object/layout.html.twig'), + TemplateDefinitionDto::Create('modal', static::TEMPLATES_BASE_PATH.'bricks/object/modal.html.twig'), TemplateDefinitionDto::Create('mode_create', static::TEMPLATES_BASE_PATH.'bricks/object/mode_create.html.twig', true, 'create'), TemplateDefinitionDto::Create('mode_edit', static::TEMPLATES_BASE_PATH.'bricks/object/mode_edit.html.twig', true, 'edit'), TemplateDefinitionDto::Create('mode_search_hierarchy', static::TEMPLATES_BASE_PATH.'bricks/object/mode_search_hierarchy.html.twig', true, 'search_hierarchy'), @@ -117,9 +118,8 @@ class ObjectController extends BrickController protected ObjectFormHandlerHelper $oObjectFormHandlerHelper, protected NavigationRuleHelper $oNavigationRuleHelper, protected ContextManipulatorHelper $oContextManipulatorHelper, - protected array $aCombodoPortalInstanceConf = [] - ) - { + protected array $aCombodoPortalInstanceConf = [] + ) { } @@ -154,8 +154,12 @@ class ObjectController extends BrickController } // Retrieving object - $oObject = MetaModel::GetObject($sObjectClass, $sObjectId, false /* MustBeFound */, - $this->oScopeValidatorHelper->IsAllDataAllowedForScope(UserRights::ListProfiles(), $sObjectClass)); + $oObject = MetaModel::GetObject( + $sObjectClass, + $sObjectId, + false /* MustBeFound */, + $this->oScopeValidatorHelper->IsAllDataAllowedForScope(UserRights::ListProfiles(), $sObjectClass) + ); if ($oObject === null) { // We should never be there as the secuirty helper makes sure that the object exists, but just in case. IssueLog::Info(__METHOD__.' at line '.__LINE__.' : Could not load object '.$sObjectClass.'::'.$sObjectId.'.'); @@ -167,7 +171,7 @@ class ObjectController extends BrickController /** * Displays an cmdbAbstractObject (if the connected user is allowed to) from a specific attribute. If several or none objects are found with the attribute value, an exception is thrown. - * + * * @param \Symfony\Component\HttpFoundation\Request $oRequest * @param string $sObjectClass (Class must be an instance of cmdbAbstractObject) * @param string $sObjectAttCode @@ -192,8 +196,13 @@ class ObjectController extends BrickController throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, Dict::Format('UI:Error:3ParametersMissing', 'class', 'attcode', 'attvalue')); } - $oObject = MetaModel::GetObjectByColumn($sObjectClass, $sObjectAttCode, $sObjectAttValue, false, - $this->oScopeValidatorHelper->IsAllDataAllowedForScope(UserRights::ListProfiles(), $sObjectClass)); + $oObject = MetaModel::GetObjectByColumn( + $sObjectClass, + $sObjectAttCode, + $sObjectAttValue, + false, + $this->oScopeValidatorHelper->IsAllDataAllowedForScope(UserRights::ListProfiles(), $sObjectClass) + ); if ($oObject === null) { // null if object not found or multiple matches IssueLog::Info(__METHOD__.' at line '.__LINE__.' : Could not load object '.$sObjectClass.'" and "'.$sObjectAttCode.' / '.$sObjectAttValue.'.'); @@ -235,22 +244,21 @@ class ObjectController extends BrickController $oObject->FireEvent(EVENT_DISPLAY_OBJECT_DETAILS); - $aData = array('sMode' => 'view'); + $aData = ['sMode' => 'view']; $aData['form'] = $this->oObjectFormHandlerHelper->HandleForm($oRequest, $aData['sMode'], $sObjectClass, $sObjectId); $aData['form']['title'] = Dict::Format('Brick:Portal:Object:Form:View:Title', $oObject->GetName()); $aData['form']['title_complement'] = MetaModel::GetName($sObjectClass); - // Add an edit button if user is allowed if ($this->oSecurityHelper->IsActionAllowed(UR_ACTION_MODIFY, $sObjectClass, $sObjectId)) { - $sModifyUrl = $this->oUrlGenerator->generate('p_object_edit', array('sObjectClass' => $sObjectClass, 'sObjectId' => $sObjectId)); + $sModifyUrl = $this->oUrlGenerator->generate('p_object_edit', ['sObjectClass' => $sObjectClass, 'sObjectId' => $sObjectId]); $oModifyButton = new JSButtonItem( 'modify_object', Dict::S('UI:Menu:Modify'), 'CombodoModal.OpenUrlInModal("'.$sModifyUrl.'", true);' ); // Putting this one first - $aData['form']['buttons']['actions'][] = $oModifyButton->GetMenuItem() + array('js_files' => $oModifyButton->GetLinkedScripts()); + $aData['form']['buttons']['actions'][] = $oModifyButton->GetMenuItem() + ['js_files' => $oModifyButton->GetLinkedScripts()]; } // Preparing response @@ -294,8 +302,7 @@ class ObjectController extends BrickController public function EditAction(Request $oRequest, $sObjectClass, $sObjectId) { // Checking parameters - if ($sObjectClass === '' || $sObjectId === '') - { + if ($sObjectClass === '' || $sObjectId === '') { IssueLog::Info(__METHOD__.' at line '.__LINE__.' : sObjectClass and sObjectId expected, "'.$sObjectClass.'" and "'.$sObjectId.'" given.'); throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, Dict::Format('UI:Error:2ParametersMissing', 'class', 'id')); } @@ -303,17 +310,19 @@ class ObjectController extends BrickController // Checking security layers // Warning : This is a dirty quick fix to allow editing its own contact information $bAllowWrite = ($sObjectClass === 'Person' && $sObjectId == UserRights::GetContactId()); - if (!$this->oSecurityHelper->IsActionAllowed(UR_ACTION_MODIFY, $sObjectClass, $sObjectId) && !$bAllowWrite) - { + if (!$this->oSecurityHelper->IsActionAllowed(UR_ACTION_MODIFY, $sObjectClass, $sObjectId) && !$bAllowWrite) { IssueLog::Warning(__METHOD__.' at line '.__LINE__.' : User #'.UserRights::GetUserId().' not allowed to modify '.$sObjectClass.'::'.$sObjectId.' object.'); throw new HttpException(Response::HTTP_NOT_FOUND, Dict::S('UI:ObjectDoesNotExist')); } // Retrieving object - $oObject = MetaModel::GetObject($sObjectClass, $sObjectId, false /* MustBeFound */, - $this->oScopeValidatorHelper->IsAllDataAllowedForScope(UserRights::ListProfiles(), $sObjectClass)); - if ($oObject === null) - { + $oObject = MetaModel::GetObject( + $sObjectClass, + $sObjectId, + false /* MustBeFound */, + $this->oScopeValidatorHelper->IsAllDataAllowedForScope(UserRights::ListProfiles(), $sObjectClass) + ); + if ($oObject === null) { // We should never be there as the secuirty helper makes sure that the object exists, but just in case. IssueLog::Info(__METHOD__.' at line '.__LINE__.' : Could not load object '.$sObjectClass.'::'.$sObjectId.'.'); throw new HttpException(Response::HTTP_NOT_FOUND, Dict::S('UI:ObjectDoesNotExist')); @@ -321,33 +330,25 @@ class ObjectController extends BrickController $sOperation = $this->oRequestManipulatorHelper->ReadParam('operation', ''); - $aData = array('sMode' => 'edit'); + $aData = ['sMode' => 'edit']; $aData['form'] = $this->oObjectFormHandlerHelper->HandleForm($oRequest, $aData['sMode'], $sObjectClass, $sObjectId); $aData['form']['title'] = Dict::Format('Brick:Portal:Object:Form:Edit:Title', $aData['form']['object_name']); $aData['form']['title_complement'] = MetaModel::GetName($sObjectClass); // Preparing response - if ($oRequest->isXmlHttpRequest()) - { + if ($oRequest->isXmlHttpRequest()) { // We have to check whether the 'operation' parameter is defined or not in order to know if the form is required via ajax (to be displayed as a modal dialog) or if it's a lifecycle call from a existing form. - if (empty($sOperation)) - { + if (empty($sOperation)) { $oResponse = $this->render($this->GetTemplatePath('modal'), $aData); - } - else - { + } else { $oResponse = new JsonResponse($aData); } - } - else - { + } else { // Adding brick if it was passed $sBrickId = $this->oRequestManipulatorHelper->ReadParam('sBrickId', ''); - if (!empty($sBrickId)) - { + if (!empty($sBrickId)) { $oBrick = $this->oBrickCollection->GetBrickById($sBrickId); - if ($oBrick !== null) - { + if ($oBrick !== null) { $aData['oBrick'] = $oBrick; } } @@ -377,13 +378,11 @@ class ObjectController extends BrickController $oResponse = null; // Checking if the target object class is abstract or not // - If is not abstract, we redirect to object creation form - if (!MetaModel::IsAbstract($sObjectClass)) - { + if (!MetaModel::IsAbstract($sObjectClass)) { $oResponse = $this->DisplayCreationForm($oRequest, $sObjectClass); } // - Else, we list the leaf classes as an intermediate step - else - { + else { $oResponse = $this->DisplayLeafClassesForm($sObjectClass); } @@ -409,11 +408,12 @@ class ObjectController extends BrickController $sMethodName = base64_decode($sEncodedMethodName); // Checking that the factory method is valid - if (!is_callable($sMethodName)) - { + if (!is_callable($sMethodName)) { IssueLog::Error(__METHOD__.' at line '.__LINE__.' : Invalid factory method "'.$sMethodName.'" used when creating an object.'); - throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, - 'Invalid factory method "'.$sMethodName.'" used when creating an object'); + throw new HttpException( + Response::HTTP_INTERNAL_SERVER_ERROR, + 'Invalid factory method "'.$sMethodName.'" used when creating an object' + ); } // Retrieving origin object @@ -421,12 +421,9 @@ class ObjectController extends BrickController $oOriginObject = MetaModel::GetObject($sObjectClass, $sObjectId, true, true); // Retrieving target object (We check if the method is a simple function or if it's part of a class in which case only static function are supported) - if (!strpos($sMethodName, '::')) - { + if (!strpos($sMethodName, '::')) { $oTargetObject = $sMethodName($oOriginObject); - } - else - { + } else { $aMethodNameParts = explode('::', $sMethodName); $sMethodClass = $aMethodNameParts[0]; $sMethodName = $aMethodNameParts[1]; @@ -435,9 +432,9 @@ class ObjectController extends BrickController // Preparing redirection // - Route - $aRouteParams = array( + $aRouteParams = [ 'sObjectClass' => get_class($oTargetObject), - ); + ]; return $this->ForwardToRoute('p_object_create', $aRouteParams, $oRequest->query->all()); } @@ -463,28 +460,26 @@ class ObjectController extends BrickController $aCombodoPortalInstanceConf = $this->getParameter('combodo.portal.instance.conf'); // Checking parameters - if ($sObjectClass === '' || $sObjectId === '' || $sStimulusCode === '') - { + if ($sObjectClass === '' || $sObjectId === '' || $sStimulusCode === '') { IssueLog::Info(__METHOD__.' at line '.__LINE__.' : sObjectClass, sObjectId and $sStimulusCode expected, "'.$sObjectClass.'", "'.$sObjectId.'" and "'.$sStimulusCode.'" given.'); - throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, - Dict::Format('UI:Error:3ParametersMissing', 'class', 'id', 'stimulus')); + throw new HttpException( + Response::HTTP_INTERNAL_SERVER_ERROR, + Dict::Format('UI:Error:3ParametersMissing', 'class', 'id', 'stimulus') + ); } // Checking security layers - if (!$this->oSecurityHelper->IsActionAllowed(UR_ACTION_MODIFY, $sObjectClass, $sObjectId)) - { + if (!$this->oSecurityHelper->IsActionAllowed(UR_ACTION_MODIFY, $sObjectClass, $sObjectId)) { IssueLog::Warning(__METHOD__.' at line '.__LINE__.' : User #'.UserRights::GetUserId().' not allowed to modify '.$sObjectClass.'::'.$sObjectId.' object.'); throw new HttpException(Response::HTTP_NOT_FOUND, Dict::S('UI:ObjectDoesNotExist')); } - if (!$this->oSecurityHelper->IsStimulusAllowed($sStimulusCode, $sObjectClass)) - { + if (!$this->oSecurityHelper->IsStimulusAllowed($sStimulusCode, $sObjectClass)) { throw new HttpException(Response::HTTP_NOT_FOUND, Dict::S('UI:ObjectDoesNotExist')); } // Retrieving object - $oObject = MetaModel::GetObject($sObjectClass, $sObjectId, false /* MustBeFound */, $this->oScopeValidatorHelper->IsAllDataAllowedForScope(UserRights::ListProfiles(), $sObjectClass)); - if ($oObject === null) - { + $oObject = MetaModel::GetObject($sObjectClass, $sObjectId, false /* MustBeFound */, $this->oScopeValidatorHelper->IsAllDataAllowedForScope(UserRights::ListProfiles(), $sObjectClass)); + if ($oObject === null) { // We should never be there as the secuirty helper makes sure that the object exists, but just in case. IssueLog::Info(__METHOD__.' at line '.__LINE__.' : Could not load object '.$sObjectClass.'::'.$sObjectId.'.'); throw new HttpException(Response::HTTP_NOT_FOUND, Dict::S('UI:ObjectDoesNotExist')); @@ -495,38 +490,34 @@ class ObjectController extends BrickController // Retrieving form properties $aStimuliForms = ApplicationHelper::GetLoadedFormFromClass($aCombodoPortalInstanceConf['forms'], $sObjectClass, 'apply_stimulus'); - if (array_key_exists($sStimulusCode, $aStimuliForms)) - { + if (array_key_exists($sStimulusCode, $aStimuliForms)) { $aFormProperties = $aStimuliForms[$sStimulusCode]; } // Or preparing a default form for the stimulus application - else - { + else { // Preparing default form - $aFormProperties = array( + $aFormProperties = [ 'id' => 'apply-stimulus', 'type' => 'custom_list', - 'fields' => array(), + 'fields' => [], 'layout' => null, - ); + ]; } // Adding stimulus code to form $aFormProperties['stimulus_code'] = $sStimulusCode; // Adding target_state to current_values - $oRequest->request->set('apply_stimulus', array('code' => $sStimulusCode)); + $oRequest->request->set('apply_stimulus', ['code' => $sStimulusCode]); - $aData = array('sMode' => 'apply_stimulus'); + $aData = ['sMode' => 'apply_stimulus']; $aData['form'] = $this->oObjectFormHandlerHelper->HandleForm($oRequest, $aData['sMode'], $sObjectClass, $sObjectId, $aFormProperties); $aData['form']['title'] = Dict::Format('Brick:Portal:Object:Form:Stimulus:Title'); // TODO : This is a ugly patch to avoid showing a modal with a readonly form to the user as it would prevent user from finishing the transition. // Instead, we apply the stimulus directly here and then go to the edited object. - if (empty($sOperation)) - { - if (isset($aData['form']['editable_fields_count']) && $aData['form']['editable_fields_count'] === 0) - { + if (empty($sOperation)) { + if (isset($aData['form']['editable_fields_count']) && $aData['form']['editable_fields_count'] === 0) { $sOperation = 'redirect'; $oSubRequest = $oRequest; @@ -535,43 +526,40 @@ class ObjectController extends BrickController $oSubRequest->request->set('formmanager_class', $aData['form']['formmanager_class']); $oSubRequest->request->set('formmanager_data', json_encode($aData['form']['formmanager_data'])); - $aData = array('sMode' => 'apply_stimulus'); - $aData['form'] = $this->oObjectFormHandlerHelper->HandleForm($oSubRequest, $aData['sMode'], $sObjectClass, $sObjectId, - $aFormProperties); + $aData = ['sMode' => 'apply_stimulus']; + $aData['form'] = $this->oObjectFormHandlerHelper->HandleForm( + $oSubRequest, + $aData['sMode'], + $sObjectClass, + $sObjectId, + $aFormProperties + ); // Reload the object to make sure we have it in a clean state $oObject->Reload(true); $aNavigationRules = $this->oNavigationRuleHelper->PrepareRulesForForm($aFormProperties, $oObject, true); // Redefining the array to be as simple as possible : - $aData = array( + $aData = [ 'redirection' => - array( + [ 'url' => $aNavigationRules['submit']['url'], - ), - ); + ], + ]; } } // Preparing response - if ($oRequest->isXmlHttpRequest()) - { + if ($oRequest->isXmlHttpRequest()) { // We have to check whether the 'operation' parameter is defined or not in order to know if the form is required via ajax (to be displayed as a modal dialog) or if it's a lifecycle call from a existing form. - if (empty($sOperation)) - { + if (empty($sOperation)) { $oResponse = $this->render($this->GetTemplatePath('modal'), $aData); - } - elseif ($sOperation === 'redirect') - { + } elseif ($sOperation === 'redirect') { $oResponse = $this->render($this->GetTemplatePath('mode_loader'), $aData); - } - else - { + } else { $oResponse = new JsonResponse($aData); } - } - else - { + } else { $oResponse = $this->render($this->GetTemplatePath('page'), $aData); } @@ -599,19 +587,18 @@ class ObjectController extends BrickController public function SearchAutocompleteAction(Request $oRequest, $sTargetAttCode, $sHostObjectClass, $sHostObjectId = null) { - $aData = array( - 'results' => array( + $aData = [ + 'results' => [ 'count' => 0, - 'items' => array(), - ), - ); + 'items' => [], + ], + ]; // Parsing parameters from request payload parse_str($oRequest->getContent(), $aRequestContent); // Checking parameters - if (!isset($aRequestContent['sQuery'])) - { + if (!isset($aRequestContent['sQuery'])) { IssueLog::Error(__METHOD__.' at line '.__LINE__.' : Parameter sQuery missing.'); throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, Dict::Format('UI:Error:ParameterMissing', 'sQuery')); } @@ -621,27 +608,23 @@ class ObjectController extends BrickController $sFieldId = $aRequestContent['sFieldId']; // Checking security layers - if (!$this->oSecurityHelper->IsActionAllowed(UR_ACTION_READ, $sHostObjectClass, $sHostObjectId)) - { + if (!$this->oSecurityHelper->IsActionAllowed(UR_ACTION_READ, $sHostObjectClass, $sHostObjectId)) { IssueLog::Warning(__METHOD__.' at line '.__LINE__.' : Could not load object '.$sHostObjectClass.'::'.$sHostObjectId.'.'); throw new HttpException(Response::HTTP_NOT_FOUND, Dict::S('UI:ObjectDoesNotExist')); } // Retrieving host object for future DBSearch parameters - if ($sHostObjectId !== null) - { + if ($sHostObjectId !== null) { // Note : AllowAllData set to true here instead of checking scope's flag because we are displaying a value that has been set and validated $oHostObject = MetaModel::GetObject($sHostObjectClass, $sHostObjectId, true, true); - } - else - { + } else { $oHostObject = MetaModel::NewObject($sHostObjectClass); // Retrieving action rules // // Note : The action rules must be a base64-encoded JSON object, this is just so users are tempted to changes values. // But it would not be a security issue as it only presets values in the form. $sActionRulesToken = $this->oRequestManipulatorHelper->ReadParam('ar_token', ''); - $aActionRules = (!empty($sActionRulesToken)) ? $this->oContextManipulatorHelper->DecodeRulesToken($sActionRulesToken) : array(); + $aActionRules = (!empty($sActionRulesToken)) ? $this->oContextManipulatorHelper->DecodeRulesToken($sActionRulesToken) : []; // Preparing object $this->oContextManipulatorHelper->PrepareObject($aActionRules, $oHostObject); } @@ -664,78 +647,67 @@ class ObjectController extends BrickController } // Updating host object - $oFormManager->OnUpdate(array('currentValues' => $aRequestContent['current_values'])); + $oFormManager->OnUpdate(['currentValues' => $aRequestContent['current_values']]); $oHostObject = $oFormManager->GetObject(); } // Building search query // - Retrieving target object class from attcode $oTargetAttDef = MetaModel::GetAttributeDef($sHostObjectClass, $sTargetAttCode); - if ($oTargetAttDef->GetEditClass() === 'CustomFields') - { + if ($oTargetAttDef->GetEditClass() === 'CustomFields') { $oRequestTemplate = $oHostObject->Get($sTargetAttCode); /** @var \DBSearch $oTemplateFieldSearch */ $oTemplateFieldSearch = $oRequestTemplate->GetForm()->GetField('user_data')->GetForm()->GetField($sFieldId)->GetSearch(); $sTargetObjectClass = $oTemplateFieldSearch->GetClass(); - } - elseif ($oTargetAttDef->IsLinkSet()) - { + } elseif ($oTargetAttDef->IsLinkSet()) { throw new Exception('Search autocomplete cannot apply on AttributeLinkedSet objects, '.get_class($oTargetAttDef).' ('.$sHostObjectClass.'->'.$sTargetAttCode.') given.'); - } - else - { + } else { $sTargetObjectClass = $oTargetAttDef->GetTargetClass(); } // - Base query from meta model - if ($oTargetAttDef->GetEditClass() === 'CustomFields') - { + if ($oTargetAttDef->GetEditClass() === 'CustomFields') { $oSearch = $oTemplateFieldSearch; - } - else - { + } else { $oSearch = DBSearch::FromOQL($oTargetAttDef->GetValuesDef()->GetFilterExpression()); } // - Adding query condition - $oSearch->AddConditionExpression(new BinaryExpression(new FieldExpression('friendlyname', $oSearch->GetClassAlias()), 'LIKE', - new VariableExpression('ac_query'))); + $oSearch->AddConditionExpression(new BinaryExpression( + new FieldExpression('friendlyname', $oSearch->GetClassAlias()), + 'LIKE', + new VariableExpression('ac_query') + )); // - Intersecting with scope constraints // Note : This do NOT apply to custom fields as the portal administrator is not supposed to know which objects will be put in the templates. // It is the responsibility of the template designer to write the right query so the user see only what he should. - if ($oTargetAttDef->GetEditClass() !== 'CustomFields') - { + if ($oTargetAttDef->GetEditClass() !== 'CustomFields') { $oScopeSearch = $this->oScopeValidatorHelper->GetScopeFilterForProfiles(UserRights::ListProfiles(), $sTargetObjectClass, UR_ACTION_READ); $oSearch = $oSearch->Intersect($oScopeSearch); // - Allowing all data if necessary - if ($oScopeSearch->IsAllDataAllowed()) - { + if ($oScopeSearch->IsAllDataAllowed()) { $oSearch->AllowAllData(); } } // Retrieving results // - Preparing object set - $oSet = new DBObjectSet($oSearch, array(), array('this' => $oHostObject, 'ac_query' => '%'.$sQuery.'%')); - $oSet->OptimizeColumnLoad(array($oSearch->GetClassAlias() => array('friendlyname'))); + $oSet = new DBObjectSet($oSearch, [], ['this' => $oHostObject, 'ac_query' => '%'.$sQuery.'%']); + $oSet->OptimizeColumnLoad([$oSearch->GetClassAlias() => ['friendlyname']]); // Note : This limit is also used in the field renderer by typeahead to determine how many suggestions to display $oSet->SetLimit(MetaModel::GetConfig()->Get('max_autocomplete_results')); // - Retrieving objects - while ($oItem = $oSet->Fetch()) - { - $aData['results']['items'][] = array( + while ($oItem = $oSet->Fetch()) { + $aData['results']['items'][] = [ 'id' => $oItem->GetKey(), 'name' => html_entity_decode($oItem->GetName(), ENT_QUOTES, 'UTF-8'), - ); + ]; $aData['results']['count']++; } // Preparing response - if ($oRequest->isXmlHttpRequest()) - { + if ($oRequest->isXmlHttpRequest()) { $oResponse = new JsonResponse($aData); - } - else - { + } else { throw new HttpException(Response::HTTP_NOT_FOUND, Dict::S('UI:ObjectDoesNotExist')); } @@ -768,35 +740,31 @@ class ObjectController extends BrickController /** @var array $aCombodoPortalInstanceConf */ $aCombodoPortalInstanceConf = $this->getParameter('combodo.portal.instance.conf'); - $aData = array( + $aData = [ 'sMode' => 'search_regular', 'sTargetAttCode' => $sTargetAttCode, 'sHostObjectClass' => $sHostObjectClass, 'sHostObjectId' => $sHostObjectId, 'sActionRulesToken' => $this->oRequestManipulatorHelper->ReadParam('ar_token', ''), - ); + ]; // Checking security layers - if (!$this->oSecurityHelper->IsActionAllowed(UR_ACTION_READ, $sHostObjectClass, $sHostObjectId)) - { + if (!$this->oSecurityHelper->IsActionAllowed(UR_ACTION_READ, $sHostObjectClass, $sHostObjectId)) { IssueLog::Warning(__METHOD__.' at line '.__LINE__.' : User #'.UserRights::GetUserId().' not allowed to read '.$sHostObjectClass.'::'.$sHostObjectId.' object.'); throw new HttpException(Response::HTTP_NOT_FOUND, Dict::S('UI:ObjectDoesNotExist')); } // Retrieving host object for future DBSearch parameters - if ($sHostObjectId !== null) - { + if ($sHostObjectId !== null) { // Note : AllowAllData set to true here instead of checking scope's flag because we are displaying a value that has been set and validated $oHostObject = MetaModel::GetObject($sHostObjectClass, $sHostObjectId, true, true); - } - else - { + } else { $oHostObject = MetaModel::NewObject($sHostObjectClass); // Retrieving action rules // // Note : The action rules must be a base64-encoded JSON object, this is just so users are tempted to changes values. // But it would not be a security issue as it only presets values in the form. - $aActionRules = !empty($aData['sActionRulesToken']) ? ContextManipulatorHelper::DecodeRulesToken($aData['sActionRulesToken']) : array(); + $aActionRules = !empty($aData['sActionRulesToken']) ? ContextManipulatorHelper::DecodeRulesToken($aData['sActionRulesToken']) : []; // Preparing object $this->oContextManipulatorHelper->PrepareObject($aActionRules, $oHostObject); } @@ -819,9 +787,9 @@ class ObjectController extends BrickController } // Updating host object - $oFormManager->OnUpdate(array( - 'currentValues' => $this->oRequestManipulatorHelper->ReadParam('current_values', array(), FILTER_UNSAFE_RAW, FILTER_REQUIRE_ARRAY), - )); + $oFormManager->OnUpdate([ + 'currentValues' => $this->oRequestManipulatorHelper->ReadParam('current_values', [], FILTER_UNSAFE_RAW, FILTER_REQUIRE_ARRAY), + ]); $oHostObject = $oFormManager->GetObject(); } @@ -837,35 +805,25 @@ class ObjectController extends BrickController // Building search query // - Retrieving target object class from attcode $oTargetAttDef = MetaModel::GetAttributeDef($sHostObjectClass, $sTargetAttCode); - if ($oTargetAttDef->IsExternalKey()) - { + if ($oTargetAttDef->IsExternalKey()) { /** @var \AttributeExternalKey $oTargetAttDef */ $sTargetObjectClass = $oTargetAttDef->GetTargetClass(); - } - elseif ($oTargetAttDef->IsLinkSet()) - { + } elseif ($oTargetAttDef->IsLinkSet()) { /** @var \AttributeLinkedSet $oTargetAttDef */ - if (!$oTargetAttDef->IsIndirect()) - { + if (!$oTargetAttDef->IsIndirect()) { $sTargetObjectClass = $oTargetAttDef->GetLinkedClass(); - } - else - { + } else { /** @var \AttributeLinkedSetIndirect $oTargetAttDef */ /** @var \AttributeExternalKey $oRemoteAttDef */ $oRemoteAttDef = MetaModel::GetAttributeDef($oTargetAttDef->GetLinkedClass(), $oTargetAttDef->GetExtKeyToRemote()); $sTargetObjectClass = $oRemoteAttDef->GetTargetClass(); } - } - elseif ($oTargetAttDef->GetEditClass() === 'CustomFields') - { + } elseif ($oTargetAttDef->GetEditClass() === 'CustomFields') { $oRequestTemplate = $oHostObject->Get($sTargetAttCode); /** @var \DBSearch $oTemplateFieldSearch */ $oTemplateFieldSearch = $oRequestTemplate->GetForm()->GetField('user_data')->GetForm()->GetField($sFieldId)->GetSearch(); $sTargetObjectClass = $oTemplateFieldSearch->GetClass(); - } - else - { + } else { throw new Exception('Search from attribute can only apply on AttributeExternalKey or AttributeLinkedSet objects, '.get_class($oTargetAttDef).' given.'); } @@ -873,101 +831,89 @@ class ObjectController extends BrickController $aAttCodes = ApplicationHelper::GetLoadedListFromClass($aCombodoPortalInstanceConf['lists'], $sTargetObjectClass, 'list'); // - Adding friendlyname attribute to the list is not already in it $sTitleAttCode = 'friendlyname'; - if (($sTitleAttCode !== null) && !in_array($sTitleAttCode, $aAttCodes)) - { - $aAttCodes = array_merge(array($sTitleAttCode), $aAttCodes); + if (($sTitleAttCode !== null) && !in_array($sTitleAttCode, $aAttCodes)) { + $aAttCodes = array_merge([$sTitleAttCode], $aAttCodes); } // - Retrieving scope search // Note : This do NOT apply to custom fields as the portal administrator is not supposed to know which objects will be put in the templates. // It is the responsibility of the template designer to write the right query so the user see only what he should. $oScopeSearch = $this->oScopeValidatorHelper->GetScopeFilterForProfiles(UserRights::ListProfiles(), $sTargetObjectClass, UR_ACTION_READ); - $aInternalParams = array(); - if (($oScopeSearch === null) && ($oTargetAttDef->GetEditClass() !== 'CustomFields')) - { + $aInternalParams = []; + if (($oScopeSearch === null) && ($oTargetAttDef->GetEditClass() !== 'CustomFields')) { IssueLog::Info(__METHOD__.' at line '.__LINE__.' : User #'.UserRights::GetUserId().' has no scope query for '.$sTargetObjectClass.' class.'); throw new HttpException(Response::HTTP_NOT_FOUND, Dict::S('UI:ObjectDoesNotExist')); } // - Base query from meta model /** @var \DBSearch $oSearch */ - if ($oTargetAttDef->IsExternalKey()) - { + if ($oTargetAttDef->IsExternalKey()) { $oSearch = DBSearch::FromOQL($oTargetAttDef->GetValuesDef()->GetFilterExpression()); - } - elseif ($oTargetAttDef->IsLinkSet()) - { + } elseif ($oTargetAttDef->IsLinkSet()) { $oSearch = $oScopeSearch; - } - elseif ($oTargetAttDef->GetEditClass() === 'CustomFields') - { + } elseif ($oTargetAttDef->GetEditClass() === 'CustomFields') { // Note : $oTemplateFieldSearch has been defined in the "Retrieving target object class from attcode" part, it is not available otherwise $oSearch = $oTemplateFieldSearch; } // - Filtering objects to ignore - if (($aObjectIdsToIgnore !== null) && (is_array($aObjectIdsToIgnore))) - { + if (($aObjectIdsToIgnore !== null) && (is_array($aObjectIdsToIgnore))) { //$oSearch->AddConditionExpression('id', $aObjectIdsToIgnore, 'NOT IN'); - $aExpressions = array(); - foreach ($aObjectIdsToIgnore as $sObjectIdToIgnore) - { + $aExpressions = []; + foreach ($aObjectIdsToIgnore as $sObjectIdToIgnore) { $aExpressions[] = new ScalarExpression($sObjectIdToIgnore); } - $oSearch->AddConditionExpression(new BinaryExpression(new FieldExpression('id', $oSearch->GetClassAlias()), 'NOT IN', - new ListExpression($aExpressions))); + $oSearch->AddConditionExpression(new BinaryExpression( + new FieldExpression('id', $oSearch->GetClassAlias()), + 'NOT IN', + new ListExpression($aExpressions) + )); } // - Adding query condition $aInternalParams['this'] = $oHostObject; - if (!empty($sQuery)) - { + if (!empty($sQuery)) { $oFullExpr = null; /** @noinspection SlowArrayOperationsInLoopInspection */ - for ($i = 0; $i < count($aAttCodes); $i++) - { + for ($i = 0; $i < count($aAttCodes); $i++) { // Checking if the current attcode is an external key in order to search on the friendlyname $oAttDef = MetaModel::GetAttributeDef($sTargetObjectClass, $aAttCodes[$i]); $sAttCode = (!$oAttDef->IsExternalKey()) ? $aAttCodes[$i] : $aAttCodes[$i].'_friendlyname'; // Building expression for the current attcode // - For attributes that need conversion from their display value to storage value // Note : This is dirty hack that will need to be refactored in the OQL core in order to be nicer and to be extended to other types such as dates etc... - if (($oAttDef instanceof AttributeEnum) || ($oAttDef instanceof AttributeFinalClass)) - { + if (($oAttDef instanceof AttributeEnum) || ($oAttDef instanceof AttributeFinalClass)) { // Looking up storage value - $aMatchedCodes = array(); - foreach ($oAttDef->GetAllowedValues() as $sValueCode => $sValueLabel) - { - if (stripos($sValueLabel, $sQuery) !== false) - { + $aMatchedCodes = []; + foreach ($oAttDef->GetAllowedValues() as $sValueCode => $sValueLabel) { + if (stripos($sValueLabel, $sQuery) !== false) { $aMatchedCodes[] = $sValueCode; } } // Building expression - if (!empty($aMatchedCodes)) - { + if (!empty($aMatchedCodes)) { $oEnumeratedListExpr = ListExpression::FromScalars($aMatchedCodes); - $oBinExpr = new BinaryExpression(new FieldExpression($sAttCode, $oSearch->GetClassAlias()), 'IN', - $oEnumeratedListExpr); - } - else - { + $oBinExpr = new BinaryExpression( + new FieldExpression($sAttCode, $oSearch->GetClassAlias()), + 'IN', + $oEnumeratedListExpr + ); + } else { $oBinExpr = new FalseExpression(); } } // - For regular attributes - else - { - $oBinExpr = new BinaryExpression(new FieldExpression($sAttCode, $oSearch->GetClassAlias()), 'LIKE', - new VariableExpression('re_query')); + else { + $oBinExpr = new BinaryExpression( + new FieldExpression($sAttCode, $oSearch->GetClassAlias()), + 'LIKE', + new VariableExpression('re_query') + ); } // Adding expression to the full expression (all attcodes) - if ($i === 0) - { + if ($i === 0) { $oFullExpr = $oBinExpr; - } - else - { + } else { $oFullExpr = new BinaryExpression($oFullExpr, 'OR', $oBinExpr); } } @@ -979,79 +925,69 @@ class ObjectController extends BrickController // - Intersecting with scope constraints // Note : This do NOT apply to custom fields as the portal administrator is not supposed to know which objects will be put in the templates. // It is the responsibility of the template designer to write the right query so the user see only what he should. - if (($oScopeSearch !== null) && ($oTargetAttDef->GetEditClass() !== 'CustomFields')) - { + if (($oScopeSearch !== null) && ($oTargetAttDef->GetEditClass() !== 'CustomFields')) { $oSearch = $oSearch->Intersect($oScopeSearch); // - Allowing all data if necessary - if ($oScopeSearch->IsAllDataAllowed()) - { + if ($oScopeSearch->IsAllDataAllowed()) { $oSearch->AllowAllData(); } } // Retrieving results // - Preparing object set - $oSet = new DBObjectSet($oSearch, array(), $aInternalParams); - $oSet->OptimizeColumnLoad(array($oSearch->GetClassAlias() => $aAttCodes)); + $oSet = new DBObjectSet($oSearch, [], $aInternalParams); + $oSet->OptimizeColumnLoad([$oSearch->GetClassAlias() => $aAttCodes]); $oSet->SetLimit($iListLength, $iListLength * ($iPageNumber - 1)); // - Retrieving columns properties - $aColumnProperties = array(); - foreach ($aAttCodes as $sAttCode) - { + $aColumnProperties = []; + foreach ($aAttCodes as $sAttCode) { $oAttDef = MetaModel::GetAttributeDef($sTargetObjectClass, $sAttCode); - $aColumnProperties[$sAttCode] = array( + $aColumnProperties[$sAttCode] = [ 'title' => $oAttDef->GetLabel(), - ); + ]; } // - Retrieving objects - $aItems = array(); - while ($oItem = $oSet->Fetch()) - { + $aItems = []; + while ($oItem = $oSet->Fetch()) { $aItems[] = $this->PrepareObjectInformation($oItem, $aAttCodes); } // Preparing response - if ($bInitialPass) - { - $aData = $aData + array( - 'form' => array( + if ($bInitialPass) { + $aData = $aData + [ + 'form' => [ 'id' => 'object_search_form_'.time(), 'title' => Dict::Format('Brick:Portal:Object:Search:Regular:Title', $oTargetAttDef->GetLabel()), - 'title_complement' => MetaModel::GetName($sTargetObjectClass) - ), + 'title_complement' => MetaModel::GetName($sTargetObjectClass), + ], 'aColumnProperties' => json_encode($aColumnProperties), - 'aResults' => array( + 'aResults' => [ 'aItems' => json_encode($aItems), 'iCount' => count($aItems), - ), + ], 'bMultipleSelect' => $oTargetAttDef->IsLinkSet(), - 'aSource' => array( + 'aSource' => [ 'sFormPath' => $sFormPath, 'sFieldId' => $sFieldId, 'aObjectIdsToIgnore' => $aObjectIdsToIgnore, 'sFormManagerClass' => $sFormManagerClass, 'sFormManagerData' => $sFormManagerData, - ), - ); + ], + ]; - if ($oRequest->isXmlHttpRequest()) - { + if ($oRequest->isXmlHttpRequest()) { $oResponse = $this->render($this->GetTemplatePath('modal'), $aData); - } - else - { + } else { //throw new HttpException(Response::HTTP_NOT_FOUND, Dict::S('UI:ObjectDoesNotExist')); $oResponse = $this->render($this->GetTemplatePath('page'), $aData); } - } - else - { - $aData = $aData + array( + } else { + $aData = $aData + [ 'levelsProperties' => $aColumnProperties, 'data' => $aItems, 'recordsTotal' => $oSet->Count(), 'recordsFiltered' => $oSet->Count(), - ); + ]; $oResponse = new JsonResponse($aData); } @@ -1077,8 +1013,7 @@ class ObjectController extends BrickController { // Setting default operation - if ($sOperation === null) - { + if ($sOperation === null) { $sOperation = 'display'; } @@ -1089,37 +1024,33 @@ class ObjectController extends BrickController $bCheckSecurity = true; // When reaching to an Attachment, we have to check security on its host object instead of the Attachment itself - if ($sObjectClass === 'Attachment') - { - + if ($sObjectClass === 'Attachment') { + $oAttachment = MetaModel::GetObject($sObjectClass, $sObjectId, false, true); if ($oAttachment === null) { throw new HttpException(Response::HTTP_NOT_FOUND, Dict::S('UI:ObjectDoesNotExist')); } $sHostClass = $oAttachment->Get('item_class'); $sHostId = $oAttachment->Get('item_id'); - + // Attachments could be linked to host objects without an org_id. Retrieving the attachment would fail if enforced silos are based on org_id - if($oAttachment->Get('item_org_id') === 0 && ($sHostId > 0) && $this->oSecurityHelper->IsActionAllowed(UR_ACTION_READ, $sHostClass, $sHostId)) { + if ($oAttachment->Get('item_org_id') === 0 && ($sHostId > 0) && $this->oSecurityHelper->IsActionAllowed(UR_ACTION_READ, $sHostClass, $sHostId)) { $bCheckSecurity = false; } - - } - else - { + + } else { $sHostClass = $sObjectClass; $sHostId = $sObjectId; // Security bypass for the image attribute of a class - if(MetaModel::GetImageAttributeCode($sObjectClass) === $sObjectField) { + if (MetaModel::GetImageAttributeCode($sObjectClass) === $sObjectField) { $bCheckSecurity = false; } } // Checking security layers // Note: Checking if host object already exists as we can try to download document from an object that is being created - if (($bCheckSecurity === true) && ($sHostId > 0) && !$this->oSecurityHelper->IsActionAllowed(UR_ACTION_READ, $sHostClass, $sHostId)) - { + if (($bCheckSecurity === true) && ($sHostId > 0) && !$this->oSecurityHelper->IsActionAllowed(UR_ACTION_READ, $sHostClass, $sHostId)) { IssueLog::Warning(__METHOD__.' at line '.__LINE__.' : User #'.UserRights::GetUserId().' not allowed to retrieve document from attribute '.$sObjectField.' as it not allowed to read '.$sHostClass.'::'.$sHostId.' object.'); throw new HttpException(Response::HTTP_NOT_FOUND, Dict::S('UI:ObjectDoesNotExist')); } @@ -1127,27 +1058,22 @@ class ObjectController extends BrickController // Retrieving object $bAllowAllDataFlag = ($bCheckSecurity === false) ? true : $this->oScopeValidatorHelper->IsAllDataAllowedForScope(UserRights::ListProfiles(), $sHostClass); $oObject = MetaModel::GetObject($sObjectClass, $sObjectId, false /* Must not be found */, $bAllowAllDataFlag); - if ($oObject === null) - { + if ($oObject === null) { IssueLog::Info(__METHOD__.' at line '.__LINE__.': Could not load object '.$sObjectClass.'::'.$sObjectId.'.'); throw new HttpException(Response::HTTP_NOT_FOUND, Dict::S('UI:ObjectDoesNotExist')); } // Setting cache timeout // Note: Attachment download should be handle through AttachmentAction() - if ($sObjectClass === 'Attachment') - { + if ($sObjectClass === 'Attachment') { // One year ahead: an attachment cannot change $iCacheSec = 31556926; - } - else - { + } else { $iCacheSec = $this->oRequestManipulatorHelper->ReadParam('cache', 0, FILTER_SANITIZE_NUMBER_INT); } - $aHeaders = array(); - if ($iCacheSec > 0) - { + $aHeaders = []; + if ($iCacheSec > 0) { $aHeaders['Expires'] = ''; $aHeaders['Cache-Control'] = 'no-transform, public,max-age='.$iCacheSec.',s-maxage='.$iCacheSec; // Reset the value set previously @@ -1198,32 +1124,26 @@ class ObjectController extends BrickController */ public function AttachmentAction(Request $oRequest, $sOperation = null) { - $aData = array( + $aData = [ 'att_id' => 0, 'preview' => false, 'msg' => '', - ); + ]; // Retrieving sOperation from request only if it wasn't forced (determined by the route) - if ($sOperation === null) - { + if ($sOperation === null) { $sOperation = $this->oRequestManipulatorHelper->ReadParam('operation', null); } - switch ($sOperation) - { + switch ($sOperation) { case 'add': $sFieldName = $this->oRequestManipulatorHelper->ReadParam('field_name', ''); $sObjectClass = $this->oRequestManipulatorHelper->ReadParam('object_class', ''); $sTempId = $this->oRequestManipulatorHelper->ReadParam('temp_id', ''); - if (empty($sObjectClass) || empty($sTempId)) - { + if (empty($sObjectClass) || empty($sTempId)) { $aData['error'] = Dict::Format('UI:Error:2ParametersMissing', 'object_class', 'temp_id'); - } - else - { - try - { + } else { + try { $oDocument = utils::ReadPostedDocument($sFieldName); /** @noinspection PhpUndefinedClassInspection */ /** @var \Attachment $oAttachment */ @@ -1250,25 +1170,23 @@ class ObjectController extends BrickController $aData['creation_date'] = $oAttachment->Get('creation_date'); $aData['user_id_friendlyname'] = $oAttachment->Get('user_id_friendlyname'); $aData['file_type'] = $oDocument->GetMimeType(); - } - catch (FileUploadException $e) - { + } catch (FileUploadException $e) { $aData['error'] = $e->GetMessage(); } } // Note : The Content-Type header is set to 'text/plain' in order to be IE9 compatible. Otherwise ('application/json') IE9 will download the response as a JSON file to the user computer... - $oResponse = new JsonResponse($aData, Response::HTTP_OK, array('Content-Type' => 'text/plain')); + $oResponse = new JsonResponse($aData, Response::HTTP_OK, ['Content-Type' => 'text/plain']); break; case 'download': // Preparing redirection // - Route - $aRouteParams = array( + $aRouteParams = [ 'sObjectClass' => 'Attachment', 'sObjectId' => $this->oRequestManipulatorHelper->ReadParam('sAttachmentId', null), 'sObjectField' => 'contents', - ); + ]; $oResponse = $this->ForwardToRoute('p_object_document_download', $aRouteParams, $oRequest->query->all()); @@ -1277,11 +1195,11 @@ class ObjectController extends BrickController case 'display': // Preparing redirection // - Route - $aRouteParams = array( + $aRouteParams = [ 'sObjectClass' => 'Attachment', 'sObjectId' => $this->oRequestManipulatorHelper->ReadParam('sAttachmentId', null), 'sObjectField' => 'contents', - ); + ]; $oResponse = $this->ForwardToRoute('p_object_document_display', $aRouteParams, $oRequest->query->all()); @@ -1316,21 +1234,23 @@ class ObjectController extends BrickController public function GetInformationAsJsonAction(Request $oRequest) { - $aData = array(); + $aData = []; // Retrieving parameters $sObjectClass = $this->oRequestManipulatorHelper->ReadParam('sObjectClass', ''); - $aObjectIds = $this->oRequestManipulatorHelper->ReadParam('aObjectIds', array(), FILTER_UNSAFE_RAW, FILTER_REQUIRE_ARRAY); - $aObjectAttCodes = $this->oRequestManipulatorHelper->ReadParam('aObjectAttCodes', array(), FILTER_UNSAFE_RAW, FILTER_REQUIRE_ARRAY); + $aObjectIds = $this->oRequestManipulatorHelper->ReadParam('aObjectIds', [], FILTER_UNSAFE_RAW, FILTER_REQUIRE_ARRAY); + $aObjectAttCodes = $this->oRequestManipulatorHelper->ReadParam('aObjectAttCodes', [], FILTER_UNSAFE_RAW, FILTER_REQUIRE_ARRAY); if (empty($sObjectClass) || empty($aObjectIds) || empty($aObjectAttCodes)) { - IssueLog::Info(__METHOD__.' at line '.__LINE__.' : sObjectClass, aObjectIds and aObjectAttCodes expected, "'.$sObjectClass.'", "'.implode('/', - $aObjectIds).'" given.'); + IssueLog::Info(__METHOD__.' at line '.__LINE__.' : sObjectClass, aObjectIds and aObjectAttCodes expected, "'.$sObjectClass.'", "'.implode( + '/', + $aObjectIds + ).'" given.'); throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, 'Invalid request data, some information are missing'); } // Building the search $bIgnoreSilos = $this->oScopeValidatorHelper->IsAllDataAllowedForScope(UserRights::ListProfiles(), $sObjectClass); - $aParams = array('objects_id' => $aObjectIds); + $aParams = ['objects_id' => $aObjectIds]; $oSearch = DBObjectSearch::FromOQL("SELECT $sObjectClass WHERE id IN (:objects_id)"); if (!$this->oScopeValidatorHelper->AddScopeToQuery($oSearch, $sObjectClass) ) { @@ -1340,13 +1260,13 @@ class ObjectController extends BrickController if ($bIgnoreSilos === true) { $oSearch->AllowAllData(); } - $oSet = new DBObjectSet($oSearch, array(), $aParams); - $oSet->OptimizeColumnLoad(array($oSearch->GetClassAlias() => $aObjectAttCodes)); + $oSet = new DBObjectSet($oSearch, [], $aParams); + $oSet->OptimizeColumnLoad([$oSearch->GetClassAlias() => $aObjectAttCodes]); // Checking that id is in the AttCodes // Note: We do that AFTER the array is used in OptimizeColumnLoad() because the function doesn't support this anymore. if (!in_array('id', $aObjectAttCodes)) { - $aObjectAttCodes = array_merge(array('id'), $aObjectAttCodes); + $aObjectAttCodes = array_merge(['id'], $aObjectAttCodes); } // Retrieving objects @@ -1375,47 +1295,48 @@ class ObjectController extends BrickController public function GetInformationForLinkedSetAsJsonAction(Request $oRequest) { // Data array - $aData = array( + $aData = [ 'js_inline' => '', 'css_inline' => '', - ); + ]; // Retrieving parameters $sObjectClass = $this->oRequestManipulatorHelper->ReadParam('sObjectClass', ''); $sLinkClass = $this->oRequestManipulatorHelper->ReadParam('sLinkClass', ''); - $aObjectIds = $this->oRequestManipulatorHelper->ReadParam('aObjectIds', array(), FILTER_UNSAFE_RAW, FILTER_REQUIRE_ARRAY); - $aObjectAttCodes = $this->oRequestManipulatorHelper->ReadParam('aObjectAttCodes', array(), FILTER_UNSAFE_RAW, FILTER_REQUIRE_ARRAY); - $aLinkAttCodes = $this->oRequestManipulatorHelper->ReadParam('aLinkAttCodes', array(), FILTER_UNSAFE_RAW, FILTER_REQUIRE_ARRAY); - $sDateTimePickerWidgetParent = $this->oRequestManipulatorHelper->ReadParam('sDateTimePickerWidgetParent', array(), FILTER_UNSAFE_RAW, FILTER_REQUIRE_ARRAY); + $aObjectIds = $this->oRequestManipulatorHelper->ReadParam('aObjectIds', [], FILTER_UNSAFE_RAW, FILTER_REQUIRE_ARRAY); + $aObjectAttCodes = $this->oRequestManipulatorHelper->ReadParam('aObjectAttCodes', [], FILTER_UNSAFE_RAW, FILTER_REQUIRE_ARRAY); + $aLinkAttCodes = $this->oRequestManipulatorHelper->ReadParam('aLinkAttCodes', [], FILTER_UNSAFE_RAW, FILTER_REQUIRE_ARRAY); + $sDateTimePickerWidgetParent = $this->oRequestManipulatorHelper->ReadParam('sDateTimePickerWidgetParent', [], FILTER_UNSAFE_RAW, FILTER_REQUIRE_ARRAY); if (!MetaModel::IsLinkClass($sLinkClass)) { IssueLog::Warning(__METHOD__.' at line '.__LINE__.' : User #'.UserRights::GetUserId().' asked for wrong lnk class '.$sLinkClass); throw new HttpException(Response::HTTP_NOT_FOUND, Dict::S('UI:ObjectDoesNotExist')); } if (empty($sObjectClass) || empty($aObjectIds) || empty($aObjectAttCodes)) { - IssueLog::Info(__METHOD__.' at line '.__LINE__.' : sObjectClass, aObjectIds and aObjectAttCodes expected, "'.$sObjectClass.'", "'.implode('/', - $aObjectIds).'" given.'); + IssueLog::Info(__METHOD__.' at line '.__LINE__.' : sObjectClass, aObjectIds and aObjectAttCodes expected, "'.$sObjectClass.'", "'.implode( + '/', + $aObjectIds + ).'" given.'); throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, 'Invalid request data, some information are missing'); } // Building the search $bIgnoreSilos = $this->oScopeValidatorHelper->IsAllDataAllowedForScope(UserRights::ListProfiles(), $sObjectClass); - $aParams = array('objects_id' => $aObjectIds); + $aParams = ['objects_id' => $aObjectIds]; $oSearch = DBObjectSearch::FromOQL("SELECT $sObjectClass WHERE id IN (:objects_id)"); if (!$this->oScopeValidatorHelper->AddScopeToQuery($oSearch, $sObjectClass)) { IssueLog::Warning(__METHOD__.' at line '.__LINE__.' : User #'.UserRights::GetUserId().' not allowed to read '.$sObjectClass.' object.'); throw new HttpException(Response::HTTP_NOT_FOUND, Dict::S('UI:ObjectDoesNotExist')); } - if ($bIgnoreSilos === true) - { + if ($bIgnoreSilos === true) { $oSearch->AllowAllData(); } - $oSet = new DBObjectSet($oSearch, array(), $aParams); - $oSet->OptimizeColumnLoad(array($oSearch->GetClassAlias() => $aObjectAttCodes)); + $oSet = new DBObjectSet($oSearch, [], $aParams); + $oSet->OptimizeColumnLoad([$oSearch->GetClassAlias() => $aObjectAttCodes]); // Checking that id is in the AttCodes // Note: We do that AFTER the array is used in OptimizeColumnLoad() because the function doesn't support this anymore. if (!in_array('id', $aObjectAttCodes)) { - $aObjectAttCodes = array_merge(array('id'), $aObjectAttCodes); + $aObjectAttCodes = array_merge(['id'], $aObjectAttCodes); } // Retrieving objects @@ -1446,7 +1367,7 @@ class ObjectController extends BrickController if ($oAttDef::GetFormFieldClass() === '\\Combodo\\iTop\\Form\\Field\\SelectObjectField') { $oFieldSearch = $oField->GetSearch(); $sFieldClass = $oFieldSearch->GetClass(); - if ($this->oScopeValidatorHelper->AddScopeToQuery($oFieldSearch, $sFieldClass)){ + if ($this->oScopeValidatorHelper->AddScopeToQuery($oFieldSearch, $sFieldClass)) { $oField->SetSearch($oFieldSearch); } else { $oField->SetSearch(DBObjectSearch::FromOQL("SELECT $sFieldClass WHERE 1=0")); @@ -1488,7 +1409,7 @@ class ObjectController extends BrickController * @throws \CoreException * @throws \Exception */ - protected function PrepareObjectInformation(DBObject $oObject, $aAttCodes = array()) + protected function PrepareObjectInformation(DBObject $oObject, $aAttCodes = []) { $sObjectClass = get_class($oObject); $aObjectData = [ @@ -1499,10 +1420,8 @@ class ObjectController extends BrickController // Retrieving attributes definitions $aAttDefs = []; - foreach ($aAttCodes as $sAttCode) - { - if ($sAttCode === 'id') - { + foreach ($aAttCodes as $sAttCode) { + if ($sAttCode === 'id') { continue; } @@ -1510,8 +1429,7 @@ class ObjectController extends BrickController } // Preparing attribute data - foreach ($aAttDefs as $oAttDef) - { + foreach ($aAttDefs as $oAttDef) { $aAttData = [ 'object_class' => $sObjectClass, 'object_id' => $oObject->GetKey(), @@ -1522,39 +1440,31 @@ class ObjectController extends BrickController // - Value raw // For simple fields, we get the raw (stored) value as well $bExcludeRawValue = false; - foreach (ApplicationHelper::GetAttDefClassesToExcludeFromMarkupMetadataRawValue() as $sAttDefClassToExclude) - { - if (is_a($oAttDef, $sAttDefClassToExclude, true)) - { + foreach (ApplicationHelper::GetAttDefClassesToExcludeFromMarkupMetadataRawValue() as $sAttDefClassToExclude) { + if (is_a($oAttDef, $sAttDefClassToExclude, true)) { $bExcludeRawValue = true; break; } } $aAttData['value_raw'] = ($bExcludeRawValue === false) ? $oObject->Get($oAttDef->GetCode()) : null; - - if ($oAttDef->IsExternalKey()) - { + if ($oAttDef->IsExternalKey()) { $aAttData['value_html'] = $oObject->GetAsHTML($oAttDef->GetCode().'_friendlyname'); // Checking if user can access object's external key - if ($this->oSecurityHelper->IsActionAllowed(UR_ACTION_READ, $oAttDef->GetTargetClass())) - { - $aAttData['url'] = $this->oUrlGenerator->generate('p_object_view', - array('sObjectClass' => $oAttDef->GetTargetClass(), 'sObjectId' => $oObject->Get($oAttDef->GetCode()))); + if ($this->oSecurityHelper->IsActionAllowed(UR_ACTION_READ, $oAttDef->GetTargetClass())) { + $aAttData['url'] = $this->oUrlGenerator->generate( + 'p_object_view', + ['sObjectClass' => $oAttDef->GetTargetClass(), 'sObjectId' => $oObject->Get($oAttDef->GetCode())] + ); } - } - elseif ($oAttDef->IsLinkSet()) - { + } elseif ($oAttDef->IsLinkSet()) { // We skip it continue; - } - elseif ($oAttDef instanceof AttributeImage) - { + } elseif ($oAttDef instanceof AttributeImage) { /** @var \ormDocument $oOrmDoc */ $oOrmDoc = $oObject->Get($oAttDef->GetCode()); - if (is_object($oOrmDoc) && !$oOrmDoc->IsEmpty()) - { + if (is_object($oOrmDoc) && !$oOrmDoc->IsEmpty()) { $sUrl = $this->oUrlGenerator->generate('p_object_document_display', [ 'sObjectClass' => get_class($oObject), 'sObjectId' => $oObject->GetKey(), @@ -1562,27 +1472,22 @@ class ObjectController extends BrickController 'cache' => 86400, 's' => $oOrmDoc->GetSignature(), ]); - } - else - { + } else { $sUrl = $oAttDef->Get('default_image'); } $aAttData['value_html'] = ''; - } - elseif ($oAttDef instanceof AttributeEnum) { + } elseif ($oAttDef instanceof AttributeEnum) { $aAttData['value_html'] = $oAttDef->GetAsPlainText($oObject->Get($oAttDef->GetCode())); - } - else - { + } else { $aAttData['value_html'] = $oAttDef->GetAsHTML($oObject->Get($oAttDef->GetCode())); - if ($oAttDef instanceof AttributeFriendlyName) - { + if ($oAttDef instanceof AttributeFriendlyName) { // Checking if user can access object - if ($this->oSecurityHelper->IsActionAllowed(UR_ACTION_READ, $sObjectClass)) - { - $aAttData['url'] = $this->oUrlGenerator->generate('p_object_view', - array('sObjectClass' => $sObjectClass, 'sObjectId' => $oObject->GetKey())); + if ($this->oSecurityHelper->IsActionAllowed(UR_ACTION_READ, $sObjectClass)) { + $aAttData['url'] = $this->oUrlGenerator->generate( + 'p_object_view', + ['sObjectClass' => $sObjectClass, 'sObjectId' => $oObject->GetKey()] + ); } } } @@ -1612,40 +1517,31 @@ class ObjectController extends BrickController protected function DisplayCreationForm(Request $oRequest, $sObjectClass) { // Checking security layers - if (!$this->oSecurityHelper->IsActionAllowed(UR_ACTION_CREATE, $sObjectClass)) - { + if (!$this->oSecurityHelper->IsActionAllowed(UR_ACTION_CREATE, $sObjectClass)) { IssueLog::Warning(__METHOD__.' at line '.__LINE__.' : User #'.UserRights::GetUserId().' not allowed to create '.$sObjectClass.' object.'); throw new HttpException(Response::HTTP_NOT_FOUND, Dict::S('UI:ObjectDoesNotExist')); } $sOperation = $this->oRequestManipulatorHelper->ReadParam('operation', ''); - $aData = array('sMode' => 'create'); + $aData = ['sMode' => 'create']; $aData['form'] = $this->oObjectFormHandlerHelper->HandleForm($oRequest, $aData['sMode'], $sObjectClass); $aData['form']['title'] = Dict::Format('Brick:Portal:Object:Form:Create:Title', MetaModel::GetName($sObjectClass)); // Preparing response - if ($oRequest->isXmlHttpRequest()) - { + if ($oRequest->isXmlHttpRequest()) { // We have to check whether the 'operation' parameter is defined or not in order to know if the form is required via ajax (to be displayed as a modal dialog) or if it's a lifecycle call from a existing form. - if (empty($sOperation)) - { + if (empty($sOperation)) { $oResponse = $this->render($this->GetTemplatePath('modal'), $aData); - } - else - { + } else { $oResponse = new JsonResponse($aData); } - } - else - { + } else { // Adding brick if it was passed $sBrickId = $this->oRequestManipulatorHelper->ReadParam('sBrickId', ''); - if (!empty($sBrickId)) - { + if (!empty($sBrickId)) { $oBrick = $this->oBrickCollection->GetBrickById($sBrickId); - if ($oBrick !== null) - { + if ($oBrick !== null) { $aData['oBrick'] = $oBrick; } } @@ -1672,17 +1568,16 @@ class ObjectController extends BrickController */ protected function DisplayLeafClassesForm($sObjectClass) { - $aData = array( - 'aLeafClasses' => array(), + $aData = [ + 'aLeafClasses' => [], 'sPageTitle' => Dict::Format('Brick:Portal:Object:Form:Create:Title', MetaModel::GetName($sObjectClass)), - 'sLeafClassesListId' => 'leaf_classes_list_' . uniqid(), + 'sLeafClassesListId' => 'leaf_classes_list_'.uniqid(), 'ar_token' => $this->oRequestManipulatorHelper->ReadParam('ar_token', ''), - ); + ]; $sTemplatePath = CreateBrick::DEFAULT_PAGE_TEMPLATE_PATH; $sBrickId = $this->oRequestManipulatorHelper->ReadParam('sBrickId', ''); - if (!empty($sBrickId)) - { + if (!empty($sBrickId)) { $oBrick = $this->oBrickCollection->GetBrickById($sBrickId); $sTemplatePath = $oBrick->GetTemplatePath('page'); @@ -1691,16 +1586,14 @@ class ObjectController extends BrickController $aData['sPageTitle'] = $oBrick->GetTitle(); } - $aLeafClasses = array(); + $aLeafClasses = []; $aChildClasses = MetaModel::EnumChildClasses($sObjectClass); - foreach ($aChildClasses as $sChildClass) - { - if (!MetaModel::IsAbstract($sChildClass) && $this->oSecurityHelper->IsActionAllowed(UR_ACTION_CREATE, $sChildClass)) - { - $aLeafClasses[] = array( + foreach ($aChildClasses as $sChildClass) { + if (!MetaModel::IsAbstract($sChildClass) && $this->oSecurityHelper->IsActionAllowed(UR_ACTION_CREATE, $sChildClass)) { + $aLeafClasses[] = [ 'id' => $sChildClass, 'name' => MetaModel::GetName($sChildClass), - ); + ]; } } $aData['aLeafClasses'] = $aLeafClasses; diff --git a/datamodels/2.x/itop-portal-base/portal/src/Controller/PreferencesController.php b/datamodels/2.x/itop-portal-base/portal/src/Controller/PreferencesController.php index 88fddd0ef..babf7b443 100644 --- a/datamodels/2.x/itop-portal-base/portal/src/Controller/PreferencesController.php +++ b/datamodels/2.x/itop-portal-base/portal/src/Controller/PreferencesController.php @@ -34,7 +34,6 @@ use Symfony\Component\HttpFoundation\Request; */ class PreferencesController extends SymfonyAbstractController { - /** * Set a preference for the current user. * @@ -51,10 +50,9 @@ class PreferencesController extends SymfonyAbstractController $sValue = $oRequest->request->get('value'); // set user preference - try{ + try { appUserPreferences::SetPref($sKey, $sValue); - } - catch(Exception){ + } catch (Exception) { $sStatus = 'error'; } diff --git a/datamodels/2.x/itop-portal-base/portal/src/Controller/UserProfileBrickController.php b/datamodels/2.x/itop-portal-base/portal/src/Controller/UserProfileBrickController.php index 6dcd59c78..0dfd9ae2b 100644 --- a/datamodels/2.x/itop-portal-base/portal/src/Controller/UserProfileBrickController.php +++ b/datamodels/2.x/itop-portal-base/portal/src/Controller/UserProfileBrickController.php @@ -45,6 +45,7 @@ use Symfony\Component\HttpKernel\Exception\HttpException; use UserRights; use utils; use Dict; + /** * Class UserProfileBrickController * @@ -60,7 +61,7 @@ class UserProfileBrickController extends BrickController * @param \Combodo\iTop\Portal\Brick\BrickCollection $oBrickCollection * @param \Combodo\iTop\Portal\Routing\UrlGenerator $oUrlGenerator * @param \Combodo\iTop\Portal\Helper\SecurityHelper $oSecurityHelper - + * * @since 3.2.0 N°6933 */ @@ -70,12 +71,11 @@ class UserProfileBrickController extends BrickController protected BrickCollection $oBrickCollection, protected UrlGenerator $oUrlGenerator, protected SecurityHelper $oSecurityHelper - ) - { + ) { } /** @var string ENUM_FORM_TYPE_PICTURE */ - const ENUM_FORM_TYPE_PICTURE = 'picture'; + public const ENUM_FORM_TYPE_PICTURE = 'picture'; /** * @param \Symfony\Component\HttpFoundation\Request $oRequest @@ -92,26 +92,20 @@ class UserProfileBrickController extends BrickController public function DisplayAction(Request $oRequest, $sBrickId) { // If the brick id was not specified, we get the first one registered that is an instance of UserProfileBrick as default - if ($sBrickId === null) - { + if ($sBrickId === null) { /** @var \Combodo\iTop\Portal\Brick\PortalBrick $oTmpBrick */ - foreach ($this->oBrickCollection->GetBricks() as $oTmpBrick) - { - if ($oTmpBrick instanceof UserProfileBrick) - { + foreach ($this->oBrickCollection->GetBricks() as $oTmpBrick) { + if ($oTmpBrick instanceof UserProfileBrick) { $oBrick = $oTmpBrick; } } // We make sure a UserProfileBrick was found - if (!isset($oBrick) || $oBrick === null) - { + if (!isset($oBrick) || $oBrick === null) { $oBrick = new UserProfileBrick(); //throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, 'UserProfileBrick : Brick could not be loaded as there was no UserProfileBrick loaded in the application.'); } - } - else - { + } else { $oBrick = $this->oBrickCollection->GetBrickById($sBrickId); } @@ -124,11 +118,14 @@ class UserProfileBrickController extends BrickController $sTab = $this->oRequestManipulatorHelper->ReadParam('sTab', 'user-info', FILTER_UNSAFE_RAW, FILTER_FLAG_EMPTY_STRING_NULL); // If this is ajax call, we are just submitting preferences or password forms - if ($oRequest->isXmlHttpRequest()) - { + if ($oRequest->isXmlHttpRequest()) { if ($sTab === "user-info") { - $aCurrentValues = $this->oRequestManipulatorHelper->ReadParam('current_values', array(), FILTER_UNSAFE_RAW, - FILTER_REQUIRE_ARRAY); + $aCurrentValues = $this->oRequestManipulatorHelper->ReadParam( + 'current_values', + [], + FILTER_UNSAFE_RAW, + FILTER_REQUIRE_ARRAY + ); $sFormType = $aCurrentValues['form_type']; if ($sFormType === PreferencesFormManager::FORM_TYPE) { $aData['form'] = $this->HandlePreferencesForm($oRequest, $sFormMode); @@ -143,8 +140,7 @@ class UserProfileBrickController extends BrickController $oResponse = new JsonResponse($aData); } // Else, we are displaying page for first time - else - { + else { if ($sTab === "user-info") { // Retrieving current contact /** @var \DBObject $oCurContact */ @@ -175,7 +171,6 @@ class UserProfileBrickController extends BrickController return $oResponse; } - private function ManageUserProfileBrickExtensibility(string $sTab, array &$aData): void { $aData['sTab'] = $sTab; @@ -193,7 +188,7 @@ class UserProfileBrickController extends BrickController // Read the current tab content From iPortalTabSectionExtension $aTabSectionExtensions = ExtensibilityHelper::GetInstance()->GetPortalTabContentExtensions(iUserProfileTabContentExtension::class, $sTab); - if (count($aTabSectionExtensions) !== 0 && count($_POST) !== 0){ + if (count($aTabSectionExtensions) !== 0 && count($_POST) !== 0) { $sTransactionId = utils::ReadPostedParam('transaction_id', null, utils::ENUM_SANITIZATION_FILTER_TRANSACTION_ID); IssueLog::Debug(__FUNCTION__.": transaction [$sTransactionId]"); if (utils::IsNullOrEmptyString($sTransactionId) || !utils::IsTransactionValid($sTransactionId, false)) { @@ -214,30 +209,28 @@ class UserProfileBrickController extends BrickController } } + public function EditPerson(Request $oRequest) + { + $oCurContact = UserRights::GetContactObject(); + $sObjectClass = get_class($oCurContact); + $sObjectId = $oCurContact->GetKey(); - public function EditPerson(Request $oRequest) - { - $oCurContact = UserRights::GetContactObject(); - $sObjectClass = get_class($oCurContact); - $sObjectId = $oCurContact->GetKey(); + // Checking security layers + // Warning : This is a dirty quick fix to allow editing its own contact information + $bAllowWrite = ($sObjectClass === 'Person' && $sObjectId == UserRights::GetContactId()); + if (!$this->oSecurityHelper->IsActionAllowed(UR_ACTION_MODIFY, $sObjectClass, $sObjectId) && !$bAllowWrite) { + IssueLog::Warning(__METHOD__.' at line '.__LINE__.' : User #'.UserRights::GetUserId().' not allowed to modify '.$sObjectClass.'::'.$sObjectId.' object.'); + throw new HttpException(Response::HTTP_NOT_FOUND, Dict::S('UI:ObjectDoesNotExist')); + } - // Checking security layers - // Warning : This is a dirty quick fix to allow editing its own contact information - $bAllowWrite = ($sObjectClass === 'Person' && $sObjectId == UserRights::GetContactId()); - if (!$this->oSecurityHelper->IsActionAllowed(UR_ACTION_MODIFY, $sObjectClass, $sObjectId) && !$bAllowWrite) { - IssueLog::Warning(__METHOD__ . ' at line ' . __LINE__ . ' : User #' . UserRights::GetUserId() . ' not allowed to modify ' . $sObjectClass . '::' . $sObjectId . ' object.'); - throw new HttpException(Response::HTTP_NOT_FOUND, Dict::S('UI:ObjectDoesNotExist')); - } + $aForm = $this->GetBrick()->GetForm(); + $aForm['submit_endpoint'] = $this->generateUrl('p_user_profile_brick_edit_person'); - $aForm = $this->GetBrick()->GetForm(); - $aForm['submit_endpoint'] = $this->generateUrl('p_user_profile_brick_edit_person'); - - $aData = ['sMode' => 'edit']; - $aData['form'] = $this->ObjectFormHandlerHelper->HandleForm($oRequest, $aData['sMode'], $sObjectClass, $sObjectId, $aForm); - - return new JsonResponse($aData); - } + $aData = ['sMode' => 'edit']; + $aData['form'] = $this->ObjectFormHandlerHelper->HandleForm($oRequest, $aData['sMode'], $sObjectClass, $sObjectId, $aForm); + return new JsonResponse($aData); + } /** * @param \Symfony\Component\HttpFoundation\Request $oRequest @@ -249,13 +242,12 @@ class UserProfileBrickController extends BrickController */ public function HandlePreferencesForm(Request $oRequest, $sFormMode) { - $aFormData = array(); + $aFormData = []; // Handling form $sOperation = $this->oRequestManipulatorHelper->ReadParam('operation', null); // - Create - if ($sOperation === null) - { + if ($sOperation === null) { // - Creating renderer $oFormRenderer = new BsFormRenderer(); $oFormRenderer->SetEndpoint($this->oUrlGenerator->generate('p_user_profile_brick')); @@ -264,50 +256,47 @@ class UserProfileBrickController extends BrickController $oFormManager->SetRenderer($oFormRenderer) ->Build(); // - Checking if we have to make the form read only - if ($sFormMode === ObjectFormHandlerHelper::ENUM_MODE_VIEW) - { + if ($sFormMode === ObjectFormHandlerHelper::ENUM_MODE_VIEW) { $oFormManager->GetForm()->MakeReadOnly(); } } // - Submit - else - { - if ($sOperation === 'submit') - { + else { + if ($sOperation === 'submit') { $sFormManagerClass = $this->oRequestManipulatorHelper->ReadParam('formmanager_class', null, FILTER_UNSAFE_RAW); $sFormManagerData = $this->oRequestManipulatorHelper->ReadParam('formmanager_data', null, FILTER_UNSAFE_RAW); - if ($sFormManagerClass === null || $sFormManagerData === null) - { + if ($sFormManagerClass === null || $sFormManagerData === null) { IssueLog::Error(__METHOD__.' at line '.__LINE__.' : Parameters formmanager_class and formmanager_data must be defined.'); - throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, - 'Parameters formmanager_class and formmanager_data must be defined.'); + throw new HttpException( + Response::HTTP_INTERNAL_SERVER_ERROR, + 'Parameters formmanager_class and formmanager_data must be defined.' + ); } // Rebuilding manager from json /** @var \Combodo\iTop\Form\FormManager $oFormManager */ $oFormManager = $sFormManagerClass::FromJSON($sFormManagerData); // Applying modification to object - $aFormData['validation'] = $oFormManager->OnSubmit(array( - 'currentValues' => $this->oRequestManipulatorHelper->ReadParam('current_values', array(), FILTER_UNSAFE_RAW, FILTER_REQUIRE_ARRAY), - )); + $aFormData['validation'] = $oFormManager->OnSubmit([ + 'currentValues' => $this->oRequestManipulatorHelper->ReadParam('current_values', [], FILTER_UNSAFE_RAW, FILTER_REQUIRE_ARRAY), + ]); // Reloading page only if preferences were changed - if (($aFormData['validation']['valid'] === true) && !empty($aFormData['validation']['messages']['success'])) - { - $aFormData['validation']['redirection'] = array( + if (($aFormData['validation']['valid'] === true) && !empty($aFormData['validation']['messages']['success'])) { + $aFormData['validation']['redirection'] = [ 'url' => $this->oUrlGenerator->generate('p_user_profile_brick'), 'timeout_duration' => 1000, //since there are several ajax request, we use a longer timeout in hope that they will all be finished in time. A promise would have been more reliable, but since this change is made in a minor version, this approach is less error prone. - ); + ]; } } } // Else, submit from another form // Preparing field_set data - $aFieldSetData = array( + $aFieldSetData = [ 'fields_list' => $oFormManager->GetRenderer()->Render(), 'fields_impacts' => $oFormManager->GetForm()->GetFieldsImpacts(), 'form_path' => $oFormManager->GetForm()->GetId(), - ); + ]; // Preparing form data $aFormData['id'] = $oFormManager->GetForm()->GetId(); @@ -329,14 +318,13 @@ class UserProfileBrickController extends BrickController */ public function HandlePasswordForm(Request $oRequest, $sFormMode) { - $aFormData = array(); + $aFormData = []; // Handling form $sOperation = /** @var \Combodo\iTop\Portal\Helper\RequestManipulatorHelper $oRequestManipulator */ $this->oRequestManipulatorHelper->ReadParam('operation', null); // - Create - if ($sOperation === null) - { + if ($sOperation === null) { // - Creating renderer $oFormRenderer = new BsFormRenderer(); $oFormRenderer->SetEndpoint($this->oUrlGenerator->generate('p_user_profile_brick')); @@ -345,41 +333,40 @@ class UserProfileBrickController extends BrickController $oFormManager->SetRenderer($oFormRenderer) ->Build(); // - Checking if we have to make the form read only - if ($sFormMode === ObjectFormHandlerHelper::ENUM_MODE_VIEW) - { + if ($sFormMode === ObjectFormHandlerHelper::ENUM_MODE_VIEW) { $oFormManager->GetForm()->MakeReadOnly(); } } // - Submit - else - { - if ($sOperation === 'submit') - { + else { + if ($sOperation === 'submit') { $sFormManagerClass = $this->oRequestManipulatorHelper->ReadParam('formmanager_class', null, FILTER_UNSAFE_RAW); $sFormManagerData = $this->oRequestManipulatorHelper->ReadParam('formmanager_data', null, FILTER_UNSAFE_RAW); if ($sFormManagerClass === null || $sFormManagerData === null) { IssueLog::Error(__METHOD__.' at line '.__LINE__.' : Parameters formmanager_class and formmanager_data must be defined.'); - throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, - 'Parameters formmanager_class and formmanager_data must be defined.'); + throw new HttpException( + Response::HTTP_INTERNAL_SERVER_ERROR, + 'Parameters formmanager_class and formmanager_data must be defined.' + ); } // Rebuilding manager from json /** @var \Combodo\iTop\Form\FormManager $oFormManager */ $oFormManager = $sFormManagerClass::FromJSON($sFormManagerData); // Applying modification to object - $aFormData['validation'] = $oFormManager->OnSubmit(array( - 'currentValues' => $this->oRequestManipulatorHelper->ReadParam('current_values', array(), FILTER_UNSAFE_RAW, FILTER_REQUIRE_ARRAY), - )); + $aFormData['validation'] = $oFormManager->OnSubmit([ + 'currentValues' => $this->oRequestManipulatorHelper->ReadParam('current_values', [], FILTER_UNSAFE_RAW, FILTER_REQUIRE_ARRAY), + ]); } } // Else, submit from another form // Preparing field_set data - $aFieldSetData = array( + $aFieldSetData = [ 'fields_list' => $oFormManager->GetRenderer()->Render(), 'fields_impacts' => $oFormManager->GetForm()->GetFieldsImpacts(), 'form_path' => $oFormManager->GetForm()->GetId(), - ); + ]; // Preparing form data $aFormData['id'] = $oFormManager->GetForm()->GetId(); @@ -400,32 +387,27 @@ class UserProfileBrickController extends BrickController */ public function HandlePictureForm(Request $oRequest) { - $aFormData = array(); + $aFormData = []; $sPictureAttCode = 'picture'; // Handling form $sOperation = $this->oRequestManipulatorHelper->ReadParam('operation', null); // - No operation specified - if ($sOperation === null) - { + if ($sOperation === null) { IssueLog::Error(__METHOD__.' at line '.__LINE__.' : Operation parameter must be specified.'); throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, 'Operation parameter must be specified.'); } // - Submit - else - { - if ($sOperation === 'submit') - { + else { + if ($sOperation === 'submit') { $oRequestFiles = $oRequest->files; $oPictureFile = $oRequestFiles->get($sPictureAttCode); - if ($oPictureFile === null) - { + if ($oPictureFile === null) { IssueLog::Error(__METHOD__.' at line '.__LINE__.' : Parameter picture must be defined.'); throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, 'Parameter picture must be defined.'); } - try - { + try { // Retrieving image as an ORMDocument $oImage = utils::ReadPostedDocument($sPictureAttCode); // Retrieving current contact @@ -442,9 +424,7 @@ class UserProfileBrickController extends BrickController // Forcing allowed writing on the object if necessary. $oCurContact->AllowWrite(true); $oCurContact->DBUpdate(); - } - catch (FileUploadException $e) - { + } catch (FileUploadException $e) { $aFormData['error'] = $e->GetMessage(); } @@ -457,10 +437,10 @@ class UserProfileBrickController extends BrickController 'cache' => 86400, 's' => $oOrmDoc->GetSignature(), ]); - $aFormData['validation'] = array( + $aFormData['validation'] = [ 'valid' => true, - 'messages' => array(), - ); + 'messages' => [], + ]; } } @@ -469,30 +449,30 @@ class UserProfileBrickController extends BrickController return $aFormData; } - /** - * @param $sBrickId - * @return \Combodo\iTop\Portal\Brick\PortalBrick|UserProfileBrick - * @throws \Combodo\iTop\Portal\Brick\BrickNotFoundException - */ - public function GetBrick($sBrickId = null) - { - // If the brick id was not specified, we get the first one registered that is an instance of UserProfileBrick as default - if ($sBrickId === null) { - /** @var \Combodo\iTop\Portal\Brick\PortalBrick $oTmpBrick */ - foreach ($this->oBrickCollection->GetBricks() as $oTmpBrick) { - if ($oTmpBrick instanceof UserProfileBrick) { - $oBrick = $oTmpBrick; - } - } + /** + * @param $sBrickId + * @return \Combodo\iTop\Portal\Brick\PortalBrick|UserProfileBrick + * @throws \Combodo\iTop\Portal\Brick\BrickNotFoundException + */ + public function GetBrick($sBrickId = null) + { + // If the brick id was not specified, we get the first one registered that is an instance of UserProfileBrick as default + if ($sBrickId === null) { + /** @var \Combodo\iTop\Portal\Brick\PortalBrick $oTmpBrick */ + foreach ($this->oBrickCollection->GetBricks() as $oTmpBrick) { + if ($oTmpBrick instanceof UserProfileBrick) { + $oBrick = $oTmpBrick; + } + } - // We make sure a UserProfileBrick was found - if (!isset($oBrick) || $oBrick === null) { - $oBrick = new UserProfileBrick(); - //throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, 'UserProfileBrick : Brick could not be loaded as there was no UserProfileBrick loaded in the application.'); - } - } else { - $oBrick = $this->oBrickCollection->GetBrickById($sBrickId); - } - return $oBrick; - } + // We make sure a UserProfileBrick was found + if (!isset($oBrick) || $oBrick === null) { + $oBrick = new UserProfileBrick(); + //throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, 'UserProfileBrick : Brick could not be loaded as there was no UserProfileBrick loaded in the application.'); + } + } else { + $oBrick = $this->oBrickCollection->GetBrickById($sBrickId); + } + return $oBrick; + } } diff --git a/datamodels/2.x/itop-portal-base/portal/src/DependencyInjection/SilexCompatBootstrap/PortalXmlConfiguration/Basic.php b/datamodels/2.x/itop-portal-base/portal/src/DependencyInjection/SilexCompatBootstrap/PortalXmlConfiguration/Basic.php index 21414dd33..573c1a154 100644 --- a/datamodels/2.x/itop-portal-base/portal/src/DependencyInjection/SilexCompatBootstrap/PortalXmlConfiguration/Basic.php +++ b/datamodels/2.x/itop-portal-base/portal/src/DependencyInjection/SilexCompatBootstrap/PortalXmlConfiguration/Basic.php @@ -1,4 +1,5 @@ GetInitialPortalConf(); @@ -55,9 +55,7 @@ class Basic extends AbstractConfiguration $aPortalConf = $this->AppendLogoUri($aPortalConf); // - Rectifying portal favicon url $aPortalConf = $this->AppendFavIconUri($aPortalConf); - } - catch (Exception $oException) - { + } catch (Exception $oException) { throw new Exception('Error while parsing portal configuration file : '.$oException->getMessage()); } @@ -72,8 +70,8 @@ class Basic extends AbstractConfiguration */ private function GetInitialPortalConf() { - $aPortalConf = array( - 'properties' => array( + $aPortalConf = [ + 'properties' => [ 'id' => $_ENV['PORTAL_ID'], 'ui_version' => 'v3', 'ui_settings' => [ @@ -82,29 +80,29 @@ class Basic extends AbstractConfiguration 'name' => 'Page:DefaultTitle', 'logo' => Branding::GetPortalLogoAbsoluteUrl(), 'favicon' => Branding::GetPortalFavIconAbsoluteUrl(), - 'themes' => array( + 'themes' => [ 'bootstrap' => 'itop-portal-base/portal/public/css/bootstrap-theme-combodo.scss', 'portal' => 'itop-portal-base/portal/public/css/portal.scss', 'main' => 'itop-portal-base/portal/public/css/main.scss', - 'others' => array(), - ), - 'templates' => array( + 'others' => [], + ], + 'templates' => [ 'layout' => 'itop-portal-base/portal/templates/layout.html.twig', 'home' => 'itop-portal-base/portal/templates/home/layout.html.twig', - ), + ], 'urlmaker_class' => null, 'triggers_query' => null, - 'attachments' => array( + 'attachments' => [ 'allow_delete' => true, - ), - 'allowed_portals' => array( + ], + 'allowed_portals' => [ 'opening_mode' => null, - ), - ), - 'forms' => array(), - 'bricks' => array(), + ], + ], + 'forms' => [], + 'bricks' => [], 'bricks_total_width' => 0, - ); + ]; return $aPortalConf; } @@ -118,10 +116,8 @@ class Basic extends AbstractConfiguration private function ParseGlobalProperties(array $aPortalConf) { /** @var \MFElement $oPropertyNode */ - foreach ($this->GetModuleDesign()->GetNodes('/module_design/properties/*') as $oPropertyNode) - { - switch ($oPropertyNode->nodeName) - { + foreach ($this->GetModuleDesign()->GetNodes('/module_design/properties/*') as $oPropertyNode) { + switch ($oPropertyNode->nodeName) { case 'ui_version': case 'name': case 'urlmaker_class': @@ -131,7 +127,7 @@ class Basic extends AbstractConfiguration $aPortalConf['properties'][$oPropertyNode->nodeName] = $oPropertyNode->GetText( $aPortalConf['properties'][$oPropertyNode->nodeName] ); - break; + break; case 'ui_settings': foreach ($oPropertyNode->GetNodes('*') as $oSubNode) { $aPortalConf['properties'][$oPropertyNode->nodeName][$oSubNode->nodeName] = $oSubNode->GetText(); @@ -163,22 +159,20 @@ class Basic extends AbstractConfiguration private function ParseTemplateAndTheme(array $aPortalConf, DesignElement $oPropertyNode) { /** @var \MFElement $oSubNode */ - foreach ($oPropertyNode->GetNodes('template|theme') as $oSubNode) - { - if (!$oSubNode->hasAttribute('id') || $oSubNode->GetText(null) === null) - { + foreach ($oPropertyNode->GetNodes('template|theme') as $oSubNode) { + if (!$oSubNode->hasAttribute('id') || $oSubNode->GetText(null) === null) { throw new DOMFormatException( 'Tag '.$oSubNode->nodeName.' must have a "id" attribute as well as a value', - null, null, $oSubNode + null, + null, + $oSubNode ); } $sNodeId = $oSubNode->getAttribute('id'); - switch ($oSubNode->nodeName) - { + switch ($oSubNode->nodeName) { case 'theme': - switch ($sNodeId) - { + switch ($sNodeId) { case 'bootstrap': case 'portal': case 'custom': @@ -190,8 +184,7 @@ class Basic extends AbstractConfiguration } break; case 'template': - switch ($sNodeId) - { + switch ($sNodeId) { case 'layout': case 'home': $aPortalConf['properties']['templates'][$sNodeId] = $oSubNode->GetText(null); @@ -199,19 +192,21 @@ class Basic extends AbstractConfiguration default: $aMatches = []; // allowed format is: : - if(preg_match('#([\w\\\d_]+):(\w+)#', $sNodeId, $aMatches)){ - try{ + if (preg_match('#([\w\\\d_]+):(\w+)#', $sNodeId, $aMatches)) { + try { $oClass = new ReflectionClass($aMatches[1]); - if($oClass->implementsInterface(TemplatesProviderInterface::class)){ + if ($oClass->implementsInterface(TemplatesProviderInterface::class)) { $aPortalConf['properties']['templates'][$aMatches[1]][$aMatches[2]] = $oSubNode->GetText(null); break; } + } catch (Exception) { } - catch(Exception){} } throw new DOMFormatException( 'Template ID "'.$sNodeId.'" is not handled in module design templates property', - null, null, $oSubNode + null, + null, + $oSubNode ); } break; @@ -230,16 +225,13 @@ class Basic extends AbstractConfiguration private function ParseAttachments(array $aPortalConf, DesignElement $oPropertyNode) { /** @var \MFElement $oSubNode */ - foreach ($oPropertyNode->GetNodes('*') as $oSubNode) - { - switch ($oSubNode->nodeName) - { + foreach ($oPropertyNode->GetNodes('*') as $oSubNode) { + switch ($oSubNode->nodeName) { case 'allow_delete': $sValue = $oSubNode->GetText(); // If the text is null, we keep the default value // Else we set it - if ($sValue !== null) - { + if ($sValue !== null) { $aPortalConf['properties']['attachments'][$oSubNode->nodeName] = ($sValue === 'true') ? true : false; } break; @@ -258,16 +250,13 @@ class Basic extends AbstractConfiguration private function ParseAllowedPortalsOptions(array $aPortalConf, DesignElement $oPropertyNode) { /** @var \MFElement $oSubNode */ - foreach ($oPropertyNode->GetNodes('*') as $oSubNode) - { - switch ($oSubNode->nodeName) - { + foreach ($oPropertyNode->GetNodes('*') as $oSubNode) { + switch ($oSubNode->nodeName) { case 'opening_mode': $sValue = $oSubNode->GetText(); // If the text is null, we keep the default value // Else we set it - if ($sValue !== null) - { + if ($sValue !== null) { $aPortalConf['properties']['allowed_portals'][$oSubNode->nodeName] = ($sValue === 'self') ? 'self' : 'tab'; } break; @@ -313,4 +302,4 @@ class Basic extends AbstractConfiguration return $aPortalConf; } -} \ No newline at end of file +} diff --git a/datamodels/2.x/itop-portal-base/portal/src/Helper/ApplicationHelper.php b/datamodels/2.x/itop-portal-base/portal/src/Helper/ApplicationHelper.php index 747edae3f..c0987a13e 100644 --- a/datamodels/2.x/itop-portal-base/portal/src/Helper/ApplicationHelper.php +++ b/datamodels/2.x/itop-portal-base/portal/src/Helper/ApplicationHelper.php @@ -41,13 +41,13 @@ use utils; class ApplicationHelper { /** @var string FORM_ENUM_DISPLAY_MODE_COSY */ - const FORM_ENUM_DISPLAY_MODE_COSY = 'cosy'; + public const FORM_ENUM_DISPLAY_MODE_COSY = 'cosy'; /** @var string FORM_ENUM_DISPLAY_MODE_COMPACT */ - const FORM_ENUM_DISPLAY_MODE_COMPACT = 'compact'; + public const FORM_ENUM_DISPLAY_MODE_COMPACT = 'compact'; /** @var string FORM_DEFAULT_DISPLAY_MODE */ - const FORM_DEFAULT_DISPLAY_MODE = self::FORM_ENUM_DISPLAY_MODE_COSY; + public const FORM_DEFAULT_DISPLAY_MODE = self::FORM_ENUM_DISPLAY_MODE_COSY; /** @var bool FORM_DEFAULT_ALWAYS_SHOW_SUBMIT */ - const FORM_DEFAULT_ALWAYS_SHOW_SUBMIT = false; + public const FORM_DEFAULT_ALWAYS_SHOW_SUBMIT = false; /** * Loads the brick's security from the OQL queries to profiles arrays @@ -58,32 +58,25 @@ class ApplicationHelper */ public static function LoadBrickSecurity(AbstractBrick $oBrick) { - try - { + try { // Allowed profiles - if (utils::IsNotNullOrEmptyString($oBrick->GetAllowedProfilesOql())) - { + if (utils::IsNotNullOrEmptyString($oBrick->GetAllowedProfilesOql())) { $oSearch = DBObjectSearch::FromOQL_AllData($oBrick->GetAllowedProfilesOql()); $oSet = new DBObjectSet($oSearch); - while ($oProfile = $oSet->Fetch()) - { + while ($oProfile = $oSet->Fetch()) { $oBrick->AddAllowedProfile($oProfile->Get('name')); } } // Denied profiles - if (utils::IsNotNullOrEmptyString($oBrick->GetDeniedProfilesOql())) - { + if (utils::IsNotNullOrEmptyString($oBrick->GetDeniedProfilesOql())) { $oSearch = DBObjectSearch::FromOQL_AllData($oBrick->GetDeniedProfilesOql()); $oSet = new DBObjectSet($oSearch); - while ($oProfile = $oSet->Fetch()) - { + while ($oProfile = $oSet->Fetch()) { $oBrick->AddDeniedProfile($oProfile->Get('name')); } } - } - catch (Exception $e) - { + } catch (Exception $e) { throw new Exception('Error while loading security from '.$oBrick->GetId().' brick'); } } @@ -108,18 +101,14 @@ class ApplicationHelper $aForm = null; // We try to find the form for that class - if (isset($aForms[$sClass]) && isset($aForms[$sClass][$sMode])) - { + if (isset($aForms[$sClass]) && isset($aForms[$sClass][$sMode])) { $aForm = $aForms[$sClass][$sMode]; } // If not found, we try find one from the closest parent class - else - { + else { $bFound = false; - foreach (MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_EXCLUDELEAF, false) as $sParentClass) - { - if (isset($aForms[$sParentClass]) && isset($aForms[$sParentClass][$sMode])) - { + foreach (MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_EXCLUDELEAF, false) as $sParentClass) { + if (isset($aForms[$sParentClass]) && isset($aForms[$sParentClass][$sMode])) { $aForm = $aForms[$sParentClass][$sMode]; $bFound = true; break; @@ -127,8 +116,7 @@ class ApplicationHelper } // If we have still not found one, we return a default form - if (!$bFound) - { + if (!$bFound) { $aForm = static::GenerateDefaultFormForClass($sClass); } } @@ -153,32 +141,26 @@ class ApplicationHelper public static function GetLoadedListFromClass($aLists, $sClass, $sList = 'default') { $aFoundList = null; - $aAttCodes = array(); + $aAttCodes = []; // We try to find the list for that class - if (isset($aLists[$sClass]) && isset($aLists[$sClass][$sList])) - { + if (isset($aLists[$sClass]) && isset($aLists[$sClass][$sList])) { $aFoundList = $aLists[$sClass][$sList]; } // Else we try to found the default list for that class - elseif (isset($aLists[$sClass]) && isset($aLists[$sClass]['default'])) - { + elseif (isset($aLists[$sClass]) && isset($aLists[$sClass]['default'])) { $aFoundList = $aLists[$sClass]['default']; } // If not found, we try find one from the closest parent class - else - { - foreach (MetaModel::EnumParentClasses($sClass) as $sParentClass) - { + else { + foreach (MetaModel::EnumParentClasses($sClass) as $sParentClass) { // Trying to find the right list - if (isset($aLists[$sParentClass]) && isset($aLists[$sParentClass][$sList])) - { + if (isset($aLists[$sParentClass]) && isset($aLists[$sParentClass][$sList])) { $aFoundList = $aLists[$sParentClass][$sList]; break; } // Or the default list - elseif (isset($aLists[$sParentClass]) && isset($aLists[$sParentClass]['default'])) - { + elseif (isset($aLists[$sParentClass]) && isset($aLists[$sParentClass]['default'])) { $aFoundList = $aLists[$sParentClass]['default']; break; } @@ -186,15 +168,11 @@ class ApplicationHelper } // If found, we flatten the list to keep only the attribute codes (not the rank) - if ($aFoundList !== null) - { - foreach ($aFoundList as $aItem) - { + if ($aFoundList !== null) { + foreach ($aFoundList as $aItem) { $aAttCodes[] = $aItem['att_code']; } - } - else - { + } else { $aAttCodes = MetaModel::FlattenZList(MetaModel::GetZListItems($sClass, 'list')); } @@ -213,32 +191,31 @@ class ApplicationHelper */ protected static function GenerateDefaultFormForClass($sClass, $bAddLinksets = false) { - $aForm = array( + $aForm = [ 'id' => strtolower($sClass)."-default-".uniqid(), 'type' => 'custom_list', - 'properties' => array( + 'properties' => [ 'display_mode' => static::FORM_DEFAULT_DISPLAY_MODE, 'always_show_submit' => static::FORM_DEFAULT_ALWAYS_SHOW_SUBMIT, - 'navigation_rules' => array( + 'navigation_rules' => [ 'submit' => null, 'cancel' => null, - ), - ), - 'fields' => array(), - 'layout' => array( + ], + ], + 'fields' => [], + 'layout' => [ 'type' => 'xhtml', 'content' => '', - ), - ); + ], + ]; // Generate layout $sContent = ""; // - Retrieve zlist details $aDetailsList = MetaModel::GetZListItems($sClass, 'details'); - $aDetailsStruct = cmdbAbstractObject::ProcessZlist($aDetailsList, array(), 'UI:PropertiesTab', 'col1', ''); - if(!isset($aDetailsStruct['UI:PropertiesTab'])) - { + $aDetailsStruct = cmdbAbstractObject::ProcessZlist($aDetailsList, [], 'UI:PropertiesTab', 'col1', ''); + if (!isset($aDetailsStruct['UI:PropertiesTab'])) { // For the iTop administrator IssueLog::Error('Could not generate default form for "'.$sClass.'" class. Is the "details" zlist empty?'); // For the end-user @@ -248,14 +225,10 @@ class ApplicationHelper // Count cols (not linksets) $iColCount = 0; - foreach ($aPropertiesStruct as $sColId => $aColFieldsets) - { - if (substr($sColId, 0, 1) !== '_') - { - foreach ($aColFieldsets as $sFieldsetName => $aAttCodes) - { - if (substr($sFieldsetName, 0, 1) !== '_') - { + foreach ($aPropertiesStruct as $sColId => $aColFieldsets) { + if (substr($sColId, 0, 1) !== '_') { + foreach ($aColFieldsets as $sFieldsetName => $aAttCodes) { + if (substr($sFieldsetName, 0, 1) !== '_') { $iColCount++; break; } @@ -263,28 +236,24 @@ class ApplicationHelper } } // If no cols, return a default form with all fields one after another - if ($iColCount === 0) - { - return array( + if ($iColCount === 0) { + return [ 'id' => 'default', 'type' => 'zlist', 'fields' => 'details', 'layout' => null, - ); + ]; } // Warning, this might not be great when 12 modulo $iColCount is greater than 0. $sColCSSClass = 'col-sm-'.floor(12 / $iColCount); $sLinksetsHTML = ""; $sRowHTML = "
\n"; - foreach ($aPropertiesStruct as $sColId => $aColFieldsets) - { + foreach ($aPropertiesStruct as $sColId => $aColFieldsets) { $sColsHTML = "\t
\n"; - foreach ($aColFieldsets as $sFieldsetName => $aAttCodes) - { + foreach ($aColFieldsets as $sFieldsetName => $aAttCodes) { // Add fieldset, not linkset - if (substr($sFieldsetName, 0, 1) !== '_') - { + if (substr($sFieldsetName, 0, 1) !== '_') { $sFieldsetHTML = "\t\t
\n"; $sFieldsetHTML .= "\t\t\t".utils::EscapeHtml(Dict::S($sFieldsetName))."\n"; @@ -296,11 +265,8 @@ class ApplicationHelper // Add to col $sColsHTML .= $sFieldsetHTML; - } - elseif ($bAddLinksets) - { - foreach ($aAttCodes as $sAttCode) - { + } elseif ($bAddLinksets) { + foreach ($aAttCodes as $sAttCode) { $sLinksetsHTML .= "
\n"; } } @@ -329,8 +295,9 @@ class ApplicationHelper * @return array * @since 2.7.0 */ - public static function GetAttDefClassesToExcludeFromMarkupMetadataRawValue(){ - return array( + public static function GetAttDefClassesToExcludeFromMarkupMetadataRawValue() + { + return [ 'AttributeBlob', 'AttributeCustomFields', 'AttributeDashboard', @@ -338,7 +305,7 @@ class ApplicationHelper 'AttributeStopWatch', 'AttributeSubItem', 'AttributeTable', - 'AttributeText' - ); + 'AttributeText', + ]; } } diff --git a/datamodels/2.x/itop-portal-base/portal/src/Helper/ContextManipulatorHelper.php b/datamodels/2.x/itop-portal-base/portal/src/Helper/ContextManipulatorHelper.php index b04cdc52a..e53cb3d97 100644 --- a/datamodels/2.x/itop-portal-base/portal/src/Helper/ContextManipulatorHelper.php +++ b/datamodels/2.x/itop-portal-base/portal/src/Helper/ContextManipulatorHelper.php @@ -27,6 +27,7 @@ use SimpleCrypt; use Symfony\Component\Routing\RouterInterface; use TrueExpression; use UserRights; + use const UR_ACTION_READ; /** @@ -39,17 +40,17 @@ use const UR_ACTION_READ; class ContextManipulatorHelper { /** @var string ENUM_RULE_CALLBACK_BACK */ - const ENUM_RULE_CALLBACK_BACK = 'back'; + public const ENUM_RULE_CALLBACK_BACK = 'back'; /** @var string ENUM_RULE_CALLBACK_OPEN */ - const ENUM_RULE_CALLBACK_OPEN = 'open'; + public const ENUM_RULE_CALLBACK_OPEN = 'open'; /** @var string ENUM_RULE_CALLBACK_OPEN_VIEW */ - const ENUM_RULE_CALLBACK_OPEN_VIEW = 'view'; + public const ENUM_RULE_CALLBACK_OPEN_VIEW = 'view'; /** @var string ENUM_RULE_CALLBACK_OPEN_EDIT */ - const ENUM_RULE_CALLBACK_OPEN_EDIT = 'edit'; + public const ENUM_RULE_CALLBACK_OPEN_EDIT = 'edit'; /** @var string DEFAULT_RULE_CALLBACK_OPEN */ - const DEFAULT_RULE_CALLBACK_OPEN = self::ENUM_RULE_CALLBACK_OPEN_VIEW; + public const DEFAULT_RULE_CALLBACK_OPEN = self::ENUM_RULE_CALLBACK_OPEN_VIEW; - const PRIVATE_KEY = 'portal-priv-key'; + public const PRIVATE_KEY = 'portal-priv-key'; /** @var array $aRules */ protected $aRules; @@ -73,8 +74,9 @@ class ContextManipulatorHelper * * @throws \DOMFormatException */ - public function __construct(ModuleDesign $oModuleDesign, RouterInterface $oRouter, BrickCollection $oBrickCollection, ScopeValidatorHelper $oScopeValidator) { - $this->aRules = array(); + public function __construct(ModuleDesign $oModuleDesign, RouterInterface $oRouter, BrickCollection $oBrickCollection, ScopeValidatorHelper $oScopeValidator) + { + $this->aRules = []; $this->oRouter = $oRouter; $this->oBrickCollection = $oBrickCollection; @@ -92,38 +94,34 @@ class ContextManipulatorHelper */ public function Init(DOMNodeList $oNodes) { - $this->aRules = array(); + $this->aRules = []; // Iterating over the scope nodes /** @var \Combodo\iTop\DesignElement $oRuleNode */ - foreach ($oNodes as $oRuleNode) - { + foreach ($oNodes as $oRuleNode) { // Retrieving mandatory id attribute $sRuleId = $oRuleNode->getAttribute('id'); - if ($sRuleId === '') - { + if ($sRuleId === '') { throw new DOMFormatException('Rule tag must have an id attribute.', null, null, $oRuleNode); } // Setting if the rule needs a source object $bNeedsSource = false; // Note : preset and retrofit are no longer plurals as it should match as much as possible iTopObjectCopier specs. We use plurals only in the xml for the collection tags - $aRule = array( + $aRule = [ 'source_oql' => null, 'dest_class' => null, - 'preset' => array(), - 'retrofit' => array(), + 'preset' => [], + 'retrofit' => [], 'submit' => null, 'cancel' => null, - ); + ]; // Iterating over the rule's nodes /** @var \Combodo\iTop\DesignElement $oSubNode */ - foreach ($oRuleNode->GetNodes('*') as $oSubNode) - { + foreach ($oRuleNode->GetNodes('*') as $oSubNode) { $sSubNodeName = $oSubNode->nodeName; - switch ($sSubNodeName) - { + switch ($sSubNodeName) { case 'source_class': $aRule['source_oql'] = 'SELECT '.$oSubNode->GetText(); break; @@ -136,17 +134,14 @@ class ContextManipulatorHelper case 'presets': case 'retrofits': /** @var \Combodo\iTop\DesignElement $oActionNode */ - foreach ($oSubNode->GetNodes('*') as $oActionNode) - { + foreach ($oSubNode->GetNodes('*') as $oActionNode) { // Note : Caution, the index of $aRule is now $oActionNode->nodeName instead of $sSubNodeName, as we want to match iTopObjectCopier specs like told previously - if (in_array($oActionNode->nodeName, array('preset', 'retrofit'))) - { + if (in_array($oActionNode->nodeName, ['preset', 'retrofit'])) { $sActionText = $oActionNode->GetText(); $aRule[$oActionNode->nodeName][] = $sActionText; // Checking if the rule needs a source object - if (substr($sActionText, 0, 4) === 'copy') - { + if (substr($sActionText, 0, 4) === 'copy') { $bNeedsSource = true; } } @@ -157,25 +152,21 @@ class ContextManipulatorHelper case 'cancel': // Retrieving callback type and checking that it is allowed $sType = $oSubNode->getAttribute('xsi:type'); - if ($sType === '') - { + if ($sType === '') { throw new DOMFormatException($sSubNodeName.' must have an xsi:type attribute.', null, null, $oSubNode); } - if (($sType === static::ENUM_RULE_CALLBACK_OPEN) && ($sSubNodeName === 'cancel')) - { + if (($sType === static::ENUM_RULE_CALLBACK_OPEN) && ($sSubNodeName === 'cancel')) { throw new DOMFormatException('Cancel tag cannot be of type '.$sType.'.', null, null, $oSubNode); } - $aRule[$sSubNodeName] = array('type' => $sType); - switch ($sType) - { + $aRule[$sSubNodeName] = ['type' => $sType]; + switch ($sType) { case static::ENUM_RULE_CALLBACK_BACK: // Default value $sRefresh = false; // Retrieving value $oRefreshNode = $oSubNode->GetOptionalElement('refresh'); - if (($oRefreshNode !== null) && ($oRefreshNode->GetText() !== null)) - { + if (($oRefreshNode !== null) && ($oRefreshNode->GetText() !== null)) { $sRefresh = $oRefreshNode->GetText(); } @@ -187,8 +178,7 @@ class ContextManipulatorHelper $sMode = static::ENUM_RULE_CALLBACK_OPEN_VIEW; // Retrieving value $oModeNode = $oSubNode->GetOptionalElement('mode'); - if (($oModeNode !== null) && ($oModeNode->GetText() !== null)) - { + if (($oModeNode !== null) && ($oModeNode->GetText() !== null)) { $sMode = $oModeNode->GetText(); } @@ -200,8 +190,7 @@ class ContextManipulatorHelper } // If there is no source information we check if there is a preset that requires a copy in order to throw an exception - if (($aRule['source_oql'] === null) && ($bNeedsSource === true)) - { + if (($aRule['source_oql'] === null) && ($bNeedsSource === true)) { throw new DOMFormatException('Rule tag must have either a "source_oql" or a "source_class" child node.', null, null, $oRuleNode); } @@ -209,7 +198,6 @@ class ContextManipulatorHelper } } - /** * Returns a hash array of rules * @@ -230,8 +218,7 @@ class ContextManipulatorHelper */ public function GetRule($sId) { - if (!array_key_exists($sId, $this->aRules)) - { + if (!array_key_exists($sId, $this->aRules)) { throw new Exception('Context creator : Could not find "'.$sId.'" in the rules list'); } @@ -264,30 +251,26 @@ class ContextManipulatorHelper */ public function PrepareObject(array $aData, DBObject $oObject) { - if (isset($aData['rules']) && isset($aData['sources'])) - { + if (isset($aData['rules']) && isset($aData['sources'])) { $aRules = $aData['rules']; $aSources = $aData['sources']; - $aActionRulesErrors = array(); - foreach ($aRules as $sRuleId) - { - try - { + $aActionRulesErrors = []; + foreach ($aRules as $sRuleId) { + try { $this->PrepareAndExecActionRule($sRuleId, $aSources, $oObject); - } - catch (CorePortalInvalidActionRuleException $e) - { + } catch (CorePortalInvalidActionRuleException $e) { $aActionRulesErrors[$sRuleId] = $e->getMessage(); } } - if (!empty($aActionRulesErrors)) - { + if (!empty($aActionRulesErrors)) { $sDestinationObjectDesc = ''; $sDestinationObjectDesc .= get_class($oObject); $sDestinationObjectDesc .= '['.$oObject->GetKey().']'; - throw new CorePortalInvalidActionRuleException('Some action rules were not executed', + throw new CorePortalInvalidActionRuleException( + 'Some action rules were not executed', $aActionRulesErrors, - 'destination object: '.$sDestinationObjectDesc); + 'destination object: '.$sDestinationObjectDesc + ); } } } @@ -311,8 +294,7 @@ class ContextManipulatorHelper $aRule = $this->GetRule($sRuleId); // Retrieving source object if needed - if ($aRule['source_oql'] !== null) - { + if ($aRule['source_oql'] !== null) { // Preparing query to retrieve source object(s) /** @var \DBObjectSearch $oSearch */ $oSearch = DBSearch::FromOQL($aRule['source_oql']); @@ -324,45 +306,37 @@ class ContextManipulatorHelper $sSearchClass = $oSearch->GetClass(); $aSearchParams = $oSearch->GetInternalParams(); - if (array_key_exists($sSearchClass, $aSources)) - { + if (array_key_exists($sSearchClass, $aSources)) { $sourceId = $aSources[$sSearchClass]; - if (array_key_exists('id', $oSearch->GetQueryParams())) - { - if (is_array($sourceId)) - { + if (array_key_exists('id', $oSearch->GetQueryParams())) { + if (is_array($sourceId)) { throw new Exception('Context creator : ":id" parameter in rule "'.$sRuleId.'" cannot be an array (This is a limitation of DBSearch)'); } $aSearchParams['id'] = $sourceId; - } - else - { - if (!is_array($sourceId)) - { - $sourceId = array($sourceId); + } else { + if (!is_array($sourceId)) { + $sourceId = [$sourceId]; } $iLoopMax = count($sourceId); $oFullBinExpr = null; - for ($i = 0; $i < $iLoopMax; $i++) - { + for ($i = 0; $i < $iLoopMax; $i++) { // - Building full search expression - $oBinExpr = new BinaryExpression(new FieldExpression('id', $oSearch->GetClassAlias()), '=', - new ScalarExpression($sourceId[$i])); - if ($i === 0) - { + $oBinExpr = new BinaryExpression( + new FieldExpression('id', $oSearch->GetClassAlias()), + '=', + new ScalarExpression($sourceId[$i]) + ); + if ($i === 0) { $oFullBinExpr = $oBinExpr; - } - else - { + } else { $oFullBinExpr = new BinaryExpression($oFullBinExpr, 'OR', $oBinExpr); } // - Adding it to the query when complete - if ($i === ($iLoopMax - 1)) - { + if ($i === ($iLoopMax - 1)) { $oSearch->AddConditionExpression($oFullBinExpr); } } @@ -370,8 +344,7 @@ class ContextManipulatorHelper } $oSearchRootCondition = $oSearch->GetCriteria(); - if (($oSearchRootCondition === null) || ($oSearchRootCondition instanceof TrueExpression)) - { + if (($oSearchRootCondition === null) || ($oSearchRootCondition instanceof TrueExpression)) { // N°2555 : disallow searches without any condition $sErrMsg = "Portal query was stopped: action_rule '$sRuleId' searches for '$sSearchClass' without any condition is forbidden"; IssueLog::Error($sErrMsg); @@ -379,35 +352,31 @@ class ContextManipulatorHelper } // Checking for silos - $oScopeSearch = $this->oScopeValidator->GetScopeFilterForProfiles(UserRights::ListProfiles(), $sSearchClass, - UR_ACTION_READ); - if ($oScopeSearch->IsAllDataAllowed()) - { + $oScopeSearch = $this->oScopeValidator->GetScopeFilterForProfiles( + UserRights::ListProfiles(), + $sSearchClass, + UR_ACTION_READ + ); + if ($oScopeSearch->IsAllDataAllowed()) { $oSearch->AllowAllData(); } // Retrieving source object(s) and applying rules - $oSet = new DBObjectSet($oSearch, array(), $aSearchParams); - while ($oSourceObject = $oSet->Fetch()) // we need a loop for certain preset verbs like add_to_list, see N°2555 - { + $oSet = new DBObjectSet($oSearch, [], $aSearchParams); + while ($oSourceObject = $oSet->Fetch()) { // we need a loop for certain preset verbs like add_to_list, see N°2555 // Presets - if (isset($aRule['preset']) && !empty($aRule['preset'])) - { - $oDestinationObject->ExecActions($aRule['preset'], array('source' => $oSourceObject)); + if (isset($aRule['preset']) && !empty($aRule['preset'])) { + $oDestinationObject->ExecActions($aRule['preset'], ['source' => $oSourceObject]); } // Retrofits - if (isset($aRule['retrofit']) && !empty($aRule['retrofit'])) - { - $oSourceObject->ExecActions($aRule['retrofit'], array('source' => $oDestinationObject)); + if (isset($aRule['retrofit']) && !empty($aRule['retrofit'])) { + $oSourceObject->ExecActions($aRule['retrofit'], ['source' => $oDestinationObject]); } } - } - else - { + } else { // Presets - if (isset($aRule['preset']) && !empty($aRule['preset'])) - { - $oDestinationObject->ExecActions($aRule['preset'], array('source' => $oDestinationObject)); + if (isset($aRule['preset']) && !empty($aRule['preset'])) { + $oDestinationObject->ExecActions($aRule['preset'], ['source' => $oDestinationObject]); } } } @@ -420,20 +389,19 @@ class ContextManipulatorHelper * * @return array */ - public static function PrepareRulesForToken($aRules, $aObjects = array()) + public static function PrepareRulesForToken($aRules, $aObjects = []) { // Getting necessary information from objects - $aSources = array(); - foreach ($aObjects as $oObject) - { + $aSources = []; + foreach ($aObjects as $oObject) { $aSources[get_class($oObject)] = $oObject->GetKey(); } // Preparing data - $aTokenRules = array( + $aTokenRules = [ 'rules' => $aRules, 'sources' => $aSources, - ); + ]; return $aTokenRules; } @@ -464,7 +432,7 @@ class ContextManipulatorHelper * * @return string */ - public static function PrepareAndEncodeRulesToken($aRules, $aObjects = array()) + public static function PrepareAndEncodeRulesToken($aRules, $aObjects = []) { // Preparing rules before making a token $aTokenRules = static::PrepareRulesForToken($aRules, $aObjects); @@ -491,19 +459,20 @@ class ContextManipulatorHelper $sDecryptedToken = $oCrypt->Decrypt($sPrivateKey, self::base64url_decode($sToken)); $aTokenRules = json_decode($sDecryptedToken, true); - if (!is_array($aTokenRules)) - { + if (!is_array($aTokenRules)) { throw new Exception('DecodeRulesToken not a proper json structure.'); } return $aTokenRules; } - private static function base64url_encode($sData) { + private static function base64url_encode($sData) + { return rtrim(strtr(base64_encode($sData), '+/', '-_'), '='); } - private static function base64url_decode($sData) { + private static function base64url_decode($sData) + { return base64_decode(str_pad(strtr($sData, '-_', '+/'), strlen($sData) % 4, '=', STR_PAD_RIGHT)); } @@ -515,7 +484,7 @@ class ContextManipulatorHelper */ private static function GetPrivateKey() { - if(self::$sPrivateKey === null) { + if (self::$sPrivateKey === null) { self::$sPrivateKey = DBProperty::GetProperty(self::PRIVATE_KEY); if (is_null(self::$sPrivateKey)) { self::$sPrivateKey = bin2hex(random_bytes(32)); diff --git a/datamodels/2.x/itop-portal-base/portal/src/Helper/SessionMessageHelper.php b/datamodels/2.x/itop-portal-base/portal/src/Helper/SessionMessageHelper.php index a72eb28ad..fd63dbabd 100644 --- a/datamodels/2.x/itop-portal-base/portal/src/Helper/SessionMessageHelper.php +++ b/datamodels/2.x/itop-portal-base/portal/src/Helper/SessionMessageHelper.php @@ -1,4 +1,5 @@ scalar value * @param int $iRank */ - public function AddMessage($sId, $sContent, $sSeverity = self::DEFAULT_SEVERITY, $aMetadata = array(), $iRank = 1) + public function AddMessage($sId, $sContent, $sSeverity = self::DEFAULT_SEVERITY, $aMetadata = [], $iRank = 1) { $sKey = $this->GetMessagesKey(); - if(!Session::IsSet(['obj_messages', $sKey])) - { + if (!Session::IsSet(['obj_messages', $sKey])) { Session::Set(['obj_messages', $sKey], []); } @@ -115,7 +115,7 @@ class SessionMessageHelper implements IteratorAggregate */ private function GetMessagesKey() { - return 'GUI:' . $this->oContainer->getParameter('combodo.portal.instance.id'); + return 'GUI:'.$this->oContainer->getParameter('combodo.portal.instance.id'); } /** @@ -126,23 +126,18 @@ class SessionMessageHelper implements IteratorAggregate */ private function FetchMessages() { - if (!empty($this->aAllMessages)) - { + if (!empty($this->aAllMessages)) { return; } - $this->aAllMessages = array(); - if (is_array(Session::Get('obj_messages'))) - { - foreach (Session::Get('obj_messages') as $sMessageKey => $aMessageObjectData) - { - $aObjectMessages = array(); - $aRanks = array(); - foreach ($aMessageObjectData as $sMessageId => $aMessageData) - { + $this->aAllMessages = []; + if (is_array(Session::Get('obj_messages'))) { + foreach (Session::Get('obj_messages') as $sMessageKey => $aMessageObjectData) { + $aObjectMessages = []; + $aRanks = []; + foreach ($aMessageObjectData as $sMessageId => $aMessageData) { $sMsgClass = 'ipb-alert alert alert-dismissible alert-'; - switch ($aMessageData['severity']) - { + switch ($aMessageData['severity']) { case static::ENUM_SEVERITY_INFO: $sMsgClass .= 'info'; break; @@ -168,17 +163,16 @@ class SessionMessageHelper implements IteratorAggregate $sMsgMetadata .= 'data-'.str_replace('_', '-', $sMetadatumName).'="'.utils::HtmlEntities($sMetadatumValue).'" '; } } - $aObjectMessages[] = array('css_classes' => $sMsgClass, 'message' => $aMessageData['message'], 'metadata' => $sMsgMetadata); + $aObjectMessages[] = ['css_classes' => $sMsgClass, 'message' => $aMessageData['message'], 'metadata' => $sMsgMetadata]; $aRanks[] = $aMessageData['rank']; } Session::Unset(['obj_messages', $sMessageKey]); array_multisort($aRanks, $aObjectMessages); - foreach ($aObjectMessages as $aObjectMessage) - { + foreach ($aObjectMessages as $aObjectMessage) { $this->aAllMessages[] = $aObjectMessage; } } } } -} \ No newline at end of file +} diff --git a/datamodels/2.x/itop-portal-base/portal/src/Kernel.php b/datamodels/2.x/itop-portal-base/portal/src/Kernel.php index 89259afdd..c865e4e78 100644 --- a/datamodels/2.x/itop-portal-base/portal/src/Kernel.php +++ b/datamodels/2.x/itop-portal-base/portal/src/Kernel.php @@ -1,4 +1,5 @@ environment; + $logDir = $_ENV['PORTAL_ID'].'-'.$this->environment; - return utils::GetLogPath() . "/portals/$logDir"; - } + return utils::GetLogPath()."/portals/$logDir"; + } /** * @return \Generator|iterable|\Symfony\Component\HttpKernel\Bundle\BundleInterface[] */ public function registerBundles(): iterable { - $contents = require $this->getProjectDir().'/config/bundles.php'; - foreach ($contents as $class => $envs) { - if (isset($envs[$this->environment]) || isset($envs['all'])) { - yield new $class(); - } - } - } + $contents = require $this->getProjectDir().'/config/bundles.php'; + foreach ($contents as $class => $envs) { + if (isset($envs[$this->environment]) || isset($envs['all'])) { + yield new $class(); + } + } + } /** * @param \Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator $container diff --git a/datamodels/2.x/itop-portal-base/portal/src/Service/TemplatesProvider/TemplatesRegister.php b/datamodels/2.x/itop-portal-base/portal/src/Service/TemplatesProvider/TemplatesRegister.php index 5fb80b670..5e8960990 100644 --- a/datamodels/2.x/itop-portal-base/portal/src/Service/TemplatesProvider/TemplatesRegister.php +++ b/datamodels/2.x/itop-portal-base/portal/src/Service/TemplatesProvider/TemplatesRegister.php @@ -29,7 +29,6 @@ namespace Combodo\iTop\Portal\Service\TemplatesProvider; */ class TemplatesRegister { - /** @var array Templates definitions (possibly altered by portal configuration) */ private array $aTemplatesDefinitions = []; @@ -127,7 +126,7 @@ class TemplatesRegister */ public function GetProviderTemplatesIds(string $sProviderId): array { - return array_map(fn($oTemplateDefinition) => $oTemplateDefinition->GetId(), $this->aTemplatesDefinitions[$sProviderId] ?? ['tile', 'page']); + return array_map(fn ($oTemplateDefinition) => $oTemplateDefinition->GetId(), $this->aTemplatesDefinitions[$sProviderId] ?? ['tile', 'page']); } /** @@ -139,4 +138,4 @@ class TemplatesRegister { return $this->aTemplatesDefinitions; } -} \ No newline at end of file +} diff --git a/datamodels/2.x/itop-portal-base/portal/src/Twig/AppGlobal.php b/datamodels/2.x/itop-portal-base/portal/src/Twig/AppGlobal.php index a9a0483de..701c5364e 100644 --- a/datamodels/2.x/itop-portal-base/portal/src/Twig/AppGlobal.php +++ b/datamodels/2.x/itop-portal-base/portal/src/Twig/AppGlobal.php @@ -37,7 +37,6 @@ use Twig\Extension\GlobalsInterface; */ class AppGlobal extends AbstractExtension implements GlobalsInterface { - /** * Constructor. * diff --git a/datamodels/2.x/itop-portal-base/portal/src/Twig/AppIconUrlAccessor.php b/datamodels/2.x/itop-portal-base/portal/src/Twig/AppIconUrlAccessor.php index 6a699f43c..a02fb9bf7 100644 --- a/datamodels/2.x/itop-portal-base/portal/src/Twig/AppIconUrlAccessor.php +++ b/datamodels/2.x/itop-portal-base/portal/src/Twig/AppIconUrlAccessor.php @@ -8,14 +8,14 @@ use MetaModel; class AppIconUrlAccessor { private $oUrlGenerator; - + public function __construct(UrlGenerator $oUrlGenerator) { $this->oUrlGenerator = $oUrlGenerator; } /** - * + * * @param $bIgnoreOverrideCheck bool If true, use the URL set in the configuration file even if it's not a custom value * * @return string @@ -23,10 +23,10 @@ class AppIconUrlAccessor public function GetAppIconUrl($bIgnoreOverrideCheck = false): string { // Try if a custom URL was set in the configuration file - if($bIgnoreOverrideCheck === true || MetaModel::GetConfig()->IsCustomValue('app_icon_url')) { + if ($bIgnoreOverrideCheck === true || MetaModel::GetConfig()->IsCustomValue('app_icon_url')) { return $_ENV['COMBODO_CONF_APP_ICON_URL'] ; } // Otherwise use the home page return $this->oUrlGenerator->generate('p_home'); } -} \ No newline at end of file +} diff --git a/datamodels/2.x/itop-portal/dictionaries/it.dict.itop-portal.php b/datamodels/2.x/itop-portal/dictionaries/it.dict.itop-portal.php index b6304ef14..0fd8dd189 100644 --- a/datamodels/2.x/itop-portal/dictionaries/it.dict.itop-portal.php +++ b/datamodels/2.x/itop-portal/dictionaries/it.dict.itop-portal.php @@ -1,16 +1,17 @@ * */ -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'portal:itop-portal' => 'Portale Standard', 'Page:DefaultTitle' => '%1$s - Portale Utente', 'Brick:Portal:UserProfile:Title' => 'Il mio profilo', @@ -26,4 +27,4 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Brick:Portal:ListAllRequests:Tab' => 'On-going and closed~~', 'Brick:Portal:SearchInAllRequests:Title' => 'Cerca in tutte le richieste', 'Brick:Portal:SearchInAllRequests:Title+' => '

A prescindere dal loro stato.

', -)); +]); diff --git a/datamodels/2.x/itop-portal/module.itop-portal.php b/datamodels/2.x/itop-portal/module.itop-portal.php index 828711d53..97dd09351 100644 --- a/datamodels/2.x/itop-portal/module.itop-portal.php +++ b/datamodels/2.x/itop-portal/module.itop-portal.php @@ -1,4 +1,5 @@ 'Enhanced Customer Portal', 'category' => 'Portal', // Setup - 'dependencies' => array( - 'itop-portal-base/2.7.0' - ), + 'dependencies' => [ + 'itop-portal-base/2.7.0', + ], 'mandatory' => false, 'visible' => true, // Components - 'datamodel' => array( + 'datamodel' => [ 'main.itop-portal.php', - ), - 'webservice' => array( + ], + 'webservice' => [ //'webservices.itop-portal.php', - ), + ], - 'data.struct' => array( + 'data.struct' => [ //'data.struct.itop-portal.xml', - ), - 'data.sample' => array( + ], + 'data.sample' => [ //'data.sample.itop-portal.xml', - ), + ], // Documentation 'doc.manual_setup' => '', 'doc.more_information' => '', // Default settings - 'settings' => array( - ), - ) + 'settings' => [ + ], + ] ); diff --git a/datamodels/2.x/itop-problem-mgmt/dictionaries/it.dict.itop-problem-mgmt.php b/datamodels/2.x/itop-problem-mgmt/dictionaries/it.dict.itop-problem-mgmt.php index 7cbc37d6a..fa59b8673 100644 --- a/datamodels/2.x/itop-problem-mgmt/dictionaries/it.dict.itop-problem-mgmt.php +++ b/datamodels/2.x/itop-problem-mgmt/dictionaries/it.dict.itop-problem-mgmt.php @@ -1,15 +1,16 @@ 'Gestione dei problemi', 'Menu:ProblemManagement+' => 'Gestione dei problemi', 'Menu:Problem:Overview' => 'Panoramica', @@ -32,12 +33,12 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'UI:ProblemMgmtMenuOverview:Title' => 'Dashboard per la gestione dei problemi', 'UI:ProblemMgmtMenuOverview:Title+' => 'Dashboard per la gestione dei problemi', -)); +]); // // Class: Problem // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:Problem' => 'Problema', 'Class:Problem+' => '', 'Class:Problem/Attribute:status' => 'Stato', @@ -110,4 +111,4 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:Problem/Stimulus:ev_resolve+' => '', 'Class:Problem/Stimulus:ev_close' => 'Chiudere', 'Class:Problem/Stimulus:ev_close+' => '', -)); +]); diff --git a/datamodels/2.x/itop-problem-mgmt/module.itop-problem-mgmt.php b/datamodels/2.x/itop-problem-mgmt/module.itop-problem-mgmt.php index 2aa224425..0603efaff 100755 --- a/datamodels/2.x/itop-problem-mgmt/module.itop-problem-mgmt.php +++ b/datamodels/2.x/itop-problem-mgmt/module.itop-problem-mgmt.php @@ -1,10 +1,9 @@ 'Problem Management', @@ -12,23 +11,23 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( + 'dependencies' => [ 'itop-tickets/2.0.0', - ), + ], 'mandatory' => false, 'visible' => true, // Components // - 'datamodel' => array( - ), - 'data.struct' => array( + 'datamodel' => [ + ], + 'data.struct' => [ //'data.struct.itop-problem-mgmt.xml', - ), - 'data.sample' => array( + ], + 'data.sample' => [ //'data.sample.itop-problem-mgmt.xml', - ), - + ], + // Documentation // 'doc.manual_setup' => '', @@ -36,7 +35,7 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array( - ), - ) + 'settings' => [ + ], + ] ); diff --git a/datamodels/2.x/itop-profiles-itil/module.itop-profiles-itil.php b/datamodels/2.x/itop-profiles-itil/module.itop-profiles-itil.php index be5f2ac89..4b1b8c8fb 100755 --- a/datamodels/2.x/itop-profiles-itil/module.itop-profiles-itil.php +++ b/datamodels/2.x/itop-profiles-itil/module.itop-profiles-itil.php @@ -1,9 +1,10 @@ - SetupWebPage::AddModule( __FILE__, // Path to the current file, all other file names are relative to the directory containing this file 'itop-profiles-itil/3.3.0', - array( + [ // Identification // 'label' => 'Create standard ITIL profiles', @@ -28,25 +28,25 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( - ), + 'dependencies' => [ + ], 'mandatory' => true, 'visible' => false, // Components // - 'datamodel' => array( - ), - 'webservice' => array( + 'datamodel' => [ + ], + 'webservice' => [ //'webservices.itop-profiles-itil.php', - ), - 'data.struct' => array( + ], + 'data.struct' => [ //'data.struct.itop-profiles-itil.xml', - ), - 'data.sample' => array( + ], + 'data.sample' => [ //'data.sample.itop-profiles-itil.xml', - ), - + ], + // Documentation // 'doc.manual_setup' => '', @@ -54,8 +54,8 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array( + 'settings' => [ //'some_setting' => 'some value', - ), - ) + ], + ] ); diff --git a/datamodels/2.x/itop-request-mgmt-itil/dictionaries/it.dict.itop-request-mgmt-itil.php b/datamodels/2.x/itop-request-mgmt-itil/dictionaries/it.dict.itop-request-mgmt-itil.php index 2cb825455..e3ccd4d13 100644 --- a/datamodels/2.x/itop-request-mgmt-itil/dictionaries/it.dict.itop-request-mgmt-itil.php +++ b/datamodels/2.x/itop-request-mgmt-itil/dictionaries/it.dict.itop-request-mgmt-itil.php @@ -1,15 +1,16 @@ 'Service Request', 'Menu:RequestManagement+' => 'Service Request', 'Menu:RequestManagementProvider' => 'Service Request Fornitore', @@ -41,7 +42,7 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'UI-RequestManagementOverview-OpenRequestByCustomer' => 'Richieste aperte dal cliente', 'Class:UserRequest:KnownErrorList' => 'Errori conosciuti', 'Class:UserRequest:KnownErrorList+' => 'Errori conosciuti relativi al CI funzionale collegato al ticket corrente', -)); +]); // Dictionnay conventions // Class: @@ -57,7 +58,7 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( // Class: UserRequest // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:UserRequest' => 'Richiesta utente', 'Class:UserRequest+' => '~~', 'Class:UserRequest/Attribute:status' => 'Stato', @@ -255,11 +256,10 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:UserRequest/Error:CannotAssignParentRequestIdToSelf' => 'Non si può assegnare una richiesta padre a se stesso', 'Class:UserRequest/Method:ResolveChildTickets' => 'Risoluzione richieste figlie', 'Class:UserRequest/Method:ResolveChildTickets+' => 'Risoluzione a cascata delle richieste figlie (ev_autoresolve), e allineare le seguenti caratteristiche: servizio, team, agente e risoluzione', -)); +]); - -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Organization:Overview:UserRequests' => 'Richieste utente per questa organizzazione', 'Organization:Overview:MyUserRequests' => 'Le mie richieste per questa organizzazione', 'Organization:Overview:Tickets' => 'Ticket per questa organizzazione', -)); +]); diff --git a/datamodels/2.x/itop-request-mgmt-itil/dictionaries/pt_br.dict.itop-request-mgmt-itil.php b/datamodels/2.x/itop-request-mgmt-itil/dictionaries/pt_br.dict.itop-request-mgmt-itil.php index a7f126e9a..766165827 100644 --- a/datamodels/2.x/itop-request-mgmt-itil/dictionaries/pt_br.dict.itop-request-mgmt-itil.php +++ b/datamodels/2.x/itop-request-mgmt-itil/dictionaries/pt_br.dict.itop-request-mgmt-itil.php @@ -1,15 +1,16 @@ 'Gerenciamento de Solicitações', 'Menu:RequestManagement+' => '', 'Menu:RequestManagementProvider' => 'Solicitações a provedores(as)', @@ -41,7 +42,7 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'UI-RequestManagementOverview-OpenRequestByCustomer' => 'Solicitações abertas por cliente', 'Class:UserRequest:KnownErrorList' => 'Erros conhecidos', 'Class:UserRequest:KnownErrorList+' => 'Known Errors related to Functional CI linked to the current ticket~~', -)); +]); // Dictionnay conventions // Class: @@ -57,7 +58,7 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( // Class: UserRequest // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:UserRequest' => 'Solicitação de Usuário', 'Class:UserRequest+' => '', 'Class:UserRequest/Attribute:status' => 'Status', @@ -255,11 +256,10 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:UserRequest/Error:CannotAssignParentRequestIdToSelf' => 'Não é possível atribuir a solicitação pai a própria solicitação', 'Class:UserRequest/Method:ResolveChildTickets' => 'ResolveChildTickets (resolver solicitações filhas)', 'Class:UserRequest/Method:ResolveChildTickets+' => 'Conecte a solução a solicitações filhas (ev_autoresolve) e alinhe as seguintes características da requisição: serviço, equipe, agente, info de solução', -)); +]); - -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Organization:Overview:UserRequests' => 'Solicitações de usuários desta organização', 'Organization:Overview:MyUserRequests' => 'Minhas solicitações de usuário para esta organização', 'Organization:Overview:Tickets' => 'Solicitações desta organização', -)); +]); diff --git a/datamodels/2.x/itop-request-mgmt-itil/module.itop-request-mgmt-itil.php b/datamodels/2.x/itop-request-mgmt-itil/module.itop-request-mgmt-itil.php index 4218a965b..f955dfc55 100755 --- a/datamodels/2.x/itop-request-mgmt-itil/module.itop-request-mgmt-itil.php +++ b/datamodels/2.x/itop-request-mgmt-itil/module.itop-request-mgmt-itil.php @@ -1,10 +1,9 @@ 'User request Management ITIL', @@ -12,24 +11,24 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( + 'dependencies' => [ 'itop-tickets/2.4.0', - ), + ], 'mandatory' => false, 'visible' => true, // Components // - 'datamodel' => array( + 'datamodel' => [ 'main.itop-request-mgmt-itil.php', - ), - 'data.struct' => array( + ], + 'data.struct' => [ - ), - 'data.sample' => array( + ], + 'data.sample' => [ //'data.sample.itop-request-mgmt.xml', - ), - + ], + // Documentation // 'doc.manual_setup' => '', @@ -37,7 +36,7 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array( - ), - ) + 'settings' => [ + ], + ] ); diff --git a/datamodels/2.x/itop-request-mgmt/dictionaries/it.dict.itop-request-mgmt.php b/datamodels/2.x/itop-request-mgmt/dictionaries/it.dict.itop-request-mgmt.php index 738fcf53f..0c8a03981 100644 --- a/datamodels/2.x/itop-request-mgmt/dictionaries/it.dict.itop-request-mgmt.php +++ b/datamodels/2.x/itop-request-mgmt/dictionaries/it.dict.itop-request-mgmt.php @@ -1,15 +1,16 @@ 'Service Request', 'Menu:RequestManagement+' => 'Service Request', 'Menu:RequestManagementProvider' => 'Service Request Fornitore', @@ -45,7 +46,7 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Menu:UserRequest:MyWorkOrders+' => 'Tutti i work order assegnati a me', 'Class:Problem:KnownProblemList' => 'Problemi conosciuti', 'Tickets:Related:OpenIncidents' => 'Incidenti aperti', -)); +]); // Dictionnay conventions // Class: @@ -61,7 +62,7 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( // Class: UserRequest // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:UserRequest' => 'Richiesta utente', 'Class:UserRequest+' => '~~', 'Class:UserRequest/Attribute:status' => 'Stato', @@ -255,10 +256,9 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:UserRequest/Stimulus:ev_wait_for_approval' => 'In attesa di essere approvata', 'Class:UserRequest/Stimulus:ev_wait_for_approval+' => '~~', 'Class:UserRequest/Error:CannotAssignParentRequestIdToSelf' => 'Non si può assegnare una richiesta padre a se stesso', -)); +]); - -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Portal:TitleDetailsFor_Request' => 'Dettagi della richiesta', 'Portal:ButtonUpdate' => 'Aggiornameno', 'Portal:ButtonClose' => 'Chiuso', @@ -283,11 +283,10 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Portal:ChooseYourFavoriteLanguage' => 'Selezionate la vostra lingua preferita', 'Class:UserRequest/Method:ResolveChildTickets' => 'Risolve ticket figli', 'Class:UserRequest/Method:ResolveChildTickets+' => 'Inoltra la risolzuione ai ticket collegati ev_autosolve), e allinea le caratteriche della richiesta: Servizio, team , agente e informazioni della risoluzione', -)); +]); - -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Organization:Overview:UserRequests' => 'Richieste utente per questa organizzazione', 'Organization:Overview:MyUserRequests' => 'Le Mie richieste utente per questa organizzazione', 'Organization:Overview:Tickets' => 'Ticket per questa organizzazione', -)); +]); diff --git a/datamodels/2.x/itop-request-mgmt/module.itop-request-mgmt.php b/datamodels/2.x/itop-request-mgmt/module.itop-request-mgmt.php index 46ed98429..eb9243c94 100755 --- a/datamodels/2.x/itop-request-mgmt/module.itop-request-mgmt.php +++ b/datamodels/2.x/itop-request-mgmt/module.itop-request-mgmt.php @@ -1,10 +1,9 @@ 'Simple Ticket Management', @@ -12,24 +11,24 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( + 'dependencies' => [ 'itop-tickets/2.4.0', - ), + ], 'mandatory' => false, 'visible' => true, // Components // - 'datamodel' => array( + 'datamodel' => [ 'main.itop-request-mgmt.php', - ), - 'data.struct' => array( + ], + 'data.struct' => [ - ), - 'data.sample' => array( + ], + 'data.sample' => [ //'data.sample.itop-request-mgmt.xml', - ), - + ], + // Documentation // 'doc.manual_setup' => '', @@ -37,7 +36,7 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array( - ), - ) + 'settings' => [ + ], + ] ); diff --git a/datamodels/2.x/itop-service-mgmt-provider/dictionaries/pt_br.dict.itop-service-mgmt-provider.php b/datamodels/2.x/itop-service-mgmt-provider/dictionaries/pt_br.dict.itop-service-mgmt-provider.php index 50d506814..b9369cc4b 100644 --- a/datamodels/2.x/itop-service-mgmt-provider/dictionaries/pt_br.dict.itop-service-mgmt-provider.php +++ b/datamodels/2.x/itop-service-mgmt-provider/dictionaries/pt_br.dict.itop-service-mgmt-provider.php @@ -1,15 +1,16 @@ 'Gerenciamento de serviços', 'Menu:ServiceManagement+' => 'Gerenciamento de serviços', 'Menu:Service:Overview' => 'Visão geral', @@ -38,7 +39,7 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Contract:baseinfo' => 'General information~~', 'Contract:moreinfo' => 'Contractual information~~', 'Contract:cost' => 'Cost information~~', -)); +]); /* 'UI:ServiceManagementMenu' => 'Gestion des Services', @@ -53,30 +54,27 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( // Class: Organization // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Organization/Attribute:deliverymodel_id' => 'Modelo de entrega', 'Class:Organization/Attribute:deliverymodel_id+' => '', 'Class:Organization/Attribute:deliverymodel_name' => 'Nome do modelo de entrega', 'Class:Organization/Attribute:deliverymodel_name+' => '', -)); - - +]); // // Class: ContractType // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:ContractType' => 'Tipo de contrato', 'Class:ContractType+' => '', -)); - +]); // // Class: Contract // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Contract' => 'Contrato', 'Class:Contract+' => '', 'Class:Contract/Attribute:name' => 'Nome', @@ -125,13 +123,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Contract/Attribute:status/Value:production+' => '', 'Class:Contract/Attribute:finalclass' => 'Tipo de contrato', 'Class:Contract/Attribute:finalclass+' => '', -)); +]); // // Class: CustomerContract // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:CustomerContract' => 'Contrato de cliente', 'Class:CustomerContract+' => '', 'Class:CustomerContract/Attribute:services_list' => 'Serviços', @@ -140,13 +138,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:CustomerContract/Attribute:functionalcis_list+' => 'Todos os Itens de Configuração (IC) que são utilizados para a prestação deste Contrato de cliente', 'Class:CustomerContract/Attribute:providercontracts_list' => 'Contratos de provedores', 'Class:CustomerContract/Attribute:providercontracts_list+' => 'Todos os Contratos de provedores para suportar este Contrato de cliente', -)); +]); // // Class: ProviderContract // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:ProviderContract' => 'Contrato de provedor', 'Class:ProviderContract+' => '', 'Class:ProviderContract/Attribute:functionalcis_list' => 'ICs', @@ -155,13 +153,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:ProviderContract/Attribute:sla+' => 'Acordo de Nível de Serviço (ANS)', 'Class:ProviderContract/Attribute:coverage' => 'Horário de serviço', 'Class:ProviderContract/Attribute:coverage+' => 'Horário de cobertura do serviço', -)); +]); // // Class: lnkContactToContract // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkContactToContract' => 'Relação entre Contato / Contrato', 'Class:lnkContactToContract+' => '', 'Class:lnkContactToContract/Name' => '%1$s / %2$s~~', @@ -173,13 +171,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkContactToContract/Attribute:contact_id+' => '', 'Class:lnkContactToContract/Attribute:contact_name' => 'Nome do contato', 'Class:lnkContactToContract/Attribute:contact_name+' => '', -)); +]); // // Class: lnkContractToDocument // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkContractToDocument' => 'Relação entre Contrato / Documento', 'Class:lnkContractToDocument+' => '', 'Class:lnkContractToDocument/Name' => '%1$s / %2$s~~', @@ -191,13 +189,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkContractToDocument/Attribute:document_id+' => '', 'Class:lnkContractToDocument/Attribute:document_name' => 'Nome do documento', 'Class:lnkContractToDocument/Attribute:document_name+' => '', -)); +]); // // Class: lnkFunctionalCIToProviderContract // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkFunctionalCIToProviderContract' => 'Relação entre IC / Contrato de provedor', 'Class:lnkFunctionalCIToProviderContract+' => '', 'Class:lnkFunctionalCIToProviderContract/Name' => '%1$s / %2$s~~', @@ -209,13 +207,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkFunctionalCIToProviderContract/Attribute:functionalci_id+' => '', 'Class:lnkFunctionalCIToProviderContract/Attribute:functionalci_name' => 'Nome do IC', 'Class:lnkFunctionalCIToProviderContract/Attribute:functionalci_name+' => '', -)); +]); // // Class: ServiceFamily // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:ServiceFamily' => 'Família de serviços', 'Class:ServiceFamily+' => '', 'Class:ServiceFamily/Attribute:name' => 'Nome', @@ -224,13 +222,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:ServiceFamily/Attribute:icon+' => '', 'Class:ServiceFamily/Attribute:services_list' => 'Serviços', 'Class:ServiceFamily/Attribute:services_list+' => 'Todos os Serviços associados à esta Família de serviços', -)); +]); // // Class: Service // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Service' => 'Serviço', 'Class:Service+' => '', 'Class:Service/ComplementaryName' => '%1$s - %2$s~~', @@ -264,13 +262,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Service/Attribute:customercontracts_list+' => 'Todos os Contratos de clientes que contrataram este Serviço', 'Class:Service/Attribute:servicesubcategories_list' => 'Subcategorias de serviço', 'Class:Service/Attribute:servicesubcategories_list+' => 'Todas as Subcategorias de serviço associadas à este Serviço', -)); +]); // // Class: lnkDocumentToService // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkDocumentToService' => 'Relação entre Documento / Serviço', 'Class:lnkDocumentToService+' => '', 'Class:lnkDocumentToService/Name' => '%1$s / %2$s~~', @@ -282,13 +280,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkDocumentToService/Attribute:document_id+' => '', 'Class:lnkDocumentToService/Attribute:document_name' => 'Nome do documento', 'Class:lnkDocumentToService/Attribute:document_name+' => '', -)); +]); // // Class: lnkContactToService // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkContactToService' => 'Relação entre Contato / Serviço', 'Class:lnkContactToService+' => '', 'Class:lnkContactToService/Name' => '%1$s / %2$s~~', @@ -300,13 +298,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkContactToService/Attribute:contact_id+' => '', 'Class:lnkContactToService/Attribute:contact_name' => 'Nome do contato', 'Class:lnkContactToService/Attribute:contact_name+' => '', -)); +]); // // Class: ServiceSubcategory // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:ServiceSubcategory' => 'Subcategorias de serviço', 'Class:ServiceSubcategory+' => '', 'Class:ServiceSubcategory/ComplementaryName' => '%1$s - %2$s~~', @@ -334,13 +332,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:ServiceSubcategory/Attribute:request_type/Value:service_request+' => '', 'Class:ServiceSubcategory/Attribute:service_provider' => 'Nome do provedor', 'Class:ServiceSubcategory/Attribute:service_org_id' => 'Provedor', -)); +]); // // Class: SLA // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:SLA' => 'SLA', 'Class:SLA+' => '', 'Class:SLA/Attribute:name' => 'Nome', @@ -356,13 +354,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:SLA/Attribute:customercontracts_list' => 'Contratos de clientes', 'Class:SLA/Attribute:customercontracts_list+' => 'Todos os Contratos de clientes utilizando este Acordo de Nível de Serviço (SLA)', 'Class:SLA/Error:UniqueLnkCustomerContractToService' => 'Não foi possível salvar o vínculo entre o Contrato de cliente %1$s e o Serviço %2$s : SLA já existe', -)); +]); // // Class: SLT // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:SLT' => 'SLT', 'Class:SLT+' => '', 'Class:SLT/Attribute:name' => 'Nome', @@ -397,13 +395,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:SLT/Attribute:unit/Value:hours+' => '', 'Class:SLT/Attribute:unit/Value:minutes' => 'Minutos', 'Class:SLT/Attribute:unit/Value:minutes+' => '', -)); +]); // // Class: lnkSLAToSLT // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkSLAToSLT' => 'Relação entre SLA / SLT', 'Class:lnkSLAToSLT+' => '', 'Class:lnkSLAToSLT/Name' => '%1$s / %2$s~~', @@ -425,13 +423,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkSLAToSLT/Attribute:slt_value+' => '', 'Class:lnkSLAToSLT/Attribute:slt_value_unit' => 'Unidade de valor do SLT', 'Class:lnkSLAToSLT/Attribute:slt_value_unit+' => '', -)); +]); // // Class: lnkCustomerContractToService // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkCustomerContractToService' => 'Relação entre Contrato de cliente / Serviço', 'Class:lnkCustomerContractToService+' => '', 'Class:lnkCustomerContractToService/Name' => '%1$s / %2$s~~', @@ -447,13 +445,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkCustomerContractToService/Attribute:sla_id+' => '', 'Class:lnkCustomerContractToService/Attribute:sla_name' => 'Nome do SLA', 'Class:lnkCustomerContractToService/Attribute:sla_name+' => '', -)); +]); // // Class: lnkCustomerContractToProviderContract // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkCustomerContractToProviderContract' => 'Relação entre Contrato de cliente / Contrato de provedor', 'Class:lnkCustomerContractToProviderContract+' => '', 'Class:lnkCustomerContractToProviderContract/Name' => '%1$s / %2$s~~', @@ -465,13 +463,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkCustomerContractToProviderContract/Attribute:providercontract_id+' => '', 'Class:lnkCustomerContractToProviderContract/Attribute:providercontract_name' => 'Nome do contrato de provedor', 'Class:lnkCustomerContractToProviderContract/Attribute:providercontract_name+' => '', -)); +]); // // Class: lnkCustomerContractToFunctionalCI // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkCustomerContractToFunctionalCI' => 'Relação entre Contrato de cliente / IC', 'Class:lnkCustomerContractToFunctionalCI+' => '', 'Class:lnkCustomerContractToFunctionalCI/Name' => '%1$s / %2$s~~', @@ -483,13 +481,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkCustomerContractToFunctionalCI/Attribute:functionalci_id+' => '', 'Class:lnkCustomerContractToFunctionalCI/Attribute:functionalci_name' => 'Nome do CI', 'Class:lnkCustomerContractToFunctionalCI/Attribute:functionalci_name+' => '', -)); +]); // // Class: DeliveryModel // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:DeliveryModel' => 'Modelo de entrega', 'Class:DeliveryModel+' => '', 'Class:DeliveryModel/Attribute:name' => 'Nome', @@ -504,13 +502,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:DeliveryModel/Attribute:contacts_list+' => 'Todos os Contatos (Equipes e Pessoas) associados à este Modelo de entrega', 'Class:DeliveryModel/Attribute:customers_list' => 'Clientes', 'Class:DeliveryModel/Attribute:customers_list+' => 'Todos os clientes atendidos por este Modelo de entrega', -)); +]); // // Class: lnkDeliveryModelToContact // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkDeliveryModelToContact' => 'Relação entre Modelo de entrega / Contato', 'Class:lnkDeliveryModelToContact+' => '', 'Class:lnkDeliveryModelToContact/Name' => '%1$s / %2$s~~', @@ -526,35 +524,35 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkDeliveryModelToContact/Attribute:role_id+' => '', 'Class:lnkDeliveryModelToContact/Attribute:role_name' => 'Nome da função', 'Class:lnkDeliveryModelToContact/Attribute:role_name+' => '', -)); +]); // // Class: lnkContactToContract // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkContactToContract/Attribute:customer_id' => 'Customer id~~', 'Class:lnkContactToContract/Attribute:customer_id+' => '~~', 'Class:lnkContactToContract/Attribute:provider_id' => 'Provider id~~', 'Class:lnkContactToContract/Attribute:provider_id+' => '~~', -)); +]); // // Class: lnkContractToDocument // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkContractToDocument/Attribute:customer_id' => 'Customer id~~', 'Class:lnkContractToDocument/Attribute:customer_id+' => '~~', 'Class:lnkContractToDocument/Attribute:provider_id' => 'Provider id~~', 'Class:lnkContractToDocument/Attribute:provider_id+' => '~~', -)); +]); // // Class: lnkCustomerContractToService // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkCustomerContractToService/Attribute:provider_id' => 'Provider id~~', 'Class:lnkCustomerContractToService/Attribute:provider_id+' => '~~', -)); +]); diff --git a/datamodels/2.x/itop-service-mgmt-provider/module.itop-service-mgmt-provider.php b/datamodels/2.x/itop-service-mgmt-provider/module.itop-service-mgmt-provider.php index d8d36d0b0..3356b8448 100755 --- a/datamodels/2.x/itop-service-mgmt-provider/module.itop-service-mgmt-provider.php +++ b/datamodels/2.x/itop-service-mgmt-provider/module.itop-service-mgmt-provider.php @@ -1,10 +1,9 @@ 'Service Management for Service Providers', @@ -12,21 +11,21 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( - 'itop-tickets/2.0.0', - ), + 'dependencies' => [ + 'itop-tickets/2.0.0', + ], 'mandatory' => false, 'visible' => true, 'installer' => 'ServiceMgmtProviderInstaller', // Components // - 'datamodel' => array( - ), - 'data.struct' => array( + 'datamodel' => [ + ], + 'data.struct' => [ //'data.struct.itop-service-mgmt.xml', - ), - 'data.sample' => array( + ], + 'data.sample' => [ 'data.sample.organizations.xml', 'data.sample.contracts.xml', 'data.sample.servicefamilies.xml', @@ -39,8 +38,8 @@ SetupWebPage::AddModule( 'data.sample.contractservice.xml', // 'data.sample.deliverymodel.xml', 'data.sample.deliverymodelcontact.xml', - ), - + ], + // Documentation // 'doc.manual_setup' => '', @@ -48,13 +47,12 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array( - ), - ) + 'settings' => [ + ], + ] ); -if (!class_exists('ServiceMgmtProviderInstaller')) -{ +if (!class_exists('ServiceMgmtProviderInstaller')) { // Module installation handler // class ServiceMgmtProviderInstaller extends ModuleInstallerAPI @@ -73,15 +71,14 @@ if (!class_exists('ServiceMgmtProviderInstaller')) */ public static function BeforeDatabaseCreation(Config $oConfiguration, $sPreviousVersion, $sCurrentVersion) { - if (strlen($sPreviousVersion) > 0) - { + if (strlen($sPreviousVersion) > 0) { // If you want to migrate data from one format to another, do it here self::RenameClassInDB('ServiceFamilly', 'ServiceFamily'); self::RenameEnumValueInDB('SLT', 'request_type', 'servicerequest', 'service_request'); } } - + /** * Handler called after the creation/update of the database schema * @param $oConfiguration Config The new configuration of the application diff --git a/datamodels/2.x/itop-service-mgmt/dictionaries/pt_br.dict.itop-service-mgmt.php b/datamodels/2.x/itop-service-mgmt/dictionaries/pt_br.dict.itop-service-mgmt.php index c489eb670..7ed0936f5 100644 --- a/datamodels/2.x/itop-service-mgmt/dictionaries/pt_br.dict.itop-service-mgmt.php +++ b/datamodels/2.x/itop-service-mgmt/dictionaries/pt_br.dict.itop-service-mgmt.php @@ -1,15 +1,16 @@ 'Gerenciamento de serviços', 'Menu:ServiceManagement+' => '', 'Menu:Service:Overview' => 'Visão geral', @@ -40,34 +41,33 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Contract:baseinfo' => 'General information~~', 'Contract:moreinfo' => 'Contractual information~~', 'Contract:cost' => 'Cost information~~', -)); +]); // // Class: Organization // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Organization/Attribute:deliverymodel_id' => 'Modelo de entrega', 'Class:Organization/Attribute:deliverymodel_id+' => 'This is required for Tickets handling. The delivery model specifies the teams to which tickets can be assigned.~~', 'Class:Organization/Attribute:deliverymodel_name' => 'Nome do modelo de entrega', -)); - +]); // // Class: ContractType // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:ContractType' => 'Tipo de contrato', 'Class:ContractType+' => '', -)); +]); // // Class: Contract // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Contract' => 'Contrato', 'Class:Contract+' => '', 'Class:Contract/Attribute:name' => 'Nome', @@ -116,23 +116,23 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Contract/Attribute:status/Value:production+' => '', 'Class:Contract/Attribute:finalclass' => 'Tipo', 'Class:Contract/Attribute:finalclass+' => '', -)); +]); // // Class: CustomerContract // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:CustomerContract' => 'Contrato de Cliente', 'Class:CustomerContract+' => '', 'Class:CustomerContract/Attribute:services_list' => 'Serviços', 'Class:CustomerContract/Attribute:services_list+' => 'Todos os serviços contratados para este contrato de cliente', -)); +]); // // Class: ProviderContract // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:ProviderContract' => 'Contrato de provedor', 'Class:ProviderContract+' => '', 'Class:ProviderContract/Attribute:functionalcis_list' => 'ICs', @@ -147,13 +147,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:ProviderContract/Attribute:contracttype_name+' => '', 'Class:ProviderContract/Attribute:services_list' => 'Services~~', 'Class:ProviderContract/Attribute:services_list+' => 'All the services purchased with this contract~~', -)); +]); // // Class: lnkContactToContract // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkContactToContract' => 'Relação entre Contato / Contrato', 'Class:lnkContactToContract+' => '', 'Class:lnkContactToContract/Name' => '%1$s / %2$s~~', @@ -165,13 +165,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkContactToContract/Attribute:contact_id+' => '', 'Class:lnkContactToContract/Attribute:contact_name' => 'Nome do contato', 'Class:lnkContactToContract/Attribute:contact_name+' => '', -)); +]); // // Class: lnkContractToDocument // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkContractToDocument' => 'Relação entre Contrato / Documento', 'Class:lnkContractToDocument+' => '', 'Class:lnkContractToDocument/Name' => '%1$s / %2$s~~', @@ -183,13 +183,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkContractToDocument/Attribute:document_id+' => '', 'Class:lnkContractToDocument/Attribute:document_name' => 'Nome do documento', 'Class:lnkContractToDocument/Attribute:document_name+' => '', -)); +]); // // Class: ServiceFamily // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:ServiceFamily' => 'Família de serviços', 'Class:ServiceFamily+' => '', 'Class:ServiceFamily/Attribute:name' => 'Nome', @@ -198,13 +198,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:ServiceFamily/Attribute:icon+' => '', 'Class:ServiceFamily/Attribute:services_list' => 'Serviços', 'Class:ServiceFamily/Attribute:services_list+' => 'Todos os serviços associados à esta família de serviços', -)); +]); // // Class: Service // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Service' => 'Serviço', 'Class:Service+' => '', 'Class:Service/ComplementaryName' => '%1$s - %2$s~~', @@ -242,13 +242,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Service/Attribute:functionalcis_list+' => 'Todos os itens de configuração (ICs) que são utilizados para a prestação deste serviço', 'Class:Service/Attribute:servicesubcategories_list' => 'Subcategorias de serviço', 'Class:Service/Attribute:servicesubcategories_list+' => 'Todas as subcategorias de serviço para esse serviço', -)); +]); // // Class: lnkDocumentToService // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkDocumentToService' => 'Relação entre Documento / Serviço', 'Class:lnkDocumentToService+' => '', 'Class:lnkDocumentToService/Name' => '%1$s / %2$s~~', @@ -260,13 +260,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkDocumentToService/Attribute:document_id+' => '', 'Class:lnkDocumentToService/Attribute:document_name' => 'Nome documento', 'Class:lnkDocumentToService/Attribute:document_name+' => '', -)); +]); // // Class: lnkContactToService // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkContactToService' => 'Relação entre Contato / Serviço', 'Class:lnkContactToService+' => '', 'Class:lnkContactToService/Name' => '%1$s / %2$s~~', @@ -278,13 +278,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkContactToService/Attribute:contact_id+' => '', 'Class:lnkContactToService/Attribute:contact_name' => 'Nome do contato', 'Class:lnkContactToService/Attribute:contact_name+' => '', -)); +]); // // Class: ServiceSubcategory // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:ServiceSubcategory' => 'Subcategoria de serviço', 'Class:ServiceSubcategory+' => '', 'Class:ServiceSubcategory/ComplementaryName' => '%1$s - %2$s~~', @@ -310,13 +310,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:ServiceSubcategory/Attribute:status/Value:obsolete+' => '', 'Class:ServiceSubcategory/Attribute:status/Value:production' => 'Em produção', 'Class:ServiceSubcategory/Attribute:status/Value:production+' => '', -)); +]); // // Class: SLA // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:SLA' => 'SLA', 'Class:SLA+' => '', 'Class:SLA/Attribute:name' => 'Nome', @@ -332,13 +332,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:SLA/Attribute:customercontracts_list' => 'Contratos de clientes', 'Class:SLA/Attribute:customercontracts_list+' => 'Todos os Contratos de clientes utilizando esse Acordo de Nível de Serviço (SLA)', 'Class:SLA/Error:UniqueLnkCustomerContractToService' => 'Não foi possível salvar o vínculo entre o Contrato de cliente "%1$s" e o Serviço "%2$s": SLA já existe', -)); +]); // // Class: SLT // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:SLT' => 'SLT', 'Class:SLT+' => '', 'Class:SLT/Attribute:name' => 'Nome', @@ -375,13 +375,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:SLT/Attribute:unit/Value:minutes+' => '', 'Class:SLT/Attribute:slas_list' => 'SLAs~~', 'Class:SLT/Attribute:slas_list+' => 'All the service level agreements using this SLT~~', -)); +]); // // Class: lnkSLAToSLT // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkSLAToSLT' => 'Relação entre SLA / SLT', 'Class:lnkSLAToSLT+' => '', 'Class:lnkSLAToSLT/Name' => '%1$s / %2$s~~', @@ -403,13 +403,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkSLAToSLT/Attribute:slt_value+' => '', 'Class:lnkSLAToSLT/Attribute:slt_value_unit' => 'Unidade de valor do SLT', 'Class:lnkSLAToSLT/Attribute:slt_value_unit+' => '', -)); +]); // // Class: lnkCustomerContractToService // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkCustomerContractToService' => 'Relação entre Contrato de cliente / Serviço', 'Class:lnkCustomerContractToService+' => '', 'Class:lnkCustomerContractToService/Name' => '%1$s / %2$s~~', @@ -425,13 +425,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkCustomerContractToService/Attribute:sla_id+' => '', 'Class:lnkCustomerContractToService/Attribute:sla_name' => 'Nome do SLA', 'Class:lnkCustomerContractToService/Attribute:sla_name+' => '', -)); +]); // // Class: lnkProviderContractToService // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkProviderContractToService' => 'Relação entre Contrato de provedor / Serviço', 'Class:lnkProviderContractToService+' => '', 'Class:lnkProviderContractToService/Name' => '%1$s / %2$s~~', @@ -443,13 +443,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkProviderContractToService/Attribute:providercontract_id+' => '', 'Class:lnkProviderContractToService/Attribute:providercontract_name' => 'Nome do contrato de provedor', 'Class:lnkProviderContractToService/Attribute:providercontract_name+' => '', -)); +]); // // Class: DeliveryModel // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:DeliveryModel' => 'Modelo de entrega', 'Class:DeliveryModel+' => '', 'Class:DeliveryModel/Attribute:name' => 'Nome', @@ -464,13 +464,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:DeliveryModel/Attribute:contacts_list+' => 'Todos os Contatos (Equipes e Pessoas) associados à este Modelo de entrega', 'Class:DeliveryModel/Attribute:customers_list' => 'Clientes', 'Class:DeliveryModel/Attribute:customers_list+' => 'Todos os clientes atendidos por este Modelo de entrega', -)); +]); // // Class: lnkDeliveryModelToContact // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkDeliveryModelToContact' => 'Relação entre Modelo de entrega / Contato', 'Class:lnkDeliveryModelToContact+' => '', 'Class:lnkDeliveryModelToContact/Name' => '%1$s / %2$s~~', @@ -486,44 +486,44 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkDeliveryModelToContact/Attribute:role_id+' => '', 'Class:lnkDeliveryModelToContact/Attribute:role_name' => 'Nome da função', 'Class:lnkDeliveryModelToContact/Attribute:role_name+' => '', -)); +]); // // Class: lnkContactToContract // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkContactToContract/Attribute:customer_id' => 'Customer id~~', 'Class:lnkContactToContract/Attribute:customer_id+' => '~~', 'Class:lnkContactToContract/Attribute:provider_id' => 'Provider id~~', 'Class:lnkContactToContract/Attribute:provider_id+' => '~~', -)); +]); // // Class: lnkContractToDocument // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkContractToDocument/Attribute:customer_id' => 'Customer id~~', 'Class:lnkContractToDocument/Attribute:customer_id+' => '~~', 'Class:lnkContractToDocument/Attribute:provider_id' => 'Provider id~~', 'Class:lnkContractToDocument/Attribute:provider_id+' => '~~', -)); +]); // // Class: lnkCustomerContractToService // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkCustomerContractToService/Attribute:provider_id' => 'Provider id~~', 'Class:lnkCustomerContractToService/Attribute:provider_id+' => '~~', -)); +]); // // Class: lnkProviderContractToService // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkProviderContractToService/Attribute:provider_id' => 'Provider id~~', 'Class:lnkProviderContractToService/Attribute:provider_id+' => '~~', -)); +]); diff --git a/datamodels/2.x/itop-service-mgmt/module.itop-service-mgmt.php b/datamodels/2.x/itop-service-mgmt/module.itop-service-mgmt.php index 994524ceb..c4253b91e 100755 --- a/datamodels/2.x/itop-service-mgmt/module.itop-service-mgmt.php +++ b/datamodels/2.x/itop-service-mgmt/module.itop-service-mgmt.php @@ -1,10 +1,9 @@ 'Service Management', @@ -12,21 +11,21 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( + 'dependencies' => [ 'itop-tickets/2.0.0', - ), + ], 'mandatory' => false, 'visible' => true, 'installer' => 'ServiceMgmtInstaller', // Components // - 'datamodel' => array( - ), - 'data.struct' => array( + 'datamodel' => [ + ], + 'data.struct' => [ //'data.struct.itop-service-mgmt.xml', - ), - 'data.sample' => array( + ], + 'data.sample' => [ 'data.sample.organizations.xml', 'data.sample.contracts.xml', 'data.sample.servicefamilies.xml', @@ -39,8 +38,8 @@ SetupWebPage::AddModule( 'data.sample.contractservice.xml', // 'data.sample.deliverymodel.xml', 'data.sample.deliverymodelcontact.xml', - ), - + ], + // Documentation // 'doc.manual_setup' => '', @@ -48,13 +47,12 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array( - ), - ) + 'settings' => [ + ], + ] ); -if (!class_exists('ServiceMgmtInstaller')) -{ +if (!class_exists('ServiceMgmtInstaller')) { // Module installation handler // class ServiceMgmtInstaller extends ModuleInstallerAPI @@ -73,12 +71,11 @@ if (!class_exists('ServiceMgmtInstaller')) */ public static function BeforeDatabaseCreation(Config $oConfiguration, $sPreviousVersion, $sCurrentVersion) { - if (strlen($sPreviousVersion) > 0) - { + if (strlen($sPreviousVersion) > 0) { self::RenameEnumValueInDB('SLT', 'request_type', 'servicerequest', 'service_request'); } } - + /** * Handler called after the creation/update of the database schema * @param $oConfiguration Config The new configuration of the application diff --git a/datamodels/2.x/itop-sla-computation/main.itop-sla-computation.php b/datamodels/2.x/itop-sla-computation/main.itop-sla-computation.php index 0be798850..c1b8771c2 100644 --- a/datamodels/2.x/itop-sla-computation/main.itop-sla-computation.php +++ b/datamodels/2.x/itop-sla-computation/main.itop-sla-computation.php @@ -1,9 +1,10 @@ - /** * Module itop-sla-computation: deprecated * @@ -27,8 +27,8 @@ /** * @deprecated 3.3.0 This is actually a breaking change. The class has been left to ease migration to 3.3.0 (see N°2683) */ -class SLAComputation { - +class SLAComputation +{ /** * @deprecated 3.3.0 This is actually a breaking change. The function has been left to ease migration to 3.3.0 (see N°2683) */ diff --git a/datamodels/2.x/itop-sla-computation/module.itop-sla-computation.php b/datamodels/2.x/itop-sla-computation/module.itop-sla-computation.php index bdae76e40..8218badb8 100644 --- a/datamodels/2.x/itop-sla-computation/module.itop-sla-computation.php +++ b/datamodels/2.x/itop-sla-computation/module.itop-sla-computation.php @@ -1,9 +1,10 @@ 'SLA Computation', @@ -27,36 +28,36 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( - - ), + 'dependencies' => [ + + ], 'mandatory' => true, 'visible' => false, // Components // - 'datamodel' => array( + 'datamodel' => [ 'main.itop-sla-computation.php', - ), - 'webservice' => array( - - ), - 'data.struct' => array( + ], + 'webservice' => [ + + ], + 'data.struct' => [ // add your 'structure' definition XML files here, - ), - 'data.sample' => array( + ], + 'data.sample' => [ // add your sample data XML files here, - ), - + ], + // Documentation // 'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any - 'doc.more_information' => '', // hyperlink to more information, if any + 'doc.more_information' => '', // hyperlink to more information, if any // Default settings // - 'settings' => array( + 'settings' => [ // Module specific settings go here, if any - ), - ) + ], + ] ); diff --git a/datamodels/2.x/itop-storage-mgmt/module.itop-storage-mgmt.php b/datamodels/2.x/itop-storage-mgmt/module.itop-storage-mgmt.php index 5149e0a0c..f21ae12c5 100644 --- a/datamodels/2.x/itop-storage-mgmt/module.itop-storage-mgmt.php +++ b/datamodels/2.x/itop-storage-mgmt/module.itop-storage-mgmt.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/AGPL-3.0 */ - - SetupWebPage::AddModule( + +SetupWebPage::AddModule( __FILE__, // Path to the current file, all other file names are relative to the directory containing this file - 'itop-storage-mgmt/3.3.0', - array( + 'itop-storage-mgmt/3.3.0', + [ // Identification // 'label' => 'Advanced Storage Management', @@ -34,42 +35,41 @@ // Setup // - 'dependencies' => array( - 'itop-config-mgmt/2.4.0' - ), + 'dependencies' => [ + 'itop-config-mgmt/2.4.0', + ], 'mandatory' => false, 'visible' => true, 'installer' => 'StorageMgmtInstaller', // Components // - 'datamodel' => array( - ), - 'webservice' => array( - - ), - 'data.struct' => array( + 'datamodel' => [ + ], + 'webservice' => [ + + ], + 'data.struct' => [ // add your 'structure' definition XML files here, - ), - 'data.sample' => array( + ], + 'data.sample' => [ // add your sample data XML files here, - ), - + ], + // Documentation // 'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any - 'doc.more_information' => '', // hyperlink to more information, if any + 'doc.more_information' => '', // hyperlink to more information, if any // Default settings // - 'settings' => array( + 'settings' => [ // Module specific settings go here, if any - ), - ) + ], + ] ); -if (!class_exists('StorageMgmtInstaller')) -{ +if (!class_exists('StorageMgmtInstaller')) { // Module installation handler // class StorageMgmtInstaller extends ModuleInstallerAPI @@ -88,13 +88,12 @@ if (!class_exists('StorageMgmtInstaller')) */ public static function BeforeDatabaseCreation(Config $oConfiguration, $sPreviousVersion, $sCurrentVersion) { - if (strlen($sPreviousVersion) > 0) - { + if (strlen($sPreviousVersion) > 0) { // If you want to migrate data from one format to another, do it here self::RenameClassInDB('NasFileSystem', 'NASFileSystem'); } } - + /** * Handler called after the creation/update of the database schema * @param $oConfiguration Config The new configuration of the application diff --git a/datamodels/2.x/itop-structure/dictionaries/pt_br.dict.itop-structure.php b/datamodels/2.x/itop-structure/dictionaries/pt_br.dict.itop-structure.php index f97f4f713..1c76d8a57 100644 --- a/datamodels/2.x/itop-structure/dictionaries/pt_br.dict.itop-structure.php +++ b/datamodels/2.x/itop-structure/dictionaries/pt_br.dict.itop-structure.php @@ -1,16 +1,17 @@ * */ -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Organization' => 'Organização', 'Class:Organization+' => '', 'Class:Organization/Attribute:name' => 'Nome', @@ -37,13 +38,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Organization:Overview:FunctionalCIs' => 'Itens de Configuração (ICs) associados à esta Organização', 'Organization:Overview:FunctionalCIs:subtitle' => 'por tipo', 'Organization:Overview:Users' => 'Usuários do '.ITOP_APPLICATION_SHORT.' associados à esta Organização', -)); +]); // // Class: Location // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Location' => 'Localização', 'Class:Location+' => 'Qualquer tipo de localização: Região, País, Cidade, Lugar, Edifício, Andar, Sala, Rack, etc.', 'Class:Location/Attribute:name' => 'Nome', @@ -70,13 +71,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Location/Attribute:physicaldevice_list+' => 'Todos os Dispositivos associados à esta Localização', 'Class:Location/Attribute:person_list' => 'Contatos', 'Class:Location/Attribute:person_list+' => 'Todos os Contatos associados à esta Localização', -)); +]); // // Class: Contact // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Contact' => 'Contato', 'Class:Contact+' => '', 'Class:Contact/ComplementaryName' => '%1$s - %2$s~~', @@ -108,13 +109,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Contact/Attribute:cis_list+' => 'Todos os Itens de Configuração (ICs) associados à este Contato', 'Class:Contact/Attribute:finalclass' => 'Tipo de contato', 'Class:Contact/Attribute:finalclass+' => '', -)); +]); // // Class: Person // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Person' => 'Pessoa', 'Class:Person+' => '', 'Class:Person/ComplementaryName' => '%1$s - %2$s~~', @@ -149,13 +150,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Person/UniquenessRule:name+' => 'O nome do colaborador deve ser único dentro de sua organização', 'Class:Person/UniquenessRule:name' => 'Já existe uma pessoa na organização \'$this->org_name$\' com o mesmo nome', 'Class:Person/Error:ChangingOrgDenied' => 'Impossible to move this person under organization \'%1$s\' as it would break his access to the User Portal, his associated user not being allowed on this organization~~', -)); +]); // // Class: Team // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Team' => 'Equipe', 'Class:Team+' => '', 'Class:Team/ComplementaryName' => '%1$s - %2$s~~', @@ -163,13 +164,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Team/Attribute:persons_list+' => 'Todas as pessoas que pertencem a essa equipe', 'Class:Team/Attribute:tickets_list' => 'Solicitações', 'Class:Team/Attribute:tickets_list+' => 'Todas as solicitações atribuídas a essa equipe', -)); +]); // // Class: Document // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Document' => 'Documento', 'Class:Document+' => '', 'Class:Document/ComplementaryName' => '%1$s - %2$s - %3$s~~', @@ -199,77 +200,77 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Document/Attribute:cis_list+' => 'Todos os Itens de Configuração (IC) associados à este Documento', 'Class:Document/Attribute:finalclass' => 'Tipo de documento', 'Class:Document/Attribute:finalclass+' => '', -)); +]); // // Class: DocumentFile // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:DocumentFile' => 'Arquivo', 'Class:DocumentFile+' => '', 'Class:DocumentFile/Attribute:file' => 'Arquivo', 'Class:DocumentFile/Attribute:file+' => '', -)); +]); // // Class: DocumentNote // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:DocumentNote' => 'Texto', 'Class:DocumentNote+' => '', 'Class:DocumentNote/Attribute:text' => 'Texto', 'Class:DocumentNote/Attribute:text+' => '', -)); +]); // // Class: DocumentWeb // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:DocumentWeb' => 'Web', 'Class:DocumentWeb+' => '', 'Class:DocumentWeb/Attribute:url' => 'URL', 'Class:DocumentWeb/Attribute:url+' => '', -)); +]); // // Class: Typology // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Typology' => 'Tipologia', 'Class:Typology+' => '', 'Class:Typology/Attribute:name' => 'Nome', 'Class:Typology/Attribute:name+' => '', 'Class:Typology/Attribute:finalclass' => 'Tipo', 'Class:Typology/Attribute:finalclass+' => '', -)); +]); // // Class: DocumentType // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:DocumentType' => 'Tipo de documento', 'Class:DocumentType+' => '', -)); +]); // // Class: ContactType // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:ContactType' => 'Tipo de contato', 'Class:ContactType+' => '', -)); +]); // // Class: lnkPersonToTeam // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkPersonToTeam' => 'Relação entre Pessoa / Equipe', 'Class:lnkPersonToTeam+' => '', 'Class:lnkPersonToTeam/Name' => '%1$s / %2$s~~', @@ -286,13 +287,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkPersonToTeam/Attribute:role_id+' => 'Define a função da Pessoa na Equipe (Líder de Equipe, Gerente...).', 'Class:lnkPersonToTeam/Attribute:role_name' => 'Nome da função', 'Class:lnkPersonToTeam/Attribute:role_name+' => '', -)); +]); // // Application Menu // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Menu:DataAdministration' => 'Administração de dados', 'Menu:DataAdministration+' => '', 'Menu:Catalogs' => 'Catálogos', @@ -330,20 +331,20 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Menu:Typology+' => 'Lista de tipologias', 'UI_WelcomeMenu_AllConfigItems' => 'Índice', 'Menu:ConfigManagement:Typology' => 'Configuração de tipologias', -)); +]); // Add translation for Fieldsets -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Person:info' => 'Informações gerais', 'User:info' => 'Informações gerais', 'User:profiles' => 'Profiles (minimum one)~~', 'Person:personal_info' => 'Informações pessoais', 'Person:notifiy' => 'Notificações', -)); +]); // Themes -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'theme:fullmoon' => 'Full moon', 'theme:test-red' => 'Test instance (Red)', -)); +]); diff --git a/datamodels/2.x/itop-structure/module.itop-structure.php b/datamodels/2.x/itop-structure/module.itop-structure.php index 4b63eced0..918b6b144 100644 --- a/datamodels/2.x/itop-structure/module.itop-structure.php +++ b/datamodels/2.x/itop-structure/module.itop-structure.php @@ -1,10 +1,9 @@ 'Core iTop Structure', @@ -12,28 +11,28 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( - ), + 'dependencies' => [ + ], 'mandatory' => true, 'visible' => false, 'installer' => 'StructureInstaller', // Components // - 'datamodel' => array( + 'datamodel' => [ 'main.itop-structure.php', - ), - 'data.struct' => array( - ), - 'data.sample' => array( + ], + 'data.struct' => [ + ], + 'data.sample' => [ 'data.sample.organizations.xml', 'data.sample.locations.xml', 'data.sample.persons.xml', 'data.sample.teams.xml', 'data.sample.contactteam.xml', 'data.sample.contacttype.xml', - ), - + ], + // Documentation // 'doc.manual_setup' => '', @@ -41,13 +40,12 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array( - ), - ) + 'settings' => [ + ], + ] ); -if (!class_exists('StructureInstaller')) -{ +if (!class_exists('StructureInstaller')) { // Module installation handler // class StructureInstaller extends ModuleInstallerAPI @@ -66,14 +64,13 @@ if (!class_exists('StructureInstaller')) */ public static function BeforeDatabaseCreation(Config $oConfiguration, $sPreviousVersion, $sCurrentVersion) { - if (strlen($sPreviousVersion) > 0) - { + if (strlen($sPreviousVersion) > 0) { // Search for existing ActionEmail where the language attribute was defined on its child if (version_compare($sPreviousVersion, '3.2.0', '<')) { SetupLog::Info("| Migrate ActionEmail language attribute values to its parent."); $sTableToRead = MetaModel::DBGetTable('ActionEmail'); $sTableToSet = MetaModel::DBGetTable('ActionNotification'); - self::MoveColumnInDB($sTableToRead, 'language', $sTableToSet, 'language', true); + self::MoveColumnInDB($sTableToRead, 'language', $sTableToSet, 'language', true); SetupLog::Info("| ActionEmail migration done."); } // If you want to migrate data from one format to another, do it here @@ -93,7 +90,7 @@ if (!class_exists('StructureInstaller')) self::RenameClassInDB('IPinterface', 'IPInterface'); } } - + /** * Handler called after the creation/update of the database schema * @param $oConfiguration Config The new configuration of the application @@ -225,7 +222,7 @@ if (!class_exists('StructureInstaller')) 'subject' => 'Vous avez été mentionné dans "$this->friendlyname$"', 'body' => '

Bonjour $mentioned->first_name$,

Vous avez été mentionné par $current_contact->friendlyname$ dans $this->hyperlink()$

', - ] + ], ]; // Create action in app. default language and link it to the triggers @@ -275,7 +272,7 @@ if (!class_exists('StructureInstaller')) 'FR FR' => [ 'name' => 'Notification aux personnes mentionnées dans les journaux', 'message' => 'Vous avez été mentionné par $current_contact->friendlyname$', - ] + ], ]; // Start by creating the default action no matter what (even if there is no relevant trigger, it will be there for future use) @@ -293,7 +290,7 @@ if (!class_exists('StructureInstaller')) SetupLog::Info("|- Created newsroom action \"{$oAction->Get('name')}\"."); // Retrieve all triggers and find those with a mentioned_filter on the Person class - $oTriggersSearch = DBObjectSearch::FromOQL("SELECT " . TriggerOnObjectMention::class); + $oTriggersSearch = DBObjectSearch::FromOQL("SELECT ".TriggerOnObjectMention::class); $oTriggersSearch->AllowAllData(); $oTriggersSet = new DBObjectSet($oTriggersSearch); @@ -330,7 +327,7 @@ if (!class_exists('StructureInstaller')) if (version_compare($sPreviousVersion, '3.2.0', '<')) { SetupLog::Info("Forcing subscription policy to ForceAtLeastOneChannel for all existing TriggerOnObjectMention..."); - $oTriggersSearch = DBObjectSearch::FromOQL("SELECT " . TriggerOnObjectMention::class); + $oTriggersSearch = DBObjectSearch::FromOQL("SELECT ".TriggerOnObjectMention::class); $oTriggersSearch->AllowAllData(); $oTriggersSet = new DBObjectSet($oTriggersSearch); @@ -358,7 +355,7 @@ if (!class_exists('StructureInstaller')) 'FR FR' => [ 'name' => 'Notification sur MAJ du journal public via le portail', 'message' => 'Nouveau message de $current_contact->friendlyname$', - ] + ], ]; // - Create action in app. default language and link it to the triggers @@ -385,7 +382,7 @@ if (!class_exists('StructureInstaller')) 'FR FR' => [ 'name' => 'Notification à l\'agent à l\'assignation du ticket', 'message' => 'Le ticket vous a été assigné', - ] + ], ]; // Create action in app. default language and link it to the triggers @@ -418,7 +415,6 @@ if (!class_exists('StructureInstaller')) $aColumnsObjectd = array_keys($oAttDefObjectId->GetSQLColumns()); $sColumnObjectId = $aColumnsObjectd[0]; // We know that a string has only one column - $oSearch = DBObjectSearch::FromOQL('SELECT TriggerOnObject'); $oSet = new DBObjectSet($oSearch); $aTriggerIdToTargetClass = []; diff --git a/datamodels/2.x/itop-themes-compat/dictionaries/pt_br.dict.itop-themes-compat.php b/datamodels/2.x/itop-themes-compat/dictionaries/pt_br.dict.itop-themes-compat.php index 7300308aa..5015c0ec7 100644 --- a/datamodels/2.x/itop-themes-compat/dictionaries/pt_br.dict.itop-themes-compat.php +++ b/datamodels/2.x/itop-themes-compat/dictionaries/pt_br.dict.itop-themes-compat.php @@ -1,14 +1,15 @@ 'Light Grey (depreciado)', -)); +]); diff --git a/datamodels/2.x/itop-themes-compat/module.itop-themes-compat.php b/datamodels/2.x/itop-themes-compat/module.itop-themes-compat.php index 2f0a11129..796174be9 100644 --- a/datamodels/2.x/itop-themes-compat/module.itop-themes-compat.php +++ b/datamodels/2.x/itop-themes-compat/module.itop-themes-compat.php @@ -1,4 +1,5 @@ 'Light grey and Test red themes compatibility', @@ -14,35 +15,35 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( + 'dependencies' => [ 'itop-structure/3.1.0', - ), + ], 'mandatory' => false, 'visible' => true, // Components // - 'datamodel' => array( - ), - 'webservice' => array( - - ), - 'data.struct' => array( + 'datamodel' => [ + ], + 'webservice' => [ + + ], + 'data.struct' => [ // add your 'structure' definition XML files here, - ), - 'data.sample' => array( + ], + 'data.sample' => [ // add your sample data XML files here, - ), - + ], + // Documentation // 'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any - 'doc.more_information' => '', // hyperlink to more information, if any + 'doc.more_information' => '', // hyperlink to more information, if any // Default settings // - 'settings' => array( + 'settings' => [ // Module specific settings go here, if any - ), - ) + ], + ] ); diff --git a/datamodels/2.x/itop-tickets/dictionaries/pt_br.dict.itop-tickets.php b/datamodels/2.x/itop-tickets/dictionaries/pt_br.dict.itop-tickets.php index 620bd3d25..e1577d56f 100755 --- a/datamodels/2.x/itop-tickets/dictionaries/pt_br.dict.itop-tickets.php +++ b/datamodels/2.x/itop-tickets/dictionaries/pt_br.dict.itop-tickets.php @@ -1,15 +1,16 @@ 'Solicitação', 'Class:Ticket+' => '', 'Class:Ticket/Attribute:ref' => 'Ref.', @@ -61,14 +62,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Ticket/Attribute:operational_status/Value:closed' => 'Fechado', 'Class:Ticket/Attribute:operational_status/Value:closed+' => '', 'Ticket:ImpactAnalysis' => 'Análise de impacto', -)); - +]); // // Class: lnkContactToTicket // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkContactToTicket' => 'Relação entre Contato / Solicitação', 'Class:lnkContactToTicket+' => '', 'Class:lnkContactToTicket/Name' => '%1$s / %2$s~~', @@ -88,13 +88,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkContactToTicket/Attribute:role_code/Value:manual' => 'Adicionado manualmente', 'Class:lnkContactToTicket/Attribute:role_code/Value:computed' => 'Computado', 'Class:lnkContactToTicket/Attribute:role_code/Value:do_not_notify' => 'Não notificar', -)); +]); // // Class: WorkOrder // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:WorkOrder' => 'Ordem de serviço', 'Class:WorkOrder+' => '', 'Class:WorkOrder/Attribute:name' => 'Nome', @@ -127,11 +127,10 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:WorkOrder/Attribute:log+' => '', 'Class:WorkOrder/Stimulus:ev_close' => 'Fechar', 'Class:WorkOrder/Stimulus:ev_close+' => '', -)); - +]); // Fieldset translation -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Ticket:baseinfo' => 'Informações gerais', 'Ticket:date' => 'Datas', 'Ticket:contact' => 'Contatos', @@ -221,14 +220,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:ResponseTicketTTO/Interface:iMetricComputer+' => 'Objetivo baseado em um SLT do tipo TTO', 'Class:ResponseTicketTTR/Interface:iMetricComputer' => 'Time To Resolve', 'Class:ResponseTicketTTR/Interface:iMetricComputer+' => 'Objetivo baseado em um SLT do tipo TTR', -)); - +]); // // Class: Ticket // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Ticket/Attribute:team_email' => 'Team email~~', 'Class:Ticket/Attribute:team_email+' => '~~', -)); +]); diff --git a/datamodels/2.x/itop-tickets/main.itop-tickets.php b/datamodels/2.x/itop-tickets/main.itop-tickets.php index 219da38e8..3b81b4e03 100755 --- a/datamodels/2.x/itop-tickets/main.itop-tickets.php +++ b/datamodels/2.x/itop-tickets/main.itop-tickets.php @@ -1,4 +1,5 @@ Get('request_type'); } @@ -49,43 +45,40 @@ class ResponseTicketSLT $aArgs['request_type'] = $sRequestType; //echo "

Managing:".$sMetric."-".$this->Get('request_type')."-".$this->Get('importance')."

\n"; - $oSLTSet = new DBObjectSet(DBObjectSearch::FromOQL(RESPONSE_TICKET_SLT_QUERY), - array(), - $aArgs - ); + $oSLTSet = new DBObjectSet( + DBObjectSearch::FromOQL(RESPONSE_TICKET_SLT_QUERY), + [], + $aArgs + ); $iMinDuration = PHP_INT_MAX; $sSLTName = ''; - while($oSLT = $oSLTSet->Fetch()) - { + while ($oSLT = $oSLTSet->Fetch()) { $iDuration = (int)$oSLT->Get('value'); $sUnit = $oSLT->Get('unit'); - switch($sUnit) - { + switch ($sUnit) { case 'days': - $iDuration = $iDuration * 24; // 24 hours in 1 days - // Fall though + $iDuration = $iDuration * 24; // 24 hours in 1 days + // Fall though + // no break case 'hours': - $iDuration = $iDuration * 60; // 60 minutes in 1 hour - // Fall though + $iDuration = $iDuration * 60; // 60 minutes in 1 hour + // Fall though + // no break case 'minutes': - $iDuration = $iDuration * 60; + $iDuration = $iDuration * 60; } - if ($iDuration < $iMinDuration) - { + if ($iDuration < $iMinDuration) { $iMinDuration = $iDuration; $sSLTName = $oSLT->GetName(); } } - if ($iMinDuration == PHP_INT_MAX) - { + if ($iMinDuration == PHP_INT_MAX) { $iDeadline = null; - } - else - { + } else { // Store $sSLTName to keep track of which SLT has been used $iDeadline = $iMinDuration; } @@ -129,7 +122,6 @@ class ResponseTicketTTR extends ResponseTicketSLT implements iMetricComputer } } - class _Ticket extends cmdbAbstractObject { /** @@ -154,24 +146,19 @@ class _Ticket extends cmdbAbstractObject require_once(APPROOT.'core/displayablegraph.class.inc.php'); /** @var ormLinkSet $oContactsSet */ $oContactsSet = $this->Get('contacts_list'); - $aCIsToImpactCode = array(); - $aSources = array(); - $aExcluded = array(); - if (MetaModel::IsValidClass('FunctionalCI') && MetaModel::IsValidAttCode('Ticket', 'functionalcis_list')) - { + $aCIsToImpactCode = []; + $aSources = []; + $aExcluded = []; + if (MetaModel::IsValidClass('FunctionalCI') && MetaModel::IsValidAttCode('Ticket', 'functionalcis_list')) { /** @var ormLinkSet $oCIsSet */ $oCIsSet = $this->Get('functionalcis_list'); - foreach ($oCIsSet as $oLink) - { + foreach ($oCIsSet as $oLink) { $iKey = $oLink->Get('functionalci_id'); - $aCIsToImpactCode[$iKey] = array('link' => $oLink->GetKey(), 'code' => $oLink->Get('impact_code')); - if ($oLink->Get('impact_code') == 'manual') - { + $aCIsToImpactCode[$iKey] = ['link' => $oLink->GetKey(), 'code' => $oLink->Get('impact_code')]; + if ($oLink->Get('impact_code') == 'manual') { $oObj = MetaModel::GetObject('FunctionalCI', $iKey); $aSources[$iKey] = $oObj; - } - else if ($oLink->Get('impact_code') == 'not_impacted') - { + } elseif ($oLink->Get('impact_code') == 'not_impacted') { $oObj = MetaModel::GetObject('FunctionalCI', $iKey); $aExcluded[] = $oObj; } @@ -179,128 +166,111 @@ class _Ticket extends cmdbAbstractObject } - $aContactsToRoleCode = array(); - foreach ($oContactsSet as $oLink) - { + $aContactsToRoleCode = []; + foreach ($oContactsSet as $oLink) { $iKey = $oLink->Get('contact_id'); - $aContactsToRoleCode[$iKey] = array('link' => $oLink->GetKey(), 'code' => $oLink->Get('role_code')); - if ($oLink->Get('role_code') == 'do_not_notify') - { + $aContactsToRoleCode[$iKey] = ['link' => $oLink->GetKey(), 'code' => $oLink->Get('role_code')]; + if ($oLink->Get('role_code') == 'do_not_notify') { $oObj = MetaModel::GetObject('Contact', $iKey); $aExcluded[] = $oObj; } } - + $sContextKey = 'itop-tickets/relation_context/'.get_class($this).'/impacts/down'; - $aContextDefs = DisplayableGraph::GetContextDefinitions($sContextKey, true, array('this' => $this)); - $aDefaultContexts = array(); - foreach($aContextDefs as $sKey => $aDefinition) - { + $aContextDefs = DisplayableGraph::GetContextDefinitions($sContextKey, true, ['this' => $this]); + $aDefaultContexts = []; + foreach ($aContextDefs as $sKey => $aDefinition) { // Add the default context queries to the computation - if (array_key_exists('default', $aDefinition) && ($aDefinition['default'] == 'yes')) - { + if (array_key_exists('default', $aDefinition) && ($aDefinition['default'] == 'yes')) { $aDefaultContexts[] = $aDefinition['oql']; } } // Merge the directly impacted items with the "new" ones added by the "context" queries - $aGraphObjects = array(); - $oRawGraph = MetaModel::GetRelatedObjectsDown('impacts', $aSources, $this->GetImpactAnalysisMaxDepth(), true /* bEnableRedundancy */, $aExcluded); - $oIterator = new RelationTypeIterator($oRawGraph, 'Node'); - foreach ($oIterator as $oNode) - { - // Any object node reached AND different from a source will do - if ( ($oNode instanceof RelationObjectNode) && ($oNode->GetProperty('is_reached')) && (!$oNode->GetProperty('source')) ) - { - $this->StoreComputedObject($aGraphObjects, $oNode->GetProperty('object')); - } - } - if (count($aDefaultContexts) > 0) - { + $aGraphObjects = []; + $oRawGraph = MetaModel::GetRelatedObjectsDown('impacts', $aSources, $this->GetImpactAnalysisMaxDepth(), true /* bEnableRedundancy */, $aExcluded); + $oIterator = new RelationTypeIterator($oRawGraph, 'Node'); + foreach ($oIterator as $oNode) { + // Any object node reached AND different from a source will do + if (($oNode instanceof RelationObjectNode) && ($oNode->GetProperty('is_reached')) && (!$oNode->GetProperty('source'))) { + $this->StoreComputedObject($aGraphObjects, $oNode->GetProperty('object')); + } + } + if (count($aDefaultContexts) > 0) { $oAnnotatedGraph = MetaModel::GetRelatedObjectsDown('impacts', $aSources, $this->GetImpactAnalysisMaxDepth(), true /* bEnableRedundancy */, $aExcluded, $aDefaultContexts); $oIterator = new RelationTypeIterator($oAnnotatedGraph, 'Node'); - foreach ($oIterator as $oNode) - { - // Only pick the nodes which are NOT impacted by a context root cause, and merge them in the list - if (($oNode instanceof RelationObjectNode) && ($oNode->GetProperty('is_reached')) && (!$oNode->GetProperty('source')) && ($oNode->GetProperty('context_root_causes', null) == null)) - { - $this->StoreComputedObject($aGraphObjects, $oNode->GetProperty('object')); - } + foreach ($oIterator as $oNode) { + // Only pick the nodes which are NOT impacted by a context root cause, and merge them in the list + if (($oNode instanceof RelationObjectNode) && ($oNode->GetProperty('is_reached')) && (!$oNode->GetProperty('source')) && ($oNode->GetProperty('context_root_causes', null) == null)) { + $this->StoreComputedObject($aGraphObjects, $oNode->GetProperty('object')); + } } } // Remove unnecessary "computed" CIs and Contacts - foreach($aCIsToImpactCode as $iKey => $aCode) - { - if (($aCode['code'] == 'computed') && (!isset($aGraphObjects['FunctionalCI']) || (!array_key_exists($iKey, $aGraphObjects['FunctionalCI'])))) - { - $oCIsSet->RemoveItem($aCode['link']); - } - } - foreach($aContactsToRoleCode as $iKey => $aCode) - { - if (($aCode['code'] == 'computed') && (!isset($aGraphObjects['Contact']) || (!array_key_exists($iKey, $aGraphObjects['Contact'])))) - { - $oContactsSet->RemoveItem($aCode['link']); - } - } - - // Add new nodes - foreach ($aGraphObjects as $sRootClass => $aObjects) - { - switch ($sRootClass) - { - case 'FunctionalCI': - // Only FunctionalCIs which are not already linked to the ticket - foreach($aObjects as $iKey => $oObj) - { - if (!array_key_exists($iKey, $aCIsToImpactCode)) - { - $oNewLink = new lnkFunctionalCIToTicket(); - $oNewLink->Set('functionalci_id', $iKey); - $oNewLink->Set('impact_code', 'computed'); - $oCIsSet->AddItem($oNewLink); - } - } - break; - - case 'Contact': - // Only link Contacts which are not already linked to the ticket - foreach($aObjects as $iKey => $oObj) - { - if (!array_key_exists($iKey, $aContactsToRoleCode)) - { - $oNewLink = new lnkContactToTicket(); - $oNewLink->Set('contact_id', $iKey); - $oNewLink->Set('role_code', 'computed'); - $oContactsSet->AddItem($oNewLink); - } - } - break; + foreach ($aCIsToImpactCode as $iKey => $aCode) { + if (($aCode['code'] == 'computed') && (!isset($aGraphObjects['FunctionalCI']) || (!array_key_exists($iKey, $aGraphObjects['FunctionalCI'])))) { + $oCIsSet->RemoveItem($aCode['link']); } } - if (MetaModel::IsValidClass('FunctionalCI')) - { + foreach ($aContactsToRoleCode as $iKey => $aCode) { + if (($aCode['code'] == 'computed') && (!isset($aGraphObjects['Contact']) || (!array_key_exists($iKey, $aGraphObjects['Contact'])))) { + $oContactsSet->RemoveItem($aCode['link']); + } + } + + // Add new nodes + foreach ($aGraphObjects as $sRootClass => $aObjects) { + switch ($sRootClass) { + case 'FunctionalCI': + // Only FunctionalCIs which are not already linked to the ticket + foreach ($aObjects as $iKey => $oObj) { + if (!array_key_exists($iKey, $aCIsToImpactCode)) { + $oNewLink = new lnkFunctionalCIToTicket(); + $oNewLink->Set('functionalci_id', $iKey); + $oNewLink->Set('impact_code', 'computed'); + $oCIsSet->AddItem($oNewLink); + } + } + break; + + case 'Contact': + // Only link Contacts which are not already linked to the ticket + foreach ($aObjects as $iKey => $oObj) { + if (!array_key_exists($iKey, $aContactsToRoleCode)) { + $oNewLink = new lnkContactToTicket(); + $oNewLink->Set('contact_id', $iKey); + $oNewLink->Set('role_code', 'computed'); + $oContactsSet->AddItem($oNewLink); + } + } + break; + } + } + if (MetaModel::IsValidClass('FunctionalCI')) { $this->Set('functionalcis_list', $oCIsSet); } $this->Set('contacts_list', $oContactsSet); } private function StoreComputedObject(&$aGraphObjects, $oObj) - { - $iKey = $oObj->GetKey(); - $sRootClass = MetaModel::GetRootClass(get_class($oObj)); - $aGraphObjects[$sRootClass][$iKey] = $oObj; - } + { + $iKey = $oObj->GetKey(); + $sRootClass = MetaModel::GetRootClass(get_class($oObj)); + $aGraphObjects[$sRootClass][$iKey] = $oObj; + } public function DisplayBareRelations(WebPage $oPage, $bEditMode = false) { parent::DisplayBareRelations($oPage, $bEditMode); // Display the impact analysis for tickets not in 'closed' or 'resolved' status... and not in edition - if ((!$bEditMode) && (!in_array($this->Get('status'), array('resolved', 'closed')))) - { - $oPage->AddAjaxTab('Ticket:ImpactAnalysis', + if ((!$bEditMode) && (!in_array($this->Get('status'), ['resolved', 'closed']))) { + $oPage->AddAjaxTab( + 'Ticket:ImpactAnalysis', utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php?operation=ticket_impact&class='.get_class($this).'&id='.$this->GetKey(), - true, null, AjaxTab::ENUM_TAB_PLACEHOLDER_MISC); + true, + null, + AjaxTab::ENUM_TAB_PLACEHOLDER_MISC + ); } } } diff --git a/datamodels/2.x/itop-tickets/module.itop-tickets.php b/datamodels/2.x/itop-tickets/module.itop-tickets.php index f46fc1f23..96b407a34 100755 --- a/datamodels/2.x/itop-tickets/module.itop-tickets.php +++ b/datamodels/2.x/itop-tickets/module.itop-tickets.php @@ -1,10 +1,9 @@ 'Tickets Management', @@ -12,24 +11,24 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( + 'dependencies' => [ 'itop-structure/2.7.1', - ), + ], 'mandatory' => false, 'visible' => true, 'installer' => 'TicketsInstaller', // Components // - 'datamodel' => array( + 'datamodel' => [ 'main.itop-tickets.php', - ), - 'data.struct' => array( + ], + 'data.struct' => [ // 'data.struct.ta-actions.xml', - ), - 'data.sample' => array( - ), - + ], + 'data.sample' => [ + ], + // Documentation // 'doc.manual_setup' => '', @@ -37,9 +36,9 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array( - ), - ) + 'settings' => [ + ], + ] ); // Module installation handler @@ -52,17 +51,12 @@ class TicketsInstaller extends ModuleInstallerAPI CMDBObject::SetTrackInfo('Uninstallation'); $oSearch = new DBObjectSearch('TriggerOnObject'); $oSet = new DBObjectSet($oSearch); - while($oTrigger = $oSet->Fetch()) - { - try - { - if (!MetaModel::IsValidClass($oTrigger->Get('target_class'))) - { + while ($oTrigger = $oSet->Fetch()) { + try { + if (!MetaModel::IsValidClass($oTrigger->Get('target_class'))) { $oTrigger->DBDelete(); } - } - catch(Exception $e) - { + } catch (Exception $e) { utils::EnrichRaisedException($oTrigger, $e); } } diff --git a/datamodels/2.x/itop-virtualization-mgmt/module.itop-virtualization-mgmt.php b/datamodels/2.x/itop-virtualization-mgmt/module.itop-virtualization-mgmt.php index f92c29b42..286d63648 100644 --- a/datamodels/2.x/itop-virtualization-mgmt/module.itop-virtualization-mgmt.php +++ b/datamodels/2.x/itop-virtualization-mgmt/module.itop-virtualization-mgmt.php @@ -1,4 +1,5 @@ 'Virtualization Management', @@ -25,23 +26,23 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( - 'itop-config-mgmt/2.4.0' - ), + 'dependencies' => [ + 'itop-config-mgmt/2.4.0', + ], 'mandatory' => false, 'visible' => true, // Components // - 'datamodel' => array( - ), - 'webservice' => array( - - ), - 'data.struct' => array( + 'datamodel' => [ + ], + 'webservice' => [ + + ], + 'data.struct' => [ // add your 'structure' definition XML files here, - ), - 'data.sample' => array( + ], + 'data.sample' => [ // add your sample data XML files here, 'data.sample.farm.xml', 'data.sample.hypervisor.xml', @@ -51,17 +52,17 @@ SetupWebPage::AddModule( 'data.sample.webserver.xml', 'data.sample.webapp.xml', 'data.sample.applicationsolutionci.xml', - ), - + ], + // Documentation // 'doc.manual_setup' => '', // hyperlink to manual setup documentation, if any - 'doc.more_information' => '', // hyperlink to more information, if any + 'doc.more_information' => '', // hyperlink to more information, if any // Default settings // - 'settings' => array( + 'settings' => [ // Module specific settings go here, if any - ), - ) + ], + ] ); diff --git a/datamodels/2.x/itop-welcome-itil/module.itop-welcome-itil.php b/datamodels/2.x/itop-welcome-itil/module.itop-welcome-itil.php index 2e229ef08..296780f6f 100755 --- a/datamodels/2.x/itop-welcome-itil/module.itop-welcome-itil.php +++ b/datamodels/2.x/itop-welcome-itil/module.itop-welcome-itil.php @@ -1,10 +1,9 @@ 'ITIL skin', @@ -12,26 +11,26 @@ SetupWebPage::AddModule( // Setup // - 'dependencies' => array( - ), + 'dependencies' => [ + ], 'mandatory' => true, 'visible' => false, //'installer' => 'MyInstaller', // Components // - 'datamodel' => array( - ), - 'webservice' => array( + 'datamodel' => [ + ], + 'webservice' => [ //'webservices.itop-welcome-itil.php', - ), - 'data.struct' => array( + ], + 'data.struct' => [ //'data.struct.itop-welcome-itil.xml', - ), - 'data.sample' => array( + ], + 'data.sample' => [ //'data.sample.itop-welcome-itil.xml', - ), - + ], + // Documentation // 'doc.manual_setup' => '', @@ -39,8 +38,8 @@ SetupWebPage::AddModule( // Default settings // - 'settings' => array( + 'settings' => [ //'some_setting' => 'some value', - ), - ) + ], + ] ); diff --git a/dictionaries/cs.dictionary.itop.core.php b/dictionaries/cs.dictionary.itop.core.php index b13591a9b..a3cdd5345 100755 --- a/dictionaries/cs.dictionary.itop.core.php +++ b/dictionaries/cs.dictionary.itop.core.php @@ -1,17 +1,18 @@ * @author Daniel Rokos * */ -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Core:DeletedObjectLabel' => '%1s (odstraněn)', 'Core:DeletedObjectTip' => 'Objekt byl odstraněn %1$s (%2$s)', 'Core:UnknownObjectLabel' => 'Objekt nenalezen (třída: %1$s, id: %2$d)', @@ -159,8 +160,7 @@ Operátory:
'Core:Context=GUI:Console' => 'Konzole', 'Core:Context=CRON' => 'cron', 'Core:Context=GUI:Portal' => 'Portal', -)); - +]); ////////////////////////////////////////////////////////////////////// // Classes in 'core/cmdb' @@ -171,7 +171,7 @@ Operátory:
// Class: CMDBChange // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:CMDBChange' => 'Změna', 'Class:CMDBChange+' => 'Trasování změn', 'Class:CMDBChange/Attribute:date' => 'datum', @@ -186,13 +186,13 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Class:CMDBChange/Attribute:origin/Value:webservice-rest' => 'Webové služby REST/JSON', 'Class:CMDBChange/Attribute:origin/Value:webservice-soap' => 'Wbové služby SOAP', 'Class:CMDBChange/Attribute:origin/Value:custom-extension' => 'Rozšíření', -)); +]); // // Class: CMDBChangeOp // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:CMDBChangeOp' => 'Změna operace', 'Class:CMDBChangeOp+' => 'Tracking provozu změn', 'Class:CMDBChangeOp/Attribute:change' => 'změna', @@ -207,51 +207,51 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Class:CMDBChangeOp/Attribute:objkey+' => '', 'Class:CMDBChangeOp/Attribute:finalclass' => 'typ', 'Class:CMDBChangeOp/Attribute:finalclass+' => '', -)); +]); // // Class: CMDBChangeOpCreate // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:CMDBChangeOpCreate' => 'vytvoření objektu', 'Class:CMDBChangeOpCreate+' => 'Tracking vytvoření objektu', -)); +]); // // Class: CMDBChangeOpDelete // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:CMDBChangeOpDelete' => 'odstranění objektu', 'Class:CMDBChangeOpDelete+' => 'Tracking odstranění objektu', -)); +]); // // Class: CMDBChangeOpSetAttribute // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:CMDBChangeOpSetAttribute' => 'změna objektu', 'Class:CMDBChangeOpSetAttribute+' => 'Tracking úprav objektu', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode' => 'Atribut', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode+' => 'kód upravené vlastnosti', -)); +]); // // Class: CMDBChangeOpSetAttributeScalar // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:CMDBChangeOpSetAttributeScalar' => 'změna vlastnosti objektu', 'Class:CMDBChangeOpSetAttributeScalar+' => 'Záznam změny objektu', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue' => 'Předchozí hodnota', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue+' => '', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue' => 'Nová hodnota', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue+' => '', -)); +]); // Used by CMDBChangeOp... & derived classes -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Change:ObjectCreated' => 'Objekt vytvořen', 'Change:ObjectDeleted' => 'Objekt odstraněn', 'Change:ObjectModified' => 'Objekt upraven', @@ -268,35 +268,35 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Change:LinkSet:Added' => 'přidán %1$s', 'Change:LinkSet:Removed' => 'odstraněn %1$s', 'Change:LinkSet:Modified' => 'upraven %1$s', -)); +]); // // Class: CMDBChangeOpSetAttributeBlob // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:CMDBChangeOpSetAttributeBlob' => 'změna dat', 'Class:CMDBChangeOpSetAttributeBlob+' => 'Tracking změny dat', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata' => 'Předchozí data', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata+' => '', -)); +]); // // Class: CMDBChangeOpSetAttributeText // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:CMDBChangeOpSetAttributeText' => 'změna textu', 'Class:CMDBChangeOpSetAttributeText+' => 'Tracking změny textu', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata' => 'Předchozí data', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata+' => '', -)); +]); // // Class: Event // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:Event' => 'Událost', 'Class:Event+' => '', 'Class:Event/Attribute:message' => 'Zpráva', @@ -307,13 +307,13 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Class:Event/Attribute:userinfo+' => 'identifikace uživatele, který spustil tuto událost', 'Class:Event/Attribute:finalclass' => 'Typ', 'Class:Event/Attribute:finalclass+' => '', -)); +]); // // Class: EventNotification // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:EventNotification' => 'Upozornění', 'Class:EventNotification+' => '', 'Class:EventNotification/Attribute:trigger_id' => 'Triger', @@ -322,13 +322,13 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Class:EventNotification/Attribute:action_id+' => '', 'Class:EventNotification/Attribute:object_id' => 'Objekt', 'Class:EventNotification/Attribute:object_id+' => '', -)); +]); // // Class: EventNotificationEmail // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:EventNotificationEmail' => 'Odeslání emailu', 'Class:EventNotificationEmail+' => '', 'Class:EventNotificationEmail/Attribute:to' => 'Pro', @@ -345,13 +345,13 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Class:EventNotificationEmail/Attribute:body+' => '', 'Class:EventNotificationEmail/Attribute:attachments' => 'Přílohy', 'Class:EventNotificationEmail/Attribute:attachments+' => '', -)); +]); // // Class: EventIssue // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:EventIssue' => 'Chyba', 'Class:EventIssue+' => '', 'Class:EventIssue/Attribute:issue' => 'Chyba', @@ -368,13 +368,13 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Class:EventIssue/Attribute:callstack+' => '', 'Class:EventIssue/Attribute:data' => 'Data', 'Class:EventIssue/Attribute:data+' => '', -)); +]); // // Class: EventWebService // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:EventWebService' => 'Volání webové služby', 'Class:EventWebService+' => '', 'Class:EventWebService/Attribute:verb' => 'Název operace', @@ -389,9 +389,9 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Class:EventWebService/Attribute:log_error+' => '', 'Class:EventWebService/Attribute:data' => 'Data', 'Class:EventWebService/Attribute:data+' => '', -)); +]); -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:EventRestService' => 'Volání REST/JSON', 'Class:EventRestService+' => 'Stopa REST/JSON volání', 'Class:EventRestService/Attribute:operation' => 'Operace', @@ -406,13 +406,13 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Class:EventRestService/Attribute:json_output+' => 'HTTP response (json)', 'Class:EventRestService/Attribute:provider' => 'Poskytovatel', 'Class:EventRestService/Attribute:provider+' => 'Třída PHP implementující očekávanou operaci', -)); +]); // // Class: EventLoginUsage // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:EventLoginUsage' => 'Použití aplikace', 'Class:EventLoginUsage+' => '', 'Class:EventLoginUsage/Attribute:user_id' => 'Login', @@ -421,13 +421,13 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Class:EventLoginUsage/Attribute:contact_name+' => 'Kontaktní informace uživatele', 'Class:EventLoginUsage/Attribute:contact_email' => 'Emailová adresa uživatele', 'Class:EventLoginUsage/Attribute:contact_email+' => '', -)); +]); // // Class: EventNotificationNewsroom // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:EventNotificationNewsroom' => 'Zaslané novinky', 'Class:EventNotificationNewsroom+' => '~~', 'Class:EventNotificationNewsroom/Attribute:title' => 'Titulek', @@ -456,13 +456,13 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Class:EventNotificationNewsroom/Attribute:read_date+' => '~~', 'Class:EventNotificationNewsroom/Attribute:contact_id' => 'Kontakt', 'Class:EventNotificationNewsroom/Attribute:contact_id+' => '~~', -)); +]); // // Class: Action // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:Action' => 'Vlastní akce', 'Class:Action+' => '', 'Class:Action/ComplementaryName' => '%1$s: %2$s', @@ -492,22 +492,22 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Action:last_executions_tab_panel_title' => 'Provedení této akce (%1$s)', 'Action:last_executions_tab_limit_days' => 'posledních %1$s dní', 'Action:last_executions_tab_limit_none' => 'bez omezení', -)); +]); // // Class: ActionNotification // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:ActionNotification' => 'Upozornění', 'Class:ActionNotification+' => 'Upozornění (abstraktní)', -)); +]); // // Class: ActionEmail // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:ActionEmail' => 'Emailové upozornění', 'Class:ActionEmail+' => '', 'Class:ActionEmail/Attribute:status+' => 'Tento stav určuje, kdo bude upozorněn: @@ -562,14 +562,13 @@ If omitted the From (label) is used.', 'ActionEmail:preview_warning' => 'Finální podoba emailu může vypadat v emailovém klientu jinak, než tento aktuální náhled v prohlížeci', 'ActionEmail:preview_more_info' => 'Další informace ohledně podpory CSS v emailových klientech, se dozvíte zde %1$s', 'ActionEmail:content_placeholder_missing' => 'Odkaz "%1$s" nebyl v HMTL šabloně nalezen. Obsah pole "%2$s" nebude součástí generovaného emailu', -)); - +]); // // Class: ActionNewsroom // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'ActionNewsroom:trigger' => 'Triger', 'ActionNewsroom:content' => 'Zpráva', 'ActionNewsroom:settings' => 'Nastavení', @@ -604,13 +603,13 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Class:ActionNewsroom/Attribute:recipients+' => 'Dotaz OQL vracející objekty Kontaktu', 'Class:ActionNewsroom/Attribute:url' => 'URL', 'Class:ActionNewsroom/Attribute:url+' => 'Pokud je URL prázdná, bude odkazovat na objekt, který upozornění spustil. Můžete však zadat vlastní URL adresu.', -)); +]); // // Class: Trigger // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:Trigger' => 'Triger', 'Class:Trigger+' => '', 'Class:Trigger/ComplementaryName' => '%1$s, %2$s~~', @@ -629,13 +628,13 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Class:Trigger/Attribute:subscription_policy/Value:allow_no_channel' => 'Povolit úplné odhlášení odběru', 'Class:Trigger/Attribute:subscription_policy/Value:force_at_least_one_channel' => 'Vynucení alespoň jednoho kanálu (Novinka nebo Email)', 'Class:Trigger/Attribute:subscription_policy/Value:force_all_channels' => 'Zakázat odmítnutí odběru', -)); +]); // // Class: TriggerOnObject // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:TriggerOnObject' => 'Triger \'závislý na třídě objektů\'', 'Class:TriggerOnObject+' => '', 'Class:TriggerOnObject/Attribute:target_class' => 'Cílová třída', @@ -644,115 +643,115 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Class:TriggerOnObject/Attribute:filter+' => 'Omezit seznam objektů (cílové třídy), které aktivují triger', 'TriggerOnObject:WrongFilterQuery' => 'Špatný filtrační dotaz: %1$s', 'TriggerOnObject:WrongFilterClass' => 'Filtrační dotaz musí vrátit objekty třídy "%1$s"', -)); +]); // // Class: TriggerOnPortalUpdate // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:TriggerOnPortalUpdate' => 'Triger \'aktualizace přes portál\'', 'Class:TriggerOnPortalUpdate+' => 'Triger při aktualizaci koncovým uživatelem přes portál', -)); +]); // // Class: TriggerOnStateChange // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:TriggerOnStateChange' => 'Triger \'změna stavu\'', 'Class:TriggerOnStateChange+' => '', 'Class:TriggerOnStateChange/Attribute:state' => 'Stav', 'Class:TriggerOnStateChange/Attribute:state+' => '', -)); +]); // // Class: TriggerOnStateEnter // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:TriggerOnStateEnter' => 'Triger \'změna stavu na\'', 'Class:TriggerOnStateEnter+' => '', -)); +]); // // Class: TriggerOnStateLeave // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:TriggerOnStateLeave' => 'Triger \'změna stavu z\'', 'Class:TriggerOnStateLeave+' => '', -)); +]); // // Class: TriggerOnObjectCreate // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:TriggerOnObjectCreate' => 'Triger \'vytvoření objektu\'', 'Class:TriggerOnObjectCreate+' => '', -)); +]); // // Class: TriggerOnObjectDelete // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:TriggerOnObjectDelete' => 'Triger \'smazání objektu\'', 'Class:TriggerOnObjectDelete+' => 'Spustit při smazání objektu [podřízené třídy] dané třídy', -)); +]); // // Class: TriggerOnObjectUpdate // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:TriggerOnObjectUpdate' => 'Triger \'aktualizace objektu\'', 'Class:TriggerOnObjectUpdate+' => 'Spustit při aktualizaci objektu [podřízené třídy] dané třídy', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes' => 'Cílová pole', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes+' => '', -)); +]); // // Class: TriggerOnObjectMention // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:TriggerOnObjectMention' => 'Triger (při zmíňce objektu)', 'Class:TriggerOnObjectMention+' => 'Spustit při zmínce (@xxx) o objektu [podřízené třídy] dané třídy v logu atributu', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter' => 'Filtr zmínek', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter+' => 'Omezit seznam zmíněných objektů, které aktivují triger. Pokud je prázdný, aktivuje jej libovolný zmíněný objekt (libovolné třídy).', -)); +]); // // Class: TriggerOnAttributeBlobDownload // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:TriggerOnAttributeBlobDownload' => 'Triger (při stažení pole dokumentu objektu)', 'Class:TriggerOnAttributeBlobDownload+' => 'Spustit při stažení pole dokumentu objektu [podřízené třídy] dané třídy', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes' => 'Cílová pole', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes+' => '', -)); +]); // // Class: TriggerOnThresholdReached // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:TriggerOnThresholdReached' => 'Triger \'prahová hodnota\'', 'Class:TriggerOnThresholdReached+' => '', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code' => 'Stopky', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code+' => '', 'Class:TriggerOnThresholdReached/Attribute:threshold_index' => 'Prahová hodnota', 'Class:TriggerOnThresholdReached/Attribute:threshold_index+' => '', -)); +]); // // Class: lnkTriggerAction // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:lnkTriggerAction' => 'Spojení (Akce / Triger)', 'Class:lnkTriggerAction+' => '', 'Class:lnkTriggerAction/Attribute:action_id' => 'Akce', @@ -765,12 +764,12 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Class:lnkTriggerAction/Attribute:trigger_name+' => '', 'Class:lnkTriggerAction/Attribute:order' => 'Pořadí', 'Class:lnkTriggerAction/Attribute:order+' => 'Pořadí, v jakém jsou akce vykonány', -)); +]); // // Synchro Data Source // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:SynchroDataSource' => 'Zdroje dat pro synchronizaci', 'Class:SynchroDataSource/Attribute:name' => 'Název', 'Class:SynchroDataSource/Attribute:name+' => '', @@ -1058,13 +1057,13 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Core:Validator:MustBeInteger' => 'Musí být celé číslo', 'Core:Validator:MustSelectOne' => 'Zvolte prosím jednu hodnotu', 'Menu:DataSources' => 'Zdroje dat pro synchronizaci', - 'Menu:DataSources+' => 'Všechny zdroje dat pro synchronizaci' -)); + 'Menu:DataSources+' => 'Všechny zdroje dat pro synchronizaci', +]); // // Class: TagSetFieldData // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:TagSetFieldData' => '%2$s pro třídu %1$s', 'Class:TagSetFieldData+' => '', 'Class:TagSetFieldData/Attribute:code' => 'Kód', @@ -1086,12 +1085,12 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Core:TagSetFieldData:ErrorAttCodeUpdateNotAllowed' => 'Atribut kód u Tagu nemůže být změněn', 'Core:TagSetFieldData:WhereIsThisTagTab' => 'Použití Tagu (%1$d)', 'Core:TagSetFieldData:NoEntryFound' => 'Pro Tag nebyl nalezen žádný vstup', -)); +]); // // Class: DBProperty // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:DBProperty' => 'Nastavení DB', 'Class:DBProperty+' => '', 'Class:DBProperty/Attribute:name' => 'Jméno', @@ -1104,12 +1103,12 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Class:DBProperty/Attribute:change_date+' => '', 'Class:DBProperty/Attribute:change_comment' => 'Změna komentáře', 'Class:DBProperty/Attribute:change_comment+' => '', -)); +]); // // Class: BackgroundTask // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:BackgroundTask' => 'Úkoly běžící na pozadí', 'Class:BackgroundTask+' => '', 'Class:BackgroundTask/Attribute:class_name' => 'Jméno třídy', @@ -1134,12 +1133,12 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Class:BackgroundTask/Attribute:running+' => '', 'Class:BackgroundTask/Attribute:status' => 'Status', 'Class:BackgroundTask/Attribute:status+' => '', -)); +]); // // Class: AsyncTask // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:AsyncTask' => 'Asynchronní úkoly', 'Class:AsyncTask+' => '', 'Class:AsyncTask/Attribute:created' => 'Vytvořeno', @@ -1164,47 +1163,44 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'Class:AsyncTask/Attribute:last_attempt+' => '', 'Class:AsyncTask:InvalidConfig_Class_Keys' => 'Špatný formát pro nastavení "async_task_retries[%1$s]". Je očekáváno pole obsahující následující klíče: %2$s', 'Class:AsyncTask:InvalidConfig_Class_InvalidKey_Keys' => 'Špatný formát pro nastavení "async_task_retries[%1$s]": neočekávaný klíč "%2$s". Je očekáván jeden z následujících klíčů: %3$s', -)); +]); // // Class: AbstractResource // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:AbstractResource' => 'Abstraktní zdroj', 'Class:AbstractResource+' => '', -)); +]); // // Class: ResourceAdminMenu // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:ResourceAdminMenu' => 'Resource Admin Menu~~', 'Class:ResourceAdminMenu+' => '', -)); +]); // // Class: ResourceRunQueriesMenu // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:ResourceRunQueriesMenu' => 'Resource Run Queries Menu~~', 'Class:ResourceRunQueriesMenu+' => '', -)); +]); // // Class: Action // -Dict::Add('CS CZ', 'Czech', 'Čeština', array( +Dict::Add('CS CZ', 'Czech', 'Čeština', [ 'Class:ResourceSystemMenu' => 'Resource System Menu~~', 'Class:ResourceSystemMenu+' => '', - 'Class:EventNotification/Attribute:object_class' => 'Object class~~', - 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', + 'Class:EventNotification/Attribute:object_class' => 'Object class~~', + 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', 'Core:EventNotificationNewsroom:ErrorNotificationNotSent' => 'Notification not sent~~', 'Core:EventNotificationNewsroom:ErrorOnDBInsert' => 'An error occurred while saving the notification~~', -)); - - - +]); diff --git a/dictionaries/da.dictionary.itop.core.php b/dictionaries/da.dictionary.itop.core.php index 6552e63c7..b293e10ac 100644 --- a/dictionaries/da.dictionary.itop.core.php +++ b/dictionaries/da.dictionary.itop.core.php @@ -1,16 +1,17 @@ * */ -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Core:DeletedObjectLabel' => '%1s (slettet)', 'Core:DeletedObjectTip' => 'Objektet er slettet på %1$s (%2$s)', 'Core:UnknownObjectLabel' => 'Objektet ikke fundet (klasse: %1$s, id: %2$d)', @@ -158,8 +159,7 @@ Operators:
'Core:Context=GUI:Console' => 'Console~~', 'Core:Context=CRON' => 'cron~~', 'Core:Context=GUI:Portal' => 'Portal~~', -)); - +]); ////////////////////////////////////////////////////////////////////// // Classes in 'core/cmdb' @@ -170,7 +170,7 @@ Operators:
// Class: CMDBChange // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:CMDBChange' => 'Change', 'Class:CMDBChange+' => '', 'Class:CMDBChange/Attribute:date' => 'Dato', @@ -185,13 +185,13 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Class:CMDBChange/Attribute:origin/Value:webservice-rest' => 'REST/JSON webservices~~', 'Class:CMDBChange/Attribute:origin/Value:webservice-soap' => 'SOAP webservices~~', 'Class:CMDBChange/Attribute:origin/Value:custom-extension' => 'By an extension~~', -)); +]); // // Class: CMDBChangeOp // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:CMDBChangeOp' => 'Change Operation', 'Class:CMDBChangeOp+' => '', 'Class:CMDBChangeOp/Attribute:change' => 'Change', @@ -206,51 +206,51 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Class:CMDBChangeOp/Attribute:objkey+' => '', 'Class:CMDBChangeOp/Attribute:finalclass' => 'Type', 'Class:CMDBChangeOp/Attribute:finalclass+' => '', -)); +]); // // Class: CMDBChangeOpCreate // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:CMDBChangeOpCreate' => 'Object oprettelse', 'Class:CMDBChangeOpCreate+' => '', -)); +]); // // Class: CMDBChangeOpDelete // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:CMDBChangeOpDelete' => 'Object sletning', 'Class:CMDBChangeOpDelete+' => '', -)); +]); // // Class: CMDBChangeOpSetAttribute // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:CMDBChangeOpSetAttribute' => 'Object ændring', 'Class:CMDBChangeOpSetAttribute+' => '', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode' => 'Attribut', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode+' => '', -)); +]); // // Class: CMDBChangeOpSetAttributeScalar // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:CMDBChangeOpSetAttributeScalar' => 'Property ændring', 'Class:CMDBChangeOpSetAttributeScalar+' => '', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue' => 'Tidligere værdi', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue+' => '', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue' => 'Ny værdi', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue+' => '', -)); +]); // Used by CMDBChangeOp... & derived classes -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Change:ObjectCreated' => 'Objekt oprettet', 'Change:ObjectDeleted' => 'Objekt slettet', 'Change:ObjectModified' => 'Objekt ændret', @@ -267,35 +267,35 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Change:LinkSet:Added' => 'tilføjet %1$s', 'Change:LinkSet:Removed' => 'fjernet %1$s', 'Change:LinkSet:Modified' => 'ændret %1$s', -)); +]); // // Class: CMDBChangeOpSetAttributeBlob // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:CMDBChangeOpSetAttributeBlob' => 'Data ændring', 'Class:CMDBChangeOpSetAttributeBlob+' => '', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata' => 'Tidligere data', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata+' => '', -)); +]); // // Class: CMDBChangeOpSetAttributeText // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:CMDBChangeOpSetAttributeText' => 'Tekst ændring', 'Class:CMDBChangeOpSetAttributeText+' => '', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata' => 'Tidligere data', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata+' => '', -)); +]); // // Class: Event // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:Event' => 'Log Hændelse', 'Class:Event+' => '', 'Class:Event/Attribute:message' => 'Besked', @@ -306,13 +306,13 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Class:Event/Attribute:userinfo+' => '', 'Class:Event/Attribute:finalclass' => 'Type', 'Class:Event/Attribute:finalclass+' => '', -)); +]); // // Class: EventNotification // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:EventNotification' => 'Notifikation hændelse', 'Class:EventNotification+' => '', 'Class:EventNotification/Attribute:trigger_id' => 'Trigger', @@ -321,13 +321,13 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Class:EventNotification/Attribute:action_id+' => '', 'Class:EventNotification/Attribute:object_id' => 'Object id', 'Class:EventNotification/Attribute:object_id+' => '', -)); +]); // // Class: EventNotificationEmail // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:EventNotificationEmail' => 'Email emission hændelse', 'Class:EventNotificationEmail+' => '', 'Class:EventNotificationEmail/Attribute:to' => 'Til', @@ -344,13 +344,13 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Class:EventNotificationEmail/Attribute:body+' => '', 'Class:EventNotificationEmail/Attribute:attachments' => 'Vedhæftning(er)', 'Class:EventNotificationEmail/Attribute:attachments+' => '', -)); +]); // // Class: EventIssue // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:EventIssue' => 'Hændelses emne', 'Class:EventIssue+' => '', 'Class:EventIssue/Attribute:issue' => 'Emne', @@ -367,13 +367,13 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Class:EventIssue/Attribute:callstack+' => '', 'Class:EventIssue/Attribute:data' => 'Data', 'Class:EventIssue/Attribute:data+' => '', -)); +]); // // Class: EventWebService // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:EventWebService' => 'Web service hændelse', 'Class:EventWebService+' => '', 'Class:EventWebService/Attribute:verb' => 'Verb', @@ -388,9 +388,9 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Class:EventWebService/Attribute:log_error+' => '', 'Class:EventWebService/Attribute:data' => 'Data', 'Class:EventWebService/Attribute:data+' => '', -)); +]); -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:EventRestService' => 'REST/JSON call~~', 'Class:EventRestService+' => 'Trace of a REST/JSON service call~~', 'Class:EventRestService/Attribute:operation' => 'Operation~~', @@ -405,13 +405,13 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Class:EventRestService/Attribute:json_output+' => 'HTTP response (json)~~', 'Class:EventRestService/Attribute:provider' => 'Provider~~', 'Class:EventRestService/Attribute:provider+' => 'PHP class implementing the expected operation~~', -)); +]); // // Class: EventLoginUsage // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:EventLoginUsage' => 'Login Usage', 'Class:EventLoginUsage+' => '', 'Class:EventLoginUsage/Attribute:user_id' => 'Login', @@ -420,13 +420,13 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Class:EventLoginUsage/Attribute:contact_name+' => '', 'Class:EventLoginUsage/Attribute:contact_email' => 'Bruger Email', 'Class:EventLoginUsage/Attribute:contact_email+' => '', -)); +]); // // Class: EventNotificationNewsroom // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:EventNotificationNewsroom' => 'News sent~~', 'Class:EventNotificationNewsroom+' => '~~', 'Class:EventNotificationNewsroom/Attribute:title' => 'Title~~', @@ -455,13 +455,13 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Class:EventNotificationNewsroom/Attribute:read_date+' => '~~', 'Class:EventNotificationNewsroom/Attribute:contact_id' => 'Contact~~', 'Class:EventNotificationNewsroom/Attribute:contact_id+' => '~~', -)); +]); // // Class: Action // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:Action' => 'Brugerdefineret handling', 'Class:Action+' => '', 'Class:Action/ComplementaryName' => '%1$s: %2$s~~', @@ -491,22 +491,22 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Action:last_executions_tab_panel_title' => 'Executions of this action (%1$s)~~', 'Action:last_executions_tab_limit_days' => 'past %1$s days~~', 'Action:last_executions_tab_limit_none' => 'no limit~~', -)); +]); // // Class: ActionNotification // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:ActionNotification' => 'Notifikation', 'Class:ActionNotification+' => '', -)); +]); // // Class: ActionEmail // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:ActionEmail' => 'Email besked', 'Class:ActionEmail+' => '', 'Class:ActionEmail/Attribute:status+' => 'This status drives who will be notified: @@ -561,14 +561,13 @@ If omitted the From (label) is used.~~', 'ActionEmail:preview_warning' => 'The actual eMail may look different in the eMail client than this preview in your browser.~~', 'ActionEmail:preview_more_info' => 'For more information about the CSS features supported by the different eMail clients, refer to %1$s~~', 'ActionEmail:content_placeholder_missing' => 'The placeholder "%1$s" was not found in the HTML template. The content of the field "%2$s" will not be included in the generated emails.~~', -)); - +]); // // Class: ActionNewsroom // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'ActionNewsroom:trigger' => 'Trigger~~', 'ActionNewsroom:content' => 'Message~~', 'ActionNewsroom:settings' => 'Settings~~', @@ -603,13 +602,13 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Class:ActionNewsroom/Attribute:recipients+' => 'An OQL query returning Contact objects~~', 'Class:ActionNewsroom/Attribute:url' => 'URL~~', 'Class:ActionNewsroom/Attribute:url+' => 'By default, it points to the object triggering the notification. But you can also specify a custom URL.~~', -)); +]); // // Class: Trigger // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:Trigger' => 'Triggere', 'Class:Trigger+' => '', 'Class:Trigger/ComplementaryName' => '%1$s, %2$s~~', @@ -628,13 +627,13 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Class:Trigger/Attribute:subscription_policy/Value:allow_no_channel' => 'Allow complete unsubscription~~', 'Class:Trigger/Attribute:subscription_policy/Value:force_at_least_one_channel' => 'Force at least one channel (News or Email)~~', 'Class:Trigger/Attribute:subscription_policy/Value:force_all_channels' => 'Deny unsubscription~~', -)); +]); // // Class: TriggerOnObject // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:TriggerOnObject' => 'Trigger (klasse afhængig)', 'Class:TriggerOnObject+' => '', 'Class:TriggerOnObject/Attribute:target_class' => 'Target klasse', @@ -643,115 +642,115 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Class:TriggerOnObject/Attribute:filter+' => 'Limit the object list (of the target class) which will activate the trigger~~', 'TriggerOnObject:WrongFilterQuery' => 'Wrong filter query: %1$s~~', 'TriggerOnObject:WrongFilterClass' => 'The filter query must return objects of class "%1$s"~~', -)); +]); // // Class: TriggerOnPortalUpdate // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:TriggerOnPortalUpdate' => 'Trigger (Når opdateret fra portalen)', 'Class:TriggerOnPortalUpdate+' => '', -)); +]); // // Class: TriggerOnStateChange // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:TriggerOnStateChange' => 'Trigger (i tilstand ændring)', 'Class:TriggerOnStateChange+' => '', 'Class:TriggerOnStateChange/Attribute:state' => 'Tilstand', 'Class:TriggerOnStateChange/Attribute:state+' => '', -)); +]); // // Class: TriggerOnStateEnter // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:TriggerOnStateEnter' => 'Trigger (ved indtræden i en tilstand)', 'Class:TriggerOnStateEnter+' => '', -)); +]); // // Class: TriggerOnStateLeave // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:TriggerOnStateLeave' => 'Trigger (når en tilstand forlades)', 'Class:TriggerOnStateLeave+' => '', -)); +]); // // Class: TriggerOnObjectCreate // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:TriggerOnObjectCreate' => 'Trigger (ved oprettelse af objekt)', 'Class:TriggerOnObjectCreate+' => '', -)); +]); // // Class: TriggerOnObjectDelete // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:TriggerOnObjectDelete' => 'Trigger (on object deletion)~~', 'Class:TriggerOnObjectDelete+' => 'Trigger on object deletion of [a child class of] the given class~~', -)); +]); // // Class: TriggerOnObjectUpdate // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:TriggerOnObjectUpdate' => 'Trigger (on object update)~~', 'Class:TriggerOnObjectUpdate+' => 'Trigger on object update of [a child class of] the given class~~', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes' => 'Target fields~~', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes+' => '', -)); +]); // // Class: TriggerOnObjectMention // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:TriggerOnObjectMention' => 'Trigger (on object mention)~~', 'Class:TriggerOnObjectMention+' => 'Trigger on mention (@xxx) of an object of [a child class of] the given class in a log attribute~~', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter' => 'Mentioned filter~~', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter+' => 'Limit the list of mentioned objects which will activate the trigger. If empty, any mentioned object (of any class) will activate it.~~', -)); +]); // // Class: TriggerOnAttributeBlobDownload // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:TriggerOnAttributeBlobDownload' => 'Trigger (on object\'s document download)~~', 'Class:TriggerOnAttributeBlobDownload+' => 'Trigger on object\'s document field download of [a child class of] the given class~~', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes' => 'Target fields~~', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes+' => '~~', -)); +]); // // Class: TriggerOnThresholdReached // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:TriggerOnThresholdReached' => 'Trigger (grænseværdi)', 'Class:TriggerOnThresholdReached+' => '', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code' => 'Stopur', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code+' => '', 'Class:TriggerOnThresholdReached/Attribute:threshold_index' => 'Grænse', 'Class:TriggerOnThresholdReached/Attribute:threshold_index+' => '', -)); +]); // // Class: lnkTriggerAction // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:lnkTriggerAction' => 'Handling/Trigger', 'Class:lnkTriggerAction+' => '', 'Class:lnkTriggerAction/Attribute:action_id' => 'Handling', @@ -764,12 +763,12 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Class:lnkTriggerAction/Attribute:trigger_name+' => '', 'Class:lnkTriggerAction/Attribute:order' => 'Rækkefølge', 'Class:lnkTriggerAction/Attribute:order+' => '', -)); +]); // // Synchro Data Source // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:SynchroDataSource' => 'Synchro Data Kilde', 'Class:SynchroDataSource/Attribute:name' => 'Navn', 'Class:SynchroDataSource/Attribute:name+' => '', @@ -1057,13 +1056,13 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Core:Validator:MustBeInteger' => 'Must be an integer~~', 'Core:Validator:MustSelectOne' => 'Please, select one~~', 'Menu:DataSources' => 'Synkroniserings Data Kilder', - 'Menu:DataSources+' => '' -)); + 'Menu:DataSources+' => '', +]); // // Class: TagSetFieldData // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:TagSetFieldData' => '%2$s for class %1$s~~', 'Class:TagSetFieldData+' => '', 'Class:TagSetFieldData/Attribute:code' => 'Code~~', @@ -1085,12 +1084,12 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Core:TagSetFieldData:ErrorAttCodeUpdateNotAllowed' => 'Tags "Attribute Code" cannot be changed~~', 'Core:TagSetFieldData:WhereIsThisTagTab' => 'Tag usage (%1$d)~~', 'Core:TagSetFieldData:NoEntryFound' => 'No entry found for this tag~~', -)); +]); // // Class: DBProperty // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:DBProperty' => 'DB property~~', 'Class:DBProperty+' => '', 'Class:DBProperty/Attribute:name' => 'Name~~', @@ -1103,12 +1102,12 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Class:DBProperty/Attribute:change_date+' => '', 'Class:DBProperty/Attribute:change_comment' => 'Change comment~~', 'Class:DBProperty/Attribute:change_comment+' => '', -)); +]); // // Class: BackgroundTask // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:BackgroundTask' => 'Background task~~', 'Class:BackgroundTask+' => '', 'Class:BackgroundTask/Attribute:class_name' => 'Class name~~', @@ -1133,12 +1132,12 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Class:BackgroundTask/Attribute:running+' => '', 'Class:BackgroundTask/Attribute:status' => 'Status~~', 'Class:BackgroundTask/Attribute:status+' => '', -)); +]); // // Class: AsyncTask // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:AsyncTask' => 'Async. task~~', 'Class:AsyncTask+' => '', 'Class:AsyncTask/Attribute:created' => 'Created~~', @@ -1163,47 +1162,44 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'Class:AsyncTask/Attribute:last_attempt+' => '', 'Class:AsyncTask:InvalidConfig_Class_Keys' => 'Invalid format for the configuration of "async_task_retries[%1$s]". Expecting an array with the following keys: %2$s~~', 'Class:AsyncTask:InvalidConfig_Class_InvalidKey_Keys' => 'Invalid format for the configuration of "async_task_retries[%1$s]": unexpected key "%2$s". Expecting only the following keys: %3$s~~', -)); +]); // // Class: AbstractResource // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:AbstractResource' => 'Abstract Resource~~', 'Class:AbstractResource+' => '', -)); +]); // // Class: ResourceAdminMenu // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:ResourceAdminMenu' => 'Resource Admin Menu~~', 'Class:ResourceAdminMenu+' => '', -)); +]); // // Class: ResourceRunQueriesMenu // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:ResourceRunQueriesMenu' => 'Resource Run Queries Menu~~', 'Class:ResourceRunQueriesMenu+' => '', -)); +]); // // Class: Action // -Dict::Add('DA DA', 'Danish', 'Dansk', array( +Dict::Add('DA DA', 'Danish', 'Dansk', [ 'Class:ResourceSystemMenu' => 'Resource System Menu~~', 'Class:ResourceSystemMenu+' => '', - 'Class:EventNotification/Attribute:object_class' => 'Object class~~', - 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', + 'Class:EventNotification/Attribute:object_class' => 'Object class~~', + 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', 'Core:EventNotificationNewsroom:ErrorNotificationNotSent' => 'Notification not sent~~', 'Core:EventNotificationNewsroom:ErrorOnDBInsert' => 'An error occurred while saving the notification~~', -)); - - - +]); diff --git a/dictionaries/de.dictionary.itop.core.php b/dictionaries/de.dictionary.itop.core.php index 98711b90a..a0e513d3c 100644 --- a/dictionaries/de.dictionary.itop.core.php +++ b/dictionaries/de.dictionary.itop.core.php @@ -1,4 +1,5 @@ * @author Martin Raenker * @author Attila Baroti - * + * */ -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Core:DeletedObjectLabel' => '%1s (gelöscht)', 'Core:DeletedObjectTip' => 'Das Objekt wurde gelöscht am %1$s (%2$s)', 'Core:UnknownObjectLabel' => 'Objekt nicht gefunden (Klasse: %1$s, id: %2$d)', @@ -157,8 +158,7 @@ Operatoren:
'Core:Context=GUI:Console' => 'Konsole', 'Core:Context=CRON' => 'cron', 'Core:Context=GUI:Portal' => 'Portal', -)); - +]); ////////////////////////////////////////////////////////////////////// // Classes in 'core/cmdb' @@ -169,7 +169,7 @@ Operatoren:
// Class: CMDBChange // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:CMDBChange' => 'Change', 'Class:CMDBChange+' => 'Protokollierung der Änderungen', 'Class:CMDBChange/Attribute:date' => 'Datum', @@ -184,13 +184,13 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Class:CMDBChange/Attribute:origin/Value:webservice-rest' => 'REST/JSON Webservices', 'Class:CMDBChange/Attribute:origin/Value:webservice-soap' => 'SOAP Webservices', 'Class:CMDBChange/Attribute:origin/Value:custom-extension' => 'Durch eine Extension', -)); +]); // // Class: CMDBChangeOp // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:CMDBChangeOp' => 'Change-Operation', 'Class:CMDBChangeOp+' => 'Protokoll einer Änderung', 'Class:CMDBChangeOp/Attribute:change' => 'Change', @@ -205,51 +205,51 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Class:CMDBChangeOp/Attribute:objkey+' => '', 'Class:CMDBChangeOp/Attribute:finalclass' => 'Typ', 'Class:CMDBChangeOp/Attribute:finalclass+' => '', -)); +]); // // Class: CMDBChangeOpCreate // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:CMDBChangeOpCreate' => 'Objekterstellung', 'Class:CMDBChangeOpCreate+' => 'Protokoll der Objekterstellung', -)); +]); // // Class: CMDBChangeOpDelete // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:CMDBChangeOpDelete' => 'Objektlöschung', 'Class:CMDBChangeOpDelete+' => 'Protokoll der Objektlöschung', -)); +]); // // Class: CMDBChangeOpSetAttribute // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:CMDBChangeOpSetAttribute' => 'Objektänderung', 'Class:CMDBChangeOpSetAttribute+' => 'Protokoll der Objektänderungen', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode' => 'Attribut', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode+' => 'Code der geänderten Eigenschaft', -)); +]); // // Class: CMDBChangeOpSetAttributeScalar // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:CMDBChangeOpSetAttributeScalar' => 'Eigenschaften ändern', 'Class:CMDBChangeOpSetAttributeScalar+' => 'Aufzeichnen der Änderungen am Objekt', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue' => 'Vorheriger Wert', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue+' => 'Vorheriger Wert des Attributes', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue' => 'Neuer Wert', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue+' => 'Neuer Wert des Attributes', -)); +]); // Used by CMDBChangeOp... & derived classes -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Change:ObjectCreated' => 'Objekt erstellt', 'Change:ObjectDeleted' => 'Objekt gelöscht', 'Change:ObjectModified' => 'Objekt geändert', @@ -266,35 +266,35 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Change:LinkSet:Added' => 'hinzugefügt: %1$s', 'Change:LinkSet:Removed' => 'entfernt: %1$s', 'Change:LinkSet:Modified' => 'modifizert: %1$s', -)); +]); // // Class: CMDBChangeOpSetAttributeBlob // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:CMDBChangeOpSetAttributeBlob' => 'Daten ändern', 'Class:CMDBChangeOpSetAttributeBlob+' => 'Aufzeichnen der Datenänderung', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata' => 'Vorherige Daten', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata+' => 'Vorherige Inhalte des Attributes', -)); +]); // // Class: CMDBChangeOpSetAttributeText // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:CMDBChangeOpSetAttributeText' => 'Text ändern', 'Class:CMDBChangeOpSetAttributeText+' => 'Aufzeichnen der Textänderung', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata' => 'Vorherige Daten', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata+' => 'Vorherige Inhalte des Attributes', -)); +]); // // Class: Event // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:Event' => 'Log Event', 'Class:Event+' => 'Ein anwendungsinternes Event', 'Class:Event/Attribute:message' => 'Nachricht', @@ -305,13 +305,13 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Class:Event/Attribute:userinfo+' => 'Identifikation des Benutzers, der die Aktion ausführte, die dieses Event ausgelöst hat', 'Class:Event/Attribute:finalclass' => 'Typ', 'Class:Event/Attribute:finalclass+' => '', -)); +]); // // Class: EventNotification // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:EventNotification' => 'Gesendete Benachrichtigung', 'Class:EventNotification+' => 'Protokollierung der gesendeten Benachrichtigungen', 'Class:EventNotification/Attribute:trigger_id' => 'Trigger', @@ -320,13 +320,13 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Class:EventNotification/Attribute:action_id+' => '', 'Class:EventNotification/Attribute:object_id' => 'Objekt-ID', 'Class:EventNotification/Attribute:object_id+' => '', -)); +]); // // Class: EventNotificationEmail // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:EventNotificationEmail' => 'E-Mail Emission Event', 'Class:EventNotificationEmail+' => 'Verfolgung einer E-Mail, die gesendet wurde', 'Class:EventNotificationEmail/Attribute:to' => 'An', @@ -343,13 +343,13 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Class:EventNotificationEmail/Attribute:body+' => '', 'Class:EventNotificationEmail/Attribute:attachments' => 'Anhänge', 'Class:EventNotificationEmail/Attribute:attachments+' => 'Anhänge in der Nachricht', -)); +]); // // Class: EventIssue // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:EventIssue' => 'Issue Event', 'Class:EventIssue+' => 'Protokollierung eines Issues (Warnungen, Fehler, etc.)', 'Class:EventIssue/Attribute:issue' => 'Issue', @@ -366,13 +366,13 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Class:EventIssue/Attribute:callstack+' => 'Call stack', 'Class:EventIssue/Attribute:data' => 'Daten', 'Class:EventIssue/Attribute:data+' => 'Mehr Informationen', -)); +]); // // Class: EventWebService // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:EventWebService' => 'Web Service Event', 'Class:EventWebService+' => 'Protokollierung eines Web Service Calls', 'Class:EventWebService/Attribute:verb' => 'Verb', @@ -387,9 +387,9 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Class:EventWebService/Attribute:log_error+' => 'Ergebnis der Fehlerprotokollierung', 'Class:EventWebService/Attribute:data' => 'Daten', 'Class:EventWebService/Attribute:data+' => 'Ergebnisdaten', -)); +]); -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:EventRestService' => 'REST/JSON Call', 'Class:EventRestService+' => 'Trace eines REST/JSON-Calls', 'Class:EventRestService/Attribute:operation' => 'Operation', @@ -404,13 +404,13 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Class:EventRestService/Attribute:json_output+' => 'HTTP Antwort (JSON)', 'Class:EventRestService/Attribute:provider' => 'Provider', 'Class:EventRestService/Attribute:provider+' => 'PHP-Klasse, die die erwartete Operation implementiert', -)); +]); // // Class: EventLoginUsage // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:EventLoginUsage' => 'Login Verwendung', 'Class:EventLoginUsage+' => '', 'Class:EventLoginUsage/Attribute:user_id' => 'Login', @@ -419,13 +419,13 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Class:EventLoginUsage/Attribute:contact_name+' => '', 'Class:EventLoginUsage/Attribute:contact_email' => 'Benutzer-Mailadresse', 'Class:EventLoginUsage/Attribute:contact_email+' => '', -)); +]); // // Class: EventNotificationNewsroom // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:EventNotificationNewsroom' => 'Gesendete Newsroom-Benachrichtigung', 'Class:EventNotificationNewsroom+' => '', 'Class:EventNotificationNewsroom/Attribute:title' => 'Titel', @@ -454,13 +454,13 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Class:EventNotificationNewsroom/Attribute:read_date+' => '', 'Class:EventNotificationNewsroom/Attribute:contact_id' => 'Kontakt', 'Class:EventNotificationNewsroom/Attribute:contact_id+' => '', -)); +]); // // Class: Action // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:Action' => 'Benutzerdefinierte Aktion', 'Class:Action+' => 'Benutzerdefinierte Aktionen', 'Class:Action/ComplementaryName' => '%1$s: %2$s', @@ -490,22 +490,22 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Action:last_executions_tab_panel_title' => 'Ausführungen dieser Aktion (%1$s)', 'Action:last_executions_tab_limit_days' => 'die letzten %1$s Tage', 'Action:last_executions_tab_limit_none' => 'keine Einschränkung', -)); +]); // // Class: ActionNotification // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:ActionNotification' => 'Benachrichtigung', 'Class:ActionNotification+' => 'Benachrichtigung (Kurzbeschreibung)', -)); +]); // // Class: ActionEmail // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:ActionEmail' => 'Benachrichtigung via E-mail', 'Class:ActionEmail+' => '', 'Class:ActionEmail/Attribute:status+' => 'Dieser Zustand entscheidet, wer benachrichtigt werden soll: nur der Testempfänger, alle (To, cc und Bcc) oder niemand', @@ -556,14 +556,13 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'ActionEmail:preview_warning' => 'Die tatsächliche E-Mail kann im E-Mail-Client anders aussehen als diese Vorschau in Ihrem Browser.', 'ActionEmail:preview_more_info' => 'Weitere Informationen zu den CSS-Funktionen, die von den verschiedenen E-Mail-Clients unterstützt werden, finden Sie unter %1$s', 'ActionEmail:content_placeholder_missing' => 'Der Platzhalter "%1$s" wurde in der HTML-Vorlage nicht gefunden. Der Inhalt des Feldes "%2$s" wird nicht in den generierten E-Mails enthalten sein.', -)); - +]); // // Class: ActionNewsroom // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'ActionNewsroom:trigger' => 'Trigger', 'ActionNewsroom:content' => 'Nachricht', 'ActionNewsroom:settings' => 'Einstellungen', @@ -600,13 +599,13 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Class:ActionNewsroom/Attribute:recipients+' => 'Eine OQL-Abfrage, die Kontakt-Objekte zurückgibt', 'Class:ActionNewsroom/Attribute:url' => 'URL', 'Class:ActionNewsroom/Attribute:url+' => 'Wenn leer, verweist die URL auf das Objekt, das die Benachrichtigung ausgelöst hat. Sie können jedoch auch eine benutzerdefinierte URL angeben.', -)); +]); // // Class: Trigger // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:Trigger' => 'Trigger', 'Class:Trigger+' => 'Custom event handler', 'Class:Trigger/ComplementaryName' => '%1$s, %2$s', @@ -625,13 +624,13 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Class:Trigger/Attribute:subscription_policy/Value:allow_no_channel' => 'Vollständige Abmeldung erlauben', 'Class:Trigger/Attribute:subscription_policy/Value:force_at_least_one_channel' => 'Mindestens einen Kanal erzwingen (Nachricht oder E-Mail)', 'Class:Trigger/Attribute:subscription_policy/Value:force_all_channels' => 'Abmeldung verweigern', -)); +]); // // Class: TriggerOnObject // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:TriggerOnObject' => 'Trigger (klassenunabhängig)', 'Class:TriggerOnObject+' => 'Trigger einer gegebenen Klasse an Objekten', 'Class:TriggerOnObject/Attribute:target_class' => 'Zielklasse', @@ -640,115 +639,115 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Class:TriggerOnObject/Attribute:filter+' => 'Einschränkung der Objekte (der Zielklasse) welche den Trigger aktivieren.', 'TriggerOnObject:WrongFilterQuery' => 'Fehlerhafter Filter-Query: %1$s', 'TriggerOnObject:WrongFilterClass' => 'Der Filter muss Objekte vom Typ \\"%1$s\\" zurückgeben.', -)); +]); // // Class: TriggerOnPortalUpdate // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:TriggerOnPortalUpdate' => 'Trigger (bei Update aus dem Portal)', 'Class:TriggerOnPortalUpdate+' => '', -)); +]); // // Class: TriggerOnStateChange // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:TriggerOnStateChange' => 'Trigger (bei Statusänderung)', 'Class:TriggerOnStateChange+' => 'Trigger bei Änderung des Objektstatus', 'Class:TriggerOnStateChange/Attribute:state' => 'Status', 'Class:TriggerOnStateChange/Attribute:state+' => '', -)); +]); // // Class: TriggerOnStateEnter // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:TriggerOnStateEnter' => 'Trigger (beim Eintritt eines Status)', 'Class:TriggerOnStateEnter+' => 'Trigger bei Eintritt einer Objektstatusänderung', -)); +]); // // Class: TriggerOnStateLeave // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:TriggerOnStateLeave' => 'Trigger (beim Verlassen eines Status)', 'Class:TriggerOnStateLeave+' => 'Trigger beim Verlassen einer Objektstatusänderung', -)); +]); // // Class: TriggerOnObjectCreate // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:TriggerOnObjectCreate' => 'Trigger (bei Objekterstellung)', 'Class:TriggerOnObjectCreate+' => 'Trigger bei Objekterstellung (einer Kindklasse) einer gegebenen Klasse', -)); +]); // // Class: TriggerOnObjectDelete // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:TriggerOnObjectDelete' => 'Trigger (bei Objektlöschung)', 'Class:TriggerOnObjectDelete+' => 'Trigger bei Objektlöschung einer gegebenen Klasse oder Kindklasse', -)); +]); // // Class: TriggerOnObjectUpdate // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:TriggerOnObjectUpdate' => 'Trigger (bei Objektanpassung)', 'Class:TriggerOnObjectUpdate+' => 'Trigger bei Objektanpassung einer gegebenen Klasse oder Kindklasse', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes' => 'Ziel-Felder', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes+' => '', -)); +]); // // Class: TriggerOnObjectMention // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:TriggerOnObjectMention' => 'Trigger (bei Objekterwähnung)', 'Class:TriggerOnObjectMention+' => 'Trigger bei Objekterwähnung (@xxx) einer Objekt mit [eine Kinderklasse von] eine gegebene Klasse in ein Log-Attribut', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter' => 'Filter für Objekterwähnung', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter+' => 'Einschränkung der Objekte welche diesen Trigger aktivieren. Wenn leer, wird er von jedem Objekt (beliebige Klasse) aktiviert.', -)); +]); // // Class: TriggerOnAttributeBlobDownload // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:TriggerOnAttributeBlobDownload' => 'Trigger (beim Herunterladen einer Datei eines Objekts)', 'Class:TriggerOnAttributeBlobDownload+' => 'Trigger für das Herunterladen einer Datei (Blob) der angegebenen Klasse oder einer Unterklasse', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes' => 'Ziel-Felder', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes+' => '', -)); +]); // // Class: TriggerOnThresholdReached // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:TriggerOnThresholdReached' => 'Trigger (bei Schwellenwert)', 'Class:TriggerOnThresholdReached+' => '', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code' => 'Uhr stoppen', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code+' => '', 'Class:TriggerOnThresholdReached/Attribute:threshold_index' => 'Schwellenwert', 'Class:TriggerOnThresholdReached/Attribute:threshold_index+' => '', -)); +]); // // Class: lnkTriggerAction // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:lnkTriggerAction' => 'Aktion/Trigger', 'Class:lnkTriggerAction+' => 'Verknüpfung zwischen einem Trigger und einer Aktion', 'Class:lnkTriggerAction/Attribute:action_id' => 'Aktion', @@ -761,12 +760,12 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Class:lnkTriggerAction/Attribute:trigger_name+' => '', 'Class:lnkTriggerAction/Attribute:order' => 'Reihenfolge', 'Class:lnkTriggerAction/Attribute:order+' => 'Reihenfolge der Aktionsausführungen', -)); +]); // // Synchro Data Source // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:SynchroDataSource' => 'Synchronisations-Datenquelle', 'Class:SynchroDataSource/Attribute:name' => 'Name', 'Class:SynchroDataSource/Attribute:name+' => '', @@ -1054,13 +1053,13 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Core:Validator:MustBeInteger' => 'Muss ein Integer sein', 'Core:Validator:MustSelectOne' => 'Min. ein Eintrag muss ausgewählt sein', 'Menu:DataSources' => 'Datenquellen für die Synchronisation', - 'Menu:DataSources+' => 'Alle Datenquellen für die Synchronisation' -)); + 'Menu:DataSources+' => 'Alle Datenquellen für die Synchronisation', +]); // // Class: TagSetFieldData // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:TagSetFieldData' => '%2$s für die Klasse %1$s', 'Class:TagSetFieldData+' => '', 'Class:TagSetFieldData/Attribute:code' => 'Code', @@ -1082,12 +1081,12 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Core:TagSetFieldData:ErrorAttCodeUpdateNotAllowed' => 'Tag "Attribute Code" kann nicht geändert werden', 'Core:TagSetFieldData:WhereIsThisTagTab' => 'Tag Verwendung (%1$d)', 'Core:TagSetFieldData:NoEntryFound' => 'Kein Eintrag für dieses Tag gefunden', -)); +]); // // Class: DBProperty // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:DBProperty' => 'DB Eigenschaft', 'Class:DBProperty+' => '', 'Class:DBProperty/Attribute:name' => 'Name', @@ -1100,12 +1099,12 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Class:DBProperty/Attribute:change_date+' => '', 'Class:DBProperty/Attribute:change_comment' => 'Änderungskommentar', 'Class:DBProperty/Attribute:change_comment+' => '', -)); +]); // // Class: BackgroundTask // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:BackgroundTask' => 'Hintergrund-Task', 'Class:BackgroundTask+' => '', 'Class:BackgroundTask/Attribute:class_name' => 'Klassenname', @@ -1130,12 +1129,12 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Class:BackgroundTask/Attribute:running+' => '', 'Class:BackgroundTask/Attribute:status' => 'Status', 'Class:BackgroundTask/Attribute:status+' => '', -)); +]); // // Class: AsyncTask // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:AsyncTask' => 'Async. Task', 'Class:AsyncTask+' => '', 'Class:AsyncTask/Attribute:created' => 'Erstellt', @@ -1160,47 +1159,44 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'Class:AsyncTask/Attribute:last_attempt+' => '', 'Class:AsyncTask:InvalidConfig_Class_Keys' => 'Ungültiges Format der Konfiguration für "async_task_retries[%1$s]". Erwartet wird ein Array mit den Schlüsseln: %2$s', 'Class:AsyncTask:InvalidConfig_Class_InvalidKey_Keys' => 'Ungültiges Format der Konfiguration für "async_task_retries[%1$s]": unerwarteter Schlüssel "%2$s". Erwartet werden nur die Schlüssel: %3$s', -)); +]); // // Class: AbstractResource // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:AbstractResource' => 'Abstrakte Ressource', 'Class:AbstractResource+' => '', -)); +]); // // Class: ResourceAdminMenu // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:ResourceAdminMenu' => 'Ressource "Admin Menü"', 'Class:ResourceAdminMenu+' => '', -)); +]); // // Class: ResourceRunQueriesMenu // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:ResourceRunQueriesMenu' => 'Ressource "Abfrage Ausführen Menü"', 'Class:ResourceRunQueriesMenu+' => '', -)); +]); // // Class: Action // -Dict::Add('DE DE', 'German', 'Deutsch', array( +Dict::Add('DE DE', 'German', 'Deutsch', [ 'Class:ResourceSystemMenu' => 'Ressource "System Menü"', 'Class:ResourceSystemMenu+' => '', - 'Class:EventNotification/Attribute:object_class' => 'Object class~~', - 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', + 'Class:EventNotification/Attribute:object_class' => 'Object class~~', + 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', 'Core:EventNotificationNewsroom:ErrorNotificationNotSent' => 'Notification not sent~~', 'Core:EventNotificationNewsroom:ErrorOnDBInsert' => 'An error occurred while saving the notification~~', -)); - - - +]); diff --git a/dictionaries/en.dictionary.itop.core.php b/dictionaries/en.dictionary.itop.core.php index 6e7851455..a03ab7a7e 100644 --- a/dictionaries/en.dictionary.itop.core.php +++ b/dictionaries/en.dictionary.itop.core.php @@ -1,4 +1,5 @@ */ -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Core:DeletedObjectLabel' => '%1s (deleted)', 'Core:DeletedObjectTip' => 'The object has been deleted on %1$s (%2$s)', @@ -215,8 +216,7 @@ Operators:
'Core:Context=GUI:Console' => 'Console', 'Core:Context=CRON' => 'cron', 'Core:Context=GUI:Portal' => 'Portal', -)); - +]); ////////////////////////////////////////////////////////////////////// // Classes in 'core/cmdb' @@ -227,7 +227,7 @@ Operators:
// Class: CMDBChange // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:CMDBChange' => 'Change', 'Class:CMDBChange+' => 'Changes tracking', 'Class:CMDBChange/Attribute:date' => 'date', @@ -242,13 +242,13 @@ Dict::Add('EN US', 'English', 'English', array( 'Class:CMDBChange/Attribute:origin/Value:webservice-rest' => 'REST/JSON webservices', 'Class:CMDBChange/Attribute:origin/Value:webservice-soap' => 'SOAP webservices', 'Class:CMDBChange/Attribute:origin/Value:custom-extension' => 'By an extension', -)); +]); // // Class: CMDBChangeOp // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:CMDBChangeOp' => 'Change Operation', 'Class:CMDBChangeOp+' => 'Change made by one person, at a single time, on a single object', 'Class:CMDBChangeOp/Attribute:change' => 'change', @@ -263,51 +263,51 @@ Dict::Add('EN US', 'English', 'English', array( 'Class:CMDBChangeOp/Attribute:objkey+' => 'id of the object on which the change was made', 'Class:CMDBChangeOp/Attribute:finalclass' => 'CMDBChangeOp sub-class', 'Class:CMDBChangeOp/Attribute:finalclass+' => 'type of change which was performed', -)); +]); // // Class: CMDBChangeOpCreate // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:CMDBChangeOpCreate' => 'object creation', 'Class:CMDBChangeOpCreate+' => 'Object creation tracking', -)); +]); // // Class: CMDBChangeOpDelete // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:CMDBChangeOpDelete' => 'object deletion', 'Class:CMDBChangeOpDelete+' => 'Object deletion tracking', -)); +]); // // Class: CMDBChangeOpSetAttribute // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:CMDBChangeOpSetAttribute' => 'object change', 'Class:CMDBChangeOpSetAttribute+' => 'Object properties change tracking', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode' => 'Attribute', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode+' => 'code of the modified property', -)); +]); // // Class: CMDBChangeOpSetAttributeScalar // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:CMDBChangeOpSetAttributeScalar' => 'property change', 'Class:CMDBChangeOpSetAttributeScalar+' => 'Object scalar properties change tracking', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue' => 'Previous value', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue+' => 'previous value of the attribute', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue' => 'New value', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue+' => 'new value of the attribute', -)); +]); // Used by CMDBChangeOp... & derived classes -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Change:ObjectCreated' => 'Object created', 'Change:ObjectDeleted' => 'Object deleted', 'Change:ObjectModified' => 'Object modified', @@ -324,35 +324,35 @@ Dict::Add('EN US', 'English', 'English', array( 'Change:LinkSet:Added' => 'added %1$s', 'Change:LinkSet:Removed' => 'removed %1$s', 'Change:LinkSet:Modified' => 'modified %1$s', -)); +]); // // Class: CMDBChangeOpSetAttributeBlob // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:CMDBChangeOpSetAttributeBlob' => 'data change', 'Class:CMDBChangeOpSetAttributeBlob+' => 'data change tracking', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata' => 'Previous data', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata+' => 'previous contents of the attribute', -)); +]); // // Class: CMDBChangeOpSetAttributeText // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:CMDBChangeOpSetAttributeText' => 'text change', 'Class:CMDBChangeOpSetAttributeText+' => 'text change tracking', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata' => 'Previous data', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata+' => 'previous contents of the attribute', -)); +]); // // Class: Event // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:Event' => 'Log Event', 'Class:Event+' => 'An application internal event', 'Class:Event/Attribute:message' => 'Message', @@ -363,13 +363,13 @@ Dict::Add('EN US', 'English', 'English', array( 'Class:Event/Attribute:userinfo+' => 'identification of the user that was doing the action that triggered this event', 'Class:Event/Attribute:finalclass' => 'Event sub-class', 'Class:Event/Attribute:finalclass+' => 'Name of the final class: specifies the sort of event which occurred', -)); +]); // // Class: EventNotification // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:EventNotification' => 'Notification sent', 'Class:EventNotification+' => 'Trace of a notification that has been sent', 'Class:EventNotification/Attribute:trigger_id' => 'Trigger', @@ -378,15 +378,15 @@ Dict::Add('EN US', 'English', 'English', array( 'Class:EventNotification/Attribute:action_id+' => '', 'Class:EventNotification/Attribute:object_id' => 'Object id', 'Class:EventNotification/Attribute:object_id+' => 'object id (class defined by the trigger ?)', - 'Class:EventNotification/Attribute:object_class' => 'Object class', - 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)', -)); + 'Class:EventNotification/Attribute:object_class' => 'Object class', + 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)', +]); // // Class: EventNotificationEmail // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:EventNotificationEmail' => 'Email sent', 'Class:EventNotificationEmail+' => 'Trace of an email that has been sent', 'Class:EventNotificationEmail/Attribute:to' => 'TO', @@ -403,13 +403,13 @@ Dict::Add('EN US', 'English', 'English', array( 'Class:EventNotificationEmail/Attribute:body+' => '', 'Class:EventNotificationEmail/Attribute:attachments' => 'Attachments', 'Class:EventNotificationEmail/Attribute:attachments+' => '', -)); +]); // // Class: EventIssue // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:EventIssue' => 'Issue event', 'Class:EventIssue+' => 'Trace of an issue (warning, error, etc.)', 'Class:EventIssue/Attribute:issue' => 'Issue', @@ -426,13 +426,13 @@ Dict::Add('EN US', 'English', 'English', array( 'Class:EventIssue/Attribute:callstack+' => '', 'Class:EventIssue/Attribute:data' => 'Data', 'Class:EventIssue/Attribute:data+' => 'More information', -)); +]); // // Class: EventWebService // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:EventWebService' => 'Web service event', 'Class:EventWebService+' => 'Trace of a web service call', 'Class:EventWebService/Attribute:verb' => 'Verb', @@ -447,9 +447,9 @@ Dict::Add('EN US', 'English', 'English', array( 'Class:EventWebService/Attribute:log_error+' => 'Result error log', 'Class:EventWebService/Attribute:data' => 'Data', 'Class:EventWebService/Attribute:data+' => 'Result data', -)); +]); -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:EventRestService' => 'REST/JSON call', 'Class:EventRestService+' => 'Trace of a REST/JSON service call', 'Class:EventRestService/Attribute:operation' => 'Operation', @@ -464,13 +464,13 @@ Dict::Add('EN US', 'English', 'English', array( 'Class:EventRestService/Attribute:json_output+' => 'HTTP response (json)', 'Class:EventRestService/Attribute:provider' => 'Provider', 'Class:EventRestService/Attribute:provider+' => 'PHP class implementing the expected operation', -)); +]); // // Class: EventLoginUsage // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:EventLoginUsage' => 'Login Usage', 'Class:EventLoginUsage+' => 'Connection to the application', 'Class:EventLoginUsage/Attribute:user_id' => 'Login', @@ -479,13 +479,13 @@ Dict::Add('EN US', 'English', 'English', array( 'Class:EventLoginUsage/Attribute:contact_name+' => '', 'Class:EventLoginUsage/Attribute:contact_email' => 'User Email', 'Class:EventLoginUsage/Attribute:contact_email+' => 'Email Address of the User', -)); +]); // // Class: EventNotificationNewsroom // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:EventNotificationNewsroom' => 'News sent', 'Class:EventNotificationNewsroom+' => '', 'Class:EventNotificationNewsroom/Attribute:title' => 'Title', @@ -516,13 +516,13 @@ Dict::Add('EN US', 'English', 'English', array( 'Class:EventNotificationNewsroom/Attribute:contact_id+' => '', 'Core:EventNotificationNewsroom:ErrorNotificationNotSent' => 'Notification not sent', 'Core:EventNotificationNewsroom:ErrorOnDBInsert' => 'An error occurred while saving the notification', -)); +]); // // Class: Action // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:Action' => 'Action', 'Class:Action+' => 'User defined action', 'Class:Action/ComplementaryName' => '%1$s: %2$s', @@ -552,24 +552,24 @@ Dict::Add('EN US', 'English', 'English', array( 'Action:last_executions_tab_panel_title' => 'Executions of this action (%1$s)', 'Action:last_executions_tab_limit_days' => 'past %1$s days', 'Action:last_executions_tab_limit_none' => 'no limit', -)); +]); // // Class: ActionNotification // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:ActionNotification' => 'Notification Action', 'Class:ActionNotification+' => 'Notification Action (abstract)', 'Class:ActionNotification/Attribute:language' => 'Language', 'Class:ActionNotification/Attribute:language+' => '', -)); +]); // // Class: ActionEmail // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:ActionEmail' => 'Notification by Email', 'Class:ActionEmail+' => '', 'Class:ActionEmail/Attribute:status+' => 'This status drives who will be notified: @@ -638,14 +638,13 @@ While editing, click on the magnifier to get pertinent examples', 'ActionEmail:preview_warning' => 'The actual eMail may look different in the eMail client than this preview in your browser.', 'ActionEmail:preview_more_info' => 'For more information about the CSS features supported by the different eMail clients, refer to %1$s', 'ActionEmail:content_placeholder_missing' => 'The placeholder "%1$s" was not found in the HTML template. The content of the field "%2$s" will not be included in the generated emails.', -)); - +]); // // Class: ActionNewsroom // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'ActionNewsroom:trigger' => 'Trigger', 'ActionNewsroom:content' => 'Message', 'ActionNewsroom:settings' => 'Settings', @@ -680,13 +679,13 @@ Dict::Add('EN US', 'English', 'English', array( 'Class:ActionNewsroom/Attribute:recipients+' => 'An OQL query returning Contact objects', 'Class:ActionNewsroom/Attribute:url' => 'URL', 'Class:ActionNewsroom/Attribute:url+' => 'By default, it points to the object triggering the notification. But you can also specify a custom URL.', -)); +]); // // Class: Trigger // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:Trigger' => 'Trigger', 'Class:Trigger+' => 'Custom event handler', 'Class:Trigger/ComplementaryName' => '%1$s, %2$s', @@ -705,13 +704,13 @@ Dict::Add('EN US', 'English', 'English', array( 'Class:Trigger/Attribute:subscription_policy/Value:allow_no_channel' => 'Allow complete unsubscription', 'Class:Trigger/Attribute:subscription_policy/Value:force_at_least_one_channel' => 'Force at least one channel (News or Email)', 'Class:Trigger/Attribute:subscription_policy/Value:force_all_channels' => 'Deny unsubscription', -)); +]); // // Class: TriggerOnObject // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:TriggerOnObject' => 'Trigger (class dependent)', 'Class:TriggerOnObject+' => 'Trigger on a given class of objects', 'Class:TriggerOnObject/Attribute:target_class' => 'Target class', @@ -720,115 +719,115 @@ Dict::Add('EN US', 'English', 'English', array( 'Class:TriggerOnObject/Attribute:filter+' => 'Limit the object list (of the target class) which will activate the trigger', 'TriggerOnObject:WrongFilterQuery' => 'Wrong filter query: %1$s', 'TriggerOnObject:WrongFilterClass' => 'The filter query must return objects of class "%1$s"', -)); +]); // // Class: TriggerOnPortalUpdate // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:TriggerOnPortalUpdate' => 'Trigger (when updated from the portal)', 'Class:TriggerOnPortalUpdate+' => 'Trigger on an end-user\'s update from the portal', -)); +]); // // Class: TriggerOnStateChange // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:TriggerOnStateChange' => 'Trigger (on state change)', 'Class:TriggerOnStateChange+' => 'Trigger on object state change', 'Class:TriggerOnStateChange/Attribute:state' => 'State', 'Class:TriggerOnStateChange/Attribute:state+' => '', -)); +]); // // Class: TriggerOnStateEnter // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:TriggerOnStateEnter' => 'Trigger (on entering a state)', 'Class:TriggerOnStateEnter+' => 'Trigger on object state change - entering', -)); +]); // // Class: TriggerOnStateLeave // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:TriggerOnStateLeave' => 'Trigger (on leaving a state)', 'Class:TriggerOnStateLeave+' => 'Trigger on object state change - leaving', -)); +]); // // Class: TriggerOnObjectCreate // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:TriggerOnObjectCreate' => 'Trigger (on object creation)', 'Class:TriggerOnObjectCreate+' => 'Trigger on object creation of [a child class of] the given class', -)); +]); // // Class: TriggerOnObjectDelete // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:TriggerOnObjectDelete' => 'Trigger (on object deletion)', 'Class:TriggerOnObjectDelete+' => 'Trigger on object deletion of [a child class of] the given class', -)); +]); // // Class: TriggerOnObjectUpdate // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:TriggerOnObjectUpdate' => 'Trigger (on object update)', 'Class:TriggerOnObjectUpdate+' => 'Trigger on object update of [a child class of] the given class', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes' => 'Target fields', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes+' => '', -)); +]); // // Class: TriggerOnObjectMention // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:TriggerOnObjectMention' => 'Trigger (on object mention)', 'Class:TriggerOnObjectMention+' => 'Trigger on mention (@xxx) of an object of [a child class of] the given class in a log attribute', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter' => 'Mentioned filter', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter+' => 'Limit the list of mentioned objects which will activate the trigger. If empty, any mentioned object (of any class) will activate it.', -)); +]); // // Class: TriggerOnAttributeBlobDownload // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:TriggerOnAttributeBlobDownload' => 'Trigger (on object\'s document download)', 'Class:TriggerOnAttributeBlobDownload+' => 'Trigger on object\'s document field download of [a child class of] the given class', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes' => 'Target fields', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes+' => '', -)); +]); // // Class: TriggerOnThresholdReached // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:TriggerOnThresholdReached' => 'Trigger (on threshold)', 'Class:TriggerOnThresholdReached+' => 'Trigger on Stop-Watch threshold reached', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code' => 'Stop watch', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code+' => '', 'Class:TriggerOnThresholdReached/Attribute:threshold_index' => 'Threshold', 'Class:TriggerOnThresholdReached/Attribute:threshold_index+' => '', -)); +]); // // Class: lnkTriggerAction // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:lnkTriggerAction' => 'Action/Trigger', 'Class:lnkTriggerAction+' => 'Link between a trigger and an action', 'Class:lnkTriggerAction/Attribute:action_id' => 'Action', @@ -841,12 +840,12 @@ Dict::Add('EN US', 'English', 'English', array( 'Class:lnkTriggerAction/Attribute:trigger_name+' => '', 'Class:lnkTriggerAction/Attribute:order' => 'Order', 'Class:lnkTriggerAction/Attribute:order+' => 'Actions execution order', -)); +]); // // Synchro Data Source // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:SynchroDataSource' => 'Synchro Data Source', 'Class:SynchroDataSource/Attribute:name' => 'Name', 'Class:SynchroDataSource/Attribute:name+' => '', @@ -1145,12 +1144,12 @@ The hyperlink is displayed in the tooltip appearing on the “Lock” symbol of 'Core:Validator:Mandatory' => 'Please, fill this field', 'Core:Validator:MustBeInteger' => 'Must be an integer', 'Core:Validator:MustSelectOne' => 'Please, select one', -)); +]); // // Class: TagSetFieldData // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:TagSetFieldData' => '%2$s for class %1$s', 'Class:TagSetFieldData+' => '', @@ -1174,12 +1173,12 @@ Dict::Add('EN US', 'English', 'English', array( 'Core:TagSetFieldData:ErrorAttCodeUpdateNotAllowed' => 'Tags "Attribute Code" cannot be changed', 'Core:TagSetFieldData:WhereIsThisTagTab' => 'Tag usage (%1$d)', 'Core:TagSetFieldData:NoEntryFound' => 'No entry found for this tag', -)); +]); // // Class: DBProperty // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:DBProperty' => 'DB property', 'Class:DBProperty+' => '', 'Class:DBProperty/Attribute:name' => 'Name', @@ -1192,12 +1191,12 @@ Dict::Add('EN US', 'English', 'English', array( 'Class:DBProperty/Attribute:change_date+' => '', 'Class:DBProperty/Attribute:change_comment' => 'Change comment', 'Class:DBProperty/Attribute:change_comment+' => '', -)); +]); // // Class: BackgroundTask // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:BackgroundTask' => 'Background task', 'Class:BackgroundTask+' => '', 'Class:BackgroundTask/Attribute:class_name' => 'Class name', @@ -1222,12 +1221,12 @@ Dict::Add('EN US', 'English', 'English', array( 'Class:BackgroundTask/Attribute:running+' => '', 'Class:BackgroundTask/Attribute:status' => 'Status', 'Class:BackgroundTask/Attribute:status+' => '', -)); +]); // // Class: AsyncTask // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:AsyncTask' => 'Async. task', 'Class:AsyncTask+' => '', 'Class:AsyncTask/Attribute:created' => 'Created', @@ -1250,45 +1249,42 @@ Dict::Add('EN US', 'English', 'English', array( 'Class:AsyncTask/Attribute:last_error+' => '', 'Class:AsyncTask/Attribute:last_attempt' => 'Last attempt', 'Class:AsyncTask/Attribute:last_attempt+' => '', - 'Class:AsyncTask:InvalidConfig_Class_Keys' => 'Invalid format for the configuration of "async_task_retries[%1$s]". Expecting an array with the following keys: %2$s', - 'Class:AsyncTask:InvalidConfig_Class_InvalidKey_Keys' => 'Invalid format for the configuration of "async_task_retries[%1$s]": unexpected key "%2$s". Expecting only the following keys: %3$s', -)); + 'Class:AsyncTask:InvalidConfig_Class_Keys' => 'Invalid format for the configuration of "async_task_retries[%1$s]". Expecting an array with the following keys: %2$s', + 'Class:AsyncTask:InvalidConfig_Class_InvalidKey_Keys' => 'Invalid format for the configuration of "async_task_retries[%1$s]": unexpected key "%2$s". Expecting only the following keys: %3$s', +]); // // Class: AbstractResource // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:AbstractResource' => 'Abstract Resource', 'Class:AbstractResource+' => '', -)); +]); // // Class: ResourceAdminMenu // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:ResourceAdminMenu' => 'Resource Admin Menu', 'Class:ResourceAdminMenu+' => '', -)); +]); // // Class: ResourceRunQueriesMenu // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:ResourceRunQueriesMenu' => 'Resource Run Queries Menu', 'Class:ResourceRunQueriesMenu+' => '', -)); +]); // // Class: Action // -Dict::Add('EN US', 'English', 'English', array( +Dict::Add('EN US', 'English', 'English', [ 'Class:ResourceSystemMenu' => 'Resource System Menu', 'Class:ResourceSystemMenu+' => '', -)); - - - +]); diff --git a/dictionaries/es_cr.dictionary.itop.core.php b/dictionaries/es_cr.dictionary.itop.core.php index 22f8beb01..27aecf970 100644 --- a/dictionaries/es_cr.dictionary.itop.core.php +++ b/dictionaries/es_cr.dictionary.itop.core.php @@ -1,13 +1,14 @@ - * @notas Utilizar codificación UTF-8 para mostrar acentos y otros caracteres especiales + * @notas Utilizar codificación UTF-8 para mostrar acentos y otros caracteres especiales */ -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Core:DeletedObjectLabel' => '%1s (eliminado)', 'Core:DeletedObjectTip' => 'Elemento ha sido Eliminado en %1$s (%2$s)', 'Core:UnknownObjectLabel' => 'Elemento No Encontrado (Clase: %1$s, Identificador: %2$d)', @@ -155,8 +156,7 @@ Operadores:
'Core:Context=GUI:Console' => 'Consola', 'Core:Context=CRON' => 'cron', 'Core:Context=GUI:Portal' => 'Portal', -)); - +]); ////////////////////////////////////////////////////////////////////// // Classes in 'core/cmdb' @@ -167,7 +167,7 @@ Operadores:
// Class: CMDBChange // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:CMDBChange' => 'Cambio', 'Class:CMDBChange+' => 'Cambios', 'Class:CMDBChange/Attribute:date' => 'Fecha', @@ -182,13 +182,13 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Class:CMDBChange/Attribute:origin/Value:webservice-rest' => 'REST/JSON webservices', 'Class:CMDBChange/Attribute:origin/Value:webservice-soap' => 'SOAP webservices', 'Class:CMDBChange/Attribute:origin/Value:custom-extension' => 'Por una extensión', -)); +]); // // Class: CMDBChangeOp // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:CMDBChangeOp' => 'Operación de Cambios', 'Class:CMDBChangeOp+' => 'Operación de Cambios', 'Class:CMDBChangeOp/Attribute:change' => 'Cambio', @@ -203,51 +203,51 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Class:CMDBChangeOp/Attribute:objkey+' => 'Id de Objeto', 'Class:CMDBChangeOp/Attribute:finalclass' => 'Clase', 'Class:CMDBChangeOp/Attribute:finalclass+' => 'Clase', -)); +]); // // Class: CMDBChangeOpCreate // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:CMDBChangeOpCreate' => 'Creación de Objeto', 'Class:CMDBChangeOpCreate+' => 'Creación de Objeto', -)); +]); // // Class: CMDBChangeOpDelete // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:CMDBChangeOpDelete' => 'Borrado de Objeto', 'Class:CMDBChangeOpDelete+' => 'Borrado de Objeto', -)); +]); // // Class: CMDBChangeOpSetAttribute // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:CMDBChangeOpSetAttribute' => 'Cambio en Objeto', 'Class:CMDBChangeOpSetAttribute+' => 'Cambio en Objeto', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode' => 'Atributo', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode+' => 'Código de la propiedad modificada', -)); +]); // // Class: CMDBChangeOpSetAttributeScalar // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:CMDBChangeOpSetAttributeScalar' => 'Cambio de Propiedad', 'Class:CMDBChangeOpSetAttributeScalar+' => 'Cambio de Propiedades escalares del Objeto', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue' => 'Valor Anterior', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue+' => 'valor Anterior del Atributo', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue' => 'Nuevo Valor', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue+' => 'Nuevo Valor del Atributo', -)); +]); // Used by CMDBChangeOp... & derived classes -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Change:ObjectCreated' => 'Objeto Creado', 'Change:ObjectDeleted' => 'Objeto Eliminado', 'Change:ObjectModified' => 'Objeto Modificado', @@ -264,35 +264,35 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Change:LinkSet:Added' => 'Agregado %1$s', 'Change:LinkSet:Removed' => 'Removido %1$s', 'Change:LinkSet:Modified' => 'Modificado %1$s', -)); +]); // // Class: CMDBChangeOpSetAttributeBlob // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:CMDBChangeOpSetAttributeBlob' => 'Cambio de Datos', 'Class:CMDBChangeOpSetAttributeBlob+' => 'Cambio de Datos', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata' => 'Valor Anterior', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata+' => 'Valor Anterior del Atributo', -)); +]); // // Class: CMDBChangeOpSetAttributeText // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:CMDBChangeOpSetAttributeText' => 'Cambio de Texto', 'Class:CMDBChangeOpSetAttributeText+' => 'Cambio de Texto', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata' => 'Valor Anterior', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata+' => 'Valor Anterior del Atributo', -)); +]); // // Class: Event // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:Event' => 'Bitácora de Eventos', 'Class:Event+' => 'Evento interno de aplicación', 'Class:Event/Attribute:message' => 'Mensaje', @@ -303,13 +303,13 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Class:Event/Attribute:userinfo+' => 'Indentificación de la actividad que realizaba el usuario durante la cual se disparó este evento', 'Class:Event/Attribute:finalclass' => 'Clase', 'Class:Event/Attribute:finalclass+' => 'Clase', -)); +]); // // Class: EventNotification // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:EventNotification' => 'Notificación de Evento', 'Class:EventNotification+' => 'Notificación de Evento', 'Class:EventNotification/Attribute:trigger_id' => 'Disparador', @@ -318,13 +318,13 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Class:EventNotification/Attribute:action_id+' => 'Cuenta de usuario', 'Class:EventNotification/Attribute:object_id' => 'Id de Objeto', 'Class:EventNotification/Attribute:object_id+' => 'Id de objeto (¿clase definida por el disparador?)', -)); +]); // // Class: EventNotificationEmail // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:EventNotificationEmail' => 'Correo Electrónico de Notificación de Evento', 'Class:EventNotificationEmail+' => 'Correo Electrónico de Notificación de Evento', 'Class:EventNotificationEmail/Attribute:to' => 'Para', @@ -341,13 +341,13 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Class:EventNotificationEmail/Attribute:body+' => 'Cuerpo del mensaje', 'Class:EventNotificationEmail/Attribute:attachments' => 'Anexos', 'Class:EventNotificationEmail/Attribute:attachments+' => 'Anexos', -)); +]); // // Class: EventIssue // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:EventIssue' => 'Registro de Evento', 'Class:EventIssue+' => 'Evidencia de un evento (warning, error, etc.)', 'Class:EventIssue/Attribute:issue' => 'Evento', @@ -364,13 +364,13 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Class:EventIssue/Attribute:callstack+' => 'Pila de llamadas', 'Class:EventIssue/Attribute:data' => 'Datos', 'Class:EventIssue/Attribute:data+' => 'Más información', -)); +]); // // Class: EventWebService // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:EventWebService' => 'Evento de WebService', 'Class:EventWebService+' => 'Evidencia de una llamada de servicio Web', 'Class:EventWebService/Attribute:verb' => 'Verbo', @@ -385,9 +385,9 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Class:EventWebService/Attribute:log_error+' => 'Bitácora de Error de Resultado', 'Class:EventWebService/Attribute:data' => 'Datos', 'Class:EventWebService/Attribute:data+' => 'Datos de Resultado', -)); +]); -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:EventRestService' => 'Llamada REST/JSON', 'Class:EventRestService+' => 'Traza de llamada a servicio REST/JSON', 'Class:EventRestService/Attribute:operation' => 'Operación', @@ -402,13 +402,13 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Class:EventRestService/Attribute:json_output+' => 'respuesta HTTP (json)', 'Class:EventRestService/Attribute:provider' => 'Proveedor', 'Class:EventRestService/Attribute:provider+' => 'Clase PHP implementando la operación esperada', -)); +]); // // Class: EventLoginUsage // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:EventLoginUsage' => 'Uso de la Cuenta', 'Class:EventLoginUsage+' => 'Uso de la Cuenta', 'Class:EventLoginUsage/Attribute:user_id' => 'Usuario', @@ -417,13 +417,13 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Class:EventLoginUsage/Attribute:contact_name+' => 'Nombre', 'Class:EventLoginUsage/Attribute:contact_email' => 'Correo Electrónico', 'Class:EventLoginUsage/Attribute:contact_email+' => 'Correo Electrónico del usuario', -)); +]); // // Class: EventNotificationNewsroom // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:EventNotificationNewsroom' => 'Noticias enviadas', 'Class:EventNotificationNewsroom+' => 'Noticias enviadas', 'Class:EventNotificationNewsroom/Attribute:title' => 'Título', @@ -452,13 +452,13 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Class:EventNotificationNewsroom/Attribute:read_date+' => 'Fecha lectura', 'Class:EventNotificationNewsroom/Attribute:contact_id' => 'Contacto', 'Class:EventNotificationNewsroom/Attribute:contact_id+' => 'Contacto', -)); +]); // // Class: Action // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:Action' => 'Acción Personalizada', 'Class:Action+' => 'Acción definida por el usuario', 'Class:Action/ComplementaryName' => '%1$s: %2$s', @@ -488,22 +488,22 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Action:last_executions_tab_panel_title' => 'Ejecuciones de esta acción (%1$s)', 'Action:last_executions_tab_limit_days' => 'últimos %1$s días', 'Action:last_executions_tab_limit_none' => 'Sin límite', -)); +]); // // Class: ActionNotification // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:ActionNotification' => 'Notificación', 'Class:ActionNotification+' => 'Notificación (resúmen)', -)); +]); // // Class: ActionEmail // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:ActionEmail' => 'Notificación por Correo Electrónico', 'Class:ActionEmail+' => 'Notificación por Correo Electrónico', 'Class:ActionEmail/Attribute:status+' => 'Este estatus determina quién será notificado: Sólo el destinatario de la prueba, todos (Para, CC y CCO) o nadie', @@ -554,14 +554,13 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'ActionEmail:preview_warning' => 'El correo electrónico real puede verse diferente en el cliente de correo electrónico que esta vista previa en su navegador.', 'ActionEmail:preview_more_info' => 'Para obtener más información sobre las funciones CSS admitidas por los diferentes clientes de correo electrónico, consulte %1$s', 'ActionEmail:content_placeholder_missing' => 'El marcador de posición "%1$s" no se encontró en la plantilla HTML. El contenido del campo "%2$s" no se incluirá en los correos electrónicos generados.', -)); - +]); // // Class: ActionNewsroom // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'ActionNewsroom:trigger' => 'Disparador', 'ActionNewsroom:content' => 'Mensaje', 'ActionNewsroom:settings' => 'Configuración', @@ -590,14 +589,14 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Class:ActionNewsroom/Attribute:recipients' => 'Destinatarios', 'Class:ActionNewsroom/Attribute:recipients+' => 'Destinatarios', 'Class:ActionNewsroom/Attribute:url' => 'URL', - 'Class:ActionNewsroom/Attribute:url+' => 'URL' -)); + 'Class:ActionNewsroom/Attribute:url+' => 'URL', +]); // // Class: Trigger // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:Trigger' => 'Disparador', 'Class:Trigger+' => 'Disparador', 'Class:Trigger/ComplementaryName' => '%1$s, %2$s', @@ -616,13 +615,13 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Class:Trigger/Attribute:subscription_policy/Value:allow_no_channel' => 'Permitir baja completa', 'Class:Trigger/Attribute:subscription_policy/Value:force_at_least_one_channel' => 'Forzar al menos un canal (Noticias o Correo electrónico)', 'Class:Trigger/Attribute:subscription_policy/Value:force_all_channels' => 'Denegar baja de suscripción', -)); +]); // // Class: TriggerOnObject // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:TriggerOnObject' => 'Disparador (Depende de la clase)', 'Class:TriggerOnObject+' => 'Disparador en una clase de objeto dada', 'Class:TriggerOnObject/Attribute:target_class' => 'Clase destino', @@ -631,115 +630,115 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Class:TriggerOnObject/Attribute:filter+' => '', 'TriggerOnObject:WrongFilterQuery' => 'Filtro de consulta incorrecto: %1$s', 'TriggerOnObject:WrongFilterClass' => 'El filtro de consulta debe regresar un objeto de la clase \\"%1$s\\"', -)); +]); // // Class: TriggerOnPortalUpdate // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:TriggerOnPortalUpdate' => 'Disparador (cuando se actualiza desde el portal)', 'Class:TriggerOnPortalUpdate+' => 'Disparador cuando un usuario actualiza desde el portal', -)); +]); // // Class: TriggerOnStateChange // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:TriggerOnStateChange' => 'Disparador (en cambio de estado)', 'Class:TriggerOnStateChange+' => 'Disparador en cambio de estado de objeto', 'Class:TriggerOnStateChange/Attribute:state' => 'Estado', 'Class:TriggerOnStateChange/Attribute:state+' => 'Estado', -)); +]); // // Class: TriggerOnStateEnter // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:TriggerOnStateEnter' => 'Disparador (entrando a un estado)', 'Class:TriggerOnStateEnter+' => 'Disparador en cambio de estado de objeto - entrando', -)); +]); // // Class: TriggerOnStateLeave // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:TriggerOnStateLeave' => 'Disparador (saliendo de un estado)', 'Class:TriggerOnStateLeave+' => 'Disparador en cambio de estado de objeto - saliendo', -)); +]); // // Class: TriggerOnObjectCreate // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:TriggerOnObjectCreate' => 'Disparador (creación de objeto)', 'Class:TriggerOnObjectCreate+' => 'Disparador en la creación de objeto (hija de clase) de una clase dada', -)); +]); // // Class: TriggerOnObjectDelete // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:TriggerOnObjectDelete' => 'Disparador (eliminando un objecto)', 'Class:TriggerOnObjectDelete+' => 'Disparador al eliminar un objecto de la clase dada [o una clase hija] ', -)); +]); // // Class: TriggerOnObjectUpdate // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:TriggerOnObjectUpdate' => 'Disparador (actualizando un objecto)', 'Class:TriggerOnObjectUpdate+' => 'Disparador al actualizar un objeto de la clase dada [o una clase hija]', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes' => 'Campos objetivo', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes+' => 'Campos que serán monitorizados', -)); +]); // // Class: TriggerOnObjectMention // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:TriggerOnObjectMention' => 'Disparador (en mención de objeto)', 'Class:TriggerOnObjectMention+' => 'Disparador en mención (@xxx) de un objeto de [clase hijo de] clase dada en un registro de atributo', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter' => 'Filtro mencionado', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter+' => 'Limite la lista de objetos mencionados que activarán el disparador. Si está vacío, cualquier objeto mencionado (de cualquier clase) lo activará.', -)); +]); // // Class: TriggerOnAttributeBlobDownload // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:TriggerOnAttributeBlobDownload' => 'Disparador (al descargar el documento del objeto)', 'Class:TriggerOnAttributeBlobDownload+' => 'Disparador en la descarga del campo de documento del objeto de [una clase secundaria de] la clase dada', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes' => 'Campos de destino', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes+' => 'Campos de destino', -)); +]); // // Class: TriggerOnThresholdReached // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:TriggerOnThresholdReached' => 'Disparador (en umbral)', 'Class:TriggerOnThresholdReached+' => 'Disparador en umbral Stop-Watch alcanzado', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code' => 'Detener watch', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code+' => 'Detener watch', 'Class:TriggerOnThresholdReached/Attribute:threshold_index' => 'Umbral', 'Class:TriggerOnThresholdReached/Attribute:threshold_index+' => 'Umbral', -)); +]); // // Class: lnkTriggerAction // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:lnkTriggerAction' => 'Relación Acción y Disparador', 'Class:lnkTriggerAction+' => 'Relación Acción y Disparador', 'Class:lnkTriggerAction/Attribute:action_id' => 'Acción', @@ -752,12 +751,12 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Class:lnkTriggerAction/Attribute:trigger_name+' => 'Disparador', 'Class:lnkTriggerAction/Attribute:order' => 'Orden', 'Class:lnkTriggerAction/Attribute:order+' => 'Orden de realización de acciones', -)); +]); // // Synchro Data Source // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:SynchroDataSource' => 'Fuente de Datos Sincronizable', 'Class:SynchroDataSource/Attribute:name' => 'Nombre', 'Class:SynchroDataSource/Attribute:name+' => 'Nombre de la Fuente de Datos', @@ -1045,13 +1044,13 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Core:Validator:MustBeInteger' => 'Debe ser un entero', 'Core:Validator:MustSelectOne' => 'Por favor, seleccione uno', 'Menu:DataSources' => 'Fuentes de Datos Sincronizables', - 'Menu:DataSources+' => 'Fuentes de Datos Sincronizables' -)); + 'Menu:DataSources+' => 'Fuentes de Datos Sincronizables', +]); // // Class: TagSetFieldData // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:TagSetFieldData' => '%2$s para la clase %1$s', 'Class:TagSetFieldData+' => 'Datos de campo', 'Class:TagSetFieldData/Attribute:code' => 'Código', @@ -1073,12 +1072,12 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Core:TagSetFieldData:ErrorAttCodeUpdateNotAllowed' => 'Etiquetas "Attribute Code" no pueden ser cambiadas', 'Core:TagSetFieldData:WhereIsThisTagTab' => 'Uso de la etiqueta (%1$d)', 'Core:TagSetFieldData:NoEntryFound' => 'No hay entradas para esta etiqueta', -)); +]); // // Class: DBProperty // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:DBProperty' => 'Propiedad BD', 'Class:DBProperty+' => 'Propiedad de Base de Datos', 'Class:DBProperty/Attribute:name' => 'Nombre', @@ -1091,12 +1090,12 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Class:DBProperty/Attribute:change_date+' => 'Fecha de Cambio', 'Class:DBProperty/Attribute:change_comment' => 'Comentario Cambio', 'Class:DBProperty/Attribute:change_comment+' => 'Comentario del Cambio', -)); +]); // // Class: BackgroundTask // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:BackgroundTask' => 'Tarea en Segundo Plano', 'Class:BackgroundTask+' => 'Tarea en Segundo Plano', 'Class:BackgroundTask/Attribute:class_name' => 'Nombre de Clase', @@ -1121,12 +1120,12 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Class:BackgroundTask/Attribute:running+' => 'Indicador de proceso en Ejecución', 'Class:BackgroundTask/Attribute:status' => 'Estatus', 'Class:BackgroundTask/Attribute:status+' => 'Estatus', -)); +]); // // Class: AsyncTask // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:AsyncTask' => 'Tarea Asíncrona', 'Class:AsyncTask+' => 'Tarea Asíncrona', 'Class:AsyncTask/Attribute:created' => 'Creado', @@ -1151,47 +1150,44 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'Class:AsyncTask/Attribute:last_attempt+' => 'Último intento', 'Class:AsyncTask:InvalidConfig_Class_Keys' => 'Formato no válido para la configuración de "async_taks_retries[%1$s]". Esperando una matriz con las siguientes claves: %2$s', 'Class:AsyncTask:InvalidConfig_Class_InvalidKey_Keys' => 'Formato no válido para la configuración de "async_taks_retries[%1$s]": llave inesperada "%2$s". Esperando solo las siguientes llaves: %3$s', -)); +]); // // Class: AbstractResource // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:AbstractResource' => 'Recurso abstracto', 'Class:AbstractResource+' => 'Recurso abstracto', -)); +]); // // Class: ResourceAdminMenu // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:ResourceAdminMenu' => 'Recursos de Menú de Administración', 'Class:ResourceAdminMenu+' => '', -)); +]); // // Class: ResourceRunQueriesMenu // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:ResourceRunQueriesMenu' => 'Recurso Libreta de Consultas', 'Class:ResourceRunQueriesMenu+' => '', -)); +]); // // Class: Action // -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'Class:ResourceSystemMenu' => 'Recurso Menú de Sistema', 'Class:ResourceSystemMenu+' => '', 'Class:EventNotification/Attribute:object_class' => 'Object class~~', - 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', + 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', 'Core:EventNotificationNewsroom:ErrorNotificationNotSent' => 'Notification not sent~~', 'Core:EventNotificationNewsroom:ErrorOnDBInsert' => 'An error occurred while saving the notification~~', -)); - - - +]); diff --git a/dictionaries/fr.dictionary.itop.core.php b/dictionaries/fr.dictionary.itop.core.php index b09979427..bebafc8ba 100644 --- a/dictionaries/fr.dictionary.itop.core.php +++ b/dictionaries/fr.dictionary.itop.core.php @@ -1,15 +1,16 @@ '%1s (effacé)', 'Core:DeletedObjectTip' => 'L\'objet a été effacé le %1$s (%2$s)', 'Core:UnknownObjectLabel' => 'Classe: %1$s, Identifiant: %2$d', @@ -159,9 +160,8 @@ Opérateurs :
'Core:Context=CRON' => 'cron', 'Core:Context=CRON+' => 'cron', 'Core:Context=GUI:Portal' => 'Portal', - 'Core:Context=GUI:Portal+' => 'GUI:Portal' -)); - + 'Core:Context=GUI:Portal+' => 'GUI:Portal', +]); ////////////////////////////////////////////////////////////////////// // Classes in 'core/cmdb' @@ -172,7 +172,7 @@ Opérateurs :
// Class: CMDBChange // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:CMDBChange' => 'Modification', 'Class:CMDBChange+' => '', 'Class:CMDBChange/Attribute:date' => 'Date', @@ -187,13 +187,13 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Class:CMDBChange/Attribute:origin/Value:webservice-rest' => 'Webservices REST/JSON', 'Class:CMDBChange/Attribute:origin/Value:webservice-soap' => 'Webservices SOAP', 'Class:CMDBChange/Attribute:origin/Value:custom-extension' => 'Par une extension', -)); +]); // // Class: CMDBChangeOp // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:CMDBChangeOp' => 'Operation de changement', 'Class:CMDBChangeOp+' => '', 'Class:CMDBChangeOp/Attribute:change' => 'Modification', @@ -208,51 +208,51 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Class:CMDBChangeOp/Attribute:objkey+' => '', 'Class:CMDBChangeOp/Attribute:finalclass' => 'Type', 'Class:CMDBChangeOp/Attribute:finalclass+' => 'Nom de la classe instanciable', -)); +]); // // Class: CMDBChangeOpCreate // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:CMDBChangeOpCreate' => 'Création de l\'objet', 'Class:CMDBChangeOpCreate+' => '', -)); +]); // // Class: CMDBChangeOpDelete // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:CMDBChangeOpDelete' => 'Effacement de l\'objet', 'Class:CMDBChangeOpDelete+' => '', -)); +]); // // Class: CMDBChangeOpSetAttribute // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:CMDBChangeOpSetAttribute' => 'Modification de l\'objet', 'Class:CMDBChangeOpSetAttribute+' => '', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode' => 'Champ', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode+' => '', -)); +]); // // Class: CMDBChangeOpSetAttributeScalar // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:CMDBChangeOpSetAttributeScalar' => 'Modification de valeur', 'Class:CMDBChangeOpSetAttributeScalar+' => '', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue' => 'Ancienne valeur', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue+' => '', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue' => 'Nouvelle valeur', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue+' => '', -)); +]); // Used by CMDBChangeOp... & derived classes -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Change:ObjectCreated' => 'Elément créé', 'Change:ObjectDeleted' => 'Elément effacé', 'Change:ObjectModified' => 'Elément modifié', @@ -269,35 +269,35 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Change:LinkSet:Added' => 'ajout de %1$s', 'Change:LinkSet:Removed' => 'suppression de %1$s', 'Change:LinkSet:Modified' => 'modification de %1$s', -)); +]); // // Class: CMDBChangeOpSetAttributeBlob // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:CMDBChangeOpSetAttributeBlob' => 'Modification de données', 'Class:CMDBChangeOpSetAttributeBlob+' => '', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata' => 'Ancienne valeur', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata+' => '', -)); +]); // // Class: CMDBChangeOpSetAttributeText // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:CMDBChangeOpSetAttributeText' => 'Modification de texte', 'Class:CMDBChangeOpSetAttributeText+' => '', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata' => 'Ancienne valeur', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata+' => '', -)); +]); // // Class: Event // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:Event' => 'Evènement', 'Class:Event+' => '', 'Class:Event/Attribute:message' => 'Message', @@ -308,13 +308,13 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Class:Event/Attribute:userinfo+' => '', 'Class:Event/Attribute:finalclass' => 'Sous-classe d\'évènement', 'Class:Event/Attribute:finalclass+' => 'Nom de la classe instanciable', -)); +]); // // Class: EventNotification // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:EventNotification' => 'Notification envoyée', 'Class:EventNotification+' => '', 'Class:EventNotification/Attribute:trigger_id' => 'Déclencheur', @@ -323,13 +323,13 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Class:EventNotification/Attribute:action_id+' => '', 'Class:EventNotification/Attribute:object_id' => 'Identifiant de l\'objet', 'Class:EventNotification/Attribute:object_id+' => '', -)); +]); // // Class: EventNotificationEmail // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:EventNotificationEmail' => 'Envoi d\'Email', 'Class:EventNotificationEmail+' => '', 'Class:EventNotificationEmail/Attribute:to' => 'A', @@ -346,13 +346,13 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Class:EventNotificationEmail/Attribute:body+' => '', 'Class:EventNotificationEmail/Attribute:attachments' => 'Pièces jointes', 'Class:EventNotificationEmail/Attribute:attachments+' => '', -)); +]); // // Class: EventIssue // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:EventIssue' => 'Erreur', 'Class:EventIssue+' => '', 'Class:EventIssue/Attribute:issue' => 'Erreur', @@ -369,13 +369,13 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Class:EventIssue/Attribute:callstack+' => '', 'Class:EventIssue/Attribute:data' => 'Données', 'Class:EventIssue/Attribute:data+' => '', -)); +]); // // Class: EventWebService // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:EventWebService' => 'Appel de webservice', 'Class:EventWebService+' => '', 'Class:EventWebService/Attribute:verb' => 'Verbe', @@ -390,9 +390,9 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Class:EventWebService/Attribute:log_error+' => '', 'Class:EventWebService/Attribute:data' => 'Données', 'Class:EventWebService/Attribute:data+' => '', -)); +]); -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:EventRestService' => 'Appel REST/JSON', 'Class:EventRestService+' => 'Trace de l\'appel au service REST/JSON (rest.php)', 'Class:EventRestService/Attribute:operation' => 'Opération', @@ -407,13 +407,13 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Class:EventRestService/Attribute:json_output+' => 'Réponse HTTP (structure json)', 'Class:EventRestService/Attribute:provider' => 'Fournisseur', 'Class:EventRestService/Attribute:provider+' => 'Classe PHP qui a pris en charge l\'opération demandée', -)); +]); // // Class: EventLoginUsage // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:EventLoginUsage' => 'Utilisation de l\'application', 'Class:EventLoginUsage+' => '', 'Class:EventLoginUsage/Attribute:user_id' => 'Login', @@ -422,13 +422,13 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Class:EventLoginUsage/Attribute:contact_name+' => '', 'Class:EventLoginUsage/Attribute:contact_email' => 'Email', 'Class:EventLoginUsage/Attribute:contact_email+' => '', -)); +]); // // Class: EventNotificationNewsroom // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:EventNotificationNewsroom' => 'News envoyée', 'Class:EventNotificationNewsroom+' => '', 'Class:EventNotificationNewsroom/Attribute:title' => 'Titre', @@ -457,13 +457,13 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Class:EventNotificationNewsroom/Attribute:read_date+' => '', 'Class:EventNotificationNewsroom/Attribute:contact_id' => 'Contact', 'Class:EventNotificationNewsroom/Attribute:contact_id+' => '', -)); +]); // // Class: Action // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:Action' => 'Action', 'Class:Action+' => 'Action spécifique', 'Class:Action/ComplementaryName' => '%1$s: %2$s', @@ -493,24 +493,24 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Action:last_executions_tab_panel_title' => 'Exécutions de cette action (%1$s)', 'Action:last_executions_tab_limit_days' => '%1$s derniers jours', 'Action:last_executions_tab_limit_none' => 'depuis sa création', -)); +]); // // Class: ActionNotification // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:ActionNotification' => 'Action de notification', 'Class:ActionNotification+' => '', 'Class:ActionNotification/Attribute:language' => 'Langue', 'Class:ActionNotification/Attribute:language+' => '', -)); +]); // // Class: ActionEmail // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:ActionEmail' => 'Notification par mél', 'Class:ActionEmail+' => '', 'Class:ActionEmail/Attribute:status+' => 'Cet état définit qui va être notifié: @@ -583,14 +583,13 @@ En édition, cliquez sur la loupe pour obtenir des exemples pertinents.', 'ActionEmail:preview_warning' => 'Le mèl peut s\'afficher différement dans les clients mèl par rapport à cet aperçu dans votre navigateur.', 'ActionEmail:preview_more_info' => 'Pour plus d\'informations sur les fonctionnalités CSS supportées par les différents client mèl, consultez %1$s.', 'ActionEmail:content_placeholder_missing' => 'The mot-clé "%1$s" ne figure pas dans le modèle HTML. Le contenu du champ "%2$s" ne sera pas intégré dans les mèls générés.', -)); - +]); // // Class: ActionNewsroom // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'ActionNewsroom:trigger' => 'Conditions de déclenchement', 'ActionNewsroom:content' => 'Message', 'ActionNewsroom:settings' => 'Paramètres', @@ -625,13 +624,13 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Class:ActionNewsroom/Attribute:recipients+' => 'Une requête OQL retournant les des objets de type Contact', 'Class:ActionNewsroom/Attribute:url' => 'URL', 'Class:ActionNewsroom/Attribute:url+' => 'Par défaut, l\'URL pointe vers l\'objet ayant déclenché la notification. Mais vous pouvez également spécifier une URL personnalisée.', -)); +]); // // Class: Trigger // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:Trigger' => 'Déclencheur', 'Class:Trigger+' => '', 'Class:Trigger/ComplementaryName' => '%1$s, %2$s', @@ -650,13 +649,13 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Class:Trigger/Attribute:subscription_policy/Value:allow_no_channel' => 'Autoriser la désinscription de tous les canaux', 'Class:Trigger/Attribute:subscription_policy/Value:force_at_least_one_channel' => 'Forcer la conservation d\'un canal (News ou Email)', 'Class:Trigger/Attribute:subscription_policy/Value:force_all_channels' => 'Interdire la désinscription', -)); +]); // // Class: TriggerOnObject // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:TriggerOnObject' => 'Déclencheur sur modification de données', 'Class:TriggerOnObject+' => '', 'Class:TriggerOnObject/Attribute:target_class' => 'Classe cible', @@ -665,115 +664,115 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Class:TriggerOnObject/Attribute:filter+' => 'Permet de limiter la liste des objets (de la classe cible) activant le déclencheur', 'TriggerOnObject:WrongFilterQuery' => 'Requête de filtrage incorrecte: %1$s', 'TriggerOnObject:WrongFilterClass' => 'La requête de filtrage doit retourner des objets de la classe "%1$s"', -)); +]); // // Class: TriggerOnPortalUpdate // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:TriggerOnPortalUpdate' => 'Déclencheur sur mise à jour depuis le portail', 'Class:TriggerOnPortalUpdate+' => '', -)); +]); // // Class: TriggerOnStateChange // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:TriggerOnStateChange' => 'Déclencheur sur changement d\'état', 'Class:TriggerOnStateChange+' => '', 'Class:TriggerOnStateChange/Attribute:state' => 'Etat', 'Class:TriggerOnStateChange/Attribute:state+' => '', -)); +]); // // Class: TriggerOnStateEnter // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:TriggerOnStateEnter' => 'Déclencheur sur un objet entrant dans un état', 'Class:TriggerOnStateEnter+' => '', -)); +]); // // Class: TriggerOnStateLeave // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:TriggerOnStateLeave' => 'Déclencheur sur un objet quittant un état', 'Class:TriggerOnStateLeave+' => '', -)); +]); // // Class: TriggerOnObjectCreate // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:TriggerOnObjectCreate' => 'Déclencheur sur la création d\'un objet', 'Class:TriggerOnObjectCreate+' => '', -)); +]); // // Class: TriggerOnObjectDelete // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:TriggerOnObjectDelete' => 'Déclencheur sur la suppression d\'un objet', 'Class:TriggerOnObjectDelete+' => '', -)); +]); // // Class: TriggerOnObjectUpdate // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:TriggerOnObjectUpdate' => 'Déclencheur sur la modification d\'un objet', 'Class:TriggerOnObjectUpdate+' => '', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes' => 'Attributs cible', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes+' => '', -)); +]); // // Class: TriggerOnObjectMention // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:TriggerOnObjectMention' => 'Déclencheur sur mention d\'objet', 'Class:TriggerOnObjectMention+' => 'Déclencheur sur un objet mentionné (@xxx) de la classe choisie (ou de ses filles) dans un attribut de type journal', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter' => 'Objets mentionnés', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter+' => 'Permet de limiter la liste des objets mentionnés pour lesquels le déclencheur s\'activera. Si vide, n\'importe quel objet mentionné (de n\'importe quelle classe) l\'activera.', -)); +]); // // Class: TriggerOnAttributeBlobDownload // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:TriggerOnAttributeBlobDownload' => 'Déclencheur sur le téléchargement d\'un document d\'un objet', 'Class:TriggerOnAttributeBlobDownload+' => '', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes' => 'Attributs cible', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes+' => '', -)); +]); // // Class: TriggerOnThresholdReached // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:TriggerOnThresholdReached' => 'Déclencheur sur dépassement de seuil', 'Class:TriggerOnThresholdReached+' => 'Déclencheur sur franchissement de seuil d\'un chronomètre', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code' => 'Chronomètre', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code+' => '', 'Class:TriggerOnThresholdReached/Attribute:threshold_index' => 'Seuil', 'Class:TriggerOnThresholdReached/Attribute:threshold_index+' => '', -)); +]); // // Class: lnkTriggerAction // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:lnkTriggerAction' => 'Actions-Déclencheur', 'Class:lnkTriggerAction+' => '', 'Class:lnkTriggerAction/Attribute:action_id' => 'Action', @@ -786,12 +785,12 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Class:lnkTriggerAction/Attribute:trigger_name+' => '', 'Class:lnkTriggerAction/Attribute:order' => 'Ordre', 'Class:lnkTriggerAction/Attribute:order+' => '', -)); +]); // // Synchro Data Source // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:SynchroDataSource' => 'Source de données', 'Class:SynchroDataSource/Attribute:name' => 'Nom', 'Class:SynchroDataSource/Attribute:name+' => '', @@ -1085,12 +1084,12 @@ Plusieurs champs peuvent ainsi être modifiés lors d\'une "mise à jour" en app 'Core:Validator:Mandatory' => 'Veuillez remplir ce champ', 'Core:Validator:MustBeInteger' => 'Ce champ ne peut contenir qu\'un nombre entier', 'Core:Validator:MustSelectOne' => 'Veuillez choisir une valeur', -)); +]); // // Class: TagSetFieldData // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:TagSetFieldData' => '%2$s pour la classe %1$s', 'Class:TagSetFieldData+' => '', 'Class:TagSetFieldData/Attribute:code' => 'Code', @@ -1112,12 +1111,12 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Core:TagSetFieldData:ErrorAttCodeUpdateNotAllowed' => 'L\'attribut de l\'étiquette ne peut pas être changé', 'Core:TagSetFieldData:WhereIsThisTagTab' => 'Utilisation (%1$d)', 'Core:TagSetFieldData:NoEntryFound' => 'Pas d\'utilisation de cette étiquette', -)); +]); // // Class: DBProperty // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:DBProperty' => 'Propriété de la base de données', 'Class:DBProperty+' => '', 'Class:DBProperty/Attribute:name' => 'Nom', @@ -1130,12 +1129,12 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Class:DBProperty/Attribute:change_date+' => '', 'Class:DBProperty/Attribute:change_comment' => 'Commentaire', 'Class:DBProperty/Attribute:change_comment+' => '', -)); +]); // // Class: BackgroundTask // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:BackgroundTask' => 'Tâche de fond', 'Class:BackgroundTask+' => '', 'Class:BackgroundTask/Attribute:class_name' => 'Nom de la classe', @@ -1160,12 +1159,12 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Class:BackgroundTask/Attribute:running+' => '', 'Class:BackgroundTask/Attribute:status' => 'État', 'Class:BackgroundTask/Attribute:status+' => '', -)); +]); // // Class: AsyncTask // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:AsyncTask' => 'Tâche asynchrone', 'Class:AsyncTask+' => '', 'Class:AsyncTask/Attribute:created' => 'Date de création', @@ -1190,47 +1189,44 @@ Dict::Add('FR FR', 'French', 'Français', array( 'Class:AsyncTask/Attribute:last_attempt+' => '', 'Class:AsyncTask:InvalidConfig_Class_Keys' => 'Format incorrect pour la configuration de "async_task_retries[%1$s]". La bonne syntaxe est un tableau avec comme clés: %2$s', 'Class:AsyncTask:InvalidConfig_Class_InvalidKey_Keys' => 'Format incorrect pour la configuration de "async_task_retries[%1$s]": clé "%2$s" invalide. Les clés attendues sont: %3$s', -)); +]); // // Class: AbstractResource // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:AbstractResource' => 'Ressource', 'Class:AbstractResource+' => '', -)); +]); // // Class: ResourceAdminMenu // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:ResourceAdminMenu' => 'Menu Administration', 'Class:ResourceAdminMenu+' => '', -)); +]); // // Class: ResourceRunQueriesMenu // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:ResourceRunQueriesMenu' => 'Menu Requête OQL', 'Class:ResourceRunQueriesMenu+' => '', -)); +]); // // Class: Action // -Dict::Add('FR FR', 'French', 'Français', array( +Dict::Add('FR FR', 'French', 'Français', [ 'Class:ResourceSystemMenu' => 'Menu System', 'Class:ResourceSystemMenu+' => '', - 'Class:EventNotification/Attribute:object_class' => 'Classe de l\'objet', - 'Class:EventNotification/Attribute:object_class+' => 'Classe de l\'objet (la même que celle du déclencheur)', + 'Class:EventNotification/Attribute:object_class' => 'Classe de l\'objet', + 'Class:EventNotification/Attribute:object_class+' => 'Classe de l\'objet (la même que celle du déclencheur)', 'Core:EventNotificationNewsroom:ErrorNotificationNotSent' => 'Notification non envoyée', 'Core:EventNotificationNewsroom:ErrorOnDBInsert' => 'Une erreur est survenue lors de l\'envoi de la notification', -)); - - - +]); diff --git a/dictionaries/hu.dictionary.itop.core.php b/dictionaries/hu.dictionary.itop.core.php index 7ad4a0cf8..810e7aab9 100755 --- a/dictionaries/hu.dictionary.itop.core.php +++ b/dictionaries/hu.dictionary.itop.core.php @@ -1,15 +1,16 @@ '%1$s (törölve)', 'Core:DeletedObjectTip' => 'A %1$s objektum törölve (%2$s)', 'Core:UnknownObjectLabel' => 'Objektum nem található (osztály: %1$s, id: %2$d)', @@ -157,8 +158,7 @@ Operátorok:
'Core:Context=GUI:Console' => 'Console', 'Core:Context=CRON' => 'cron', 'Core:Context=GUI:Portal' => 'Portál', -)); - +]); ////////////////////////////////////////////////////////////////////// // Classes in 'core/cmdb' @@ -169,7 +169,7 @@ Operátorok:
// Class: CMDBChange // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:CMDBChange' => 'Változás', 'Class:CMDBChange+' => 'Változások nyomonkövetése', 'Class:CMDBChange/Attribute:date' => 'Dátum', @@ -184,13 +184,13 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Class:CMDBChange/Attribute:origin/Value:webservice-rest' => 'REST/JSON webszolgáltatás', 'Class:CMDBChange/Attribute:origin/Value:webservice-soap' => 'SOAP webszolgáltatás', 'Class:CMDBChange/Attribute:origin/Value:custom-extension' => 'Bővítmény által', -)); +]); // // Class: CMDBChangeOp // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:CMDBChangeOp' => 'Változás művelet', 'Class:CMDBChangeOp+' => 'Egyetlen személy által, egyetlen időpontban, egyetlen tárgyon végrehajtott változtatás.', 'Class:CMDBChangeOp/Attribute:change' => 'Változás', @@ -205,51 +205,51 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Class:CMDBChangeOp/Attribute:objkey+' => 'Azon objektum azonosítója amelyen a változtatás történt', 'Class:CMDBChangeOp/Attribute:finalclass' => 'CMDBChangeOp típus', 'Class:CMDBChangeOp/Attribute:finalclass+' => 'A végrehajtott változtatás típusa', -)); +]); // // Class: CMDBChangeOpCreate // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:CMDBChangeOpCreate' => 'Objektum létrehozás ', 'Class:CMDBChangeOpCreate+' => 'Objektum létrehozás nyomonkövetése', -)); +]); // // Class: CMDBChangeOpDelete // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:CMDBChangeOpDelete' => 'Objektum törlés', 'Class:CMDBChangeOpDelete+' => 'Objektum törlés nyomonkövetése', -)); +]); // // Class: CMDBChangeOpSetAttribute // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:CMDBChangeOpSetAttribute' => 'Objektum változás', 'Class:CMDBChangeOpSetAttribute+' => 'Objektumtulajdonságok változáskövetése', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode' => 'Attribútum', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode+' => 'A módosított tulajdonság kódja', -)); +]); // // Class: CMDBChangeOpSetAttributeScalar // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:CMDBChangeOpSetAttributeScalar' => 'Tulajdonságváltozás', 'Class:CMDBChangeOpSetAttributeScalar+' => 'Objektum skalár tulajdonságok változáskövetése', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue' => 'Előző érték', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue+' => 'Az attribútum korábbi értéke', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue' => 'Új érték', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue+' => 'Az attribútum új értéke', -)); +]); // Used by CMDBChangeOp... & derived classes -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Change:ObjectCreated' => 'Objektum létrehozva', 'Change:ObjectDeleted' => 'Objektum törölve', 'Change:ObjectModified' => 'Objektum módosítva', @@ -266,35 +266,35 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Change:LinkSet:Added' => '%1$s hozzáadva', 'Change:LinkSet:Removed' => '%1$s eltávolítva', 'Change:LinkSet:Modified' => '%1$s módosítva', -)); +]); // // Class: CMDBChangeOpSetAttributeBlob // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:CMDBChangeOpSetAttributeBlob' => 'Adatváltozás', 'Class:CMDBChangeOpSetAttributeBlob+' => 'Adatváltozás nyomonkövetése', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata' => 'Előző adat', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata+' => 'Az attribútum korábbi tartalma', -)); +]); // // Class: CMDBChangeOpSetAttributeText // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:CMDBChangeOpSetAttributeText' => 'Szövegváltozás', 'Class:CMDBChangeOpSetAttributeText+' => 'Szövegváltozás nyomonkövetése', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata' => 'Előző adat', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata+' => 'Az attribútum korábbi tartalma', -)); +]); // // Class: Event // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:Event' => 'Naplóesemény', 'Class:Event+' => 'Egy alkalmazás belső esemény', 'Class:Event/Attribute:message' => 'Üzenet', @@ -305,13 +305,13 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Class:Event/Attribute:userinfo+' => 'Annak a felhasználónak az azonosítása, aki az eseményt kiváltó műveletet végrehajtotta.', 'Class:Event/Attribute:finalclass' => 'Esemény típus', 'Class:Event/Attribute:finalclass+' => 'A végleges osztály neve: a bekövetkezett esemény fajtáját határozza meg.', -)); +]); // // Class: EventNotification // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:EventNotification' => 'Értesítési esemény', 'Class:EventNotification+' => 'Az elküldött értesítések nyomonkövetése', 'Class:EventNotification/Attribute:trigger_id' => 'Eseményindító', @@ -320,13 +320,13 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Class:EventNotification/Attribute:action_id+' => '', 'Class:EventNotification/Attribute:object_id' => 'Objektum azonosító', 'Class:EventNotification/Attribute:object_id+' => 'Objektum azonosítója (eseményindító határozza meg az osztályt ?)', -)); +]); // // Class: EventNotificationEmail // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:EventNotificationEmail' => 'Email küldés esemény', 'Class:EventNotificationEmail+' => 'A kiküldött email-ek nyomonkövetése', 'Class:EventNotificationEmail/Attribute:to' => 'Címzett', @@ -343,13 +343,13 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Class:EventNotificationEmail/Attribute:body+' => '', 'Class:EventNotificationEmail/Attribute:attachments' => 'Mellékletek', 'Class:EventNotificationEmail/Attribute:attachments+' => '', -)); +]); // // Class: EventIssue // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:EventIssue' => 'Probléma esemény', 'Class:EventIssue+' => 'Egy probléma (figyelmeztetés, hiba, stb. nyomonkövetése)', 'Class:EventIssue/Attribute:issue' => 'Probléma', @@ -366,13 +366,13 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Class:EventIssue/Attribute:callstack+' => '', 'Class:EventIssue/Attribute:data' => 'Adat', 'Class:EventIssue/Attribute:data+' => 'További információ', -)); +]); // // Class: EventWebService // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:EventWebService' => 'Webszolgáltatás esemény', 'Class:EventWebService+' => 'Webszolgáltatás hívás nyomonkövetése', 'Class:EventWebService/Attribute:verb' => 'Művelet', @@ -387,9 +387,9 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Class:EventWebService/Attribute:log_error+' => 'A kapott hibák naplója ', 'Class:EventWebService/Attribute:data' => 'Adat', 'Class:EventWebService/Attribute:data+' => 'A kapott adatok', -)); +]); -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:EventRestService' => 'REST/JSON hívás', 'Class:EventRestService+' => 'REST/JSON szolgáltatáshívás nyomonkövetése', 'Class:EventRestService/Attribute:operation' => 'Művelet', @@ -404,13 +404,13 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Class:EventRestService/Attribute:json_output+' => 'HTTP válasz (json)', 'Class:EventRestService/Attribute:provider' => 'Szolgáltató', 'Class:EventRestService/Attribute:provider+' => 'A várt műveletet végrehajtó PHP osztály', -)); +]); // // Class: EventLoginUsage // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:EventLoginUsage' => 'Belépések', 'Class:EventLoginUsage+' => 'Kapcsolódások az alkalmazáshoz', 'Class:EventLoginUsage/Attribute:user_id' => 'Felhasználónév', @@ -419,13 +419,13 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Class:EventLoginUsage/Attribute:contact_name+' => '', 'Class:EventLoginUsage/Attribute:contact_email' => 'Kapcsolattartó email cím', 'Class:EventLoginUsage/Attribute:contact_email+' => 'A felhasználó email címe', -)); +]); // // Class: EventNotificationNewsroom // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:EventNotificationNewsroom' => 'News sent~~', 'Class:EventNotificationNewsroom+' => '~~', 'Class:EventNotificationNewsroom/Attribute:title' => 'Title~~', @@ -454,13 +454,13 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Class:EventNotificationNewsroom/Attribute:read_date+' => '~~', 'Class:EventNotificationNewsroom/Attribute:contact_id' => 'Contact~~', 'Class:EventNotificationNewsroom/Attribute:contact_id+' => '~~', -)); +]); // // Class: Action // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:Action' => 'Egyéni művelet', 'Class:Action+' => 'A felhasználó által meghatározott művelet', 'Class:Action/ComplementaryName' => '%1$s: %2$s~~', @@ -490,22 +490,22 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Action:last_executions_tab_panel_title' => 'Executions of this action (%1$s)~~', 'Action:last_executions_tab_limit_days' => 'past %1$s days~~', 'Action:last_executions_tab_limit_none' => 'no limit~~', -)); +]); // // Class: ActionNotification // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:ActionNotification' => 'Értesítés', 'Class:ActionNotification+' => 'Értesítés (absztrakt)', -)); +]); // // Class: ActionEmail // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:ActionEmail' => 'Email értesítés', 'Class:ActionEmail+' => '', 'Class:ActionEmail/Attribute:status+' => 'Ez az állapot határozza meg, hogy ki kapjon értesítést: csak a teszt címzettje, mindenki (Címzett, cc és Bcc) vagy senki.', @@ -556,14 +556,13 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'ActionEmail:preview_warning' => 'The actual eMail may look different in the eMail client than this preview in your browser.~~', 'ActionEmail:preview_more_info' => 'For more information about the CSS features supported by the different eMail clients, refer to %1$s~~', 'ActionEmail:content_placeholder_missing' => 'The placeholder "%1$s" was not found in the HTML template. The content of the field "%2$s" will not be included in the generated emails.~~', -)); - +]); // // Class: ActionNewsroom // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'ActionNewsroom:trigger' => 'Trigger~~', 'ActionNewsroom:content' => 'Message~~', 'ActionNewsroom:settings' => 'Settings~~', @@ -598,13 +597,13 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Class:ActionNewsroom/Attribute:recipients+' => 'An OQL query returning Contact objects~~', 'Class:ActionNewsroom/Attribute:url' => 'URL~~', 'Class:ActionNewsroom/Attribute:url+' => 'By default, it points to the object triggering the notification. But you can also specify a custom URL.~~', -)); +]); // // Class: Trigger // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:Trigger' => 'Eseményindító', 'Class:Trigger+' => 'Egyéni eseménykezelés', 'Class:Trigger/ComplementaryName' => '%1$s, %2$s~~', @@ -623,13 +622,13 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Class:Trigger/Attribute:subscription_policy/Value:allow_no_channel' => 'Allow complete unsubscription~~', 'Class:Trigger/Attribute:subscription_policy/Value:force_at_least_one_channel' => 'Force at least one channel (News or Email)~~', 'Class:Trigger/Attribute:subscription_policy/Value:force_all_channels' => 'Deny unsubscription~~', -)); +]); // // Class: TriggerOnObject // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:TriggerOnObject' => 'Eseményindító (osztályfüggő)', 'Class:TriggerOnObject+' => 'Az objektumok egy adott osztályára történő eseményindítás', 'Class:TriggerOnObject/Attribute:target_class' => 'Cél osztály', @@ -638,115 +637,115 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Class:TriggerOnObject/Attribute:filter+' => 'Korlátozza az objektumlistát (a célosztályból), amely aktiválja az eseményindítót.', 'TriggerOnObject:WrongFilterQuery' => 'Helytelen szűrőkérdés: %1$s', 'TriggerOnObject:WrongFilterClass' => 'A szűrő lekérdezésnek %1$s osztályú objektumokat kell visszaadnia.', -)); +]); // // Class: TriggerOnPortalUpdate // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:TriggerOnPortalUpdate' => 'Eseményindító (amikor a portálról frissül)', 'Class:TriggerOnPortalUpdate+' => 'Eseményindító egy végfelhasználó által a portálon történő frissítéskor', -)); +]); // // Class: TriggerOnStateChange // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:TriggerOnStateChange' => 'Eseményindító (állapotváltozásnál)', 'Class:TriggerOnStateChange+' => 'Eseményindító egy objektum állapotának változásakor', 'Class:TriggerOnStateChange/Attribute:state' => 'Állapot', 'Class:TriggerOnStateChange/Attribute:state+' => '', -)); +]); // // Class: TriggerOnStateEnter // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:TriggerOnStateEnter' => 'Eseményindító (állapot felvételekor)', 'Class:TriggerOnStateEnter+' => 'Az objektum állapotváltozásba lépéskor elinduló eseményindító', -)); +]); // // Class: TriggerOnStateLeave // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:TriggerOnStateLeave' => 'Eseményindító (állapot elhagyáskor)', 'Class:TriggerOnStateLeave+' => 'Az objektum állapotváltozás elhagyásakor elinduló eseményindító', -)); +]); // // Class: TriggerOnObjectCreate // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:TriggerOnObjectCreate' => 'Eseményindító (objektum létrehozáskor)', 'Class:TriggerOnObjectCreate+' => 'Az adott osztály [egy gyermekosztálya] objektumának létrehozásakor elinduló eseményindító.', -)); +]); // // Class: TriggerOnObjectDelete // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:TriggerOnObjectDelete' => 'Eseményindító (objektum törléskor)', 'Class:TriggerOnObjectDelete+' => 'Az adott osztály [egy gyermekosztálya] objektumának törlésekor elinduló eseményindító.', -)); +]); // // Class: TriggerOnObjectUpdate // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:TriggerOnObjectUpdate' => 'Eseményindító (objektum frissítéskor)', 'Class:TriggerOnObjectUpdate+' => 'Az adott osztály [egy gyermekosztálya] objektumának frissítésekor elinduló eseményindító', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes' => 'Célmezők', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes+' => '', -)); +]); // // Class: TriggerOnObjectMention // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:TriggerOnObjectMention' => 'Eseményindító (objektumra hivatkozáskor)', 'Class:TriggerOnObjectMention+' => 'Az adott osztály [egy gyermekosztálya] objektumára (@xxx) hivatkozáskor egy naplóattribútumban', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter' => 'Hivatkozás szűrő', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter+' => 'A hivatkozott objektumok listájának korlátozása, amelyek aktiválják az eseményindítót. Ha üres, akkor bármelyik említett objektum (bármely osztályból) aktiválja azt.', -)); +]); // // Class: TriggerOnAttributeBlobDownload // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:TriggerOnAttributeBlobDownload' => 'Trigger (on object\'s document download)~~', 'Class:TriggerOnAttributeBlobDownload+' => 'Trigger on object\'s document field download of [a child class of] the given class~~', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes' => 'Target fields~~', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes+' => '~~', -)); +]); // // Class: TriggerOnThresholdReached // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:TriggerOnThresholdReached' => 'Eseményindító (küszöbértéknél)', 'Class:TriggerOnThresholdReached+' => 'Eseményindító egy időzítő küszöbértékének elérésekor', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code' => 'Időzítő', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code+' => '', 'Class:TriggerOnThresholdReached/Attribute:threshold_index' => 'Küszöbérték', 'Class:TriggerOnThresholdReached/Attribute:threshold_index+' => '', -)); +]); // // Class: lnkTriggerAction // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:lnkTriggerAction' => 'Művelet/Eseményindító', 'Class:lnkTriggerAction+' => 'Kapcsolat egy eseményindító és egy művelet között', 'Class:lnkTriggerAction/Attribute:action_id' => 'Művelet', @@ -759,12 +758,12 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Class:lnkTriggerAction/Attribute:trigger_name+' => '', 'Class:lnkTriggerAction/Attribute:order' => 'Sorrend', 'Class:lnkTriggerAction/Attribute:order+' => 'A műveletek végrehajtási sorrendje', -)); +]); // // Synchro Data Source // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:SynchroDataSource' => 'Szinkron adatforrás', 'Class:SynchroDataSource/Attribute:name' => 'Név', 'Class:SynchroDataSource/Attribute:name+' => '', @@ -1052,13 +1051,13 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Core:Validator:MustBeInteger' => 'Egész számnak kell lennie', 'Core:Validator:MustSelectOne' => 'Egyet válasszon', 'Menu:DataSources' => 'Szinkronizációs adatforrások', - 'Menu:DataSources+' => 'Minden szinkronizációs adatforrás' -)); + 'Menu:DataSources+' => 'Minden szinkronizációs adatforrás', +]); // // Class: TagSetFieldData // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:TagSetFieldData' => '%2$s a %1$s osztályhoz', 'Class:TagSetFieldData+' => '', 'Class:TagSetFieldData/Attribute:code' => 'Kód', @@ -1080,12 +1079,12 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Core:TagSetFieldData:ErrorAttCodeUpdateNotAllowed' => 'Az "Attribútumkód" címkék nem módosíthatók', 'Core:TagSetFieldData:WhereIsThisTagTab' => 'Címkehasználat (%1$d)', 'Core:TagSetFieldData:NoEntryFound' => 'Nincs bejegyzés ehhez a címkéhez', -)); +]); // // Class: DBProperty // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:DBProperty' => 'DB tulajdonságok', 'Class:DBProperty+' => '', 'Class:DBProperty/Attribute:name' => 'Név', @@ -1098,12 +1097,12 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Class:DBProperty/Attribute:change_date+' => '', 'Class:DBProperty/Attribute:change_comment' => 'Megjegyzés', 'Class:DBProperty/Attribute:change_comment+' => '', -)); +]); // // Class: BackgroundTask // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:BackgroundTask' => 'Háttérfeladat', 'Class:BackgroundTask+' => '', 'Class:BackgroundTask/Attribute:class_name' => 'Osztálynév', @@ -1128,12 +1127,12 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Class:BackgroundTask/Attribute:running+' => '', 'Class:BackgroundTask/Attribute:status' => 'Állapot', 'Class:BackgroundTask/Attribute:status+' => '', -)); +]); // // Class: AsyncTask // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:AsyncTask' => 'Aszinkron feladat', 'Class:AsyncTask+' => '', 'Class:AsyncTask/Attribute:created' => 'Létrehozva', @@ -1158,47 +1157,44 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'Class:AsyncTask/Attribute:last_attempt+' => '', 'Class:AsyncTask:InvalidConfig_Class_Keys' => 'Érvénytelen formátum az async_task_retries[%1$s] konfigurációhoz. A következő kulcsokkal rendelkező tömböt vár: %2$s', 'Class:AsyncTask:InvalidConfig_Class_InvalidKey_Keys' => 'Az async_task_retries[%1$s] konfigurációjának érvénytelen formátuma: %2$s váratlan kulcs. Csak a következő kulcsokat várja: %3$s', -)); +]); // // Class: AbstractResource // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:AbstractResource' => 'Absztrakt erőforrás', 'Class:AbstractResource+' => '', -)); +]); // // Class: ResourceAdminMenu // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:ResourceAdminMenu' => 'Erőforrás admin menü', 'Class:ResourceAdminMenu+' => '', -)); +]); // // Class: ResourceRunQueriesMenu // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:ResourceRunQueriesMenu' => 'Erőforrás lekérdezések futtatása menü', 'Class:ResourceRunQueriesMenu+' => '', -)); +]); // // Class: Action // -Dict::Add('HU HU', 'Hungarian', 'Magyar', array( +Dict::Add('HU HU', 'Hungarian', 'Magyar', [ 'Class:ResourceSystemMenu' => 'Erőforrás rendszer menü', 'Class:ResourceSystemMenu+' => '', - 'Class:EventNotification/Attribute:object_class' => 'Object class~~', - 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', + 'Class:EventNotification/Attribute:object_class' => 'Object class~~', + 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', 'Core:EventNotificationNewsroom:ErrorNotificationNotSent' => 'Notification not sent~~', 'Core:EventNotificationNewsroom:ErrorOnDBInsert' => 'An error occurred while saving the notification~~', -)); - - - +]); diff --git a/dictionaries/it.dictionary.itop.core.php b/dictionaries/it.dictionary.itop.core.php index c0734d8f3..d7c2d9744 100644 --- a/dictionaries/it.dictionary.itop.core.php +++ b/dictionaries/it.dictionary.itop.core.php @@ -1,15 +1,16 @@ '%1s (cancellato)', 'Core:DeletedObjectTip' => 'L\'oggetto è stato cancellato il %1$s (%2$s)', 'Core:UnknownObjectLabel' => 'Oggetto non trovato (classe: %1$s, id: %2$d)', @@ -157,8 +158,7 @@ Operatori:
'Core:Context=GUI:Console' => 'Console', 'Core:Context=CRON' => 'cron', 'Core:Context=GUI:Portal' => 'Portale', -)); - +]); ////////////////////////////////////////////////////////////////////// // Classes in 'core/cmdb' @@ -169,7 +169,7 @@ Operatori:
// Class: CMDBChange // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:CMDBChange' => 'Cambio', 'Class:CMDBChange+' => 'Rilevamento delle modifiche', 'Class:CMDBChange/Attribute:date' => 'data', @@ -184,13 +184,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:CMDBChange/Attribute:origin/Value:webservice-rest' => 'Servizi web REST/JSON', 'Class:CMDBChange/Attribute:origin/Value:webservice-soap' => 'Servizi web SOAP', 'Class:CMDBChange/Attribute:origin/Value:custom-extension' => 'Da un\'estensione', -)); +]); // // Class: CMDBChangeOp // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:CMDBChangeOp' => 'Operazione di cambio', 'Class:CMDBChangeOp+' => 'Rilevamento delle operazioni di cambio', 'Class:CMDBChangeOp/Attribute:change' => 'cambio', @@ -205,51 +205,51 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:CMDBChangeOp/Attribute:objkey+' => '', 'Class:CMDBChangeOp/Attribute:finalclass' => 'tipo', 'Class:CMDBChangeOp/Attribute:finalclass+' => '', -)); +]); // // Class: CMDBChangeOpCreate // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:CMDBChangeOpCreate' => 'creazione oggetto', 'Class:CMDBChangeOpCreate+' => 'Rilevamento creazione oggetto', -)); +]); // // Class: CMDBChangeOpDelete // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:CMDBChangeOpDelete' => 'cancellazione oggetto', 'Class:CMDBChangeOpDelete+' => 'Rilevamento cancellazione oggetto', -)); +]); // // Class: CMDBChangeOpSetAttribute // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:CMDBChangeOpSetAttribute' => 'cambio oggetto', 'Class:CMDBChangeOpSetAttribute+' => 'Rilevamento modifiche delle proprietà dell\'oggetto', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode' => 'Attributo', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode+' => 'ccodice della proprietà modificata', -)); +]); // // Class: CMDBChangeOpSetAttributeScalar // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:CMDBChangeOpSetAttributeScalar' => 'proprietà cambio', 'Class:CMDBChangeOpSetAttributeScalar+' => 'Rilevamento delle modifiche delle proprietà scalari dell\'oggetto', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue' => 'Valore precedente', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue+' => 'valore precedente dell\'attributo', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue' => 'Nuovo valore', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue+' => 'nuovo valore dell\'attributo', -)); +]); // Used by CMDBChangeOp... & derived classes -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Change:ObjectCreated' => 'Oggetto creato', 'Change:ObjectDeleted' => 'Oggetto cancellato', 'Change:ObjectModified' => 'Oggetto modificato', @@ -266,35 +266,35 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Change:LinkSet:Added' => 'aggiunto %1$s', 'Change:LinkSet:Removed' => 'rimosso %1$s', 'Change:LinkSet:Modified' => 'modificato %1$s', -)); +]); // // Class: CMDBChangeOpSetAttributeBlob // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:CMDBChangeOpSetAttributeBlob' => 'dati del cambio', 'Class:CMDBChangeOpSetAttributeBlob+' => 'rilevamento dati del cambio', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata' => 'Dati precedente', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata+' => 'contenuto precedente dell\'attributo', -)); +]); // // Class: CMDBChangeOpSetAttributeText // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:CMDBChangeOpSetAttributeText' => 'cambio testo', 'Class:CMDBChangeOpSetAttributeText+' => 'rilevamento cambio testo', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata' => 'Dati precendenti', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata+' => 'contenuto precedente dell\'attributo', -)); +]); // // Class: Event // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:Event' => 'Log Evento', 'Class:Event+' => 'Un\'applicazione evento interno', 'Class:Event/Attribute:message' => 'Messagio', @@ -305,13 +305,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:Event/Attribute:userinfo+' => 'l\'identificazione dell\'utente che stava facendo l\'azione che ha attivato questo evento', 'Class:Event/Attribute:finalclass' => 'Tipo', 'Class:Event/Attribute:finalclass+' => '', -)); +]); // // Class: EventNotification // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:EventNotification' => 'Notifica dell\'evento', 'Class:EventNotification+' => 'Traccia di una notifica che è stato inviato', 'Class:EventNotification/Attribute:trigger_id' => 'Trigger', @@ -320,13 +320,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:EventNotification/Attribute:action_id+' => 'account utente', 'Class:EventNotification/Attribute:object_id' => 'Id oggetto', 'Class:EventNotification/Attribute:object_id+' => 'Id oggetto (classe definita dal trigger ?)', -)); +]); // // Class: EventNotificationEmail // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:EventNotificationEmail' => 'Emissione evento Email', 'Class:EventNotificationEmail+' => 'Traccia di una e-mail che è stato inviata', 'Class:EventNotificationEmail/Attribute:to' => 'A', @@ -343,13 +343,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:EventNotificationEmail/Attribute:body+' => '', 'Class:EventNotificationEmail/Attribute:attachments' => 'Allegati', 'Class:EventNotificationEmail/Attribute:attachments+' => '', -)); +]); // // Class: EventIssue // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:EventIssue' => 'Evento Problematico', 'Class:EventIssue+' => 'Traccia di un problema (avviso, errore, etc)', 'Class:EventIssue/Attribute:issue' => 'Problema', @@ -366,13 +366,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:EventIssue/Attribute:callstack+' => '', 'Class:EventIssue/Attribute:data' => 'Dati', 'Class:EventIssue/Attribute:data+' => 'Informazioni aggiuntive', -)); +]); // // Class: EventWebService // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:EventWebService' => 'Evento di servizio web', 'Class:EventWebService+' => 'Traccia di una chiamata di servizio web', 'Class:EventWebService/Attribute:verb' => 'Verbo', @@ -387,9 +387,9 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:EventWebService/Attribute:log_error+' => 'Risultati error log', 'Class:EventWebService/Attribute:data' => 'Dati', 'Class:EventWebService/Attribute:data+' => 'Risultati dei dati', -)); +]); -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:EventRestService' => 'Chiamata REST/JSON', 'Class:EventRestService+' => 'Traccia di una chiamata del servizio REST/JSON', 'Class:EventRestService/Attribute:operation' => 'Operazione', @@ -404,13 +404,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:EventRestService/Attribute:json_output+' => 'Risposta HTTP (json)', 'Class:EventRestService/Attribute:provider' => 'Provider', 'Class:EventRestService/Attribute:provider+' => 'Classe PHP che implementa l\'operazione prevista', -)); +]); // // Class: EventLoginUsage // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:EventLoginUsage' => 'Uso Login', 'Class:EventLoginUsage+' => 'Connessione all\'applicazione', 'Class:EventLoginUsage/Attribute:user_id' => 'Login', @@ -419,13 +419,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:EventLoginUsage/Attribute:contact_name+' => '', 'Class:EventLoginUsage/Attribute:contact_email' => 'User Email', 'Class:EventLoginUsage/Attribute:contact_email+' => 'Indirizzo email dell\'utente', -)); +]); // // Class: EventNotificationNewsroom // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:EventNotificationNewsroom' => 'Notizia inviata', 'Class:EventNotificationNewsroom+' => '~~', 'Class:EventNotificationNewsroom/Attribute:title' => 'Titolo', @@ -454,13 +454,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:EventNotificationNewsroom/Attribute:read_date+' => '~~', 'Class:EventNotificationNewsroom/Attribute:contact_id' => 'Contatto', 'Class:EventNotificationNewsroom/Attribute:contact_id+' => '', -)); +]); // // Class: Action // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:Action' => 'Azione personalizzata', 'Class:Action+' => 'Azione definita dall\'utente', 'Class:Action/ComplementaryName' => '%1$s: %2$s~~', @@ -490,22 +490,22 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Action:last_executions_tab_panel_title' => 'Esecuzioni di questa azione (%1$s)', 'Action:last_executions_tab_limit_days' => 'ultimi %1$s giorni', 'Action:last_executions_tab_limit_none' => 'nessun limite', -)); +]); // // Class: ActionNotification // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:ActionNotification' => 'Notifica', 'Class:ActionNotification+' => 'Notifica (sommario)', -)); +]); // // Class: ActionEmail // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:ActionEmail' => 'Email di notifica', 'Class:ActionEmail+' => '', 'Class:ActionEmail/Attribute:status+' => 'Questo stato determina chi verrà notificato: solo il destinatario di prova, tutti (To, Cc e Bcc) o nessuno', @@ -556,14 +556,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'ActionEmail:preview_warning' => 'L\'e-mail effettiva potrebbe apparire diversa nel client di posta elettronica rispetto a questa anteprima nel tuo browser.', 'ActionEmail:preview_more_info' => 'Per ulteriori informazioni sulle funzionalità CSS supportate dai diversi client di posta elettronica, consulta %1$s', 'ActionEmail:content_placeholder_missing' => 'Il segnaposto "%1$s" non è stato trovato nel template HTML. Il contenuto del campo "%2$s" non verrà incluso nelle email generate.', -)); - +]); // // Class: ActionNewsroom // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'ActionNewsroom:trigger' => 'Trigger', 'ActionNewsroom:content' => 'Messaggio', 'ActionNewsroom:settings' => 'Impostazioni', @@ -598,13 +597,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:ActionNewsroom/Attribute:recipients+' => 'Una query OQL che restituisce oggetti Contatto', 'Class:ActionNewsroom/Attribute:url' => 'URL', 'Class:ActionNewsroom/Attribute:url+' => 'L\'URL punterà all\'oggetto che attiva la notifica. Ma puoi anche specificare un URL personalizzato.', -)); +]); // // Class: Trigger // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:Trigger' => 'Trigger', 'Class:Trigger+' => 'Gestore di eventi personalizzati', 'Class:Trigger/ComplementaryName' => '%1$s, %2$s', @@ -623,13 +622,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:Trigger/Attribute:subscription_policy/Value:allow_no_channel' => 'Consenti annullamento completo dell\'iscrizione', 'Class:Trigger/Attribute:subscription_policy/Value:force_at_least_one_channel' => 'Obbliga almeno un canale (News o Email)', 'Class:Trigger/Attribute:subscription_policy/Value:force_all_channels' => 'Nega l\'annullamento dell\'iscrizione', -)); +]); // // Class: TriggerOnObject // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:TriggerOnObject' => 'Trigger (classe dipendente)', 'Class:TriggerOnObject+' => 'Trigger su una determinata classe di oggetti', 'Class:TriggerOnObject/Attribute:target_class' => 'Classe Bersaglio', @@ -638,115 +637,115 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:TriggerOnObject/Attribute:filter+' => 'Limita l\'elenco degli oggetti (della classe bersaglio) che attiveranno il trigger', 'TriggerOnObject:WrongFilterQuery' => 'Query di filtro errata: %1$s', 'TriggerOnObject:WrongFilterClass' => 'La query di filtro deve restituire oggetti della classe \\"%1$s\\"', -)); +]); // // Class: TriggerOnPortalUpdate // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:TriggerOnPortalUpdate' => 'Trigger (dopo l\'aggiornamento dal portale )', 'Class:TriggerOnPortalUpdate+' => 'Trigger sull\'aggiornamento dell\'utente dal portale', -)); +]); // // Class: TriggerOnStateChange // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:TriggerOnStateChange' => 'Trigger (su cambio stato)', 'Class:TriggerOnStateChange+' => 'Trigger su cambio stato di un oggetto', 'Class:TriggerOnStateChange/Attribute:state' => 'Stato', 'Class:TriggerOnStateChange/Attribute:state+' => '', -)); +]); // // Class: TriggerOnStateEnter // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:TriggerOnStateEnter' => 'Trigger (all\'entrata di uno stato)', 'Class:TriggerOnStateEnter+' => 'Trigger su cambio stato di un oggetto - entrata', -)); +]); // // Class: TriggerOnStateLeave // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:TriggerOnStateLeave' => 'Trigger (all\'uscita di uno stato)', 'Class:TriggerOnStateLeave+' => 'Trigger su cambio stato di un oggetto - uscita', -)); +]); // // Class: TriggerOnObjectCreate // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:TriggerOnObjectCreate' => 'Trigger (sulla creazione)', 'Class:TriggerOnObjectCreate+' => 'Trigger sulla creazione di un oggetto [una classe figlia di] di una data classe', -)); +]); // // Class: TriggerOnObjectDelete // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:TriggerOnObjectDelete' => 'Trigger (alla cancellazione dell\'oggetto)', 'Class:TriggerOnObjectDelete+' => 'Trigger alla cancellazione dell\'oggetto di [una classe figlia della] classe specificata', -)); +]); // // Class: TriggerOnObjectUpdate // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:TriggerOnObjectUpdate' => 'Trigger (alla modifica dell\'oggetto)', 'Class:TriggerOnObjectUpdate+' => 'Trigger alla modifica dell\'oggetto di [una classe figlia della] classe specificata', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes' => 'Campi di destinazione', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes+' => '', -)); +]); // // Class: TriggerOnObjectMention // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:TriggerOnObjectMention' => 'Trigger (alla menzione dell\'oggetto)', 'Class:TriggerOnObjectMention+' => 'Trigger alla menzione (@xxx) di un oggetto di [una classe figlia della] classe specificata in un attributo di log', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter' => 'Filtro menzionato', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter+' => 'Limita l\'elenco degli oggetti menzionati che attiveranno il trigger. Se vuoto, qualsiasi oggetto menzionato (di qualsiasi classe) lo attiverà.', -)); +]); // // Class: TriggerOnAttributeBlobDownload // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:TriggerOnAttributeBlobDownload' => 'Trigger (al download del documento dell\'oggetto)', 'Class:TriggerOnAttributeBlobDownload+' => 'Trigger al download del campo documento dell\'oggetto di [una classe figlia della] classe specificata', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes' => 'Campi di destinazione', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes+' => '', -)); +]); // // Class: TriggerOnThresholdReached // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:TriggerOnThresholdReached' => 'Trigger (sulla soglia raggiunta)', 'Class:TriggerOnThresholdReached+' => 'Trigger sulla soglia del cronometro raggiunta', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code' => 'Cronometro', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code+' => '', 'Class:TriggerOnThresholdReached/Attribute:threshold_index' => 'Soglia', 'Class:TriggerOnThresholdReached/Attribute:threshold_index+' => '', -)); +]); // // Class: lnkTriggerAction // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:lnkTriggerAction' => 'Azione/Trigger', 'Class:lnkTriggerAction+' => 'Collegamento tra trigger e azione', 'Class:lnkTriggerAction/Attribute:action_id' => 'Azione', @@ -759,12 +758,12 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:lnkTriggerAction/Attribute:trigger_name+' => '', 'Class:lnkTriggerAction/Attribute:order' => 'Ordine', 'Class:lnkTriggerAction/Attribute:order+' => 'Ordine di esecuzione delle azioni', -)); +]); // // Synchro Data Source // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:SynchroDataSource' => 'Sorgente sincronizzazione dati', 'Class:SynchroDataSource/Attribute:name' => 'Nome', 'Class:SynchroDataSource/Attribute:name+' => '', @@ -1052,13 +1051,13 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Core:Validator:MustBeInteger' => 'Deve essere un numero intero', 'Core:Validator:MustSelectOne' => 'Per favore, seleziona uno', 'Menu:DataSources' => 'Sorgente di sincronizzazione dei dati', - 'Menu:DataSources+' => '' -)); + 'Menu:DataSources+' => '', +]); // // Class: TagSetFieldData // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:TagSetFieldData' => '%2$s per la classe %1$s', 'Class:TagSetFieldData+' => '', 'Class:TagSetFieldData/Attribute:code' => 'Codice', @@ -1080,12 +1079,12 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Core:TagSetFieldData:ErrorAttCodeUpdateNotAllowed' => 'Il "Codice attributo" dei tag non può essere cambiato', 'Core:TagSetFieldData:WhereIsThisTagTab' => 'Utilizzo tag (%1$d)', 'Core:TagSetFieldData:NoEntryFound' => 'Nessuna voce trovata per questo tag', -)); +]); // // Class: DBProperty // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:DBProperty' => 'Proprietà DB', 'Class:DBProperty+' => '', 'Class:DBProperty/Attribute:name' => 'Nome', @@ -1098,12 +1097,12 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:DBProperty/Attribute:change_date+' => '', 'Class:DBProperty/Attribute:change_comment' => 'Commento modifica', 'Class:DBProperty/Attribute:change_comment+' => '', -)); +]); // // Class: BackgroundTask // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:BackgroundTask' => 'Task in background', 'Class:BackgroundTask+' => '', 'Class:BackgroundTask/Attribute:class_name' => 'Nome della classe', @@ -1128,12 +1127,12 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:BackgroundTask/Attribute:running+' => '', 'Class:BackgroundTask/Attribute:status' => 'Stato', 'Class:BackgroundTask/Attribute:status+' => '', -)); +]); // // Class: AsyncTask // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:AsyncTask' => 'Attività asincrona', 'Class:AsyncTask+' => '', 'Class:AsyncTask/Attribute:created' => 'Creata', @@ -1158,47 +1157,44 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'Class:AsyncTask/Attribute:last_attempt+' => '', 'Class:AsyncTask:InvalidConfig_Class_Keys' => 'Formato non valido per la configurazione di "async_task_retries[%1$s]". Ci si aspetta un array con le seguenti chiavi: %2$s', 'Class:AsyncTask:InvalidConfig_Class_InvalidKey_Keys' => 'Formato non valido per la configurazione di "async_task_retries[%1$s]": chiave "%2$s" inaspettata. Ci si aspetta solo le seguenti chiavi: %3$s', -)); +]); // // Class: AbstractResource // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:AbstractResource' => 'Risorsa Astratta', 'Class:AbstractResource+' => '', -)); +]); // // Class: ResourceAdminMenu // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:ResourceAdminMenu' => 'Menu di Amministrazione delle Risorse', 'Class:ResourceAdminMenu+' => '', -)); +]); // // Class: ResourceRunQueriesMenu // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:ResourceRunQueriesMenu' => 'Menu Esegui Query Risorse', 'Class:ResourceRunQueriesMenu+' => '', -)); +]); // // Class: Action // -Dict::Add('IT IT', 'Italian', 'Italiano', array( +Dict::Add('IT IT', 'Italian', 'Italiano', [ 'Class:ResourceSystemMenu' => 'Menu di Sistema delle Risorse', 'Class:ResourceSystemMenu+' => '', - 'Class:EventNotification/Attribute:object_class' => 'Object class~~', - 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', + 'Class:EventNotification/Attribute:object_class' => 'Object class~~', + 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', 'Core:EventNotificationNewsroom:ErrorNotificationNotSent' => 'Notification not sent~~', 'Core:EventNotificationNewsroom:ErrorOnDBInsert' => 'An error occurred while saving the notification~~', -)); - - - +]); diff --git a/dictionaries/ja.dictionary.itop.core.php b/dictionaries/ja.dictionary.itop.core.php index eb4295180..8f000089c 100644 --- a/dictionaries/ja.dictionary.itop.core.php +++ b/dictionaries/ja.dictionary.itop.core.php @@ -1,15 +1,16 @@ '%1$s (削除されました)', 'Core:DeletedObjectTip' => 'オブジェクトは削除されました %1$s (%2$s)', 'Core:UnknownObjectLabel' => 'オブジェクトは見つかりません (クラス: %1$s, id: %2$d)', @@ -157,8 +158,7 @@ Operators:
'Core:Context=GUI:Console' => 'Console~~', 'Core:Context=CRON' => 'cron~~', 'Core:Context=GUI:Portal' => 'Portal~~', -)); - +]); ////////////////////////////////////////////////////////////////////// // Classes in 'core/cmdb' @@ -169,7 +169,7 @@ Operators:
// Class: CMDBChange // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:CMDBChange' => '変更', 'Class:CMDBChange+' => '変更履歴', 'Class:CMDBChange/Attribute:date' => '日付', @@ -184,13 +184,13 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Class:CMDBChange/Attribute:origin/Value:webservice-rest' => 'REST/JSON webservices~~', 'Class:CMDBChange/Attribute:origin/Value:webservice-soap' => 'SOAP webservices~~', 'Class:CMDBChange/Attribute:origin/Value:custom-extension' => 'By an extension~~', -)); +]); // // Class: CMDBChangeOp // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:CMDBChangeOp' => '変更操作', 'Class:CMDBChangeOp+' => '変更操作履歴', 'Class:CMDBChangeOp/Attribute:change' => '変更', @@ -205,51 +205,51 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Class:CMDBChangeOp/Attribute:objkey+' => 'オブジェクトID', 'Class:CMDBChangeOp/Attribute:finalclass' => 'タイプ', 'Class:CMDBChangeOp/Attribute:finalclass+' => '', -)); +]); // // Class: CMDBChangeOpCreate // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:CMDBChangeOpCreate' => 'オブジェクト作成', 'Class:CMDBChangeOpCreate+' => 'オブジェクト作成履歴', -)); +]); // // Class: CMDBChangeOpDelete // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:CMDBChangeOpDelete' => 'オブジェクト削除', 'Class:CMDBChangeOpDelete+' => 'オブジェクト削除履歴', -)); +]); // // Class: CMDBChangeOpSetAttribute // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:CMDBChangeOpSetAttribute' => 'オブジェクト更新', 'Class:CMDBChangeOpSetAttribute+' => 'オブジェクトプロパティの更新履歴', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode' => '属性', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode+' => '更新プロパティのコード', -)); +]); // // Class: CMDBChangeOpSetAttributeScalar // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:CMDBChangeOpSetAttributeScalar' => 'プロパティ更新', 'Class:CMDBChangeOpSetAttributeScalar+' => 'オブジェクトのスカラープロパティの更新履歴', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue' => '変更前の値', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue+' => '属性の変更前の値', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue' => '新規の値', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue+' => '属性の新規の値', -)); +]); // Used by CMDBChangeOp... & derived classes -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Change:ObjectCreated' => 'オブジェクトを生成しました', 'Change:ObjectDeleted' => 'オブジェクトを削除しました', 'Change:ObjectModified' => 'オブジェクトを修正しました', @@ -266,35 +266,35 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Change:LinkSet:Added' => '追加されました %1$s', 'Change:LinkSet:Removed' => '削除されました %1$s', 'Change:LinkSet:Modified' => '修正されました %1$s', -)); +]); // // Class: CMDBChangeOpSetAttributeBlob // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:CMDBChangeOpSetAttributeBlob' => 'データ変更', 'Class:CMDBChangeOpSetAttributeBlob+' => 'データ変更履歴', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata' => '以前のデータ', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata+' => 'この属性の以前の内容', -)); +]); // // Class: CMDBChangeOpSetAttributeText // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:CMDBChangeOpSetAttributeText' => 'テキストの変更', 'Class:CMDBChangeOpSetAttributeText+' => 'テキストの変更履歴', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata' => '以前の内容', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata+' => 'この属性の以前の内容', -)); +]); // // Class: Event // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:Event' => 'ログイベント', 'Class:Event+' => 'アプリケーション内部イベント', 'Class:Event/Attribute:message' => 'メッセージ', @@ -305,13 +305,13 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Class:Event/Attribute:userinfo+' => 'このイベントをトリガーしたアクションを行ったユーザ', 'Class:Event/Attribute:finalclass' => 'タイプ', 'Class:Event/Attribute:finalclass+' => '', -)); +]); // // Class: EventNotification // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:EventNotification' => '通知イベント', 'Class:EventNotification+' => '送信された通知のトレース', 'Class:EventNotification/Attribute:trigger_id' => 'トリガー', @@ -320,13 +320,13 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Class:EventNotification/Attribute:action_id+' => 'ユーザアカウント', 'Class:EventNotification/Attribute:object_id' => 'オブジェクトID', 'Class:EventNotification/Attribute:object_id+' => 'オブジェクトID(トリガーでクラスが定義済み?)', -)); +]); // // Class: EventNotificationEmail // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:EventNotificationEmail' => 'メール送出イベント', 'Class:EventNotificationEmail+' => '送出されたメールのトレース', 'Class:EventNotificationEmail/Attribute:to' => 'TO', @@ -343,13 +343,13 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Class:EventNotificationEmail/Attribute:body+' => '本文', 'Class:EventNotificationEmail/Attribute:attachments' => '添付', 'Class:EventNotificationEmail/Attribute:attachments+' => '', -)); +]); // // Class: EventIssue // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:EventIssue' => '課題', 'Class:EventIssue+' => '課題(警告、エラー、etc)のトレース', 'Class:EventIssue/Attribute:issue' => '課題', @@ -366,13 +366,13 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Class:EventIssue/Attribute:callstack+' => 'スタックをコールする', 'Class:EventIssue/Attribute:data' => 'データ', 'Class:EventIssue/Attribute:data+' => '追加情報', -)); +]); // // Class: EventWebService // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:EventWebService' => 'ウェブサービスイベント', 'Class:EventWebService+' => 'ウェブサービス呼出のトレース', 'Class:EventWebService/Attribute:verb' => '動作', @@ -387,9 +387,9 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Class:EventWebService/Attribute:log_error+' => 'エラーログ結果', 'Class:EventWebService/Attribute:data' => 'データ', 'Class:EventWebService/Attribute:data+' => '結果データ', -)); +]); -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:EventRestService' => 'REST/JSON call~~', 'Class:EventRestService+' => 'Trace of a REST/JSON service call~~', 'Class:EventRestService/Attribute:operation' => 'Operation~~', @@ -404,13 +404,13 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Class:EventRestService/Attribute:json_output+' => 'HTTP response (json)~~', 'Class:EventRestService/Attribute:provider' => 'Provider~~', 'Class:EventRestService/Attribute:provider+' => 'PHP class implementing the expected operation~~', -)); +]); // // Class: EventLoginUsage // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:EventLoginUsage' => 'ログイン方法', 'Class:EventLoginUsage+' => 'アプリケーションへ接続します。', 'Class:EventLoginUsage/Attribute:user_id' => 'ログイン', @@ -419,13 +419,13 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Class:EventLoginUsage/Attribute:contact_name+' => 'ユーザ名', 'Class:EventLoginUsage/Attribute:contact_email' => 'ユーザのEmail', 'Class:EventLoginUsage/Attribute:contact_email+' => 'ユーザの電子メールアドレス', -)); +]); // // Class: EventNotificationNewsroom // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:EventNotificationNewsroom' => 'News sent~~', 'Class:EventNotificationNewsroom+' => '~~', 'Class:EventNotificationNewsroom/Attribute:title' => 'Title~~', @@ -454,13 +454,13 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Class:EventNotificationNewsroom/Attribute:read_date+' => '~~', 'Class:EventNotificationNewsroom/Attribute:contact_id' => 'Contact~~', 'Class:EventNotificationNewsroom/Attribute:contact_id+' => '~~', -)); +]); // // Class: Action // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:Action' => 'カスタムアクション', 'Class:Action+' => 'ユーザ定義アクション', 'Class:Action/ComplementaryName' => '%1$s: %2$s~~', @@ -490,22 +490,22 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Action:last_executions_tab_panel_title' => 'Executions of this action (%1$s)~~', 'Action:last_executions_tab_limit_days' => 'past %1$s days~~', 'Action:last_executions_tab_limit_none' => 'no limit~~', -)); +]); // // Class: ActionNotification // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:ActionNotification' => '通知', 'Class:ActionNotification+' => '通知(要約)', -)); +]); // // Class: ActionEmail // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:ActionEmail' => 'メール通知', 'Class:ActionEmail+' => '', 'Class:ActionEmail/Attribute:status+' => 'This status drives who will be notified: @@ -560,14 +560,13 @@ If omitted the From (label) is used.~~', 'ActionEmail:preview_warning' => 'The actual eMail may look different in the eMail client than this preview in your browser.~~', 'ActionEmail:preview_more_info' => 'For more information about the CSS features supported by the different eMail clients, refer to %1$s~~', 'ActionEmail:content_placeholder_missing' => 'The placeholder "%1$s" was not found in the HTML template. The content of the field "%2$s" will not be included in the generated emails.~~', -)); - +]); // // Class: ActionNewsroom // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'ActionNewsroom:trigger' => 'Trigger~~', 'ActionNewsroom:content' => 'Message~~', 'ActionNewsroom:settings' => 'Settings~~', @@ -602,13 +601,13 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Class:ActionNewsroom/Attribute:recipients+' => 'An OQL query returning Contact objects~~', 'Class:ActionNewsroom/Attribute:url' => 'URL~~', 'Class:ActionNewsroom/Attribute:url+' => 'By default, it points to the object triggering the notification. But you can also specify a custom URL.~~', -)); +]); // // Class: Trigger // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:Trigger' => 'トリガー', 'Class:Trigger+' => 'カスタムイベントハンドラー', 'Class:Trigger/ComplementaryName' => '%1$s, %2$s~~', @@ -627,13 +626,13 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Class:Trigger/Attribute:subscription_policy/Value:allow_no_channel' => 'Allow complete unsubscription~~', 'Class:Trigger/Attribute:subscription_policy/Value:force_at_least_one_channel' => 'Force at least one channel (News or Email)~~', 'Class:Trigger/Attribute:subscription_policy/Value:force_all_channels' => 'Deny unsubscription~~', -)); +]); // // Class: TriggerOnObject // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:TriggerOnObject' => 'トリガー(クラス依存)', 'Class:TriggerOnObject+' => 'オブジェクトの指定されたクラスのトリガー', 'Class:TriggerOnObject/Attribute:target_class' => 'ターゲットクラス', @@ -642,115 +641,115 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Class:TriggerOnObject/Attribute:filter+' => 'Limit the object list (of the target class) which will activate the trigger~~', 'TriggerOnObject:WrongFilterQuery' => 'Wrong filter query: %1$s~~', 'TriggerOnObject:WrongFilterClass' => 'The filter query must return objects of class "%1$s"~~', -)); +]); // // Class: TriggerOnPortalUpdate // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:TriggerOnPortalUpdate' => 'トリガー(ポータルから更新された時)', 'Class:TriggerOnPortalUpdate+' => 'エンドユーザがポータルから更新した場合のトリガー', -)); +]); // // Class: TriggerOnStateChange // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:TriggerOnStateChange' => '(状態変化の)トリガー', 'Class:TriggerOnStateChange+' => 'オブジェクトの状態変化のトリガー', 'Class:TriggerOnStateChange/Attribute:state' => '状態', 'Class:TriggerOnStateChange/Attribute:state+' => '状態', -)); +]); // // Class: TriggerOnStateEnter // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:TriggerOnStateEnter' => '入状態トリガー', 'Class:TriggerOnStateEnter+' => 'オブジェクトの状態へ入る変化(エンター,on entering a state)時のトリガー', -)); +]); // // Class: TriggerOnStateLeave // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:TriggerOnStateLeave' => '出状態トリガー', 'Class:TriggerOnStateLeave+' => 'オブジェクトの状態から出る変化(リーブ,on leaving a state)時のトリガー', -)); +]); // // Class: TriggerOnObjectCreate // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:TriggerOnObjectCreate' => 'オブジェクト作成トリガー', 'Class:TriggerOnObjectCreate+' => '指定されたクラスの(子クラスの)オブジェクト作成時のトリガ', -)); +]); // // Class: TriggerOnObjectDelete // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:TriggerOnObjectDelete' => 'Trigger (on object deletion)~~', 'Class:TriggerOnObjectDelete+' => 'Trigger on object deletion of [a child class of] the given class~~', -)); +]); // // Class: TriggerOnObjectUpdate // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:TriggerOnObjectUpdate' => 'Trigger (on object update)~~', 'Class:TriggerOnObjectUpdate+' => 'Trigger on object update of [a child class of] the given class~~', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes' => 'Target fields~~', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes+' => '~~', -)); +]); // // Class: TriggerOnObjectMention // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:TriggerOnObjectMention' => 'Trigger (on object mention)~~', 'Class:TriggerOnObjectMention+' => 'Trigger on mention (@xxx) of an object of [a child class of] the given class in a log attribute~~', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter' => 'Mentioned filter~~', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter+' => 'Limit the list of mentioned objects which will activate the trigger. If empty, any mentioned object (of any class) will activate it.~~', -)); +]); // // Class: TriggerOnAttributeBlobDownload // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:TriggerOnAttributeBlobDownload' => 'Trigger (on object\'s document download)~~', 'Class:TriggerOnAttributeBlobDownload+' => 'Trigger on object\'s document field download of [a child class of] the given class~~', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes' => 'Target fields~~', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes+' => '~~', -)); +]); // // Class: TriggerOnThresholdReached // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:TriggerOnThresholdReached' => 'トリガー (on threshold)', 'Class:TriggerOnThresholdReached+' => 'トリガー (on Stop-Watch threshold reached)', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code' => 'ストップウオッチ', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code+' => '', 'Class:TriggerOnThresholdReached/Attribute:threshold_index' => 'しきい値', 'Class:TriggerOnThresholdReached/Attribute:threshold_index+' => '', -)); +]); // // Class: lnkTriggerAction // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:lnkTriggerAction' => 'トリガ/アクション', 'Class:lnkTriggerAction+' => 'トリガとアクション間のリンク', 'Class:lnkTriggerAction/Attribute:action_id' => 'アクション', @@ -763,12 +762,12 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Class:lnkTriggerAction/Attribute:trigger_name+' => '', 'Class:lnkTriggerAction/Attribute:order' => '順序', 'Class:lnkTriggerAction/Attribute:order+' => 'アクション実行順序', -)); +]); // // Synchro Data Source // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:SynchroDataSource' => '同期データソース', 'Class:SynchroDataSource/Attribute:name' => '名前', 'Class:SynchroDataSource/Attribute:name+' => '名前', @@ -1056,13 +1055,13 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Core:Validator:MustBeInteger' => 'Must be an integer~~', 'Core:Validator:MustSelectOne' => 'Please, select one~~', 'Menu:DataSources' => '同期データソース', - 'Menu:DataSources+' => '全ての同期データソース' -)); + 'Menu:DataSources+' => '全ての同期データソース', +]); // // Class: TagSetFieldData // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:TagSetFieldData' => '%2$s for class %1$s~~', 'Class:TagSetFieldData+' => '~~', 'Class:TagSetFieldData/Attribute:code' => 'Code~~', @@ -1084,12 +1083,12 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Core:TagSetFieldData:ErrorAttCodeUpdateNotAllowed' => 'Tags "Attribute Code" cannot be changed~~', 'Core:TagSetFieldData:WhereIsThisTagTab' => 'Tag usage (%1$d)~~', 'Core:TagSetFieldData:NoEntryFound' => 'No entry found for this tag~~', -)); +]); // // Class: DBProperty // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:DBProperty' => 'DB property~~', 'Class:DBProperty+' => '~~', 'Class:DBProperty/Attribute:name' => 'Name~~', @@ -1102,12 +1101,12 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Class:DBProperty/Attribute:change_date+' => '~~', 'Class:DBProperty/Attribute:change_comment' => 'Change comment~~', 'Class:DBProperty/Attribute:change_comment+' => '~~', -)); +]); // // Class: BackgroundTask // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:BackgroundTask' => 'Background task~~', 'Class:BackgroundTask+' => '~~', 'Class:BackgroundTask/Attribute:class_name' => 'Class name~~', @@ -1132,12 +1131,12 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Class:BackgroundTask/Attribute:running+' => '~~', 'Class:BackgroundTask/Attribute:status' => 'Status~~', 'Class:BackgroundTask/Attribute:status+' => '~~', -)); +]); // // Class: AsyncTask // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:AsyncTask' => 'Async. task~~', 'Class:AsyncTask+' => '~~', 'Class:AsyncTask/Attribute:created' => 'Created~~', @@ -1162,47 +1161,44 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'Class:AsyncTask/Attribute:last_attempt+' => '~~', 'Class:AsyncTask:InvalidConfig_Class_Keys' => 'Invalid format for the configuration of "async_task_retries[%1$s]". Expecting an array with the following keys: %2$s~~', 'Class:AsyncTask:InvalidConfig_Class_InvalidKey_Keys' => 'Invalid format for the configuration of "async_task_retries[%1$s]": unexpected key "%2$s". Expecting only the following keys: %3$s~~', -)); +]); // // Class: AbstractResource // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:AbstractResource' => 'Abstract Resource~~', 'Class:AbstractResource+' => '~~', -)); +]); // // Class: ResourceAdminMenu // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:ResourceAdminMenu' => 'Resource Admin Menu~~', 'Class:ResourceAdminMenu+' => '~~', -)); +]); // // Class: ResourceRunQueriesMenu // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:ResourceRunQueriesMenu' => 'Resource Run Queries Menu~~', 'Class:ResourceRunQueriesMenu+' => '~~', -)); +]); // // Class: Action // -Dict::Add('JA JP', 'Japanese', '日本語', array( +Dict::Add('JA JP', 'Japanese', '日本語', [ 'Class:ResourceSystemMenu' => 'Resource System Menu~~', 'Class:ResourceSystemMenu+' => '~~', - 'Class:EventNotification/Attribute:object_class' => 'Object class~~', - 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', + 'Class:EventNotification/Attribute:object_class' => 'Object class~~', + 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', 'Core:EventNotificationNewsroom:ErrorNotificationNotSent' => 'Notification not sent~~', 'Core:EventNotificationNewsroom:ErrorOnDBInsert' => 'An error occurred while saving the notification~~', -)); - - - +]); diff --git a/dictionaries/nl.dictionary.itop.core.php b/dictionaries/nl.dictionary.itop.core.php index 3127871f5..8792932df 100644 --- a/dictionaries/nl.dictionary.itop.core.php +++ b/dictionaries/nl.dictionary.itop.core.php @@ -1,17 +1,18 @@ * @author Thomas Casteleyn * @author Jeffrey Bostoen (2019 - 2022) */ -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Core:DeletedObjectLabel' => '%1s (verwijderd)', 'Core:DeletedObjectTip' => 'Het object is verwijderd op %1$s (%2$s)', 'Core:UnknownObjectLabel' => 'Object niet gevonden (klasse: %1$s, id: %2$d)', @@ -159,8 +160,7 @@ Operators:
'Core:Context=GUI:Console' => 'Console', 'Core:Context=CRON' => 'cron', 'Core:Context=GUI:Portal' => 'Portaal', -)); - +]); ////////////////////////////////////////////////////////////////////// // Classes in 'core/cmdb' @@ -171,7 +171,7 @@ Operators:
// Class: CMDBChange // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:CMDBChange' => 'Aanpassing', 'Class:CMDBChange+' => 'Opvolging van aanpassingen', 'Class:CMDBChange/Attribute:date' => 'datum', @@ -186,13 +186,13 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Class:CMDBChange/Attribute:origin/Value:webservice-rest' => 'REST/JSON webservices', 'Class:CMDBChange/Attribute:origin/Value:webservice-soap' => 'SOAP webservices', 'Class:CMDBChange/Attribute:origin/Value:custom-extension' => 'Via een extensie', -)); +]); // // Class: CMDBChangeOp // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:CMDBChangeOp' => 'Aanpassingsactie', 'Class:CMDBChangeOp+' => 'Opvolging van uitgevoerde aanpassingen', 'Class:CMDBChangeOp/Attribute:change' => 'Aanpassing', @@ -207,51 +207,51 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Class:CMDBChangeOp/Attribute:objkey+' => '', 'Class:CMDBChangeOp/Attribute:finalclass' => 'Soort', 'Class:CMDBChangeOp/Attribute:finalclass+' => '', -)); +]); // // Class: CMDBChangeOpCreate // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:CMDBChangeOpCreate' => 'Aanmaken object', 'Class:CMDBChangeOpCreate+' => 'Historiek van aanmaken van het object', -)); +]); // // Class: CMDBChangeOpDelete // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:CMDBChangeOpDelete' => 'Verwijderen object', 'Class:CMDBChangeOpDelete+' => 'Historiek van verwijderen van het object', -)); +]); // // Class: CMDBChangeOpSetAttribute // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:CMDBChangeOpSetAttribute' => 'Aanpassen object', 'Class:CMDBChangeOpSetAttribute+' => 'Historiek van het aanpassen van de objecteigenschappen', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode' => 'Attribuut', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode+' => 'Code van de aangepaste eigenschap', -)); +]); // // Class: CMDBChangeOpSetAttributeScalar // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:CMDBChangeOpSetAttributeScalar' => 'Aanpassen objecteigenschap', 'Class:CMDBChangeOpSetAttributeScalar+' => 'Historiek van gewijzigde eigenschappen', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue' => 'Vorige waarde', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue+' => 'Vorige waarde van de eigenschap', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue' => 'Nieuwe waarde', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue+' => 'Nieuwe waarde van de eigenschap', -)); +]); // Used by CMDBChangeOp... & derived classes -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Change:ObjectCreated' => 'Object aangemaakt', 'Change:ObjectDeleted' => 'Object verwijderd', 'Change:ObjectModified' => 'Object aangepast', @@ -268,35 +268,35 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Change:LinkSet:Added' => 'toegevoegd %1$s', 'Change:LinkSet:Removed' => 'verwijderd %1$s', 'Change:LinkSet:Modified' => 'aangepast %1$s', -)); +]); // // Class: CMDBChangeOpSetAttributeBlob // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:CMDBChangeOpSetAttributeBlob' => 'Aanpassen data', 'Class:CMDBChangeOpSetAttributeBlob+' => 'Historiek van data-aanpassingen', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata' => 'Vorige data', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata+' => 'Vorige inhoud van de eigenschap', -)); +]); // // Class: CMDBChangeOpSetAttributeText // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:CMDBChangeOpSetAttributeText' => 'Aanpassen tekst', 'Class:CMDBChangeOpSetAttributeText+' => 'Historiek van tekstaanpassingen', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata' => 'Vorige data', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata+' => 'Vorige inhoud van de eigenschap', -)); +]); // // Class: Event // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:Event' => 'Gebeurtenis', 'Class:Event+' => 'Een interne gebeurtenis binnen de applicatie', 'Class:Event/Attribute:message' => 'Inhoud', @@ -307,13 +307,13 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Class:Event/Attribute:userinfo+' => 'Info over wie/wat (bv. welke service) de aanpassing heeft doorgevoerd', 'Class:Event/Attribute:finalclass' => 'Type', 'Class:Event/Attribute:finalclass+' => '', -)); +]); // // Class: EventNotification // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:EventNotification' => 'Gebeurtenis - melding', 'Class:EventNotification+' => 'Historiek van de melding die getriggerd werd', 'Class:EventNotification/Attribute:trigger_id' => 'Trigger', @@ -322,13 +322,13 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Class:EventNotification/Attribute:action_id+' => 'De gebruiker die de melding veroorzaakte', 'Class:EventNotification/Attribute:object_id' => 'ID object', 'Class:EventNotification/Attribute:object_id+' => 'ID object (klasse gedefineerd door de trigger)', -)); +]); // // Class: EventNotificationEmail // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:EventNotificationEmail' => 'Gebeurtenis - versturen van e-mail', 'Class:EventNotificationEmail+' => 'Historiek van de e-mail die verstuurd is', 'Class:EventNotificationEmail/Attribute:to' => 'Aan', @@ -345,13 +345,13 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Class:EventNotificationEmail/Attribute:body+' => '', 'Class:EventNotificationEmail/Attribute:attachments' => 'Bijlagen', 'Class:EventNotificationEmail/Attribute:attachments+' => '', -)); +]); // // Class: EventIssue // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:EventIssue' => 'Gebeurtenis - probleem', 'Class:EventIssue+' => 'Log van een probleem (waarschuwing, fout, ...)', 'Class:EventIssue/Attribute:issue' => 'Probleem', @@ -368,13 +368,13 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Class:EventIssue/Attribute:callstack+' => '', 'Class:EventIssue/Attribute:data' => 'Data', 'Class:EventIssue/Attribute:data+' => 'Meer informatie', -)); +]); // // Class: EventWebService // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:EventWebService' => 'Gebeurtenis - web service', 'Class:EventWebService+' => 'Log van een webservice-aanroep', 'Class:EventWebService/Attribute:verb' => 'Werkwoord', @@ -389,9 +389,9 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Class:EventWebService/Attribute:log_error+' => 'Resultaat foutenlog', 'Class:EventWebService/Attribute:data' => 'Data', 'Class:EventWebService/Attribute:data+' => 'Resulterende data', -)); +]); -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:EventRestService' => 'Gebeurtenis - REST/JSON API-aanroep', 'Class:EventRestService+' => 'Log van een aangeroepen REST/JSON-service', 'Class:EventRestService/Attribute:operation' => 'Handeling', @@ -406,13 +406,13 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Class:EventRestService/Attribute:json_output+' => 'HTTP-antwoord (JSON)', 'Class:EventRestService/Attribute:provider' => 'Provider', 'Class:EventRestService/Attribute:provider+' => 'PHP-klasse die de verwachte handeling gebruikt', -)); +]); // // Class: EventLoginUsage // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:EventLoginUsage' => 'Gebeurtenis - gebruik van login', 'Class:EventLoginUsage+' => 'Verbinding met de applicatie', 'Class:EventLoginUsage/Attribute:user_id' => 'Login', @@ -421,13 +421,13 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Class:EventLoginUsage/Attribute:contact_name+' => '', 'Class:EventLoginUsage/Attribute:contact_email' => 'E-mailadres van de gebruiker', 'Class:EventLoginUsage/Attribute:contact_email+' => '', -)); +]); // // Class: EventNotificationNewsroom // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:EventNotificationNewsroom' => 'News sent~~', 'Class:EventNotificationNewsroom+' => '', 'Class:EventNotificationNewsroom/Attribute:title' => 'Titel', @@ -456,13 +456,13 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Class:EventNotificationNewsroom/Attribute:read_date+' => '', 'Class:EventNotificationNewsroom/Attribute:contact_id' => 'Contact', 'Class:EventNotificationNewsroom/Attribute:contact_id+' => '', -)); +]); // // Class: Action // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:Action' => 'Actie', 'Class:Action+' => 'Door gebruiker gedefinieerde actie', 'Class:Action/ComplementaryName' => '%1$s: %2$s', @@ -492,22 +492,22 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Action:last_executions_tab_panel_title' => 'Uitvoeringen van deze actie (%1$s)', 'Action:last_executions_tab_limit_days' => 'laatste %1$s dagen', 'Action:last_executions_tab_limit_none' => 'geen limiet', -)); +]); // // Class: ActionNotification // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:ActionNotification' => 'Melding', 'Class:ActionNotification+' => 'Melding (abstract)', -)); +]); // // Class: ActionEmail // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:ActionEmail' => 'E-mailmelding', 'Class:ActionEmail+' => '', 'Class:ActionEmail/Attribute:status+' => 'Status bepaalt wie op de hoogte zal gesteld worden: enkel de testontvanger, iedereen (Aan, CC en BCC) of niemand', @@ -558,14 +558,13 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'ActionEmail:preview_warning' => 'The actual eMail may look different in the eMail client than this preview in your browser.~~', 'ActionEmail:preview_more_info' => 'For more information about the CSS features supported by the different eMail clients, refer to %1$s~~', 'ActionEmail:content_placeholder_missing' => 'The placeholder "%1$s" was not found in the HTML template. The content of the field "%2$s" will not be included in the generated emails.~~', -)); - +]); // // Class: ActionNewsroom // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'ActionNewsroom:trigger' => 'Triggers', 'ActionNewsroom:content' => 'Bericht', 'ActionNewsroom:settings' => 'Instellingen', @@ -600,13 +599,13 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Class:ActionNewsroom/Attribute:recipients+' => 'OQL die de lijst van Contacten definiëert', 'Class:ActionNewsroom/Attribute:url' => 'URL', 'Class:ActionNewsroom/Attribute:url+' => 'By default, it points to the object triggering the notification. But you can also specify a custom URL.~~', -)); +]); // // Class: Trigger // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:Trigger' => 'Trigger', 'Class:Trigger+' => 'Aanleiding tot het uitvoeren van een actie', 'Class:Trigger/ComplementaryName' => '%1$s, %2$s', @@ -625,13 +624,13 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Class:Trigger/Attribute:subscription_policy/Value:allow_no_channel' => 'Volledige uitschrijving toestaan', 'Class:Trigger/Attribute:subscription_policy/Value:force_at_least_one_channel' => 'Forceer minimaal één kanaal (nieuws of e-mail)', 'Class:Trigger/Attribute:subscription_policy/Value:force_all_channels' => 'Afmelding weigeren', -)); +]); // // Class: TriggerOnObject // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:TriggerOnObject' => 'Trigger (afhankelijk van klasse)', 'Class:TriggerOnObject+' => 'Trigger op een bepaalde klasse van objecten', 'Class:TriggerOnObject/Attribute:target_class' => 'Toegepast op klasse', @@ -640,115 +639,115 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Class:TriggerOnObject/Attribute:filter+' => 'Beperk de objecten (van de opgegeven klasse) die de trigger zullen activeren.', 'TriggerOnObject:WrongFilterQuery' => 'Verkeerde filter-query: %1$s', 'TriggerOnObject:WrongFilterClass' => 'De filter-query moet verwijzen naar objecten van klasse "%1$s"', -)); +]); // // Class: TriggerOnPortalUpdate // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:TriggerOnPortalUpdate' => 'Trigger (als er vanuit het portaal geüpdatet wordt)', 'Class:TriggerOnPortalUpdate+' => 'Trigger op de update van de eindgebruiker van het portaal', -)); +]); // // Class: TriggerOnStateChange // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:TriggerOnStateChange' => 'Trigger (als de status verandert)', 'Class:TriggerOnStateChange+' => 'Trigger als de status van het object verandert', 'Class:TriggerOnStateChange/Attribute:state' => 'Status', 'Class:TriggerOnStateChange/Attribute:state+' => '', -)); +]); // // Class: TriggerOnStateEnter // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:TriggerOnStateEnter' => 'Trigger (als een status van toepassing wordt)', 'Class:TriggerOnStateEnter+' => 'Trigger als de status van het object naar deze status verandert', -)); +]); // // Class: TriggerOnStateLeave // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:TriggerOnStateLeave' => 'Trigger (als een status niet meer van toepassing is)', 'Class:TriggerOnStateLeave+' => 'Trigger als de status van het object niet meer deze status heeft', -)); +]); // // Class: TriggerOnObjectCreate // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:TriggerOnObjectCreate' => 'Trigger (bij het aanmaken van een object)', 'Class:TriggerOnObjectCreate+' => 'Trigger bij het aanmaken van een object van de opgegeven klasse (of subklasse ervan)', -)); +]); // // Class: TriggerOnObjectDelete // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:TriggerOnObjectDelete' => 'Trigger (bij het verwijderen van een object)', 'Class:TriggerOnObjectDelete+' => 'Trigger bij het verwijderen van een object van de opgegeven klasse (of subklasse ervan)', -)); +]); // // Class: TriggerOnObjectUpdate // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:TriggerOnObjectUpdate' => 'Trigger (bij het aanpassen van een object)', 'Class:TriggerOnObjectUpdate+' => 'Trigger bij het aanpassen van een object van de opgegeven klasse (of subklasse ervan)', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes' => 'Doelvelden', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes+' => '', -)); +]); // // Class: TriggerOnObjectMention // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:TriggerOnObjectMention' => 'Trigger (bij vermelden van object)', 'Class:TriggerOnObjectMention+' => 'Trigger bij vermelden (@xxx) van een object van de opgegeven klasse (of subklasse ervan) in een log', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter' => 'Filter', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter+' => 'Beperk de lijst van vermelde objecten die de trigger zullen activeren. Indien leeg, zullen alle objecten (van eender welke klasse) de trigger activeren.', -)); +]); // // Class: TriggerOnAttributeBlobDownload // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:TriggerOnAttributeBlobDownload' => 'Trigger (on object\'s document download)~~', 'Class:TriggerOnAttributeBlobDownload+' => 'Trigger on object\'s document field download of [a child class of] the given class~~', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes' => 'Doelvelden', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes+' => '', -)); +]); // // Class: TriggerOnThresholdReached // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:TriggerOnThresholdReached' => 'Trigger (op drempelwaarde)', 'Class:TriggerOnThresholdReached+' => 'Trigger op Stopwatch drempelwaarde bereikt', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code' => 'Stopwatch', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code+' => '', 'Class:TriggerOnThresholdReached/Attribute:threshold_index' => 'Drempelwaarde', 'Class:TriggerOnThresholdReached/Attribute:threshold_index+' => '', -)); +]); // // Class: lnkTriggerAction // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:lnkTriggerAction' => 'Link Actie / Trigger', 'Class:lnkTriggerAction+' => 'Link tussen een trigger en een actie', 'Class:lnkTriggerAction/Attribute:action_id' => 'Actie', @@ -761,12 +760,12 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Class:lnkTriggerAction/Attribute:trigger_name+' => '', 'Class:lnkTriggerAction/Attribute:order' => 'Volgorde', 'Class:lnkTriggerAction/Attribute:order+' => 'De volgorde in het uitvoeren van de actie', -)); +]); // // Synchro Data Source // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:SynchroDataSource' => 'Synchronisatie-databron', 'Class:SynchroDataSource/Attribute:name' => 'Naam', 'Class:SynchroDataSource/Attribute:name+' => '', @@ -1054,13 +1053,13 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Core:Validator:MustBeInteger' => 'Dit moet een integer (geheel getal) zijn', 'Core:Validator:MustSelectOne' => 'Gelieve één optie te kiezen', 'Menu:DataSources' => 'Synchronisatie Databronnen', - 'Menu:DataSources+' => 'Alle gesynchroniseerde Databronnen' -)); + 'Menu:DataSources+' => 'Alle gesynchroniseerde Databronnen', +]); // // Class: TagSetFieldData // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:TagSetFieldData' => '%2$s voor klasse %1$s', 'Class:TagSetFieldData+' => '', 'Class:TagSetFieldData/Attribute:code' => 'Code', @@ -1082,12 +1081,12 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Core:TagSetFieldData:ErrorAttCodeUpdateNotAllowed' => 'Tags "Attribuutcode" kunnen niet aangepast worden', 'Core:TagSetFieldData:WhereIsThisTagTab' => 'Gebruik tags (%1$d)', 'Core:TagSetFieldData:NoEntryFound' => 'Geen invoer gevorden voor deze tag', -)); +]); // // Class: DBProperty // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:DBProperty' => 'Database-eigenschap', 'Class:DBProperty+' => '', 'Class:DBProperty/Attribute:name' => 'Naam', @@ -1100,12 +1099,12 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Class:DBProperty/Attribute:change_date+' => '', 'Class:DBProperty/Attribute:change_comment' => 'Commentaar wijziging', 'Class:DBProperty/Attribute:change_comment+' => '', -)); +]); // // Class: BackgroundTask // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:BackgroundTask' => 'Achtergrondtaak', 'Class:BackgroundTask+' => '', 'Class:BackgroundTask/Attribute:class_name' => 'Naam klasse', @@ -1130,12 +1129,12 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Class:BackgroundTask/Attribute:running+' => '', 'Class:BackgroundTask/Attribute:status' => 'Status', 'Class:BackgroundTask/Attribute:status+' => '', -)); +]); // // Class: AsyncTask // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:AsyncTask' => 'Asynchrone taak', 'Class:AsyncTask+' => '', 'Class:AsyncTask/Attribute:created' => 'Gemaakt', @@ -1160,47 +1159,44 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'Class:AsyncTask/Attribute:last_attempt+' => '', 'Class:AsyncTask:InvalidConfig_Class_Keys' => 'Ongeldig formaat bij de configuratie van "async_tasks_retries[%1$s]". Er wordt een Array verwacht met de volgende sleutels: %2$s', 'Class:AsyncTask:InvalidConfig_Class_InvalidKey_Keys' => 'Ongeldig formaat bij de configuratie van "async_tasks_retries[%1$s]": onverwachte sleutel "%2$s". Enkel deze sleutels worden verwacht: %3$s', -)); +]); // // Class: AbstractResource // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:AbstractResource' => 'Abstracte Tool', 'Class:AbstractResource+' => '', -)); +]); // // Class: ResourceAdminMenu // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:ResourceAdminMenu' => 'Tool "Admin Menu"', 'Class:ResourceAdminMenu+' => '', -)); +]); // // Class: ResourceRunQueriesMenu // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:ResourceRunQueriesMenu' => 'Tool "Voer query\'s uit" Menu', 'Class:ResourceRunQueriesMenu+' => '', -)); +]); // // Class: Action // -Dict::Add('NL NL', 'Dutch', 'Nederlands', array( +Dict::Add('NL NL', 'Dutch', 'Nederlands', [ 'Class:ResourceSystemMenu' => 'Tool "System Menu"', 'Class:ResourceSystemMenu+' => '', - 'Class:EventNotification/Attribute:object_class' => 'Object class~~', - 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', + 'Class:EventNotification/Attribute:object_class' => 'Object class~~', + 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', 'Core:EventNotificationNewsroom:ErrorNotificationNotSent' => 'Notification not sent~~', 'Core:EventNotificationNewsroom:ErrorOnDBInsert' => 'An error occurred while saving the notification~~', -)); - - - +]); diff --git a/dictionaries/pl.dictionary.itop.core.php b/dictionaries/pl.dictionary.itop.core.php index 790569e43..0a0d978ca 100644 --- a/dictionaries/pl.dictionary.itop.core.php +++ b/dictionaries/pl.dictionary.itop.core.php @@ -1,15 +1,16 @@ '%1s (usunięto)', 'Core:DeletedObjectTip' => 'Obiekt został usunięty w dniu %1$s (%2$s)', 'Core:UnknownObjectLabel' => 'Nie znaleziono obiektu (klasa: %1$s, id: %2$d)', @@ -157,8 +158,7 @@ Operatory:
'Core:Context=GUI:Console' => 'Konsola', 'Core:Context=CRON' => 'cron', 'Core:Context=GUI:Portal' => 'Portal', -)); - +]); ////////////////////////////////////////////////////////////////////// // Classes in 'core/cmdb' @@ -169,7 +169,7 @@ Operatory:
// Class: CMDBChange // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:CMDBChange' => 'Zmiana', 'Class:CMDBChange+' => 'Śledzenie zmian', 'Class:CMDBChange/Attribute:date' => 'data', @@ -184,13 +184,13 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Class:CMDBChange/Attribute:origin/Value:webservice-rest' => 'Usługi sieciowe REST/JSON', 'Class:CMDBChange/Attribute:origin/Value:webservice-soap' => 'Usługi internetowe SOAP', 'Class:CMDBChange/Attribute:origin/Value:custom-extension' => 'Przez rozszerzenie', -)); +]); // // Class: CMDBChangeOp // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:CMDBChangeOp' => 'Operacje zmian', 'Class:CMDBChangeOp+' => 'Zmiana dokonana przez osobę na jednym obiekcie w jednostce czasu', 'Class:CMDBChangeOp/Attribute:change' => 'zmiana', @@ -205,51 +205,51 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Class:CMDBChangeOp/Attribute:objkey+' => 'identyfikator obiektu, którego dotyczy zmiana', 'Class:CMDBChangeOp/Attribute:finalclass' => 'Podklasa CMDBChangeOp', 'Class:CMDBChangeOp/Attribute:finalclass+' => 'Nazwa finalna klasy gdzie dokonano zmiany', -)); +]); // // Class: CMDBChangeOpCreate // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:CMDBChangeOpCreate' => 'tworzenie obiektu', 'Class:CMDBChangeOpCreate+' => 'Śledzenie tworzenia obiektów', -)); +]); // // Class: CMDBChangeOpDelete // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:CMDBChangeOpDelete' => 'usunięcie obiektu', 'Class:CMDBChangeOpDelete+' => 'Śledzenie usuwania obiektów', -)); +]); // // Class: CMDBChangeOpSetAttribute // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:CMDBChangeOpSetAttribute' => 'zmiana obiektu', 'Class:CMDBChangeOpSetAttribute+' => 'Śledzenie zmian właściwości obiektu', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode' => 'Atrybut', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode+' => 'kod zmodyfikowanej właściwości', -)); +]); // // Class: CMDBChangeOpSetAttributeScalar // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:CMDBChangeOpSetAttributeScalar' => 'zmiana właściwości', 'Class:CMDBChangeOpSetAttributeScalar+' => 'Śledzenie zmian właściwości skalarnych obiektu', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue' => 'Poprzednia wartość', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue+' => 'poprzednia wartość atrybutu', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue' => 'Nowa wartość', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue+' => 'nowa wartość atrybutu', -)); +]); // Used by CMDBChangeOp... & derived classes -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Change:ObjectCreated' => 'Utworzono obiekt', 'Change:ObjectDeleted' => 'Obiekt usunięty', 'Change:ObjectModified' => 'Obiekt zmodyfikowany', @@ -266,35 +266,35 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Change:LinkSet:Added' => 'dodano %1$s', 'Change:LinkSet:Removed' => 'usunięto %1$s', 'Change:LinkSet:Modified' => 'zmodyfikowano %1$s', -)); +]); // // Class: CMDBChangeOpSetAttributeBlob // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:CMDBChangeOpSetAttributeBlob' => 'zmiana danych', 'Class:CMDBChangeOpSetAttributeBlob+' => 'śledzenie zmian danych', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata' => 'Poprzednie dane', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata+' => 'poprzednia zawartość atrybutu', -)); +]); // // Class: CMDBChangeOpSetAttributeText // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:CMDBChangeOpSetAttributeText' => 'zmiana tekstu', 'Class:CMDBChangeOpSetAttributeText+' => 'śledzenie zmian tekstu', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata' => 'Poprzednie dane', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata+' => 'poprzednia zawartość atrybutu', -)); +]); // // Class: Event // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:Event' => 'Dziennik zdarzeń', 'Class:Event+' => 'Zdarzenie wewnętrzne aplikacji', 'Class:Event/Attribute:message' => 'Wiadomość', @@ -305,13 +305,13 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Class:Event/Attribute:userinfo+' => 'identyfikacja użytkownika wykonującego czynność, która wywołała to zdarzenie', 'Class:Event/Attribute:finalclass' => 'Podklasa zdarzenia', 'Class:Event/Attribute:finalclass+' => 'Nazwa finalnej klasy: określa rodzaj zdarzenia, które miało miejsce', -)); +]); // // Class: EventNotification // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:EventNotification' => 'Powiadomienie o zdarzeniu', 'Class:EventNotification+' => 'Ślad powiadomienia, które zostało wysłane', 'Class:EventNotification/Attribute:trigger_id' => 'Wyzwalacz', @@ -320,13 +320,13 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Class:EventNotification/Attribute:action_id+' => 'konto użytkownika', 'Class:EventNotification/Attribute:object_id' => 'Id obiektu', 'Class:EventNotification/Attribute:object_id+' => 'id obiektu (klasa zdefiniowana przez wyzwalacz?)', -)); +]); // // Class: EventNotificationEmail // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:EventNotificationEmail' => 'Zdarzenie wysyłki wiadomości e-mail', 'Class:EventNotificationEmail+' => 'Ślad e-maila, który został wysłany', 'Class:EventNotificationEmail/Attribute:to' => 'TO', @@ -343,13 +343,13 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Class:EventNotificationEmail/Attribute:body+' => '', 'Class:EventNotificationEmail/Attribute:attachments' => 'Załączniki', 'Class:EventNotificationEmail/Attribute:attachments+' => '', -)); +]); // // Class: EventIssue // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:EventIssue' => 'Zdarzenie związane z problemem', 'Class:EventIssue+' => 'Ślad problemu (ostrzeżenie, błąd itp.)', 'Class:EventIssue/Attribute:issue' => 'Problem', @@ -366,13 +366,13 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Class:EventIssue/Attribute:callstack+' => '', 'Class:EventIssue/Attribute:data' => 'Dane', 'Class:EventIssue/Attribute:data+' => 'Więcej informacji', -)); +]); // // Class: EventWebService // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:EventWebService' => 'Usługa internetowa', 'Class:EventWebService+' => 'Ślad połączenia z usługą internetową', 'Class:EventWebService/Attribute:verb' => 'Operacja', @@ -387,9 +387,9 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Class:EventWebService/Attribute:log_error+' => 'Wyniki dziennika błędów', 'Class:EventWebService/Attribute:data' => 'Dane', 'Class:EventWebService/Attribute:data+' => 'Dane wynikowe', -)); +]); -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:EventRestService' => 'Połączenie REST / JSON', 'Class:EventRestService+' => 'Śledzenie wywołania usługi REST / JSON', 'Class:EventRestService/Attribute:operation' => 'Operacja', @@ -404,13 +404,13 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Class:EventRestService/Attribute:json_output+' => 'Odpowiedź HTTP (json)', 'Class:EventRestService/Attribute:provider' => 'Dostawca', 'Class:EventRestService/Attribute:provider+' => 'Klasa PHP implementująca oczekiwaną operację', -)); +]); // // Class: EventLoginUsage // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:EventLoginUsage' => 'Korzystanie z logowania', 'Class:EventLoginUsage+' => 'Połączenie z aplikacją', 'Class:EventLoginUsage/Attribute:user_id' => 'Login', @@ -419,13 +419,13 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Class:EventLoginUsage/Attribute:contact_name+' => '', 'Class:EventLoginUsage/Attribute:contact_email' => 'E-mail użytkownika', 'Class:EventLoginUsage/Attribute:contact_email+' => 'Adres e-mail użytkownika', -)); +]); // // Class: EventNotificationNewsroom // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:EventNotificationNewsroom' => 'Wiadomości wysłane', 'Class:EventNotificationNewsroom+' => '', 'Class:EventNotificationNewsroom/Attribute:title' => 'Tytuł', @@ -454,13 +454,13 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Class:EventNotificationNewsroom/Attribute:read_date+' => '', 'Class:EventNotificationNewsroom/Attribute:contact_id' => 'Kontakt', 'Class:EventNotificationNewsroom/Attribute:contact_id+' => '', -)); +]); // // Class: Action // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:Action' => 'Działanie własne', 'Class:Action+' => 'Działanie zdefiniowane przez użytkownika', 'Class:Action/ComplementaryName' => '%1$s: %2$s', @@ -490,22 +490,22 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Action:last_executions_tab_panel_title' => 'Wykonania tej akcji (%1$s)', 'Action:last_executions_tab_limit_days' => 'ostatnie %1$s dni', 'Action:last_executions_tab_limit_none' => 'bez limitu', -)); +]); // // Class: ActionNotification // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:ActionNotification' => 'Powiadomienie', 'Class:ActionNotification+' => 'Powiadomienie (abstrakcja)', -)); +]); // // Class: ActionEmail // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:ActionEmail' => 'Powiadomienie e-mail', 'Class:ActionEmail+' => '', 'Class:ActionEmail/Attribute:status+' => 'Ten status decyduje o tym, kto zostanie powiadomiony: tylko odbiorca testowy, wszyscy (Do, DW i UDW) lub nikt', @@ -556,14 +556,13 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'ActionEmail:preview_warning' => 'Rzeczywista wiadomość e-mail może wyglądać inaczej w kliencie poczty e-mail niż podgląd w przeglądarce.', 'ActionEmail:preview_more_info' => 'Aby uzyskać więcej informacji na temat funkcji CSS obsługiwanych przez różnych klientów poczty e-mail, zobacz %1$s', 'ActionEmail:content_placeholder_missing' => 'W szablonie HTML nie znaleziono symbolu zastępczego „%1$s”. Zawartość pola „%2$s” nie będzie uwzględniana w generowanych wiadomościach e-mail.', -)); - +]); // // Class: ActionNewsroom // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'ActionNewsroom:trigger' => 'Wyzwalacz', 'ActionNewsroom:content' => 'Wiadomość', 'ActionNewsroom:settings' => 'Ustawienia', @@ -600,13 +599,13 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Class:ActionNewsroom/Attribute:recipients+' => 'Zapytanie OQL zwracające obiekty Kontakt', 'Class:ActionNewsroom/Attribute:url' => 'URL', 'Class:ActionNewsroom/Attribute:url+' => 'Jeśli jest pusty, adres URL będzie wskazywał obiekt wywołujący powiadomienie. Możesz także określić niestandardowy adres URL.', -)); +]); // // Class: Trigger // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:Trigger' => 'Wyzwalacz', 'Class:Trigger+' => 'Niestandardowa obsługa zdarzeń', 'Class:Trigger/ComplementaryName' => '%1$s, %2$s', @@ -625,13 +624,13 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Class:Trigger/Attribute:subscription_policy/Value:allow_no_channel' => 'Zezwalaj na całkowite anulowanie subskrypcji', 'Class:Trigger/Attribute:subscription_policy/Value:force_at_least_one_channel' => 'Wymuś co najmniej jeden kanał (Wiadomości lub E-mail)', 'Class:Trigger/Attribute:subscription_policy/Value:force_all_channels' => 'Odmów anulowania subskrypcji', -)); +]); // // Class: TriggerOnObject // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:TriggerOnObject' => 'Wyzwalacz (zależny od klasy)', 'Class:TriggerOnObject+' => 'Wyzwalanie na danej klasie obiektów', 'Class:TriggerOnObject/Attribute:target_class' => 'Klasa docelowa', @@ -640,115 +639,115 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Class:TriggerOnObject/Attribute:filter+' => 'Ogranicz listę obiektów (klasy docelowej), które aktywują wyzwalacz', 'TriggerOnObject:WrongFilterQuery' => 'Błędne zapytanie filtru: %1$s', 'TriggerOnObject:WrongFilterClass' => 'Zapytanie filtru musi zwracać obiekty klasy "%1$s"', -)); +]); // // Class: TriggerOnPortalUpdate // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:TriggerOnPortalUpdate' => 'Wyzwalacz (po aktualizacji z portalu)', 'Class:TriggerOnPortalUpdate+' => 'Wyzwalanie po aktualizacji użytkownika z portalu', -)); +]); // // Class: TriggerOnStateChange // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:TriggerOnStateChange' => 'Wyzwalacz (przy zmianie stanu)', 'Class:TriggerOnStateChange+' => 'Wyzwalanie przy zmianie stanu obiektu', 'Class:TriggerOnStateChange/Attribute:state' => 'Stan', 'Class:TriggerOnStateChange/Attribute:state+' => '', -)); +]); // // Class: TriggerOnStateEnter // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:TriggerOnStateEnter' => 'Wyzwalacz (przy wejściu w stan)', 'Class:TriggerOnStateEnter+' => 'Wyzwalanie przy zmianie stanu obiektu - wejście', -)); +]); // // Class: TriggerOnStateLeave // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:TriggerOnStateLeave' => 'Wyzwalacz (przy opuszczaniu stanu)', 'Class:TriggerOnStateLeave+' => 'Wyzwalanie przy zmianie stanu obiektu - wyjście', -)); +]); // // Class: TriggerOnObjectCreate // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:TriggerOnObjectCreate' => 'Wyzwalacz (przy tworzeniu obiektu)', 'Class:TriggerOnObjectCreate+' => 'Wyzwalacz przy tworzeniu obiektu [klasy potomnej] danej klasy', -)); +]); // // Class: TriggerOnObjectDelete // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:TriggerOnObjectDelete' => 'Wyzwalacz (przy usunięciu obiektu)', 'Class:TriggerOnObjectDelete+' => 'Wyzwalanie w przypadku usunięcia obiektu [klasy potomnej] danej klasy', -)); +]); // // Class: TriggerOnObjectUpdate // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:TriggerOnObjectUpdate' => 'Wyzwalacz (przy aktualizacji obiektu)', 'Class:TriggerOnObjectUpdate+' => 'Wyzwalanie przy aktualizacji obiektu [klasy potomnej] danej klasy', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes' => 'Pola docelowe', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes+' => '', -)); +]); // // Class: TriggerOnObjectMention // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:TriggerOnObjectMention' => 'Wyzwalacz (przy wzmiance o obiekcie)', 'Class:TriggerOnObjectMention+' => 'Wyzwalanie przy wzmiance (@xxx) o obiekcie [klasy potomnej] danej klasy w atrybucie dziennika', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter' => 'Wspomniany filtr', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter+' => 'Ogranicz listę wymienionych obiektów, które aktywują wyzwalacz. Jeśli jest pusty, dowolny wspomniany obiekt (dowolnej klasy) aktywuje go.', -)); +]); // // Class: TriggerOnAttributeBlobDownload // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:TriggerOnAttributeBlobDownload' => 'Wyzwalacz (po pobraniu dokumentu obiektu)', 'Class:TriggerOnAttributeBlobDownload+' => 'Wyzwalaj pobranie z pola dokumentu obiektu [klasy potomnej] danej klasy', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes' => 'Pola docelowe', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes+' => '', -)); +]); // // Class: TriggerOnThresholdReached // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:TriggerOnThresholdReached' => 'Wyzwalacz (na progu)', 'Class:TriggerOnThresholdReached+' => 'Osiągnięto próg wyzwalania przy stoperze', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code' => 'Stoper', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code+' => '', 'Class:TriggerOnThresholdReached/Attribute:threshold_index' => 'Próg', 'Class:TriggerOnThresholdReached/Attribute:threshold_index+' => '', -)); +]); // // Class: lnkTriggerAction // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:lnkTriggerAction' => 'Działanie / wyzwalacz', 'Class:lnkTriggerAction+' => 'Powiązanie między wyzwalaczem a działaniem', 'Class:lnkTriggerAction/Attribute:action_id' => 'Działanie', @@ -761,12 +760,12 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Class:lnkTriggerAction/Attribute:trigger_name+' => '', 'Class:lnkTriggerAction/Attribute:order' => 'Order', 'Class:lnkTriggerAction/Attribute:order+' => 'Kolejność wykonywania działań', -)); +]); // // Synchro Data Source // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:SynchroDataSource' => 'Źródło danych synchronizacji', 'Class:SynchroDataSource/Attribute:name' => 'Nazwa', 'Class:SynchroDataSource/Attribute:name+' => '', @@ -1051,13 +1050,13 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Core:Validator:MustBeInteger' => 'Musi być liczbą całkowitą', 'Core:Validator:MustSelectOne' => 'Proszę wybrać jeden', 'Menu:DataSources' => 'Źródła danych synchronizacji', - 'Menu:DataSources+' => 'Wszystkie źródła danych synchronizacji' -)); + 'Menu:DataSources+' => 'Wszystkie źródła danych synchronizacji', +]); // // Class: TagSetFieldData // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:TagSetFieldData' => '%2$s dla klasy %1$s', 'Class:TagSetFieldData+' => '', 'Class:TagSetFieldData/Attribute:code' => 'Kod', @@ -1079,12 +1078,12 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Core:TagSetFieldData:ErrorAttCodeUpdateNotAllowed' => 'Tagów "Kod atrybutu" nie można zmieniać', 'Core:TagSetFieldData:WhereIsThisTagTab' => 'Użycie tagu (%1$d)', 'Core:TagSetFieldData:NoEntryFound' => 'Nie znaleziono wpisu dla tego tagu', -)); +]); // // Class: DBProperty // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:DBProperty' => 'Właściwości DB', 'Class:DBProperty+' => '', 'Class:DBProperty/Attribute:name' => 'Nazwa', @@ -1097,12 +1096,12 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Class:DBProperty/Attribute:change_date+' => '', 'Class:DBProperty/Attribute:change_comment' => 'Komentarz zmiany', 'Class:DBProperty/Attribute:change_comment+' => '', -)); +]); // // Class: BackgroundTask // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:BackgroundTask' => 'Zadanie w tle', 'Class:BackgroundTask+' => '', 'Class:BackgroundTask/Attribute:class_name' => 'Nazwa klasy', @@ -1127,12 +1126,12 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Class:BackgroundTask/Attribute:running+' => '', 'Class:BackgroundTask/Attribute:status' => 'Status', 'Class:BackgroundTask/Attribute:status+' => '', -)); +]); // // Class: AsyncTask // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:AsyncTask' => 'Zadanie asynchroniczne', 'Class:AsyncTask+' => '', 'Class:AsyncTask/Attribute:created' => 'Utworzono', @@ -1157,47 +1156,44 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'Class:AsyncTask/Attribute:last_attempt+' => '', 'Class:AsyncTask:InvalidConfig_Class_Keys' => 'Nieprawidłowy format konfiguracji "async_task_retries[%1$s]". Oczekuje się tablicy z następującymi kluczami: %2$s', 'Class:AsyncTask:InvalidConfig_Class_InvalidKey_Keys' => 'Nieprawidłowy format konfiguracji "async_task_retries[%1$s]": nieoczekiwany klucz "%2$s". Oczekuje się tylko następujących kluczy: %3$s', -)); +]); // // Class: AbstractResource // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:AbstractResource' => 'Zasób abstrakcyjny', 'Class:AbstractResource+' => '', -)); +]); // // Class: ResourceAdminMenu // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:ResourceAdminMenu' => 'Zasób Menu administratora', 'Class:ResourceAdminMenu+' => '', -)); +]); // // Class: ResourceRunQueriesMenu // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:ResourceRunQueriesMenu' => 'Zasób Menu zapytań uruchamiania', 'Class:ResourceRunQueriesMenu+' => '', -)); +]); // // Class: Action // -Dict::Add('PL PL', 'Polish', 'Polski', array( +Dict::Add('PL PL', 'Polish', 'Polski', [ 'Class:ResourceSystemMenu' => 'Zasób Menu systemowe', 'Class:ResourceSystemMenu+' => '', - 'Class:EventNotification/Attribute:object_class' => 'Object class~~', - 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', + 'Class:EventNotification/Attribute:object_class' => 'Object class~~', + 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', 'Core:EventNotificationNewsroom:ErrorNotificationNotSent' => 'Notification not sent~~', 'Core:EventNotificationNewsroom:ErrorOnDBInsert' => 'An error occurred while saving the notification~~', -)); - - - +]); diff --git a/dictionaries/pt_br.dictionary.itop.core.php b/dictionaries/pt_br.dictionary.itop.core.php index 7ba900a5c..447c2fe05 100644 --- a/dictionaries/pt_br.dictionary.itop.core.php +++ b/dictionaries/pt_br.dictionary.itop.core.php @@ -1,15 +1,16 @@ '%1s (excluído)', 'Core:DeletedObjectTip' => 'O objeto foi excluído em %1$s (%2$s)', 'Core:UnknownObjectLabel' => 'Objeto não encontrado (classe: %1$s, id: %2$d)', @@ -157,8 +158,7 @@ Operadores:
'Core:Context=GUI:Console' => 'Console', 'Core:Context=CRON' => 'cron', 'Core:Context=GUI:Portal' => 'Portal do usuário', -)); - +]); ////////////////////////////////////////////////////////////////////// // Classes in 'core/cmdb' @@ -169,7 +169,7 @@ Operadores:
// Class: CMDBChange // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:CMDBChange' => 'Alterações no CMDB', 'Class:CMDBChange+' => 'Controle de mudanças no CMDB', 'Class:CMDBChange/Attribute:date' => 'Data', @@ -184,13 +184,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:CMDBChange/Attribute:origin/Value:webservice-rest' => 'REST/JSON webservices', 'Class:CMDBChange/Attribute:origin/Value:webservice-soap' => 'SOAP WebServices', 'Class:CMDBChange/Attribute:origin/Value:custom-extension' => 'Por uma extensão', -)); +]); // // Class: CMDBChangeOp // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:CMDBChangeOp' => 'Operações de alteração', 'Class:CMDBChangeOp+' => 'Controle de operações de alteração', 'Class:CMDBChangeOp/Attribute:change' => 'Alteração', @@ -205,51 +205,51 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:CMDBChangeOp/Attribute:objkey+' => '', 'Class:CMDBChangeOp/Attribute:finalclass' => 'Tipo', 'Class:CMDBChangeOp/Attribute:finalclass+' => '', -)); +]); // // Class: CMDBChangeOpCreate // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:CMDBChangeOpCreate' => 'Criação de objeto', 'Class:CMDBChangeOpCreate+' => 'Controle de criação do objeto', -)); +]); // // Class: CMDBChangeOpDelete // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:CMDBChangeOpDelete' => 'Exclusão de objeto', 'Class:CMDBChangeOpDelete+' => 'Controle de exclusão do objeto', -)); +]); // // Class: CMDBChangeOpSetAttribute // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:CMDBChangeOpSetAttribute' => 'Alteração de propriedades', 'Class:CMDBChangeOpSetAttribute+' => 'Controle de alteração de propriedades do objeto', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode' => 'Atributo', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode+' => 'Código da propriedade modificada', -)); +]); // // Class: CMDBChangeOpSetAttributeScalar // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:CMDBChangeOpSetAttributeScalar' => 'Alteração de propriedades escalares', 'Class:CMDBChangeOpSetAttributeScalar+' => 'Controle de alterações de propriedades escalares do objeto', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue' => 'Valor anterior', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue+' => 'Valor anterior do atributo', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue' => 'Novo valor', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue+' => 'Novo valor do atributo', -)); +]); // Used by CMDBChangeOp... & derived classes -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Change:ObjectCreated' => 'Objeto criado', 'Change:ObjectDeleted' => 'Objeto excluído', 'Change:ObjectModified' => 'Objeto modificado', @@ -266,35 +266,35 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Change:LinkSet:Added' => 'adicionado %1$s', 'Change:LinkSet:Removed' => 'excluído %1$s', 'Change:LinkSet:Modified' => 'modificado %1$s', -)); +]); // // Class: CMDBChangeOpSetAttributeBlob // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:CMDBChangeOpSetAttributeBlob' => 'Alteração de conteúdo (Blob)', 'Class:CMDBChangeOpSetAttributeBlob+' => 'Controle de alterações de conteúdo de dados (Blob)', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata' => 'Valor anterior', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata+' => 'Conteúdo anterior do atributo', -)); +]); // // Class: CMDBChangeOpSetAttributeText // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:CMDBChangeOpSetAttributeText' => 'Alteração de texto', 'Class:CMDBChangeOpSetAttributeText+' => 'Controle de alterações de texto do objeto', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata' => 'Valor anterior', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata+' => 'Conteúdo anterior do atributo', -)); +]); // // Class: Event // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Event' => 'Registro de evento', 'Class:Event+' => 'Um evento interno da aplicação', 'Class:Event/Attribute:message' => 'Mensagem', @@ -305,13 +305,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Event/Attribute:userinfo+' => 'Identificação do usuário que estava executando a ação que desencadeou este evento', 'Class:Event/Attribute:finalclass' => 'Tipo', 'Class:Event/Attribute:finalclass+' => '', -)); +]); // // Class: EventNotification // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:EventNotification' => 'Notificação de evento', 'Class:EventNotification+' => 'Controle de notificações que foram enviadas', 'Class:EventNotification/Attribute:trigger_id' => 'Gatilho', @@ -320,13 +320,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:EventNotification/Attribute:action_id+' => 'Conta de usuário', 'Class:EventNotification/Attribute:object_id' => 'ID do objeto', 'Class:EventNotification/Attribute:object_id+' => 'ID do objeto (classe definida pelo gatilho?)', -)); +]); // // Class: EventNotificationEmail // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:EventNotificationEmail' => 'Evento de envio de e-mail', 'Class:EventNotificationEmail+' => 'Controle de e-mails que foram enviados', 'Class:EventNotificationEmail/Attribute:to' => 'Para', @@ -343,13 +343,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:EventNotificationEmail/Attribute:body+' => 'Conteúdo do e-mail', 'Class:EventNotificationEmail/Attribute:attachments' => 'Anexos', 'Class:EventNotificationEmail/Attribute:attachments+' => '', -)); +]); // // Class: EventIssue // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:EventIssue' => 'Evento de entrega', 'Class:EventIssue+' => 'Controle de entrega (aviso, erro, etc.)', 'Class:EventIssue/Attribute:issue' => 'Entrega', @@ -366,13 +366,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:EventIssue/Attribute:callstack+' => '', 'Class:EventIssue/Attribute:data' => 'Dados', 'Class:EventIssue/Attribute:data+' => 'Mais informações', -)); +]); // // Class: EventWebService // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:EventWebService' => 'Evento Web service', 'Class:EventWebService+' => 'Controle de uma solicitação de WebService', 'Class:EventWebService/Attribute:verb' => 'Verb', @@ -387,9 +387,9 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:EventWebService/Attribute:log_error+' => '', 'Class:EventWebService/Attribute:data' => 'Dados', 'Class:EventWebService/Attribute:data+' => 'Mais informações', -)); +]); -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:EventRestService' => 'Chamada REST/JSON', 'Class:EventRestService+' => 'Controle de uma chamada de serviço REST/JSON', 'Class:EventRestService/Attribute:operation' => 'Operação', @@ -404,13 +404,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:EventRestService/Attribute:json_output+' => 'Resposta HTTP (JSON)', 'Class:EventRestService/Attribute:provider' => 'Provedor', 'Class:EventRestService/Attribute:provider+' => 'Classe PHP implementando a operação esperada', -)); +]); // // Class: EventLoginUsage // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:EventLoginUsage' => 'Logins', 'Class:EventLoginUsage+' => 'Conexões com a aplicação', 'Class:EventLoginUsage/Attribute:user_id' => 'Login', @@ -419,13 +419,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:EventLoginUsage/Attribute:contact_name+' => '', 'Class:EventLoginUsage/Attribute:contact_email' => 'E-mail do usuário', 'Class:EventLoginUsage/Attribute:contact_email+' => 'Endereço de e-mail deste usuário', -)); +]); // // Class: EventNotificationNewsroom // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:EventNotificationNewsroom' => 'News sent~~', 'Class:EventNotificationNewsroom+' => '~~', 'Class:EventNotificationNewsroom/Attribute:title' => 'Title~~', @@ -454,13 +454,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:EventNotificationNewsroom/Attribute:read_date+' => '~~', 'Class:EventNotificationNewsroom/Attribute:contact_id' => 'Contact~~', 'Class:EventNotificationNewsroom/Attribute:contact_id+' => '~~', -)); +]); // // Class: Action // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Action' => 'Ação personalizada', 'Class:Action+' => 'Ações definidas pelo usuário', 'Class:Action/ComplementaryName' => '%1$s: %2$s~~', @@ -490,22 +490,22 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Action:last_executions_tab_panel_title' => 'Executions of this action (%1$s)~~', 'Action:last_executions_tab_limit_days' => 'past %1$s days~~', 'Action:last_executions_tab_limit_none' => 'no limit~~', -)); +]); // // Class: ActionNotification // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:ActionNotification' => 'Notificação', 'Class:ActionNotification+' => 'Notificação (resumo)', -)); +]); // // Class: ActionEmail // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:ActionEmail' => 'Notificação via E-mail', 'Class:ActionEmail+' => 'Lista de Notificações via E-mail', 'Class:ActionEmail/Attribute:status+' => 'Esse status especifica quem será notificado: apenas o destinatário do Teste, todos (Para, CC e CCO) ou ninguém', @@ -556,14 +556,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'ActionEmail:preview_warning' => 'The actual eMail may look different in the eMail client than this preview in your browser.~~', 'ActionEmail:preview_more_info' => 'For more information about the CSS features supported by the different eMail clients, refer to %1$s~~', 'ActionEmail:content_placeholder_missing' => 'The placeholder "%1$s" was not found in the HTML template. The content of the field "%2$s" will not be included in the generated emails.~~', -)); - +]); // // Class: ActionNewsroom // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'ActionNewsroom:trigger' => 'Trigger~~', 'ActionNewsroom:content' => 'Message~~', 'ActionNewsroom:settings' => 'Settings~~', @@ -598,13 +597,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:ActionNewsroom/Attribute:recipients+' => 'An OQL query returning Contact objects~~', 'Class:ActionNewsroom/Attribute:url' => 'URL~~', 'Class:ActionNewsroom/Attribute:url+' => 'By default, it points to the object triggering the notification. But you can also specify a custom URL.~~', -)); +]); // // Class: Trigger // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Trigger' => 'Gatilho', 'Class:Trigger+' => 'Manipulador de eventos personalizado', 'Class:Trigger/ComplementaryName' => '%1$s, %2$s~~', @@ -623,13 +622,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:Trigger/Attribute:subscription_policy/Value:allow_no_channel' => 'Allow complete unsubscription~~', 'Class:Trigger/Attribute:subscription_policy/Value:force_at_least_one_channel' => 'Force at least one channel (News or Email)~~', 'Class:Trigger/Attribute:subscription_policy/Value:force_all_channels' => 'Deny unsubscription~~', -)); +]); // // Class: TriggerOnObject // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:TriggerOnObject' => 'Gatilho (classe dependente)', 'Class:TriggerOnObject+' => 'Gatilho em uma determinada classe de objetos', 'Class:TriggerOnObject/Attribute:target_class' => 'Classe alvo', @@ -638,115 +637,115 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:TriggerOnObject/Attribute:filter+' => 'Limita a lista de objetos (da classe de destino) que irá ativar o gatilho', 'TriggerOnObject:WrongFilterQuery' => 'Consulta de filtro incorreta: %1$s', 'TriggerOnObject:WrongFilterClass' => 'A consulta de filtro deve retornar objetos da classe \\"%1$s\\"', -)); +]); // // Class: TriggerOnPortalUpdate // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:TriggerOnPortalUpdate' => 'Gatilho (quando atualizado a partir do portal do usuário)', 'Class:TriggerOnPortalUpdate+' => 'Gatilho acionado a partir de uma atualização do usuário final através do portal do usuário', -)); +]); // // Class: TriggerOnStateChange // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:TriggerOnStateChange' => 'Gatilho (na mudança de status)', 'Class:TriggerOnStateChange+' => 'Gatilho de mudança de status do objeto', 'Class:TriggerOnStateChange/Attribute:state' => 'Status', 'Class:TriggerOnStateChange/Attribute:state+' => '', -)); +]); // // Class: TriggerOnStateEnter // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:TriggerOnStateEnter' => 'Gatilho (ao entrar em um status)', 'Class:TriggerOnStateEnter+' => 'Gatilho de mudança de status do objeto - entrada', -)); +]); // // Class: TriggerOnStateLeave // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:TriggerOnStateLeave' => 'Gatilho (ao sair de um status)', 'Class:TriggerOnStateLeave+' => 'Gatilho de mudança de status do objeto - saída', -)); +]); // // Class: TriggerOnObjectCreate // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:TriggerOnObjectCreate' => 'Gatilho (na criação do objeto)', 'Class:TriggerOnObjectCreate+' => 'Gatilho de criação de objeto de [uma classe filha] de determinada classe', -)); +]); // // Class: TriggerOnObjectDelete // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:TriggerOnObjectDelete' => 'Gatilho (na exclusão de objetos)', 'Class:TriggerOnObjectDelete+' => 'Gatilho na exclusão de objeto de [uma classe filha] de determinada classe', -)); +]); // // Class: TriggerOnObjectUpdate // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:TriggerOnObjectUpdate' => 'Gatilho (na atualização do objeto)', 'Class:TriggerOnObjectUpdate+' => 'Gatilho na atualização de objeto de [uma classe filha] de uma determinada classe', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes' => 'Campos de destino', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes+' => '', -)); +]); // // Class: TriggerOnObjectMention // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:TriggerOnObjectMention' => 'Gatilho (na menção do objeto)', 'Class:TriggerOnObjectMention+' => 'Gatilho em menção (@xxx) de um objeto de [uma classe filha] de uma determinada classe em um atributo de log', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter' => 'Filtro de menções', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter+' => 'Limita a lista de objetos mencionados que ativarão o gatilho. Se vazio, qualquer objeto mencionado (de qualquer classe) irá ativá-lo', -)); +]); // // Class: TriggerOnAttributeBlobDownload // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:TriggerOnAttributeBlobDownload' => 'Trigger (on object\'s document download)~~', 'Class:TriggerOnAttributeBlobDownload+' => 'Trigger on object\'s document field download of [a child class of] the given class~~', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes' => 'Target fields~~', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes+' => '~~', -)); +]); // // Class: TriggerOnThresholdReached // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:TriggerOnThresholdReached' => 'Gatilho (no alcance do limite)', 'Class:TriggerOnThresholdReached+' => 'Gatilho no alcance do limite do cronômetro', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code' => 'Cronômetro', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code+' => '', 'Class:TriggerOnThresholdReached/Attribute:threshold_index' => 'Limite', 'Class:TriggerOnThresholdReached/Attribute:threshold_index+' => '', -)); +]); // // Class: lnkTriggerAction // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkTriggerAction' => 'Ação/Gatilho', 'Class:lnkTriggerAction+' => 'Relação entre Gatilho / Ação', 'Class:lnkTriggerAction/Attribute:action_id' => 'Ação', @@ -759,12 +758,12 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkTriggerAction/Attribute:trigger_name+' => '', 'Class:lnkTriggerAction/Attribute:order' => 'Ordem', 'Class:lnkTriggerAction/Attribute:order+' => 'Ordem de execução das ações', -)); +]); // // Synchro Data Source // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:SynchroDataSource' => 'Fonte de Sincronização de Dados', 'Class:SynchroDataSource/Attribute:name' => 'Nome', 'Class:SynchroDataSource/Attribute:name+' => '', @@ -1053,13 +1052,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Core:Validator:MustSelectOne' => 'Por favor, selecione um', 'INTERNAL:JQuery-DatePicker:LangCode' => 'pt-BR', 'Menu:DataSources' => 'Fontes de Sincronização de Dados', - 'Menu:DataSources+' => 'Lista de Fontes de Sincronização de Dados' -)); + 'Menu:DataSources+' => 'Lista de Fontes de Sincronização de Dados', +]); // // Class: TagSetFieldData // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:TagSetFieldData' => '%2$s para classe %1$s', 'Class:TagSetFieldData+' => '', 'Class:TagSetFieldData/Attribute:code' => 'Código', @@ -1081,12 +1080,12 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Core:TagSetFieldData:ErrorAttCodeUpdateNotAllowed' => 'Tags de "Código do atributo" não podem ser alteradas', 'Core:TagSetFieldData:WhereIsThisTagTab' => 'Uso de tags (%1$d)', 'Core:TagSetFieldData:NoEntryFound' => 'Nenhuma entrada encontrada para esta tag', -)); +]); // // Class: DBProperty // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:DBProperty' => 'Propriedades do DB', 'Class:DBProperty+' => '', 'Class:DBProperty/Attribute:name' => 'Nome', @@ -1099,12 +1098,12 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:DBProperty/Attribute:change_date+' => '', 'Class:DBProperty/Attribute:change_comment' => 'Editar comentário', 'Class:DBProperty/Attribute:change_comment+' => '', -)); +]); // // Class: BackgroundTask // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:BackgroundTask' => 'Tarefas de fundo', 'Class:BackgroundTask+' => '', 'Class:BackgroundTask/Attribute:class_name' => 'Nome da classe', @@ -1129,12 +1128,12 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:BackgroundTask/Attribute:running+' => '', 'Class:BackgroundTask/Attribute:status' => 'Status', 'Class:BackgroundTask/Attribute:status+' => '', -)); +]); // // Class: AsyncTask // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:AsyncTask' => 'Tarefa assíncrona', 'Class:AsyncTask+' => '', 'Class:AsyncTask/Attribute:created' => 'Criada', @@ -1159,47 +1158,44 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:AsyncTask/Attribute:last_attempt+' => '', 'Class:AsyncTask:InvalidConfig_Class_Keys' => 'Formato inválido para a configuração de "async_task_retries[%1$s]". Esperando um array com as seguintes chaves: %2$s', 'Class:AsyncTask:InvalidConfig_Class_InvalidKey_Keys' => 'Formato inválido para a configuração de "async_task_retries[%1$s]": chave inesperada "%2$s". Esperando somente as seguintes chaves: %3$s', -)); +]); // // Class: AbstractResource // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:AbstractResource' => 'Recurso Abstrato', 'Class:AbstractResource+' => '', -)); +]); // // Class: ResourceAdminMenu // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:ResourceAdminMenu' => 'Recurso Menu de Administração', 'Class:ResourceAdminMenu+' => '', -)); +]); // // Class: ResourceRunQueriesMenu // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:ResourceRunQueriesMenu' => 'Recurso Livro de Consultas', 'Class:ResourceRunQueriesMenu+' => '', -)); +]); // // Class: Action // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:ResourceSystemMenu' => 'Recurso Menu do Sistema', 'Class:ResourceSystemMenu+' => '', - 'Class:EventNotification/Attribute:object_class' => 'Object class~~', - 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', + 'Class:EventNotification/Attribute:object_class' => 'Object class~~', + 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', 'Core:EventNotificationNewsroom:ErrorNotificationNotSent' => 'Notification not sent~~', 'Core:EventNotificationNewsroom:ErrorOnDBInsert' => 'An error occurred while saving the notification~~', -)); - - - +]); diff --git a/dictionaries/pt_br.dictionary.itop.ui.php b/dictionaries/pt_br.dictionary.itop.ui.php index 76e388cbe..cfce7e213 100644 --- a/dictionaries/pt_br.dictionary.itop.ui.php +++ b/dictionaries/pt_br.dictionary.itop.ui.php @@ -1,15 +1,16 @@ 'Categoria de Auditoria', 'Class:AuditCategory+' => 'Uma seção dentro da auditoria', 'Class:AuditCategory/Attribute:name' => 'Nome', @@ -26,13 +27,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:AuditCategory/Attribute:warning_error_tolerance+' => 'Percentage of invalid objects below which the result is in error (red)~~', 'Class:AuditCategory/Attribute:domains_list' => 'Domains~~', 'Class:AuditCategory/Attribute:domains_list+' => 'Domains which include this category~~', -)); +]); // // Class: AuditRule // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:AuditRule' => 'Regra de Auditoria', 'Class:AuditRule+' => 'Uma regra para verificar se uma determinada categoria de Auditoria', 'Class:AuditRule/Attribute:name' => 'Nome', @@ -51,13 +52,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:AuditRule/Attribute:category_id+' => 'A categoria para esta regra', 'Class:AuditRule/Attribute:category_name' => 'Categoria', 'Class:AuditRule/Attribute:category_name+' => 'Nome da categoria para essa regra', -)); +]); // // Class: AuditDomain // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:AuditDomain' => 'Audit Domain~~', 'Class:AuditDomain+' => 'Audit domains allow to group the audit categories. Domain usually correspond to who is responsible for checking and fixing errors~~', @@ -69,13 +70,13 @@ Domain usually correspond to who is responsible for checking and fixing errors~~ 'Class:AuditDomain/Attribute:icon+' => '~~', 'Class:AuditDomain/Attribute:categories_list' => 'Categories~~', 'Class:AuditDomain/Attribute:categories_list+' => 'Related audit categories. When running the audit on a domain, all related audit categories are checked and only those.~~', -)); +]); // // Class: lnkAuditCategoryToAuditDomain // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:lnkAuditCategoryToAuditDomain' => 'Link AuditCategory / AuditDomain~~', 'Class:lnkAuditCategoryToAuditDomain+' => '~~', 'Class:lnkAuditCategoryToAuditDomain/Attribute:category_id' => 'Category~~', @@ -86,13 +87,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:lnkAuditCategoryToAuditDomain/Attribute:domain_id+' => 'Audit domain~~', 'Class:lnkAuditCategoryToAuditDomain/Attribute:domain_name' => 'Domain name~~', 'Class:lnkAuditCategoryToAuditDomain/Attribute:domain_name+' => 'Audit domain name~~', -)); +]); // // Class: QueryOQL // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:Query' => 'Consulta', 'Class:Query+' => 'Uma consulta é um conjunto de dados definido de uma forma dinâmica', 'Class:Query/Attribute:name' => 'Nome', @@ -119,7 +120,7 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:QueryOQL+' => 'Uma consulta baseada no Object Query Language (OQL)', 'Class:QueryOQL/Attribute:oql' => 'Expressão', 'Class:QueryOQL/Attribute:oql+' => 'Expressão Object Query Language (OQL)', -)); +]); ////////////////////////////////////////////////////////////////////// // Classes in 'addon/userrights' @@ -130,7 +131,7 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( // Class: User // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:User' => 'Usuário', 'Class:User+' => '', 'Class:User/Attribute:finalclass' => 'Tipo de conta', @@ -176,13 +177,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:User/Warning:NoContactHasImpact' => 'Cautious: there is no Person defined on this User, this prevents access to portals, news notifications and other side effects in back-office~~', 'Class:UserInternal' => 'Usuário Interno', 'Class:UserInternal+' => 'Usuário definido dentro do '.ITOP_APPLICATION_SHORT, -)); +]); // // Class: URP_Profiles // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:URP_Profiles' => 'Perfil', 'Class:URP_Profiles+' => 'Perfil do Usuário', 'Class:URP_Profiles/Attribute:name' => 'Nome', @@ -191,13 +192,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:URP_Profiles/Attribute:description+' => 'Uma descrição curta', 'Class:URP_Profiles/Attribute:user_list' => 'Usuários', 'Class:URP_Profiles/Attribute:user_list+' => 'Pessoas que possuem esse perfil', -)); +]); // // Class: URP_Dimensions // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:URP_Dimensions' => 'Dimensão', 'Class:URP_Dimensions+' => 'Dimensão de aplicação (definição de silos)', 'Class:URP_Dimensions/Attribute:name' => 'Nome', @@ -206,13 +207,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:URP_Dimensions/Attribute:description+' => 'Uma descrição curta', 'Class:URP_Dimensions/Attribute:type' => 'Tipo', 'Class:URP_Dimensions/Attribute:type+' => 'Nome da classe ou tipo de dado (unidade de mapeamento)', -)); +]); // // Class: URP_UserProfile // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:URP_UserProfile' => 'Perfil de usuário', 'Class:URP_UserProfile+' => '', 'Class:URP_UserProfile/Name' => 'Relação entre %1$s e %2$s', @@ -226,14 +227,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:URP_UserProfile/Attribute:profile+' => 'Nome do perfil', 'Class:URP_UserProfile/Attribute:reason' => 'Função', 'Class:URP_UserProfile/Attribute:reason+' => 'Explicação por que esta pessoa deve ter essa função', -)); +]); // // Class: URP_UserOrg // - -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:URP_UserOrg' => 'Organização do usuário', 'Class:URP_UserOrg+' => 'Organizações permitidas', 'Class:URP_UserOrg/Name' => 'Relação entre %1$s e %2$s', @@ -247,13 +247,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:URP_UserOrg/Attribute:allowed_org_name+' => 'Organização permitida', 'Class:URP_UserOrg/Attribute:reason' => 'Função', 'Class:URP_UserOrg/Attribute:reason+' => 'Explicação por que essa pessoa tem permissão para ver os dados pertencentes com essa organização', -)); +]); // // Class: URP_ProfileProjection // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:URP_ProfileProjection' => 'Mapeamentos de Perfil', 'Class:URP_ProfileProjection+' => '', 'Class:URP_ProfileProjection/Attribute:dimensionid' => 'Dimensão', @@ -268,13 +268,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:URP_ProfileProjection/Attribute:value+' => 'Expressão OQL (usando $user) | constante | | +código de atributo', 'Class:URP_ProfileProjection/Attribute:attribute' => 'Atributo', 'Class:URP_ProfileProjection/Attribute:attribute+' => 'Código de atributo alvo (opcional)', -)); +]); // // Class: URP_ClassProjection // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:URP_ClassProjection' => 'class_projection', 'Class:URP_ClassProjection+' => 'class projections', 'Class:URP_ClassProjection/Attribute:dimensionid' => 'Dimensão', @@ -287,13 +287,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:URP_ClassProjection/Attribute:value+' => 'Expressão OQL (usando $ user) | constante | | + código de atributo', 'Class:URP_ClassProjection/Attribute:attribute' => 'Atributo', 'Class:URP_ClassProjection/Attribute:attribute+' => 'Código de atributo alvo (opcional)', -)); +]); // // Class: URP_ActionGrant // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:URP_ActionGrant' => 'action_permission', 'Class:URP_ActionGrant+' => 'Permissões de classes', 'Class:URP_ActionGrant/Attribute:profileid' => 'Perfil', @@ -310,13 +310,13 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:URP_ActionGrant/Attribute:permission/Value:no+' => '', 'Class:URP_ActionGrant/Attribute:action' => 'Ação', 'Class:URP_ActionGrant/Attribute:action+' => 'Operações a realizar em determinada classe', -)); +]); // // Class: URP_StimulusGrant // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:URP_StimulusGrant' => 'stimulus_permission', 'Class:URP_StimulusGrant+' => 'Permissões de estímulo do ciclo de vida do objeto', 'Class:URP_StimulusGrant/Attribute:profileid' => 'Perfil', @@ -333,25 +333,25 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:URP_StimulusGrant/Attribute:permission/Value:no+' => '', 'Class:URP_StimulusGrant/Attribute:stimulus' => 'Estímulo', 'Class:URP_StimulusGrant/Attribute:stimulus+' => 'Código do estímulo', -)); +]); // // Class: URP_AttributeGrant // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:URP_AttributeGrant' => 'attribute_permission', 'Class:URP_AttributeGrant+' => 'Permissões a nível de atributos', 'Class:URP_AttributeGrant/Attribute:actiongrantid' => 'Concessão de permissão', 'Class:URP_AttributeGrant/Attribute:actiongrantid+' => 'Concessão de permissão', 'Class:URP_AttributeGrant/Attribute:attcode' => 'Atributo', 'Class:URP_AttributeGrant/Attribute:attcode+' => 'Código do atributo', -)); +]); // // Class: UserDashboard // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Class:UserDashboard' => 'Painel do usuário', 'Class:UserDashboard+' => '', 'Class:UserDashboard/Attribute:user_id' => 'Usuário', @@ -360,12 +360,12 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Class:UserDashboard/Attribute:menu_code+' => '', 'Class:UserDashboard/Attribute:contents' => 'Conteúdo', 'Class:UserDashboard/Attribute:contents+' => '', -)); +]); // // Duplicated into itop-welcome-itil ( will be removed from here...) // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Menu:WelcomeMenu' => 'Página inicial do '.ITOP_APPLICATION_SHORT, 'Menu:WelcomeMenu+' => 'Bem-vindo ao '.ITOP_APPLICATION_SHORT, 'Menu:WelcomeMenuPage' => 'Página inicial do '.ITOP_APPLICATION_SHORT, 'Menu:WelcomeMenuPage+' => 'Bem-vindo ao '.ITOP_APPLICATION_SHORT, 'Menu:AdminTools' => 'Ferramentas Administrativas', 'Menu:AdminTools+' => 'Ferramentas Administrativas', 'Menu:AdminTools?' => 'Ferramentas acessíveis apenas para usuários com perfil de administrador', @@ -380,14 +380,14 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Menu:MyShortcuts' => 'Meus atalhos', 'Menu:Notifications:Title' => 'Categorias de Auditoria', 'Menu:DataAdministration' => 'Administração de Dados', - 'Menu:DataAdministration+' => 'Administração de Dados' -)); + 'Menu:DataAdministration+' => 'Administração de Dados', +]); // // String from the User Interface: menu, messages, buttons, etc... // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'BooleanLabel:yes' => 'Sim', 'BooleanLabel:no' => 'Não', 'UI:Login:Title' => 'Login no '.ITOP_APPLICATION_SHORT, @@ -1535,13 +1535,13 @@ Quando associada a um gatilho, cada ação recebe um número de "ordem", especif 'UI:Search:Criteria:HierarchicalKey:ChildrenIncluded:Hint' => 'Os objetos filhos dos objetos selecionados serão incluídos', 'UI:Search:Criteria:Raw:Filtered' => 'Filtrado', 'UI:Search:Criteria:Raw:FilteredOn' => 'Filtrado em %1$s', - 'UI:StateChanged' => 'Status alterado' -)); + 'UI:StateChanged' => 'Status alterado', +]); // // Expression to Natural language // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Expression:Operator:AND' => ' E ', 'Expression:Operator:OR' => ' OU ', 'Expression:Operator:=' => ': ', @@ -1554,12 +1554,12 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Expression:Unit:Long:MINUTE' => 'minuto(s)', 'Expression:Verb:NOW' => 'agora', 'Expression:Verb:ISNULL' => ': indefinido', -)); +]); // // iTop Newsroom menu // -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'UI:Newsroom:NoNewMessage' => 'Nenhuma mensagem nova', 'UI:Newsroom:XNewMessage' => '%1$s nova(s) mensagem(ns)', 'UI:Newsroom:MarkAllAsRead' => 'Marcar todas as mensagens como lidas', @@ -1574,10 +1574,9 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'UI:Newsroom:Priority:2:Tooltip' => 'Urgent~~', 'UI:Newsroom:Priority:3:Tooltip' => 'Important~~', 'UI:Newsroom:Priority:4:Tooltip' => 'Normal~~', -)); +]); - -Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( +Dict::Add('PT BR', 'Brazilian', 'Brazilian', [ 'Menu:DataSources' => 'Fontes de Sincronização de Dados', 'Menu:DataSources+' => 'Lista de Fontes de Sincronização de Dados', 'Menu:AuditCategories' => 'Categorias de Auditoria', @@ -1605,4 +1604,4 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'Menu:Integrations' => 'Integrations~~', 'Menu:Integrations+' => '~~', -)); +]); diff --git a/dictionaries/ru.dictionary.itop.core.php b/dictionaries/ru.dictionary.itop.core.php index c4ad47aa0..6927cc500 100644 --- a/dictionaries/ru.dictionary.itop.core.php +++ b/dictionaries/ru.dictionary.itop.core.php @@ -1,16 +1,17 @@ * */ -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Core:DeletedObjectLabel' => '%1$sы (удален)', 'Core:DeletedObjectTip' => 'Объект был удален %1$s (%2$s)', 'Core:UnknownObjectLabel' => 'Объект не найден (class: %1$s, id: %2$d)', @@ -158,8 +159,7 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Core:Context=GUI:Console' => 'Console', 'Core:Context=CRON' => 'cron', 'Core:Context=GUI:Portal' => 'Portal', -)); - +]); ////////////////////////////////////////////////////////////////////// // Classes in 'core/cmdb' @@ -170,7 +170,7 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( // Class: CMDBChange // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:CMDBChange' => 'Изменение CMDB', 'Class:CMDBChange+' => 'Отслеживание изменений CMDB', 'Class:CMDBChange/Attribute:date' => 'Дата', @@ -185,13 +185,13 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Class:CMDBChange/Attribute:origin/Value:webservice-rest' => 'REST/JSON webservices~~', 'Class:CMDBChange/Attribute:origin/Value:webservice-soap' => 'SOAP webservices~~', 'Class:CMDBChange/Attribute:origin/Value:custom-extension' => 'By an extension~~', -)); +]); // // Class: CMDBChangeOp // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:CMDBChangeOp' => 'Операция изменения CMDB', 'Class:CMDBChangeOp+' => 'Отслеживание операции изменения CMDB', 'Class:CMDBChangeOp/Attribute:change' => 'Изменение CMDB', @@ -206,51 +206,51 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Class:CMDBChangeOp/Attribute:objkey+' => '', 'Class:CMDBChangeOp/Attribute:finalclass' => 'Итоговый класс', 'Class:CMDBChangeOp/Attribute:finalclass+' => '', -)); +]); // // Class: CMDBChangeOpCreate // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:CMDBChangeOpCreate' => 'Операция создания объекта', 'Class:CMDBChangeOpCreate+' => 'Отслеживание создания объекта', -)); +]); // // Class: CMDBChangeOpDelete // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:CMDBChangeOpDelete' => 'Операция удаления объекта', 'Class:CMDBChangeOpDelete+' => 'Отслеживание удаления объекта', -)); +]); // // Class: CMDBChangeOpSetAttribute // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:CMDBChangeOpSetAttribute' => 'Изменение объекта', 'Class:CMDBChangeOpSetAttribute+' => 'Отслеживание изменения объекта', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode' => 'Свойство', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode+' => 'Код изменённого свойства', -)); +]); // // Class: CMDBChangeOpSetAttributeScalar // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:CMDBChangeOpSetAttributeScalar' => 'Изменение свойства', 'Class:CMDBChangeOpSetAttributeScalar+' => 'Отслеживание изменения скалярного свойства объекта', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue' => 'Предыдущее значение', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue+' => 'Предыдущее значение атрибута', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue' => 'Новое значение', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue+' => 'Новое значение атрибута', -)); +]); // Used by CMDBChangeOp... & derived classes -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Change:ObjectCreated' => 'Объект создан.', 'Change:ObjectDeleted' => 'Объект удалён.', 'Change:ObjectModified' => 'Объект изменён.', @@ -267,35 +267,35 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Change:LinkSet:Added' => 'добавлен объект %1$s.', 'Change:LinkSet:Removed' => 'удалён объект %1$s.', 'Change:LinkSet:Modified' => 'изменён объект %1$s.', -)); +]); // // Class: CMDBChangeOpSetAttributeBlob // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:CMDBChangeOpSetAttributeBlob' => 'Изменение данных', 'Class:CMDBChangeOpSetAttributeBlob+' => 'Отслеживание изменения данных', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata' => 'Предыдущие данные', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata+' => 'Предыдущее содержимое атрибута', -)); +]); // // Class: CMDBChangeOpSetAttributeText // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:CMDBChangeOpSetAttributeText' => 'Изменение текста', 'Class:CMDBChangeOpSetAttributeText+' => 'Отслеживание изменения текста', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata' => 'Предыдущие данные', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata+' => 'Предыдущее содержимое атрибута', -)); +]); // // Class: Event // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:Event' => 'Событие', 'Class:Event+' => 'Внутренние событие приложения', 'Class:Event/Attribute:message' => 'Сообщение', @@ -306,13 +306,13 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Class:Event/Attribute:userinfo+' => 'Пользователь, действия которого вызвали это событие', 'Class:Event/Attribute:finalclass' => 'Тип', 'Class:Event/Attribute:finalclass+' => '', -)); +]); // // Class: EventNotification // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:EventNotification' => 'Уведомление', 'Class:EventNotification+' => 'Отслеживание отправленных уведомлений', 'Class:EventNotification/Attribute:trigger_id' => 'Триггер', @@ -321,13 +321,13 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Class:EventNotification/Attribute:action_id+' => 'Выполненное действие', 'Class:EventNotification/Attribute:object_id' => 'ID объекта', 'Class:EventNotification/Attribute:object_id+' => 'Идентификатор объекта целевого класса триггера', -)); +]); // // Class: EventNotificationEmail // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:EventNotificationEmail' => 'Уведомление по email', 'Class:EventNotificationEmail+' => 'Отслеживание уведомлений по email', 'Class:EventNotificationEmail/Attribute:to' => 'Кому', @@ -344,13 +344,13 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Class:EventNotificationEmail/Attribute:body+' => '', 'Class:EventNotificationEmail/Attribute:attachments' => 'Вложения', 'Class:EventNotificationEmail/Attribute:attachments+' => '', -)); +]); // // Class: EventIssue // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:EventIssue' => 'Ошибка', 'Class:EventIssue+' => 'Отслеживание ошибок (warning, error, др.)', 'Class:EventIssue/Attribute:issue' => 'Ошибка', @@ -367,13 +367,13 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Class:EventIssue/Attribute:callstack+' => '', 'Class:EventIssue/Attribute:data' => 'Данные', 'Class:EventIssue/Attribute:data+' => 'Подробнее', -)); +]); // // Class: EventWebService // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:EventWebService' => 'События Web-сервиса', 'Class:EventWebService+' => 'Trace of a web service call~~', 'Class:EventWebService/Attribute:verb' => 'Verb~~', @@ -388,9 +388,9 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Class:EventWebService/Attribute:log_error+' => 'Результаты логов ошибок', 'Class:EventWebService/Attribute:data' => 'Данные', 'Class:EventWebService/Attribute:data+' => 'Результаты данных', -)); +]); -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:EventRestService' => 'REST/JSON call', 'Class:EventRestService+' => 'Trace of a REST/JSON service call', 'Class:EventRestService/Attribute:operation' => 'Operation', @@ -405,13 +405,13 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Class:EventRestService/Attribute:json_output+' => 'HTTP response (json)', 'Class:EventRestService/Attribute:provider' => 'Provider', 'Class:EventRestService/Attribute:provider+' => 'PHP class implementing the expected operation', -)); +]); // // Class: EventLoginUsage // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:EventLoginUsage' => 'Статистика авторизаций', 'Class:EventLoginUsage+' => 'Connection to the application', 'Class:EventLoginUsage/Attribute:user_id' => 'Логин', @@ -420,13 +420,13 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Class:EventLoginUsage/Attribute:contact_name+' => 'Имя пользователя', 'Class:EventLoginUsage/Attribute:contact_email' => 'Email пользователя', 'Class:EventLoginUsage/Attribute:contact_email+' => 'Email Address of the User', -)); +]); // // Class: EventNotificationNewsroom // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:EventNotificationNewsroom' => 'News sent~~', 'Class:EventNotificationNewsroom+' => '~~', 'Class:EventNotificationNewsroom/Attribute:title' => 'Title~~', @@ -455,13 +455,13 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Class:EventNotificationNewsroom/Attribute:read_date+' => '~~', 'Class:EventNotificationNewsroom/Attribute:contact_id' => 'Contact~~', 'Class:EventNotificationNewsroom/Attribute:contact_id+' => '~~', -)); +]); // // Class: Action // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:Action' => 'Действие', 'Class:Action+' => 'Действие, определённое пользователем', 'Class:Action/ComplementaryName' => '%1$s: %2$s~~', @@ -491,22 +491,22 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Action:last_executions_tab_panel_title' => 'Executions of this action (%1$s)~~', 'Action:last_executions_tab_limit_days' => 'past %1$s days~~', 'Action:last_executions_tab_limit_none' => 'no limit~~', -)); +]); // // Class: ActionNotification // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:ActionNotification' => 'Уведомление', 'Class:ActionNotification+' => '', -)); +]); // // Class: ActionEmail // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:ActionEmail' => 'Уведомление по email', 'Class:ActionEmail+' => '', 'Class:ActionEmail/Attribute:status+' => 'This status drives who will be notified: @@ -561,14 +561,13 @@ If omitted the From (label) is used.~~', 'ActionEmail:preview_warning' => 'The actual eMail may look different in the eMail client than this preview in your browser.~~', 'ActionEmail:preview_more_info' => 'For more information about the CSS features supported by the different eMail clients, refer to %1$s~~', 'ActionEmail:content_placeholder_missing' => 'The placeholder "%1$s" was not found in the HTML template. The content of the field "%2$s" will not be included in the generated emails.~~', -)); - +]); // // Class: ActionNewsroom // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'ActionNewsroom:trigger' => 'Trigger~~', 'ActionNewsroom:content' => 'Message~~', 'ActionNewsroom:settings' => 'Settings~~', @@ -603,13 +602,13 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Class:ActionNewsroom/Attribute:recipients+' => 'An OQL query returning Contact objects~~', 'Class:ActionNewsroom/Attribute:url' => 'URL~~', 'Class:ActionNewsroom/Attribute:url+' => 'By default, it points to the object triggering the notification. But you can also specify a custom URL.~~', -)); +]); // // Class: Trigger // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:Trigger' => 'Триггер', 'Class:Trigger+' => 'Пользовательский обработчик событий', 'Class:Trigger/ComplementaryName' => '%1$s, %2$s~~', @@ -628,13 +627,13 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Class:Trigger/Attribute:subscription_policy/Value:allow_no_channel' => 'Allow complete unsubscription~~', 'Class:Trigger/Attribute:subscription_policy/Value:force_at_least_one_channel' => 'Force at least one channel (News or Email)~~', 'Class:Trigger/Attribute:subscription_policy/Value:force_all_channels' => 'Deny unsubscription~~', -)); +]); // // Class: TriggerOnObject // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:TriggerOnObject' => 'Триггер на класс объекта', 'Class:TriggerOnObject+' => 'Триггер на события объектов данного класса', 'Class:TriggerOnObject/Attribute:target_class' => 'Целевой класс', @@ -643,115 +642,115 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Class:TriggerOnObject/Attribute:filter+' => 'Позволяет ограничить список объектов, для которых будет срабатывать триггер', 'TriggerOnObject:WrongFilterQuery' => 'Направильный запрос фильтра: %1$s', 'TriggerOnObject:WrongFilterClass' => 'Запрос фильтра должен возвращать объекты класса "%1$s"', -)); +]); // // Class: TriggerOnPortalUpdate // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:TriggerOnPortalUpdate' => 'Триггер на обновление из портала', 'Class:TriggerOnPortalUpdate+' => 'Триггер на обновление объекта пользователем портала', -)); +]); // // Class: TriggerOnStateChange // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:TriggerOnStateChange' => 'Триггер на изменение статуса', 'Class:TriggerOnStateChange+' => 'Триггер на изменение статуса объекта', 'Class:TriggerOnStateChange/Attribute:state' => 'Статус', 'Class:TriggerOnStateChange/Attribute:state+' => 'Код статуса объекта, например \'resolved\'', -)); +]); // // Class: TriggerOnStateEnter // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:TriggerOnStateEnter' => 'Триггер на вход в статус', 'Class:TriggerOnStateEnter+' => 'Триггер на вход объекта в статус', -)); +]); // // Class: TriggerOnStateLeave // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:TriggerOnStateLeave' => 'Триггер на выход из статуса', 'Class:TriggerOnStateLeave+' => 'Триггер на выход объекта из статуса', -)); +]); // // Class: TriggerOnObjectCreate // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:TriggerOnObjectCreate' => 'Триггер на создание объекта', 'Class:TriggerOnObjectCreate+' => 'Триггер на создание объекта данного или дочернего класса', -)); +]); // // Class: TriggerOnObjectDelete // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:TriggerOnObjectDelete' => 'Триггер на удаление объекта', 'Class:TriggerOnObjectDelete+' => 'Триггер на удаление объекта данного или дочернего класса', -)); +]); // // Class: TriggerOnObjectUpdate // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:TriggerOnObjectUpdate' => 'Триггер на обновление объекта', 'Class:TriggerOnObjectUpdate+' => 'Триггер на обновление объекта данного или дочернего класса', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes' => 'Отслеживаемые поля', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes+' => 'Поля объекта, при обновлении которых сработает триггер', -)); +]); // // Class: TriggerOnObjectMention // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:TriggerOnObjectMention' => 'Trigger (on object mention)~~', 'Class:TriggerOnObjectMention+' => 'Trigger on mention (@xxx) of an object of [a child class of] the given class in a log attribute~~', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter' => 'Mentioned filter~~', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter+' => 'Limit the list of mentioned objects which will activate the trigger. If empty, any mentioned object (of any class) will activate it.~~', -)); +]); // // Class: TriggerOnAttributeBlobDownload // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:TriggerOnAttributeBlobDownload' => 'Trigger (on object\'s document download)~~', 'Class:TriggerOnAttributeBlobDownload+' => 'Trigger on object\'s document field download of [a child class of] the given class~~', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes' => 'Target fields~~', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes+' => '~~', -)); +]); // // Class: TriggerOnThresholdReached // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:TriggerOnThresholdReached' => 'Триггер на пороговое значение', 'Class:TriggerOnThresholdReached+' => 'Триггер на достижение секундомером порогового значения (TTO, TTR)', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code' => 'Секундомер', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code+' => 'По умолчанию для Инцидентов и Запросов доступны \'ttr\' и \'tto\'', 'Class:TriggerOnThresholdReached/Attribute:threshold_index' => 'Порог', 'Class:TriggerOnThresholdReached/Attribute:threshold_index+' => 'Пороговое значние секундомера в %, по умолчанию \'75\' и \'100\'', -)); +]); // // Class: lnkTriggerAction // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:lnkTriggerAction' => 'Связь Триггер/Действие', 'Class:lnkTriggerAction+' => 'Связь между триггером и действиями', 'Class:lnkTriggerAction/Attribute:action_id' => 'Действие', @@ -764,12 +763,12 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Class:lnkTriggerAction/Attribute:trigger_name+' => '', 'Class:lnkTriggerAction/Attribute:order' => 'Порядок', 'Class:lnkTriggerAction/Attribute:order+' => 'Порядок выполнения действий', -)); +]); // // Synchro Data Source // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:SynchroDataSource' => 'Источник синхронизации данных', 'Class:SynchroDataSource/Attribute:name' => 'Название', 'Class:SynchroDataSource/Attribute:name+' => '', @@ -1057,13 +1056,13 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Core:Validator:MustBeInteger' => 'Должно быть целым числом', 'Core:Validator:MustSelectOne' => 'Пожалуйста, выберите значение', 'Menu:DataSources' => 'Синхронизация данных', - 'Menu:DataSources+' => '' -)); + 'Menu:DataSources+' => '', +]); // // Class: TagSetFieldData // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:TagSetFieldData' => '%2$s для класса %1$s', 'Class:TagSetFieldData+' => '', 'Class:TagSetFieldData/Attribute:code' => 'Код', @@ -1085,12 +1084,12 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Core:TagSetFieldData:ErrorAttCodeUpdateNotAllowed' => 'Нельзя изменить "Attribute Code" тега', 'Core:TagSetFieldData:WhereIsThisTagTab' => 'Использование тега (%1$d)', 'Core:TagSetFieldData:NoEntryFound' => 'Не найдено записей с этим тегом', -)); +]); // // Class: DBProperty // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:DBProperty' => 'DB property~~', 'Class:DBProperty+' => '', 'Class:DBProperty/Attribute:name' => 'Name~~', @@ -1103,12 +1102,12 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Class:DBProperty/Attribute:change_date+' => '', 'Class:DBProperty/Attribute:change_comment' => 'Change comment~~', 'Class:DBProperty/Attribute:change_comment+' => '', -)); +]); // // Class: BackgroundTask // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:BackgroundTask' => 'Background task~~', 'Class:BackgroundTask+' => '', 'Class:BackgroundTask/Attribute:class_name' => 'Class name~~', @@ -1133,12 +1132,12 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Class:BackgroundTask/Attribute:running+' => '', 'Class:BackgroundTask/Attribute:status' => 'Status~~', 'Class:BackgroundTask/Attribute:status+' => '', -)); +]); // // Class: AsyncTask // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:AsyncTask' => 'Async. task~~', 'Class:AsyncTask+' => '', 'Class:AsyncTask/Attribute:created' => 'Created~~', @@ -1163,47 +1162,44 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'Class:AsyncTask/Attribute:last_attempt+' => '', 'Class:AsyncTask:InvalidConfig_Class_Keys' => 'Invalid format for the configuration of "async_task_retries[%1$s]". Expecting an array with the following keys: %2$s~~', 'Class:AsyncTask:InvalidConfig_Class_InvalidKey_Keys' => 'Invalid format for the configuration of "async_task_retries[%1$s]": unexpected key "%2$s". Expecting only the following keys: %3$s~~', -)); +]); // // Class: AbstractResource // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:AbstractResource' => 'Ресурс', 'Class:AbstractResource+' => '', -)); +]); // // Class: ResourceAdminMenu // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:ResourceAdminMenu' => 'Меню Инструменты администратора', 'Class:ResourceAdminMenu+' => '', -)); +]); // // Class: ResourceRunQueriesMenu // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:ResourceRunQueriesMenu' => 'Меню Выполнение запросов', 'Class:ResourceRunQueriesMenu+' => '', -)); +]); // // Class: Action // -Dict::Add('RU RU', 'Russian', 'Русский', array( +Dict::Add('RU RU', 'Russian', 'Русский', [ 'Class:ResourceSystemMenu' => 'Меню Система', 'Class:ResourceSystemMenu+' => '', - 'Class:EventNotification/Attribute:object_class' => 'Object class~~', - 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', + 'Class:EventNotification/Attribute:object_class' => 'Object class~~', + 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', 'Core:EventNotificationNewsroom:ErrorNotificationNotSent' => 'Notification not sent~~', 'Core:EventNotificationNewsroom:ErrorOnDBInsert' => 'An error occurred while saving the notification~~', -)); - - - +]); diff --git a/dictionaries/sk.dictionary.itop.core.php b/dictionaries/sk.dictionary.itop.core.php index feab4e05d..f4571bd21 100644 --- a/dictionaries/sk.dictionary.itop.core.php +++ b/dictionaries/sk.dictionary.itop.core.php @@ -1,15 +1,16 @@ '%1s (odstránené)', 'Core:DeletedObjectTip' => 'Objekt bol odstránený o %1$s (%2$s)', 'Core:UnknownObjectLabel' => 'Objekt nebol nájdený (trieda: %1$s, id: %2$d)', @@ -157,8 +158,7 @@ Operatori:
'Core:Context=GUI:Console' => 'Console~~', 'Core:Context=CRON' => 'cron~~', 'Core:Context=GUI:Portal' => 'Portal~~', -)); - +]); ////////////////////////////////////////////////////////////////////// // Classes in 'core/cmdb' @@ -169,7 +169,7 @@ Operatori:
// Class: CMDBChange // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:CMDBChange' => 'Zmena', 'Class:CMDBChange+' => 'Changes tracking~~', 'Class:CMDBChange/Attribute:date' => 'Dátum', @@ -184,13 +184,13 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Class:CMDBChange/Attribute:origin/Value:webservice-rest' => 'REST/JSON webservices~~', 'Class:CMDBChange/Attribute:origin/Value:webservice-soap' => 'SOAP webservices~~', 'Class:CMDBChange/Attribute:origin/Value:custom-extension' => 'By an extension~~', -)); +]); // // Class: CMDBChangeOp // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:CMDBChangeOp' => 'Vykonanie Zmeny', 'Class:CMDBChangeOp+' => 'Change made by one person, at a single time, on a single object~~', 'Class:CMDBChangeOp/Attribute:change' => 'Zmena', @@ -205,51 +205,51 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Class:CMDBChangeOp/Attribute:objkey+' => 'id of the object on which the change was made~~', 'Class:CMDBChangeOp/Attribute:finalclass' => 'Typ', 'Class:CMDBChangeOp/Attribute:finalclass+' => 'type of change which was performed~~', -)); +]); // // Class: CMDBChangeOpCreate // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:CMDBChangeOpCreate' => 'Vytvorenie objektu', 'Class:CMDBChangeOpCreate+' => 'Object creation tracking~~', -)); +]); // // Class: CMDBChangeOpDelete // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:CMDBChangeOpDelete' => 'Vymazanie objektu', 'Class:CMDBChangeOpDelete+' => 'Object deletion tracking~~', -)); +]); // // Class: CMDBChangeOpSetAttribute // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:CMDBChangeOpSetAttribute' => 'Zmena objektu', 'Class:CMDBChangeOpSetAttribute+' => 'Object properties change tracking~~', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode' => 'Atribút', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode+' => 'code of the modified property~~', -)); +]); // // Class: CMDBChangeOpSetAttributeScalar // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:CMDBChangeOpSetAttributeScalar' => 'Zmena vlastnosti', 'Class:CMDBChangeOpSetAttributeScalar+' => 'Object scalar properties change tracking~~', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue' => 'Predchádzajúca hodnota', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue+' => 'previous value of the attribute~~', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue' => 'Nová hodnota', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue+' => 'new value of the attribute~~', -)); +]); // Used by CMDBChangeOp... & derived classes -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Change:ObjectCreated' => 'Objekt vytvorený', 'Change:ObjectDeleted' => 'Objekt odstránený', 'Change:ObjectModified' => 'Objekt upravený', @@ -266,35 +266,35 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Change:LinkSet:Added' => 'Pridané %1$s', 'Change:LinkSet:Removed' => 'Odstránené %1$s', 'Change:LinkSet:Modified' => 'Upravené %1$s', -)); +]); // // Class: CMDBChangeOpSetAttributeBlob // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:CMDBChangeOpSetAttributeBlob' => 'Zmena údajov', 'Class:CMDBChangeOpSetAttributeBlob+' => 'data change tracking~~', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata' => 'Predchádzajúce údaje', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata+' => 'previous contents of the attribute~~', -)); +]); // // Class: CMDBChangeOpSetAttributeText // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:CMDBChangeOpSetAttributeText' => 'Zmena textu', 'Class:CMDBChangeOpSetAttributeText+' => 'text change tracking~~', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata' => 'Predchádzajúce dáta', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata+' => 'previous contents of the attribute~~', -)); +]); // // Class: Event // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:Event' => 'Logovacia Udalosť', 'Class:Event+' => 'An application internal event~~', 'Class:Event/Attribute:message' => 'Správa', @@ -305,13 +305,13 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Class:Event/Attribute:userinfo+' => 'identification of the user that was doing the action that triggered this event~~', 'Class:Event/Attribute:finalclass' => 'Typ', 'Class:Event/Attribute:finalclass+' => 'Name of the final class: specifies the sort of event which occurred~~', -)); +]); // // Class: EventNotification // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:EventNotification' => 'Notifikačná Udalosť', 'Class:EventNotification+' => 'Trace of a notification that has been sent~~', 'Class:EventNotification/Attribute:trigger_id' => 'Spúštač', @@ -320,13 +320,13 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Class:EventNotification/Attribute:action_id+' => '~~', 'Class:EventNotification/Attribute:object_id' => 'ID objektu', 'Class:EventNotification/Attribute:object_id+' => '', -)); +]); // // Class: EventNotificationEmail // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:EventNotificationEmail' => 'Udalosť emitovania emailu', 'Class:EventNotificationEmail+' => 'Trace of an email that has been sent~~', 'Class:EventNotificationEmail/Attribute:to' => 'Komu', @@ -343,13 +343,13 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Class:EventNotificationEmail/Attribute:body+' => '~~', 'Class:EventNotificationEmail/Attribute:attachments' => 'Prílohy', 'Class:EventNotificationEmail/Attribute:attachments+' => '~~', -)); +]); // // Class: EventIssue // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:EventIssue' => 'Issue event', 'Class:EventIssue+' => 'Trace of an issue (warning, error, etc.)~~', 'Class:EventIssue/Attribute:issue' => 'Issue', @@ -366,13 +366,13 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Class:EventIssue/Attribute:callstack+' => '~~', 'Class:EventIssue/Attribute:data' => 'Dáta', 'Class:EventIssue/Attribute:data+' => 'More information~~', -)); +]); // // Class: EventWebService // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:EventWebService' => 'Udalosť Webovej služby', 'Class:EventWebService+' => 'Trace of a web service call~~', 'Class:EventWebService/Attribute:verb' => 'Slovný', @@ -387,9 +387,9 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Class:EventWebService/Attribute:log_error+' => 'Result error log~~', 'Class:EventWebService/Attribute:data' => 'Dáta', 'Class:EventWebService/Attribute:data+' => 'Result data~~', -)); +]); -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:EventRestService' => 'REST/JSON call~~', 'Class:EventRestService+' => 'Trace of a REST/JSON service call~~', 'Class:EventRestService/Attribute:operation' => 'Operation~~', @@ -404,13 +404,13 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Class:EventRestService/Attribute:json_output+' => 'HTTP response (json)~~', 'Class:EventRestService/Attribute:provider' => 'Provider~~', 'Class:EventRestService/Attribute:provider+' => 'PHP class implementing the expected operation~~', -)); +]); // // Class: EventLoginUsage // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:EventLoginUsage' => 'Využívanosť prihlasovacieho mena', 'Class:EventLoginUsage+' => 'Connection to the application~~', 'Class:EventLoginUsage/Attribute:user_id' => 'Prihlasovacie meno', @@ -419,13 +419,13 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Class:EventLoginUsage/Attribute:contact_name+' => '~~', 'Class:EventLoginUsage/Attribute:contact_email' => 'Užívateľský email', 'Class:EventLoginUsage/Attribute:contact_email+' => 'Email Address of the User~~', -)); +]); // // Class: EventNotificationNewsroom // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:EventNotificationNewsroom' => 'News sent~~', 'Class:EventNotificationNewsroom+' => '~~', 'Class:EventNotificationNewsroom/Attribute:title' => 'Title~~', @@ -454,13 +454,13 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Class:EventNotificationNewsroom/Attribute:read_date+' => '~~', 'Class:EventNotificationNewsroom/Attribute:contact_id' => 'Contact~~', 'Class:EventNotificationNewsroom/Attribute:contact_id+' => '~~', -)); +]); // // Class: Action // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:Action' => 'Vlastná akcia', 'Class:Action+' => 'User defined action~~', 'Class:Action/ComplementaryName' => '%1$s: %2$s~~', @@ -490,22 +490,22 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Action:last_executions_tab_panel_title' => 'Executions of this action (%1$s)~~', 'Action:last_executions_tab_limit_days' => 'past %1$s days~~', 'Action:last_executions_tab_limit_none' => 'no limit~~', -)); +]); // // Class: ActionNotification // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:ActionNotification' => 'Upozornenie', 'Class:ActionNotification+' => 'Notification Action (abstract)~~', -)); +]); // // Class: ActionEmail // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:ActionEmail' => 'Emailová notifikácia', 'Class:ActionEmail+' => '~~', 'Class:ActionEmail/Attribute:status+' => 'This status drives who will be notified: @@ -574,14 +574,13 @@ While editing, click on the magnifier to get pertinent examples~~', 'ActionEmail:preview_warning' => 'The actual eMail may look different in the eMail client than this preview in your browser.~~', 'ActionEmail:preview_more_info' => 'For more information about the CSS features supported by the different eMail clients, refer to %1$s~~', 'ActionEmail:content_placeholder_missing' => 'The placeholder "%1$s" was not found in the HTML template. The content of the field "%2$s" will not be included in the generated emails.~~', -)); - +]); // // Class: ActionNewsroom // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'ActionNewsroom:trigger' => 'Trigger~~', 'ActionNewsroom:content' => 'Message~~', 'ActionNewsroom:settings' => 'Settings~~', @@ -616,13 +615,13 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Class:ActionNewsroom/Attribute:recipients+' => 'An OQL query returning Contact objects~~', 'Class:ActionNewsroom/Attribute:url' => 'URL~~', 'Class:ActionNewsroom/Attribute:url+' => 'By default, it points to the object triggering the notification. But you can also specify a custom URL.~~', -)); +]); // // Class: Trigger // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:Trigger' => 'Spúštač', 'Class:Trigger+' => 'Custom event handler~~', 'Class:Trigger/ComplementaryName' => '%1$s, %2$s~~', @@ -641,13 +640,13 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Class:Trigger/Attribute:subscription_policy/Value:allow_no_channel' => 'Allow complete unsubscription~~', 'Class:Trigger/Attribute:subscription_policy/Value:force_at_least_one_channel' => 'Force at least one channel (News or Email)~~', 'Class:Trigger/Attribute:subscription_policy/Value:force_all_channels' => 'Deny unsubscription~~', -)); +]); // // Class: TriggerOnObject // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:TriggerOnObject' => 'Spúštač (pre danú triedu)', 'Class:TriggerOnObject+' => 'Trigger on a given class of objects~~', 'Class:TriggerOnObject/Attribute:target_class' => 'Cieľová trieda', @@ -656,115 +655,115 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Class:TriggerOnObject/Attribute:filter+' => 'Limit the object list (of the target class) which will activate the trigger~~', 'TriggerOnObject:WrongFilterQuery' => 'Wrong filter query: %1$s~~', 'TriggerOnObject:WrongFilterClass' => 'The filter query must return objects of class "%1$s"~~', -)); +]); // // Class: TriggerOnPortalUpdate // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:TriggerOnPortalUpdate' => 'Spúštač (pri aktualizácií z portálu)', 'Class:TriggerOnPortalUpdate+' => 'Trigger on an end-user\'s update from the portal~', -)); +]); // // Class: TriggerOnStateChange // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:TriggerOnStateChange' => 'Spúšťač (pri zmene stavu)', 'Class:TriggerOnStateChange+' => 'Trigger on object state change~~', 'Class:TriggerOnStateChange/Attribute:state' => 'Stav', 'Class:TriggerOnStateChange/Attribute:state+' => '~~', -)); +]); // // Class: TriggerOnStateEnter // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:TriggerOnStateEnter' => 'Spúštač (pri vstupe do stavu)', 'Class:TriggerOnStateEnter+' => 'Trigger on object state change - entering~~', -)); +]); // // Class: TriggerOnStateLeave // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:TriggerOnStateLeave' => 'Spúštač (pri opustení stavu)', 'Class:TriggerOnStateLeave+' => 'Trigger on object state change - leaving~~', -)); +]); // // Class: TriggerOnObjectCreate // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:TriggerOnObjectCreate' => 'Spúštač (pri vytvoreni objektu)', 'Class:TriggerOnObjectCreate+' => 'Trigger on object creation of [a child class of] the given class~~', -)); +]); // // Class: TriggerOnObjectDelete // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:TriggerOnObjectDelete' => 'Trigger (on object deletion)~~', 'Class:TriggerOnObjectDelete+' => 'Trigger on object deletion of [a child class of] the given class~~', -)); +]); // // Class: TriggerOnObjectUpdate // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:TriggerOnObjectUpdate' => 'Trigger (on object update)~~', 'Class:TriggerOnObjectUpdate+' => 'Trigger on object update of [a child class of] the given class~~', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes' => 'Target fields~~', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes+' => '~~', -)); +]); // // Class: TriggerOnObjectMention // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:TriggerOnObjectMention' => 'Trigger (on object mention)~~', 'Class:TriggerOnObjectMention+' => 'Trigger on mention (@xxx) of an object of [a child class of] the given class in a log attribute~~', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter' => 'Mentioned filter~~', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter+' => 'Limit the list of mentioned objects which will activate the trigger. If empty, any mentioned object (of any class) will activate it.~~', -)); +]); // // Class: TriggerOnAttributeBlobDownload // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:TriggerOnAttributeBlobDownload' => 'Trigger (on object\'s document download)~~', 'Class:TriggerOnAttributeBlobDownload+' => 'Trigger on object\'s document field download of [a child class of] the given class~~', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes' => 'Target fields~~', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes+' => '~~', -)); +]); // // Class: TriggerOnThresholdReached // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:TriggerOnThresholdReached' => 'Spúštač (pri prekročení hranice)', 'Class:TriggerOnThresholdReached+' => 'Trigger on Stop-Watch threshold reached~~', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code' => 'Stopky', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code+' => '~~', 'Class:TriggerOnThresholdReached/Attribute:threshold_index' => 'Hranica', 'Class:TriggerOnThresholdReached/Attribute:threshold_index+' => '~~', -)); +]); // // Class: lnkTriggerAction // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:lnkTriggerAction' => 'Akcia/Spúštač', 'Class:lnkTriggerAction+' => 'Link between a trigger and an action~~', 'Class:lnkTriggerAction/Attribute:action_id' => 'Akcia', @@ -777,12 +776,12 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Class:lnkTriggerAction/Attribute:trigger_name+' => '~~', 'Class:lnkTriggerAction/Attribute:order' => 'Príkaz', 'Class:lnkTriggerAction/Attribute:order+' => 'Actions execution order~~', -)); +]); // // Synchro Data Source // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:SynchroDataSource' => 'Synchronizovaný zdroj dát', 'Class:SynchroDataSource/Attribute:name' => 'Názov', 'Class:SynchroDataSource/Attribute:name+' => '~~', @@ -1074,12 +1073,12 @@ The hyperlink is displayed in the tooltip appearing on the “Lock” symbol of 'Core:Validator:Mandatory' => 'Please, fill this field~~', 'Core:Validator:MustBeInteger' => 'Must be an integer~~', 'Core:Validator:MustSelectOne' => 'Please, select one~~', -)); +]); // // Class: TagSetFieldData // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:TagSetFieldData' => '%2$s for class %1$s~~', 'Class:TagSetFieldData+' => '~~', 'Class:TagSetFieldData/Attribute:code' => 'Code~~', @@ -1101,12 +1100,12 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Core:TagSetFieldData:ErrorAttCodeUpdateNotAllowed' => 'Tags "Attribute Code" cannot be changed~~', 'Core:TagSetFieldData:WhereIsThisTagTab' => 'Tag usage (%1$d)~~', 'Core:TagSetFieldData:NoEntryFound' => 'No entry found for this tag~~', -)); +]); // // Class: DBProperty // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:DBProperty' => 'DB property~~', 'Class:DBProperty+' => '~~', 'Class:DBProperty/Attribute:name' => 'Name~~', @@ -1119,12 +1118,12 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Class:DBProperty/Attribute:change_date+' => '~~', 'Class:DBProperty/Attribute:change_comment' => 'Change comment~~', 'Class:DBProperty/Attribute:change_comment+' => '~~', -)); +]); // // Class: BackgroundTask // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:BackgroundTask' => 'Background task~~', 'Class:BackgroundTask+' => '~~', 'Class:BackgroundTask/Attribute:class_name' => 'Class name~~', @@ -1149,12 +1148,12 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Class:BackgroundTask/Attribute:running+' => '~~', 'Class:BackgroundTask/Attribute:status' => 'Status~~', 'Class:BackgroundTask/Attribute:status+' => '~~', -)); +]); // // Class: AsyncTask // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:AsyncTask' => 'Async. task~~', 'Class:AsyncTask+' => '~~', 'Class:AsyncTask/Attribute:created' => 'Created~~', @@ -1179,47 +1178,44 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'Class:AsyncTask/Attribute:last_attempt+' => '~~', 'Class:AsyncTask:InvalidConfig_Class_Keys' => 'Invalid format for the configuration of "async_task_retries[%1$s]". Expecting an array with the following keys: %2$s~~', 'Class:AsyncTask:InvalidConfig_Class_InvalidKey_Keys' => 'Invalid format for the configuration of "async_task_retries[%1$s]": unexpected key "%2$s". Expecting only the following keys: %3$s~~', -)); +]); // // Class: AbstractResource // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:AbstractResource' => 'Abstract Resource~~', 'Class:AbstractResource+' => '~~', -)); +]); // // Class: ResourceAdminMenu // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:ResourceAdminMenu' => 'Resource Admin Menu~~', 'Class:ResourceAdminMenu+' => '~~', -)); +]); // // Class: ResourceRunQueriesMenu // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:ResourceRunQueriesMenu' => 'Resource Run Queries Menu~~', 'Class:ResourceRunQueriesMenu+' => '~~', -)); +]); // // Class: Action // -Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( +Dict::Add('SK SK', 'Slovak', 'Slovenčina', [ 'Class:ResourceSystemMenu' => 'Resource System Menu~~', 'Class:ResourceSystemMenu+' => '~~', - 'Class:EventNotification/Attribute:object_class' => 'Object class~~', - 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', + 'Class:EventNotification/Attribute:object_class' => 'Object class~~', + 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', 'Core:EventNotificationNewsroom:ErrorNotificationNotSent' => 'Notification not sent~~', 'Core:EventNotificationNewsroom:ErrorOnDBInsert' => 'An error occurred while saving the notification~~', -)); - - - +]); diff --git a/dictionaries/tr.dictionary.itop.core.php b/dictionaries/tr.dictionary.itop.core.php index cbd90e83e..0809b1226 100644 --- a/dictionaries/tr.dictionary.itop.core.php +++ b/dictionaries/tr.dictionary.itop.core.php @@ -1,16 +1,17 @@ * */ -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Core:DeletedObjectLabel' => '%1s (Silinmiş)', 'Core:DeletedObjectTip' => 'Nesne%1$s (%2$s) \'de silinmiştir', 'Core:UnknownObjectLabel' => 'Nesne bulunamadı (sınıf: %1$s, id: %2$d)', @@ -158,8 +159,7 @@ Operators:
'Core:Context=GUI:Console' => 'Console~~', 'Core:Context=CRON' => 'cron~~', 'Core:Context=GUI:Portal' => 'Portal~~', -)); - +]); ////////////////////////////////////////////////////////////////////// // Classes in 'core/cmdb' @@ -170,7 +170,7 @@ Operators:
// Class: CMDBChange // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:CMDBChange' => 'Değişiklik', 'Class:CMDBChange+' => 'Değişiklik izleme', 'Class:CMDBChange/Attribute:date' => 'tarih', @@ -185,13 +185,13 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Class:CMDBChange/Attribute:origin/Value:webservice-rest' => 'REST/JSON webservices~~', 'Class:CMDBChange/Attribute:origin/Value:webservice-soap' => 'SOAP webservices~~', 'Class:CMDBChange/Attribute:origin/Value:custom-extension' => 'By an extension~~', -)); +]); // // Class: CMDBChangeOp // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:CMDBChangeOp' => 'Değişiklik işlemi', 'Class:CMDBChangeOp+' => '', 'Class:CMDBChangeOp/Attribute:change' => 'değişiklik', @@ -206,51 +206,51 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Class:CMDBChangeOp/Attribute:objkey+' => '', 'Class:CMDBChangeOp/Attribute:finalclass' => 'tip', 'Class:CMDBChangeOp/Attribute:finalclass+' => '', -)); +]); // // Class: CMDBChangeOpCreate // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:CMDBChangeOpCreate' => 'nesne yaratımı', 'Class:CMDBChangeOpCreate+' => 'Nesne Yaratım izleme', -)); +]); // // Class: CMDBChangeOpDelete // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:CMDBChangeOpDelete' => 'nesne silimi', 'Class:CMDBChangeOpDelete+' => 'Nesne silme izleme', -)); +]); // // Class: CMDBChangeOpSetAttribute // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:CMDBChangeOpSetAttribute' => 'nesne değişikliği', 'Class:CMDBChangeOpSetAttribute+' => 'Nesne değişiminin izlemesi', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode' => 'Özellik', 'Class:CMDBChangeOpSetAttribute/Attribute:attcode+' => 'Değişen özelliğin kodu', -)); +]); // // Class: CMDBChangeOpSetAttributeScalar // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:CMDBChangeOpSetAttributeScalar' => 'özellik değişimi', 'Class:CMDBChangeOpSetAttributeScalar+' => 'Nesne özellik değişimi izleme', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue' => 'Önceki değer', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:oldvalue+' => '', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue' => 'Yeni değer', 'Class:CMDBChangeOpSetAttributeScalar/Attribute:newvalue+' => '', -)); +]); // Used by CMDBChangeOp... & derived classes -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Change:ObjectCreated' => 'Nesne yaratıldı', 'Change:ObjectDeleted' => 'Nesne silindi', 'Change:ObjectModified' => 'Nesne değiştirildi', @@ -267,35 +267,35 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Change:LinkSet:Added' => '%1$s \'eklendi', 'Change:LinkSet:Removed' => 'Kaldırıldı %1$s', 'Change:LinkSet:Modified' => 'Değiştirilmiş %1$s', -)); +]); // // Class: CMDBChangeOpSetAttributeBlob // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:CMDBChangeOpSetAttributeBlob' => 'tarih değişimi', 'Class:CMDBChangeOpSetAttributeBlob+' => 'tarih değişim izleme', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata' => 'Önceki veri', 'Class:CMDBChangeOpSetAttributeBlob/Attribute:prevdata+' => '', -)); +]); // // Class: CMDBChangeOpSetAttributeText // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:CMDBChangeOpSetAttributeText' => 'metin değişikliği', 'Class:CMDBChangeOpSetAttributeText+' => 'metin değişikliği izleme', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata' => 'Önceki veri', 'Class:CMDBChangeOpSetAttributeText/Attribute:prevdata+' => 'önceki değer', -)); +]); // // Class: Event // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:Event' => 'Olay kaydı', 'Class:Event+' => 'Uygulama olayı', 'Class:Event/Attribute:message' => 'mesaj', @@ -306,13 +306,13 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Class:Event/Attribute:userinfo+' => 'olay anındaki kullanıcı', 'Class:Event/Attribute:finalclass' => 'tip', 'Class:Event/Attribute:finalclass+' => '', -)); +]); // // Class: EventNotification // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:EventNotification' => 'Olay uyarımı', 'Class:EventNotification+' => 'Uyarının tarihçesi', 'Class:EventNotification/Attribute:trigger_id' => 'Uyarı tetikçisi', @@ -321,13 +321,13 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Class:EventNotification/Attribute:action_id+' => 'kullanıcı hesabı', 'Class:EventNotification/Attribute:object_id' => 'Nesne belirleyicisi', 'Class:EventNotification/Attribute:object_id+' => 'nesne belirleyicisi (olayı tetikleyen nesne ?)', -)); +]); // // Class: EventNotificationEmail // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:EventNotificationEmail' => 'E-posta gönderim işlemi', 'Class:EventNotificationEmail+' => 'Gönderilen E-posta tarihçesi', 'Class:EventNotificationEmail/Attribute:to' => 'Kime', @@ -344,13 +344,13 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Class:EventNotificationEmail/Attribute:body+' => '', 'Class:EventNotificationEmail/Attribute:attachments' => 'Eklentiler', 'Class:EventNotificationEmail/Attribute:attachments+' => '', -)); +]); // // Class: EventIssue // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:EventIssue' => 'Olay ekle', 'Class:EventIssue+' => 'Olay tipi (uyarı, hata, vb.)', 'Class:EventIssue/Attribute:issue' => 'Konu', @@ -367,13 +367,13 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Class:EventIssue/Attribute:callstack+' => '', 'Class:EventIssue/Attribute:data' => 'Veri', 'Class:EventIssue/Attribute:data+' => 'Diğer bilgiler', -)); +]); // // Class: EventWebService // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:EventWebService' => 'Web service olayı', 'Class:EventWebService+' => 'web service çağrım sırası', 'Class:EventWebService/Attribute:verb' => 'Fiil', @@ -388,9 +388,9 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Class:EventWebService/Attribute:log_error+' => 'Sonuç hata kaydı', 'Class:EventWebService/Attribute:data' => 'Veri', 'Class:EventWebService/Attribute:data+' => 'Sonuç veri', -)); +]); -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:EventRestService' => 'REST/JSON çağrısı', 'Class:EventRestService+' => 'REST/JSON izleme hizmet çağrısı', 'Class:EventRestService/Attribute:operation' => 'Operasyon', @@ -405,13 +405,13 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Class:EventRestService/Attribute:json_output+' => 'HTTP Yanıt (JSON)', 'Class:EventRestService/Attribute:provider' => 'Sağlayıcı', 'Class:EventRestService/Attribute:provider+' => 'PHP Sınıfı Beklenen Operasyonun Uygulanması', -)); +]); // // Class: EventLoginUsage // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:EventLoginUsage' => 'Giriş Kullanımı', 'Class:EventLoginUsage+' => 'Uygulamaya bağlantı', 'Class:EventLoginUsage/Attribute:user_id' => 'Giriş', @@ -420,13 +420,13 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Class:EventLoginUsage/Attribute:contact_name+' => '', 'Class:EventLoginUsage/Attribute:contact_email' => 'Kullanıcı e-postası', 'Class:EventLoginUsage/Attribute:contact_email+' => 'Kullanıcının e-posta adresi', -)); +]); // // Class: EventNotificationNewsroom // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:EventNotificationNewsroom' => 'News sent~~', 'Class:EventNotificationNewsroom+' => '~~', 'Class:EventNotificationNewsroom/Attribute:title' => 'Title~~', @@ -455,13 +455,13 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Class:EventNotificationNewsroom/Attribute:read_date+' => '~~', 'Class:EventNotificationNewsroom/Attribute:contact_id' => 'Contact~~', 'Class:EventNotificationNewsroom/Attribute:contact_id+' => '~~', -)); +]); // // Class: Action // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:Action' => 'Özel işlem', 'Class:Action+' => 'Kullanıcının tanımladığı işlemler', 'Class:Action/ComplementaryName' => '%1$s: %2$s~~', @@ -491,22 +491,22 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Action:last_executions_tab_panel_title' => 'Executions of this action (%1$s)~~', 'Action:last_executions_tab_limit_days' => 'past %1$s days~~', 'Action:last_executions_tab_limit_none' => 'no limit~~', -)); +]); // // Class: ActionNotification // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:ActionNotification' => 'Bildirim', 'Class:ActionNotification+' => 'Bildirim (soyut)', -)); +]); // // Class: ActionEmail // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:ActionEmail' => 'E-posta bildirimi', 'Class:ActionEmail+' => '', 'Class:ActionEmail/Attribute:status+' => 'This status drives who will be notified: @@ -561,14 +561,13 @@ If omitted the From (label) is used.~~', 'ActionEmail:preview_warning' => 'The actual eMail may look different in the eMail client than this preview in your browser.~~', 'ActionEmail:preview_more_info' => 'For more information about the CSS features supported by the different eMail clients, refer to %1$s~~', 'ActionEmail:content_placeholder_missing' => 'The placeholder "%1$s" was not found in the HTML template. The content of the field "%2$s" will not be included in the generated emails.~~', -)); - +]); // // Class: ActionNewsroom // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'ActionNewsroom:trigger' => 'Trigger~~', 'ActionNewsroom:content' => 'Message~~', 'ActionNewsroom:settings' => 'Settings~~', @@ -603,13 +602,13 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Class:ActionNewsroom/Attribute:recipients+' => 'An OQL query returning Contact objects~~', 'Class:ActionNewsroom/Attribute:url' => 'URL~~', 'Class:ActionNewsroom/Attribute:url+' => 'By default, it points to the object triggering the notification. But you can also specify a custom URL.~~', -)); +]); // // Class: Trigger // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:Trigger' => 'Tetikleyici', 'Class:Trigger+' => 'Özel olay yürütücü', 'Class:Trigger/ComplementaryName' => '%1$s, %2$s~~', @@ -628,13 +627,13 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Class:Trigger/Attribute:subscription_policy/Value:allow_no_channel' => 'Allow complete unsubscription~~', 'Class:Trigger/Attribute:subscription_policy/Value:force_at_least_one_channel' => 'Force at least one channel (News or Email)~~', 'Class:Trigger/Attribute:subscription_policy/Value:force_all_channels' => 'Deny unsubscription~~', -)); +]); // // Class: TriggerOnObject // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:TriggerOnObject' => 'Tetiklenen (sınıf bağımlılığı)', 'Class:TriggerOnObject+' => 'Verilen sınıflar üzerinde işlemleri gerçekleştir', 'Class:TriggerOnObject/Attribute:target_class' => 'Hedef sınıf', @@ -643,115 +642,115 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Class:TriggerOnObject/Attribute:filter+' => '', 'TriggerOnObject:WrongFilterQuery' => 'Yanlış filtre sorgusu: %1$s', 'TriggerOnObject:WrongFilterClass' => 'Filtre sorgusu, \\"%1$s\\" \'sınıfının nesnelerini dönmelidir.', -)); +]); // // Class: TriggerOnPortalUpdate // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:TriggerOnPortalUpdate' => 'Tetikle (portaldan güncellendiğinde)', 'Class:TriggerOnPortalUpdate+' => 'Son kullanıcının portalından gelen güncellemelerinde tetikle', -)); +]); // // Class: TriggerOnStateChange // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:TriggerOnStateChange' => 'Tetiklenen (durum değişikliğinde)', 'Class:TriggerOnStateChange+' => 'Durum değişikliğinde tetiklenen işlemler', 'Class:TriggerOnStateChange/Attribute:state' => 'Durum', 'Class:TriggerOnStateChange/Attribute:state+' => '', -)); +]); // // Class: TriggerOnStateEnter // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:TriggerOnStateEnter' => 'Tetiklenen (duruma girişte)', 'Class:TriggerOnStateEnter+' => 'Durum değişikliğinde tetiklenen işlemler (duruma giriş)', -)); +]); // // Class: TriggerOnStateLeave // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:TriggerOnStateLeave' => 'Tetiklenen (durum çıkışında)', 'Class:TriggerOnStateLeave+' => 'Durum değişikliğinde tetiklenen işlemler (duruma çıkış)', -)); +]); // // Class: TriggerOnObjectCreate // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:TriggerOnObjectCreate' => 'Tetiklenen (nesne yaratımında)', 'Class:TriggerOnObjectCreate+' => 'Verilen sınıf tipi nesne yaratımında tetiklenen işlemler', -)); +]); // // Class: TriggerOnObjectDelete // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:TriggerOnObjectDelete' => 'Trigger (on object deletion)~~', 'Class:TriggerOnObjectDelete+' => 'Trigger on object deletion of [a child class of] the given class~~', -)); +]); // // Class: TriggerOnObjectUpdate // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:TriggerOnObjectUpdate' => 'Trigger (on object update)~~', 'Class:TriggerOnObjectUpdate+' => 'Trigger on object update of [a child class of] the given class~~', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes' => 'Target fields~~', 'Class:TriggerOnObjectUpdate/Attribute:target_attcodes+' => '', -)); +]); // // Class: TriggerOnObjectMention // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:TriggerOnObjectMention' => 'Trigger (on object mention)~~', 'Class:TriggerOnObjectMention+' => 'Trigger on mention (@xxx) of an object of [a child class of] the given class in a log attribute~~', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter' => 'Mentioned filter~~', 'Class:TriggerOnObjectMention/Attribute:mentioned_filter+' => 'Limit the list of mentioned objects which will activate the trigger. If empty, any mentioned object (of any class) will activate it.~~', -)); +]); // // Class: TriggerOnAttributeBlobDownload // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:TriggerOnAttributeBlobDownload' => 'Trigger (on object\'s document download)~~', 'Class:TriggerOnAttributeBlobDownload+' => 'Trigger on object\'s document field download of [a child class of] the given class~~', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes' => 'Target fields~~', 'Class:TriggerOnAttributeBlobDownload/Attribute:target_attcodes+' => '~~', -)); +]); // // Class: TriggerOnThresholdReached // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:TriggerOnThresholdReached' => 'Tetikle (eşik üzerinde)', 'Class:TriggerOnThresholdReached+' => 'Dur-izle eşiğinde tetikle', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code' => 'İzlemeyi bırak', 'Class:TriggerOnThresholdReached/Attribute:stop_watch_code+' => '', 'Class:TriggerOnThresholdReached/Attribute:threshold_index' => 'Eşik', 'Class:TriggerOnThresholdReached/Attribute:threshold_index+' => '', -)); +]); // // Class: lnkTriggerAction // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:lnkTriggerAction' => 'İşlem/Tetikleme', 'Class:lnkTriggerAction+' => 'Tetikleme ve işlem arasındaki ilişki', 'Class:lnkTriggerAction/Attribute:action_id' => 'İşlem', @@ -764,12 +763,12 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Class:lnkTriggerAction/Attribute:trigger_name+' => '', 'Class:lnkTriggerAction/Attribute:order' => 'Order', 'Class:lnkTriggerAction/Attribute:order+' => 'İşlem uygulama sırası', -)); +]); // // Synchro Data Source // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:SynchroDataSource' => 'Synchro Veri Kaynağı', 'Class:SynchroDataSource/Attribute:name' => 'İsim', 'Class:SynchroDataSource/Attribute:name+' => '', @@ -1057,13 +1056,13 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Core:Validator:MustBeInteger' => 'Bir tamsayı olmalı', 'Core:Validator:MustSelectOne' => 'Lütfen bir tane seçin', 'Menu:DataSources' => 'Senkronizasyon Veri Kaynakları', - 'Menu:DataSources+' => 'Tüm Senkronizasyon Veri Kaynakları' -)); + 'Menu:DataSources+' => 'Tüm Senkronizasyon Veri Kaynakları', +]); // // Class: TagSetFieldData // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:TagSetFieldData' => '%2$s for class %1$s~~', 'Class:TagSetFieldData+' => '', 'Class:TagSetFieldData/Attribute:code' => 'Code~~', @@ -1085,12 +1084,12 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Core:TagSetFieldData:ErrorAttCodeUpdateNotAllowed' => 'Tags "Attribute Code" cannot be changed~~', 'Core:TagSetFieldData:WhereIsThisTagTab' => 'Tag usage (%1$d)~~', 'Core:TagSetFieldData:NoEntryFound' => 'No entry found for this tag~~', -)); +]); // // Class: DBProperty // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:DBProperty' => 'DB property~~', 'Class:DBProperty+' => '', 'Class:DBProperty/Attribute:name' => 'Name~~', @@ -1103,12 +1102,12 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Class:DBProperty/Attribute:change_date+' => '', 'Class:DBProperty/Attribute:change_comment' => 'Change comment~~', 'Class:DBProperty/Attribute:change_comment+' => '', -)); +]); // // Class: BackgroundTask // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:BackgroundTask' => 'Background task~~', 'Class:BackgroundTask+' => '', 'Class:BackgroundTask/Attribute:class_name' => 'Class name~~', @@ -1133,12 +1132,12 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Class:BackgroundTask/Attribute:running+' => '', 'Class:BackgroundTask/Attribute:status' => 'Status~~', 'Class:BackgroundTask/Attribute:status+' => '', -)); +]); // // Class: AsyncTask // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:AsyncTask' => 'Async. task~~', 'Class:AsyncTask+' => '', 'Class:AsyncTask/Attribute:created' => 'Created~~', @@ -1163,47 +1162,44 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'Class:AsyncTask/Attribute:last_attempt+' => '', 'Class:AsyncTask:InvalidConfig_Class_Keys' => 'Invalid format for the configuration of "async_task_retries[%1$s]". Expecting an array with the following keys: %2$s~~', 'Class:AsyncTask:InvalidConfig_Class_InvalidKey_Keys' => 'Invalid format for the configuration of "async_task_retries[%1$s]": unexpected key "%2$s". Expecting only the following keys: %3$s~~', -)); +]); // // Class: AbstractResource // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:AbstractResource' => 'Abstract Resource~~', 'Class:AbstractResource+' => '', -)); +]); // // Class: ResourceAdminMenu // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:ResourceAdminMenu' => 'Resource Admin Menu~~', 'Class:ResourceAdminMenu+' => '', -)); +]); // // Class: ResourceRunQueriesMenu // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:ResourceRunQueriesMenu' => 'Resource Run Queries Menu~~', 'Class:ResourceRunQueriesMenu+' => '', -)); +]); // // Class: Action // -Dict::Add('TR TR', 'Turkish', 'Türkçe', array( +Dict::Add('TR TR', 'Turkish', 'Türkçe', [ 'Class:ResourceSystemMenu' => 'Resource System Menu~~', 'Class:ResourceSystemMenu+' => '', - 'Class:EventNotification/Attribute:object_class' => 'Object class~~', - 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', + 'Class:EventNotification/Attribute:object_class' => 'Object class~~', + 'Class:EventNotification/Attribute:object_class+' => 'Object class (Same as trigger)~~', 'Core:EventNotificationNewsroom:ErrorNotificationNotSent' => 'Notification not sent~~', 'Core:EventNotificationNewsroom:ErrorOnDBInsert' => 'An error occurred while saving the notification~~', -)); - - - +]); diff --git a/dictionaries/ui/components/quick-create/cs.dictionary.itop.quick-create.php b/dictionaries/ui/components/quick-create/cs.dictionary.itop.quick-create.php index b6806209b..8d9bef401 100644 --- a/dictionaries/ui/components/quick-create/cs.dictionary.itop.quick-create.php +++ b/dictionaries/ui/components/quick-create/cs.dictionary.itop.quick-create.php @@ -1,15 +1,16 @@ 'Quickly create any type of object~~', 'UI:Component:QuickCreate:Input:Placeholder' => 'Select object type...~~', 'UI:Component:QuickCreate:Recents:Title' => 'Recents~~', @@ -17,4 +18,4 @@ Dict::Add('CS CZ', 'Czech', 'Čeština', array( 'UI:Component:QuickCreate:HistoryDisabled' => 'History is disabled~~', 'UI:Component:QuickCreate:KeyboardShortcut:OpenDrawer' => 'Open quick create~~', 'UI:Component:QuickCreate:MostPopular:Title' => 'Populární', -)); \ No newline at end of file +]); diff --git a/dictionaries/ui/components/quick-create/da.dictionary.itop.quick-create.php b/dictionaries/ui/components/quick-create/da.dictionary.itop.quick-create.php index 554053db2..83e674b9f 100644 --- a/dictionaries/ui/components/quick-create/da.dictionary.itop.quick-create.php +++ b/dictionaries/ui/components/quick-create/da.dictionary.itop.quick-create.php @@ -1,15 +1,16 @@ 'Quickly create any type of object~~', 'UI:Component:QuickCreate:Input:Placeholder' => 'Select object type...~~', 'UI:Component:QuickCreate:Recents:Title' => 'Recents~~', @@ -17,4 +18,4 @@ Dict::Add('DA DA', 'Danish', 'Dansk', array( 'UI:Component:QuickCreate:HistoryDisabled' => 'History is disabled~~', 'UI:Component:QuickCreate:KeyboardShortcut:OpenDrawer' => 'Open quick create~~', 'UI:Component:QuickCreate:MostPopular:Title' => 'Most popular~~', -)); \ No newline at end of file +]); diff --git a/dictionaries/ui/components/quick-create/de.dictionary.itop.quick-create.php b/dictionaries/ui/components/quick-create/de.dictionary.itop.quick-create.php index a8143022d..5e65da862 100644 --- a/dictionaries/ui/components/quick-create/de.dictionary.itop.quick-create.php +++ b/dictionaries/ui/components/quick-create/de.dictionary.itop.quick-create.php @@ -1,15 +1,16 @@ 'Erstellen Sie schnell jeden Typ von Objekt', 'UI:Component:QuickCreate:Input:Placeholder' => 'Wählen Sie einen Objekttyp aus...', 'UI:Component:QuickCreate:Recents:Title' => 'Letzte', @@ -17,4 +18,4 @@ Dict::Add('DE DE', 'German', 'Deutsch', array( 'UI:Component:QuickCreate:HistoryDisabled' => 'Quick-Create-Historie ist deaktiviert', 'UI:Component:QuickCreate:KeyboardShortcut:OpenDrawer' => 'Quick-Create-Menu öffnen', 'UI:Component:QuickCreate:MostPopular:Title' => 'Am beliebtesten', -)); \ No newline at end of file +]); diff --git a/dictionaries/ui/components/quick-create/es_cr.dictionary.itop.quick-create.php b/dictionaries/ui/components/quick-create/es_cr.dictionary.itop.quick-create.php index 9eaadd202..535c2a497 100644 --- a/dictionaries/ui/components/quick-create/es_cr.dictionary.itop.quick-create.php +++ b/dictionaries/ui/components/quick-create/es_cr.dictionary.itop.quick-create.php @@ -1,13 +1,14 @@ - * @notas Utilizar codificación UTF-8 para mostrar acentos y otros caracteres especiales + * @notas Utilizar codificación UTF-8 para mostrar acentos y otros caracteres especiales */ -Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( +Dict::Add('ES CR', 'Spanish', 'Español, Castellano', [ 'UI:Component:QuickCreate:Tooltip' => 'Crear rápidamente cualquier tipo de objeto', 'UI:Component:QuickCreate:Input:Placeholder' => 'Seleccionar tipo de objeto...', 'UI:Component:QuickCreate:Recents:Title' => 'Recientes', @@ -15,4 +16,4 @@ Dict::Add('ES CR', 'Spanish', 'Español, Castellano', array( 'UI:Component:QuickCreate:HistoryDisabled' => 'El historial está deshabilitado', 'UI:Component:QuickCreate:KeyboardShortcut:OpenDrawer' => 'Abrir creación rápida', 'UI:Component:QuickCreate:MostPopular:Title' => 'Más popular', -)); \ No newline at end of file +]); diff --git a/dictionaries/ui/components/quick-create/fr.dictionary.itop.quick-create.php b/dictionaries/ui/components/quick-create/fr.dictionary.itop.quick-create.php index 9561d18c9..baab3b8f8 100644 --- a/dictionaries/ui/components/quick-create/fr.dictionary.itop.quick-create.php +++ b/dictionaries/ui/components/quick-create/fr.dictionary.itop.quick-create.php @@ -1,15 +1,16 @@ 'Création rapide de n\'importe quel objet', 'UI:Component:QuickCreate:Input:Placeholder' => 'Type d\'objet...', 'UI:Component:QuickCreate:Recents:Title' => 'Types récents', @@ -17,4 +18,4 @@ Dict::Add('FR FR', 'French', 'Français', array( 'UI:Component:QuickCreate:HistoryDisabled' => 'L\'historique est désactivé', 'UI:Component:QuickCreate:KeyboardShortcut:OpenDrawer' => 'Ouvrir la création rapide', 'UI:Component:QuickCreate:MostPopular:Title' => 'Populaires', -)); \ No newline at end of file +]); diff --git a/dictionaries/ui/components/quick-create/hu.dictionary.itop.quick-create.php b/dictionaries/ui/components/quick-create/hu.dictionary.itop.quick-create.php index 0dd174cb7..7861973d9 100644 --- a/dictionaries/ui/components/quick-create/hu.dictionary.itop.quick-create.php +++ b/dictionaries/ui/components/quick-create/hu.dictionary.itop.quick-create.php @@ -1,15 +1,16 @@ 'Bármilyen típusú objektum gyors létrehozása', 'UI:Component:QuickCreate:Input:Placeholder' => 'Objektumtípus kiválasztása...', 'UI:Component:QuickCreate:Recents:Title' => 'Legutóbbiak', @@ -17,4 +18,4 @@ Dict::Add('HU HU', 'Hungarian', 'Magyar', array( 'UI:Component:QuickCreate:HistoryDisabled' => 'Az előzmények le lettek tiltva', 'UI:Component:QuickCreate:KeyboardShortcut:OpenDrawer' => 'Gyors létrehozás megnyitása', 'UI:Component:QuickCreate:MostPopular:Title' => 'Legnépszerűbb', -)); \ No newline at end of file +]); diff --git a/dictionaries/ui/components/quick-create/it.dictionary.itop.quick-create.php b/dictionaries/ui/components/quick-create/it.dictionary.itop.quick-create.php index 1fc2b87e2..1c4833e64 100644 --- a/dictionaries/ui/components/quick-create/it.dictionary.itop.quick-create.php +++ b/dictionaries/ui/components/quick-create/it.dictionary.itop.quick-create.php @@ -1,15 +1,16 @@ 'Crea rapidamente qualsiasi tipo di oggetto', 'UI:Component:QuickCreate:Input:Placeholder' => 'Seleziona il tipo di oggetto...', 'UI:Component:QuickCreate:Recents:Title' => 'Recenti', @@ -17,4 +18,4 @@ Dict::Add('IT IT', 'Italian', 'Italiano', array( 'UI:Component:QuickCreate:HistoryDisabled' => 'La cronologia è disabilitata', 'UI:Component:QuickCreate:KeyboardShortcut:OpenDrawer' => 'Apri la creazione rapida', 'UI:Component:QuickCreate:MostPopular:Title' => 'Più popolari', -)); \ No newline at end of file +]); diff --git a/dictionaries/ui/components/quick-create/ja.dictionary.itop.quick-create.php b/dictionaries/ui/components/quick-create/ja.dictionary.itop.quick-create.php index d99f41d67..391ddd1a4 100644 --- a/dictionaries/ui/components/quick-create/ja.dictionary.itop.quick-create.php +++ b/dictionaries/ui/components/quick-create/ja.dictionary.itop.quick-create.php @@ -1,15 +1,16 @@ 'Quickly create any type of object~~', 'UI:Component:QuickCreate:Input:Placeholder' => 'Select object type...~~', 'UI:Component:QuickCreate:Recents:Title' => 'Recents~~', @@ -17,4 +18,4 @@ Dict::Add('JA JP', 'Japanese', '日本語', array( 'UI:Component:QuickCreate:HistoryDisabled' => 'History is disabled~~', 'UI:Component:QuickCreate:KeyboardShortcut:OpenDrawer' => 'Open quick create~~', 'UI:Component:QuickCreate:MostPopular:Title' => 'Most popular~~', -)); \ No newline at end of file +]); diff --git a/dictionaries/ui/components/quick-create/nl.dictionary.itop.quick-create.php b/dictionaries/ui/components/quick-create/nl.dictionary.itop.quick-create.php index e23549c27..876dd5801 100644 --- a/dictionaries/ui/components/quick-create/nl.dictionary.itop.quick-create.php +++ b/dictionaries/ui/components/quick-create/nl.dictionary.itop.quick-create.php @@ -1,15 +1,16 @@ 'Snel een object aanmaken', 'UI:Component:QuickCreate:Input:Placeholder' => 'Selecteer een objectsoort…', 'UI:Component:QuickCreate:Recents:Title' => 'Recente', @@ -17,4 +18,4 @@ Dict::Add('NL NL', 'Dutch', 'Nederlands', array( 'UI:Component:QuickCreate:HistoryDisabled' => 'Geschiedenis staat uit', 'UI:Component:QuickCreate:KeyboardShortcut:OpenDrawer' => 'Open snel object aanmaken', 'UI:Component:QuickCreate:MostPopular:Title' => 'Meest populair', -)); \ No newline at end of file +]); diff --git a/dictionaries/ui/components/quick-create/pl.dictionary.itop.quick-create.php b/dictionaries/ui/components/quick-create/pl.dictionary.itop.quick-create.php index 7ce7fdd4c..b17406c93 100644 --- a/dictionaries/ui/components/quick-create/pl.dictionary.itop.quick-create.php +++ b/dictionaries/ui/components/quick-create/pl.dictionary.itop.quick-create.php @@ -1,15 +1,16 @@ 'Szybko utwórz dowolny rodzaj obiektu', 'UI:Component:QuickCreate:Input:Placeholder' => 'Wybierz typ obiektu...', 'UI:Component:QuickCreate:Recents:Title' => 'Ostatnie', @@ -17,4 +18,4 @@ Dict::Add('PL PL', 'Polish', 'Polski', array( 'UI:Component:QuickCreate:HistoryDisabled' => 'Historia jest wyłączona', 'UI:Component:QuickCreate:KeyboardShortcut:OpenDrawer' => 'Otwórz szybkie tworzenie', 'UI:Component:QuickCreate:MostPopular:Title' => 'Najbardziej popularne', -)); \ No newline at end of file +]); diff --git a/dictionaries/ui/components/quick-create/pt_br.dictionary.itop.quick-create.php b/dictionaries/ui/components/quick-create/pt_br.dictionary.itop.quick-create.php index f5f80081d..c2f7034a8 100644 --- a/dictionaries/ui/components/quick-create/pt_br.dictionary.itop.quick-create.php +++ b/dictionaries/ui/components/quick-create/pt_br.dictionary.itop.quick-create.php @@ -1,15 +1,16 @@ 'Crie rapidamente qualquer tipo de objeto', 'UI:Component:QuickCreate:Input:Placeholder' => 'Selecione o tipo de objeto...', 'UI:Component:QuickCreate:Recents:Title' => 'Recentes', @@ -17,4 +18,4 @@ Dict::Add('PT BR', 'Brazilian', 'Brazilian', array( 'UI:Component:QuickCreate:HistoryDisabled' => 'O histórico está desativado', 'UI:Component:QuickCreate:KeyboardShortcut:OpenDrawer' => 'Abrir criação rápida', 'UI:Component:QuickCreate:MostPopular:Title' => 'Mais popular', -)); \ No newline at end of file +]); diff --git a/dictionaries/ui/components/quick-create/ru.dictionary.itop.quick-create.php b/dictionaries/ui/components/quick-create/ru.dictionary.itop.quick-create.php index 7992f1511..587e6f823 100755 --- a/dictionaries/ui/components/quick-create/ru.dictionary.itop.quick-create.php +++ b/dictionaries/ui/components/quick-create/ru.dictionary.itop.quick-create.php @@ -1,15 +1,16 @@ 'Быстрое создание объекта любого типа', 'UI:Component:QuickCreate:Input:Placeholder' => 'Выбрать тип объекта...', 'UI:Component:QuickCreate:Recents:Title' => 'Недавние', @@ -17,4 +18,4 @@ Dict::Add('RU RU', 'Russian', 'Русский', array( 'UI:Component:QuickCreate:HistoryDisabled' => 'История отключена', 'UI:Component:QuickCreate:KeyboardShortcut:OpenDrawer' => 'Открыть быстрое создание объекта', 'UI:Component:QuickCreate:MostPopular:Title' => 'Популярные', -)); \ No newline at end of file +]); diff --git a/dictionaries/ui/components/quick-create/sk.dictionary.itop.quick-create.php b/dictionaries/ui/components/quick-create/sk.dictionary.itop.quick-create.php index 0e7de2c40..045891161 100644 --- a/dictionaries/ui/components/quick-create/sk.dictionary.itop.quick-create.php +++ b/dictionaries/ui/components/quick-create/sk.dictionary.itop.quick-create.php @@ -1,15 +1,16 @@ 'Quickly create any type of object~~', 'UI:Component:QuickCreate:Input:Placeholder' => 'Select object type...~~', 'UI:Component:QuickCreate:Recents:Title' => 'Recents~~', @@ -17,4 +18,4 @@ Dict::Add('SK SK', 'Slovak', 'Slovenčina', array( 'UI:Component:QuickCreate:HistoryDisabled' => 'History is disabled~~', 'UI:Component:QuickCreate:KeyboardShortcut:OpenDrawer' => 'Open quick create~~', 'UI:Component:QuickCreate:MostPopular:Title' => 'Most popular~~', -)); \ No newline at end of file +]); diff --git a/dictionaries/ui/components/quick-create/tr.dictionary.itop.quick-create.php b/dictionaries/ui/components/quick-create/tr.dictionary.itop.quick-create.php index 45597c47e..8d6effa23 100644 --- a/dictionaries/ui/components/quick-create/tr.dictionary.itop.quick-create.php +++ b/dictionaries/ui/components/quick-create/tr.dictionary.itop.quick-create.php @@ -1,15 +1,16 @@ 'Quickly create any type of object~~', 'UI:Component:QuickCreate:Input:Placeholder' => 'Select object type...~~', 'UI:Component:QuickCreate:Recents:Title' => 'Recents~~', @@ -17,4 +18,4 @@ Dict::Add('TR TR', 'Turkish', 'Türkçe', array( 'UI:Component:QuickCreate:HistoryDisabled' => 'History is disabled~~', 'UI:Component:QuickCreate:KeyboardShortcut:OpenDrawer' => 'Open quick create~~', 'UI:Component:QuickCreate:MostPopular:Title' => 'Most popular~~', -)); \ No newline at end of file +]); diff --git a/pages/UI.php b/pages/UI.php index abe2d8a2c..ce93b0614 100644 --- a/pages/UI.php +++ b/pages/UI.php @@ -1,4 +1,5 @@ 0) { TwigHelper::RenderIntoPage($oP, APPROOT."/", "templates/application/welcome-popup/layout", [ "aProvidersMessagesData" => $aProvidersMessagesData, - "sEndpointAbsURIForAcknowledgeMessage" => Router::GetInstance()->GenerateUrl(WelcomePopupController::ROUTE_NAMESPACE . ".acknowledge_message"), + "sEndpointAbsURIForAcknowledgeMessage" => Router::GetInstance()->GenerateUrl(WelcomePopupController::ROUTE_NAMESPACE.".acknowledge_message"), ]); } Session::Set("welcome", "ok"); // Try just once per session @@ -63,32 +64,25 @@ function ApplyNextAction(Webpage $oP, CMDBObject $oObj, $sNextAction) { // Here handle the apply stimulus $aTransitions = $oObj->EnumTransitions(); - if (!isset($aTransitions[$sNextAction])) - { + if (!isset($aTransitions[$sNextAction])) { // Invalid stimulus throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sNextAction, $oObj->GetName(), $oObj->GetStateLabel())); } // Get the list of missing mandatory fields for the target state, considering only the changes from the previous form (i.e don't prompt twice) $aExpectedAttributes = $oObj->GetTransitionAttributes($sNextAction); - if (count($aExpectedAttributes) == 0) - { + if (count($aExpectedAttributes) == 0) { // If all the mandatory fields are already present, just apply the transition silently... - if ($oObj->ApplyStimulus($sNextAction)) - { + if ($oObj->ApplyStimulus($sNextAction)) { $oObj->DBUpdate(); - } - else - { + } else { throw new ApplicationException(Dict::S('UI:FailedToApplyStimuli')); } ReloadAndDisplay($oP, $oObj); - } - else - { + } else { // redirect to the 'stimulus' action $oAppContext = new ApplicationContext(); -//echo "

Missing Attributes

".print_r($aExpectedAttributes, true)."

\n"; + //echo "

Missing Attributes

".print_r($aExpectedAttributes, true)."

\n"; $oP->add_header('Location: '.utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=stimulus&class='.get_class($oObj).'&stimulus='.$sNextAction.'&id='.$oObj->getKey().$oAppContext->GetForLink(true)); } @@ -97,8 +91,7 @@ function ApplyNextAction(Webpage $oP, CMDBObject $oObj, $sNextAction) function ReloadAndDisplay($oPage, $oObj, $sMessageId = '', $sMessage = '', $sSeverity = null) { $oAppContext = new ApplicationContext(); - if ($sMessageId != '') - { + if ($sMessageId != '') { cmdbAbstractObject::SetSessionMessage(get_class($oObj), $oObj->GetKey(), $sMessageId, $sMessage, $sSeverity, 0, true /* must not exist */); } $oPage->add_header('Location: '.utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=details&class='.get_class($oObj).'&id='.$oObj->getKey().$oAppContext->GetForLink(true)); @@ -126,8 +119,7 @@ function SetObjectBreadCrumbEntry(DBObject $oObj, WebPage $oPage) $sClass = get_class($oObj); // get the leaf class $sIcon = MetaModel::GetClassIcon($sClass, false); $sIconType = iTopWebPage::ENUM_BREADCRUMB_ENTRY_ICON_TYPE_IMAGE; - if ($sIcon == '') - { + if ($sIcon == '') { $sIcon = 'fas fa-cube'; $sIconType = iTopWebPage::ENUM_BREADCRUMB_ENTRY_ICON_TYPE_CSS_CLASSES; } @@ -221,7 +213,7 @@ function DisplayMultipleSelectionForm(WebPage $oP, DBSearch $oFilter, string $sN { $oAppContext = new ApplicationContext(); $iBulkActionAllowed = $oChecker->IsAllowed(); - $aExtraParams = array('selection_type' => 'multiple', 'selection_mode' => true, 'display_limit' => false, 'menu' => false); + $aExtraParams = ['selection_type' => 'multiple', 'selection_mode' => true, 'display_limit' => false, 'menu' => false]; if ($iBulkActionAllowed == UR_ALLOWED_DEPENDS) { $aExtraParams['selection_enabled'] = $oChecker->GetAllowedIDs(); } else { @@ -243,12 +235,12 @@ function DisplayMultipleSelectionForm(WebPage $oP, DBSearch $oFilter, string $sN $oDisplayBlock = new DisplayBlock($oFilter, 'list', false); //by default all the elements are selected $aExtraParams['selectionMode'] = 'negative'; - if(array_key_exists('icon', $aDisplayParams) || array_key_exists('title', $aDisplayParams)){ + if (array_key_exists('icon', $aDisplayParams) || array_key_exists('title', $aDisplayParams)) { $aExtraParams['surround_with_panel'] = true; - if(array_key_exists('icon', $aDisplayParams)){ + if (array_key_exists('icon', $aDisplayParams)) { $aExtraParams['panel_icon'] = $aDisplayParams['icon']; } - if(array_key_exists('title', $aDisplayParams)){ + if (array_key_exists('title', $aDisplayParams)) { $aExtraParams['panel_title'] = $aDisplayParams['title']; } } @@ -305,8 +297,7 @@ require_once(APPROOT.'/application/wizardhelper.class.inc.php'); require_once(APPROOT.'/application/startup.inc.php'); IssueLog::Trace('----- Request: '.utils::GetRequestUri(), LogChannels::WEB_REQUEST); -try -{ +try { $oKPI = new ExecutionKPI(); $oKPI->ComputeAndReport('Data model loaded'); @@ -342,8 +333,7 @@ try $oP->SetMessage($sLoginMessage); // All the following actions use advanced forms that require more javascript to be loaded - switch($operation) - { + switch ($operation) { case 'new': // Form to create a new object case 'form_for_modify_all': // Form to modify multiple objects (bulk modify) case 'bulk_stimulus': // For to apply a stimulus to multiple objects @@ -355,8 +345,7 @@ try break; } - switch($operation) - { + switch ($operation) { /////////////////////////////////////////////////////////////////////////////////////////// case 'details': // Details of an object @@ -394,30 +383,20 @@ try utils::PushArchiveMode(true); if (is_numeric($id)) { $oObj = MetaModel::GetObject($sClass, $id, false /* MustBeFound */); - } - else - { + } else { $oObj = MetaModel::GetObjectByName($sClass, $id, false /* MustBeFound */); } utils::PopArchiveMode(); - if (is_null($oObj)) - { + if (is_null($oObj)) { $oP->P(Dict::S('UI:ObjectDoesNotExist')); - } - else - { + } else { SetObjectBreadCrumbEntry($oObj, $oP); $oP->P(Dict::S('UI:ObjectArchived')); } - } - else - { - try - { + } else { + try { $oObj->Reload(); - } - catch(Exception $e) - { + } catch (Exception $e) { // Probably not allowed to see this instance of a derived class // Check anyhow if there is a message for this object (like you've just created it) @@ -428,14 +407,13 @@ try $oP->set_title(Dict::S('UI:ErrorPageTitle')); $oP->P(Dict::S('UI:ObjectDoesNotExist')); } - if (!is_null($oObj)) - { + if (!is_null($oObj)) { SetObjectBreadCrumbEntry($oObj, $oP); // The object could be listed, check if it is actually allowed to view it $oSet = CMDBObjectSet::FromObject($oObj); if (UserRights::IsActionAllowed($sClass, UR_ACTION_READ, $oSet) == UR_ALLOWED_NO) { - throw new SecurityException('User not allowed to view this object', array('class' => $sClass, 'id' => $id)); + throw new SecurityException('User not allowed to view this object', ['class' => $sClass, 'id' => $id]); } $sClassLabel = MetaModel::GetName($sClass); @@ -444,28 +422,27 @@ try $oObj->DisplayDetails($oP); } } - break; + break; case 'release_lock_and_details': - $oP->DisableBreadCrumb(); + $oP->DisableBreadCrumb(); - // Retrieve object - $sClass = utils::ReadParam('class', '', false, 'class'); - $id = utils::ReadParam('id', ''); - $oObj = MetaModel::GetObject($sClass, $id); + // Retrieve object + $sClass = utils::ReadParam('class', '', false, 'class'); + $id = utils::ReadParam('id', ''); + $oObj = MetaModel::GetObject($sClass, $id); - // Retrieve ownership token - $sToken = utils::ReadParam('token', ''); - if ($sToken != '') - { - iTopOwnershipLock::ReleaseLock($sClass, $id, $sToken); - } + // Retrieve ownership token + $sToken = utils::ReadParam('token', ''); + if ($sToken != '') { + iTopOwnershipLock::ReleaseLock($sClass, $id, $sToken); + } - $oP->SetContentLayout(PageContentFactory::MakeForObjectDetails($oObj, cmdbAbstractObject::ENUM_DISPLAY_MODE_VIEW)); - cmdbAbstractObject::ReloadAndDisplay($oP, $oObj, array('operation' => 'details')); - break; + $oP->SetContentLayout(PageContentFactory::MakeForObjectDetails($oObj, cmdbAbstractObject::ENUM_DISPLAY_MODE_VIEW)); + cmdbAbstractObject::ReloadAndDisplay($oP, $oObj, ['operation' => 'details']); + break; - /////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////// case 'search_oql': // OQL query $oSearchContext = new ContextTag(ContextTag::TAG_OBJECT_SEARCH); @@ -484,22 +461,20 @@ try try { $oFilter = DBObjectSearch::FromOQL($sOQL); DisplaySearchSet($oP, $oFilter, $bSearchForm, $sBaseClass, $sFormat); - } - catch(CoreException $e) { + } catch (CoreException $e) { $oFilter = new DBObjectSearch($sOQLClass); $oSet = new DBObjectSet($oFilter); if ($bSearchForm) { $oBlock = new DisplayBlock($oFilter, 'search', false); - $oBlock->Display($oP, 0, array('table_id' => 'search-widget-result-outer')); + $oBlock->Display($oP, 0, ['table_id' => 'search-widget-result-outer']); } $oP->add('

'.Dict::Format('UI:Error:IncorrectOQLQuery_Message', $e->getHtmlDesc()).'

'); - } - catch(Exception $e) { + } catch (Exception $e) { $oP->P(''.Dict::Format('UI:Error:AnErrorOccuredWhileRunningTheQuery_Message', $e->getMessage()).''); } break; - /////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////// case 'search_form': // Search form $oSearchContext = new ContextTag(ContextTag::TAG_OBJECT_SEARCH); @@ -515,15 +490,14 @@ try DisplaySearchSet($oP, $oFilter, $bSearchForm, '' /* sBaseClass */, $sFormat, $bDoSearch, true /* Search Form Expanded */); break; - /////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////// case 'search': // Serialized DBSearch $oSearchContext = new ContextTag(ContextTag::TAG_OBJECT_SEARCH); $sFilter = utils::ReadParam('filter', '', false, 'raw_data'); $sFormat = utils::ReadParam('format', ''); $bSearchForm = utils::ReadParam('search_form', true); - if (empty($sFilter)) - { + if (empty($sFilter)) { throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'filter')); } $oP->set_title(Dict::S('UI:SearchResultsPageTitle')); @@ -532,48 +506,38 @@ try //FIXME Params won't work as expected :( // During the ajax call fetching the datatable data, the URL is rewritten and the info are lost, and we are getting a worse result :( -// $sParams = utils::ReadParam('aParams', '{}', false, \utils::ENUM_SANITIZATION_FILTER_RAW_DATA); -// $aParams = json_decode($sParams, true); + // $sParams = utils::ReadParam('aParams', '{}', false, \utils::ENUM_SANITIZATION_FILTER_RAW_DATA); + // $aParams = json_decode($sParams, true); DisplaySearchSet($oP, $oFilter, $bSearchForm, '' /* sBaseClass */, $sFormat); //, true, true, $aParams break; - /////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////// case 'full_text': // Global "google-like" search $oP->DisableBreadCrumb(); $sQuery = trim(utils::ReadParam('text', '', false, 'raw_data')); $iTune = utils::ReadParam('tune', 0); - if (empty($sQuery)) - { + if (empty($sQuery)) { $oP->p(Dict::S('UI:Search:NoSearch')); - } - else - { + } else { $iErrors = 0; $sFullText = $sQuery; // Check if a class name/label is supplied to limit the search $sClassName = ''; - if (preg_match('/^([^\"]+):(.+)$/', $sFullText, $aMatches)) - { + if (preg_match('/^([^\"]+):(.+)$/', $sFullText, $aMatches)) { $sClassName = $aMatches[1]; - if (MetaModel::IsValidClass($sClassName)) - { + if (MetaModel::IsValidClass($sClassName)) { $sFullText = trim($aMatches[2]); - } - elseif ($sClassName = MetaModel::GetClassFromLabel($sClassName, false /* => not case sensitive */)) - { + } elseif ($sClassName = MetaModel::GetClassFromLabel($sClassName, false /* => not case sensitive */)) { $sFullText = trim($aMatches[2]); } } - if (preg_match('/^"(.*)"$/', $sFullText, $aMatches)) - { + if (preg_match('/^"(.*)"$/', $sFullText, $aMatches)) { // The text is surrounded by double-quotes, remove the quotes and treat it as one single expression - $aFullTextNeedles = array($aMatches[1]); - } - else - { + $aFullTextNeedles = [$aMatches[1]]; + } else { // Split the text on the blanks and treat this as a search for AND AND $aExplodedFullTextNeedles = explode(' ', $sFullText); $aFullTextNeedles = []; @@ -587,7 +551,7 @@ try // Save search to history // - Prepare icon $sQueryIconUrl = null; - if(!empty($sClassName)) { + if (!empty($sClassName)) { $sQueryIconUrl = MetaModel::GetClassIcon($sClassName, false); } // - Prepare label @@ -604,14 +568,12 @@ try if (strlen($sNeedle) < $iMinLenth) { $oP->p(Dict::Format('UI:Search:NeedleTooShort', $sNeedle, $iMinLenth)); $key = array_search($sNeedle, $aFullTextNeedles); - if ($key !== false) - { + if ($key !== false) { unset($aFullTextNeedles[$key]); } } } - if(empty($aFullTextNeedles)) - { + if (empty($aFullTextNeedles)) { $oP->p(Dict::S('UI:Search:NoSearch')); break; } @@ -620,30 +582,23 @@ try // Sanity check of the accelerators /** @var array $aAccelerators */ $aAccelerators = MetaModel::GetConfig()->Get('full_text_accelerators'); - foreach ($aAccelerators as $sClass => $aAccelerator) - { - try - { + foreach ($aAccelerators as $sClass => $aAccelerator) { + try { $bSkip = array_key_exists('skip', $aAccelerator) ? $aAccelerator['skip'] : false; - if (!$bSkip) - { + if (!$bSkip) { $oSearch = DBObjectSearch::FromOQL($aAccelerator['query']); - if ($sClass != $oSearch->GetClass()) - { + if ($sClass != $oSearch->GetClass()) { $oP->p("Full text accelerator for class '$sClass': searched class mismatch (".$oSearch->GetClass().")"); $iErrors++; } } - } - catch (OqlException $e) - { + } catch (OqlException $e) { $oP->p("Full text accelerator for class '$sClass': ".$e->getHtmlDesc()); $iErrors++; } } - if ($iErrors == 0) - { + if ($iErrors == 0) { $oP->set_title(Dict::S('UI:SearchResultsPageTitle')); $sPageId = "ui-global-search"; $sLabel = Dict::S('UI:SearchResultsTitle'); @@ -651,7 +606,7 @@ try $oP->SetBreadCrumbEntry($sPageId, $sLabel, $sDescription, '', 'fas fa-search', iTopWebPage::ENUM_BREADCRUMB_ENTRY_ICON_TYPE_CSS_CLASSES); $oP->add("
\n"); $oP->add("
\n"); - $oP->add(' '.Dict::Format('UI:Search:Ongoing', utils::EscapeHtml($sFullText)).''); + $oP->add(' '.Dict::Format('UI:Search:Ongoing', utils::EscapeHtml($sFullText)).''); $oP->add("
\n"); $oP->add("
\n"); $oP->add("
 
\n"); @@ -668,63 +623,61 @@ try }); EOF ); - if ($iTune > 0) - { + if ($iTune > 0) { $oP->add_script("var oTimeStatistics = {};"); } } } - break; + break; - /////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////// - /** @deprecated 3.1.0 Use the "object.modify" route instead */ - // Kept for backward compatibility with notification URLs, don't remove + /** @deprecated 3.1.0 Use the "object.modify" route instead */ + // Kept for backward compatibility with notification URLs, don't remove case 'modify': // Legacy operation $oController = new ObjectController(); $oP = $oController->OperationModify(); break; - /////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////// case 'select_for_modify_all': // Select the list of objects to be modified (bulk modify) UI::OperationSelectForModifyAll($oP); break; - /////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////// case 'form_for_modify_all': // Form to modify multiple objects (bulk modify) UI::OperationFormForModifyAll($oP, $oAppContext); break; - /////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////// case 'preview_or_modify_all': // Preview or apply bulk modify UI::OperationPreviewOrModifyAll($oP, $oAppContext); break; - /////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////// - /** @deprecated 3.1.0 Use the "object.new" route instead */ - // Kept for backward compatibility + /** @deprecated 3.1.0 Use the "object.new" route instead */ + // Kept for backward compatibility case 'new': // Form to create a new object $oController = new ObjectController(); $oP = $oController->OperationNew(); - break; + break; - /////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////// case 'apply_modify': // Applying the modifications to an existing object $oController = new ObjectController(); $oP = $oController->OperationApplyModify(); - break; + break; - /////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////// case 'select_for_deletion': // Select multiple objects for deletion $oP->DisableBreadCrumb(); $sFilter = utils::ReadParam('filter', '', false, 'raw_data'); - if (empty($sFilter)) - { + if (empty($sFilter)) { throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'filter')); } $oP->set_title(Dict::S('UI:BulkDeletePageTitle')); @@ -740,68 +693,57 @@ try ]; $oChecker = new ActionChecker($oFilter, UR_ACTION_BULK_DELETE); DisplayMultipleSelectionForm($oP, $oFilter, 'bulk_delete', $oChecker, [], $aDisplayParams); - break; + break; - /////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////// case 'bulk_delete_confirmed': // Confirm bulk deletion of objects $oP->DisableBreadCrumb(); $sTransactionId = utils::ReadPostedParam('transaction_id', '', 'transaction_id'); - if (!utils::IsTransactionValid($sTransactionId)) - { + if (!utils::IsTransactionValid($sTransactionId)) { $sUser = UserRights::GetUser(); $sClass = utils::ReadParam('class', '', false, 'class'); IssueLog::Error("UI.php '$operation' : invalid transaction_id ! data: user='$sUser', class='$sClass'"); throw new ApplicationException(Dict::S('UI:Error:ObjectsAlreadyDeleted')); } - // Fall through + // Fall through - /////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////// + // no break case 'delete': case 'bulk_delete': // Actual bulk deletion (if confirmed) $oP->DisableBreadCrumb(); $sClass = utils::ReadParam('class', '', false, 'class'); $sClassLabel = MetaModel::GetName($sClass); - $aObjects = array(); - if ($operation == 'delete') - { + $aObjects = []; + if ($operation == 'delete') { // Single object $id = utils::ReadParam('id', ''); $oObj = MetaModel::GetObject($sClass, $id); $aObjects[] = $oObj; - if (!UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, DBObjectSet::FromObject($oObj))) - { + if (!UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, DBObjectSet::FromObject($oObj))) { throw new SecurityException(Dict::Format('UI:Error:DeleteNotAllowedOn_Class', $sClassLabel)); } - } - else - { + } else { // Several objects $sFilter = utils::ReadPostedParam('filter', '', 'raw_data'); $oFullSetFilter = DBObjectSearch::unserialize($sFilter); // Add user filter $oFullSetFilter->UpdateContextFromUser(); $aSelectObject = utils::ReadMultipleSelection($oFullSetFilter); - if ( empty($sClass) || empty($aSelectObject)) // TO DO: check that the class name is valid ! - { + if (empty($sClass) || empty($aSelectObject)) { // TO DO: check that the class name is valid ! throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'selectObject[]')); } - foreach($aSelectObject as $iId) - { + foreach ($aSelectObject as $iId) { $aObjects[] = MetaModel::GetObject($sClass, $iId); } - if (count($aObjects) == 1) - { - if (!UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, DBObjectSet::FromArray($sClass, $aObjects))) - { + if (count($aObjects) == 1) { + if (!UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, DBObjectSet::FromArray($sClass, $aObjects))) { throw new SecurityException(Dict::Format('UI:Error:BulkDeleteNotAllowedOn_Class', $sClassLabel)); } - } - else - { - if (!UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_DELETE, DBObjectSet::FromArray($sClass, $aObjects))) - { + } else { + if (!UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_DELETE, DBObjectSet::FromArray($sClass, $aObjects))) { throw new SecurityException(Dict::Format('UI:Error:BulkDeleteNotAllowedOn_Class', $sClassLabel)); } $oP->set_title(Dict::S('UI:BulkDeletePageTitle')); @@ -811,7 +753,7 @@ try cmdbAbstractObject::DeleteObjects($oP, $sClass, $aObjects, ($operation != 'bulk_delete_confirmed'), 'bulk_delete_confirmed'); break; - /////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////// case 'apply_new': // Creation of a new object @@ -819,699 +761,613 @@ try $oP = $oController->OperationApplyNew(); break; - /////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////// case 'select_bulk_stimulus': // Form displayed when applying a stimulus to many objects - $oP->DisableBreadCrumb(); - $sFilter = utils::ReadParam('filter', '', false, 'raw_data'); - $sStimulus = utils::ReadParam('stimulus', ''); - $sState = utils::ReadParam('state', ''); - if (empty($sFilter) || empty($sStimulus) || empty($sState)) - { - throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state')); - } - $oFilter = DBObjectSearch::unserialize($sFilter); - $oFilter->UpdateContextFromUser(); - $sClass = $oFilter->GetClass(); - $aStimuli = MetaModel::EnumStimuli($sClass); - $sActionLabel = $aStimuli[$sStimulus]->GetLabel(); - $sActionDetails = $aStimuli[$sStimulus]->GetDescription(); - $oP->set_title($sActionLabel); - $sClass = $oFilter->GetClass(); - - $aDisplayParams = [ - 'icon' => MetaModel::GetClassIcon($sClass, false), - 'title' => $sActionLabel, - ]; - $oChecker = new StimulusChecker($oFilter, $sState, $sStimulus); - $aExtraFormParams = array('stimulus' => $sStimulus, 'state' => $sState); - DisplayMultipleSelectionForm($oP, $oFilter, 'bulk_stimulus', $oChecker, $aExtraFormParams, $aDisplayParams); - break; - - case 'bulk_stimulus': - $oP->DisableBreadCrumb(); - $sFilter = utils::ReadParam('filter', '', false, 'raw_data'); - $sStimulus = utils::ReadParam('stimulus', ''); - $sState = utils::ReadParam('state', ''); - if (empty($sFilter) || empty($sStimulus) || empty($sState)) - { - throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state')); - } - $oFilter = DBObjectSearch::unserialize($sFilter); - // Add user filter - $oFilter->UpdateContextFromUser(); - $sClass = $oFilter->GetClass(); - $aSelectObject = utils::ReadMultipleSelection($oFilter); - if (count($aSelectObject) == 0) - { - // Nothing to do, no object was selected ! - throw new ApplicationException(Dict::S('UI:BulkAction:NoObjectSelected')); - } - else - { - $aTransitions = MetaModel::EnumTransitions($sClass, $sState); + $oP->DisableBreadCrumb(); + $sFilter = utils::ReadParam('filter', '', false, 'raw_data'); + $sStimulus = utils::ReadParam('stimulus', ''); + $sState = utils::ReadParam('state', ''); + if (empty($sFilter) || empty($sStimulus) || empty($sState)) { + throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state')); + } + $oFilter = DBObjectSearch::unserialize($sFilter); + $oFilter->UpdateContextFromUser(); + $sClass = $oFilter->GetClass(); $aStimuli = MetaModel::EnumStimuli($sClass); - $sActionLabel = $aStimuli[$sStimulus]->GetLabel(); $sActionDetails = $aStimuli[$sStimulus]->GetDescription(); - $sTargetState = $aTransitions[$sStimulus]['target_state']; - $aStates = MetaModel::EnumStates($sClass); - $aTargetStateDef = $aStates[$sTargetState]; + $oP->set_title($sActionLabel); + $sClass = $oFilter->GetClass(); - $oP->set_title(Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aSelectObject), $sClass)); - $oP->add(<< MetaModel::GetClassIcon($sClass, false), + 'title' => $sActionLabel, + ]; + $oChecker = new StimulusChecker($oFilter, $sState, $sStimulus); + $aExtraFormParams = ['stimulus' => $sStimulus, 'state' => $sState]; + DisplayMultipleSelectionForm($oP, $oFilter, 'bulk_stimulus', $oChecker, $aExtraFormParams, $aDisplayParams); + break; + + case 'bulk_stimulus': + $oP->DisableBreadCrumb(); + $sFilter = utils::ReadParam('filter', '', false, 'raw_data'); + $sStimulus = utils::ReadParam('stimulus', ''); + $sState = utils::ReadParam('state', ''); + if (empty($sFilter) || empty($sStimulus) || empty($sState)) { + throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state')); + } + $oFilter = DBObjectSearch::unserialize($sFilter); + // Add user filter + $oFilter->UpdateContextFromUser(); + $sClass = $oFilter->GetClass(); + $aSelectObject = utils::ReadMultipleSelection($oFilter); + if (count($aSelectObject) == 0) { + // Nothing to do, no object was selected ! + throw new ApplicationException(Dict::S('UI:BulkAction:NoObjectSelected')); + } else { + $aTransitions = MetaModel::EnumTransitions($sClass, $sState); + $aStimuli = MetaModel::EnumStimuli($sClass); + + $sActionLabel = $aStimuli[$sStimulus]->GetLabel(); + $sActionDetails = $aStimuli[$sStimulus]->GetDescription(); + $sTargetState = $aTransitions[$sStimulus]['target_state']; + $aStates = MetaModel::EnumStates($sClass); + $aTargetStateDef = $aStates[$sTargetState]; + + $oP->set_title(Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aSelectObject), $sClass)); + $oP->add( + <<
HTML - ); - $oP->AddUiBlock(TitleUIBlockFactory::MakeForPage(Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aSelectObject), $sClass))); - if (!empty($sActionDetails)) { - $oP->AddUiBlock(TitleUIBlockFactory::MakeForPage($sActionDetails)); - } - - - - $aExpectedAttributes = MetaModel::GetTransitionAttributes($sClass, $sStimulus, $sState); - $aDetails = array(); - $sFormId = 'apply_stimulus'; - $sFormPrefix = $sFormId.'_'; - $iFieldIndex = 0; - $aFieldsMap = array(); - $aValues = array(); - $aObjects = array(); - foreach($aSelectObject as $iId) - { - $aObjects[] = MetaModel::GetObject($sClass, $iId); - } - $oSet = DBObjectSet::FromArray($sClass, $aObjects); - $oObj = $oSet->ComputeCommonObject($aValues); - $sStateAttCode = MetaModel::GetStateAttributeCode($sClass); - $oObj->Set($sStateAttCode,$sTargetState); - $sReadyScript = ''; - foreach($aExpectedAttributes as $sAttCode => $iExpectCode) - { - $sFieldInputId = $sFormPrefix.$sAttCode; - // Prompt for an attribute if - // - the attribute must be changed or must be displayed to the user for confirmation - // - or the field is mandatory and currently empty - if ( ($iExpectCode & (OPT_ATT_MUSTCHANGE | OPT_ATT_MUSTPROMPT)) || - (($iExpectCode & OPT_ATT_MANDATORY) && ($oObj->Get($sAttCode) == '')) ) - { - $aAttributesDef = MetaModel::ListAttributeDefs($sClass); - $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode); - $aPrerequisites = MetaModel::GetPrerequisiteAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one - if (count($aPrerequisites) > 0) - { - // When 'enabling' a field, all its prerequisites must be enabled too - $sFieldList = "['{$sFormPrefix}".implode("','{$sFormPrefix}", $aPrerequisites)."']"; - $oP->add_ready_script("$('#enable_{$sFieldInputId}').on('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, true); } );\n"); - } - $aDependents = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one - if (count($aDependents) > 0) - { - // When 'disabling' a field, all its dependent fields must be disabled too - $sFieldList = "['{$sFormPrefix}".implode("','{$sFormPrefix}", $aDependents)."']"; - $oP->add_ready_script("$('#enable_{$sFieldInputId}').on('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, false); } );\n"); - } - $aArgs = array('this' => $oObj); - $sHTMLValue = cmdbAbstractObject::GetFormElementForField($oP, $sClass, $sAttCode, $oAttDef, $oObj->Get($sAttCode), $oObj->GetEditValue($sAttCode), $sFieldInputId, '', $iExpectCode, $aArgs); - $sComments = ''; - if (!isset($aValues[$sAttCode])) - { - $aValues[$sAttCode] = array(); - } - if (count($aValues[$sAttCode]) == 1) - { - $sComments = '
1'.$sComments.'
'; - } - else - { - // Non-homogenous value - $iMaxCount = 5; - $sTip = "

".Dict::Format('UI:BulkModify_Count_DistinctValues', count($aValues[$sAttCode]))."

    "; - $index = 0; - foreach($aValues[$sAttCode] as $sCurrValue => $aVal) - { - $sDisplayValue = empty($aVal['display']) ? ''.Dict::S('Enum:Undefined').'' : str_replace(array("\n", "\r"), " ", $aVal['display']); - $sTip .= "
  • ".Dict::Format('UI:BulkModify:Value_Exists_N_Times', $sDisplayValue, $aVal['count'])."
  • "; - $index++; - if ($iMaxCount == $index) - { - $sTip .= "
  • ".Dict::Format('UI:BulkModify:N_MoreValues', count($aValues[$sAttCode]) - $iMaxCount)."
  • "; - break; - } - } - $sTip .= "

"; - $sTip = utils::HtmlEntities($sTip); - $sComments = '
'.count($aValues[$sAttCode]).$sComments.'
'; - } - $aDetails[] = array('label' => ''.$oAttDef->GetLabel().'', 'value' => "$sHTMLValue", 'comments' => $sComments); - $aFieldsMap[$sAttCode] = $sFieldInputId; - $iFieldIndex++; + ); + $oP->AddUiBlock(TitleUIBlockFactory::MakeForPage(Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aSelectObject), $sClass))); + if (!empty($sActionDetails)) { + $oP->AddUiBlock(TitleUIBlockFactory::MakeForPage($sActionDetails)); } - } - $oFormContainer = new UIContentBlock(null, ['ibo-wizard-container']); - $oP->AddUiBlock($oFormContainer); - $oForm = new Combodo\iTop\Application\UI\Base\Component\Form\Form($sFormId); - $oFormContainer->AddSubBlock($oForm); - $oForm->SetOnSubmitJsCode("return OnSubmit('{$sFormId}');") - ->AddSubBlock(InputUIBlockFactory::MakeForHidden('class', $sClass)) - ->AddSubBlock(InputUIBlockFactory::MakeForHidden('operation', 'bulk_apply_stimulus')) - ->AddSubBlock(InputUIBlockFactory::MakeForHidden('stimulus', $sStimulus)) - ->AddSubBlock(InputUIBlockFactory::MakeForHidden('preview_mode', 1)) - ->AddSubBlock(InputUIBlockFactory::MakeForHidden('filter', utils::HtmlEntities($sFilter))) - ->AddSubBlock(InputUIBlockFactory::MakeForHidden('state', $sState)) - ->AddSubBlock(InputUIBlockFactory::MakeForHidden('selectObject', implode(',',$aSelectObject))) - ->AddSubBlock(InputUIBlockFactory::MakeForHidden('transaction_id', utils::GetNewTransactionId())); - $aContextInputBlocks = $oAppContext->GetForUIForm(); - foreach ($aContextInputBlocks as $oContextInputBlock){ - $oForm->AddSubBlock($oContextInputBlock); - } - // Note: Remove the table if we want fields to occupy the whole width of the container - $oForm->AddHtml('
$sProperty$sCell
'); - $oForm->AddHtml($oP->GetDetails($aDetails)); - $oForm->AddHtml('
'); + $aExpectedAttributes = MetaModel::GetTransitionAttributes($sClass, $sStimulus, $sState); + $aDetails = []; + $sFormId = 'apply_stimulus'; + $sFormPrefix = $sFormId.'_'; + $iFieldIndex = 0; + $aFieldsMap = []; + $aValues = []; + $aObjects = []; + foreach ($aSelectObject as $iId) { + $aObjects[] = MetaModel::GetObject($sClass, $iId); + } + $oSet = DBObjectSet::FromArray($sClass, $aObjects); + $oObj = $oSet->ComputeCommonObject($aValues); + $sStateAttCode = MetaModel::GetStateAttributeCode($sClass); + $oObj->Set($sStateAttCode, $sTargetState); + $sReadyScript = ''; + foreach ($aExpectedAttributes as $sAttCode => $iExpectCode) { + $sFieldInputId = $sFormPrefix.$sAttCode; + // Prompt for an attribute if + // - the attribute must be changed or must be displayed to the user for confirmation + // - or the field is mandatory and currently empty + if (($iExpectCode & (OPT_ATT_MUSTCHANGE | OPT_ATT_MUSTPROMPT)) || + (($iExpectCode & OPT_ATT_MANDATORY) && ($oObj->Get($sAttCode) == ''))) { + $aAttributesDef = MetaModel::ListAttributeDefs($sClass); + $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode); + $aPrerequisites = MetaModel::GetPrerequisiteAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one + if (count($aPrerequisites) > 0) { + // When 'enabling' a field, all its prerequisites must be enabled too + $sFieldList = "['{$sFormPrefix}".implode("','{$sFormPrefix}", $aPrerequisites)."']"; + $oP->add_ready_script("$('#enable_{$sFieldInputId}').on('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, true); } );\n"); + } + $aDependents = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one + if (count($aDependents) > 0) { + // When 'disabling' a field, all its dependent fields must be disabled too + $sFieldList = "['{$sFormPrefix}".implode("','{$sFormPrefix}", $aDependents)."']"; + $oP->add_ready_script("$('#enable_{$sFieldInputId}').on('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, false); } );\n"); + } + $aArgs = ['this' => $oObj]; + $sHTMLValue = cmdbAbstractObject::GetFormElementForField($oP, $sClass, $sAttCode, $oAttDef, $oObj->Get($sAttCode), $oObj->GetEditValue($sAttCode), $sFieldInputId, '', $iExpectCode, $aArgs); + $sComments = ''; + if (!isset($aValues[$sAttCode])) { + $aValues[$sAttCode] = []; + } + if (count($aValues[$sAttCode]) == 1) { + $sComments = '
1'.$sComments.'
'; + } else { + // Non-homogenous value + $iMaxCount = 5; + $sTip = "

".Dict::Format('UI:BulkModify_Count_DistinctValues', count($aValues[$sAttCode]))."

    "; + $index = 0; + foreach ($aValues[$sAttCode] as $sCurrValue => $aVal) { + $sDisplayValue = empty($aVal['display']) ? ''.Dict::S('Enum:Undefined').'' : str_replace(["\n", "\r"], " ", $aVal['display']); + $sTip .= "
  • ".Dict::Format('UI:BulkModify:Value_Exists_N_Times', $sDisplayValue, $aVal['count'])."
  • "; + $index++; + if ($iMaxCount == $index) { + $sTip .= "
  • ".Dict::Format('UI:BulkModify:N_MoreValues', count($aValues[$sAttCode]) - $iMaxCount)."
  • "; + break; + } + } + $sTip .= "

"; + $sTip = utils::HtmlEntities($sTip); + $sComments = '
'.count($aValues[$sAttCode]).$sComments.'
'; + } + $aDetails[] = ['label' => ''.$oAttDef->GetLabel().'', 'value' => "$sHTMLValue", 'comments' => $sComments]; + $aFieldsMap[$sAttCode] = $sFieldInputId; + $iFieldIndex++; + } + } + $oFormContainer = new UIContentBlock(null, ['ibo-wizard-container']); + $oP->AddUiBlock($oFormContainer); + $oForm = new Combodo\iTop\Application\UI\Base\Component\Form\Form($sFormId); + $oFormContainer->AddSubBlock($oForm); + $oForm->SetOnSubmitJsCode("return OnSubmit('{$sFormId}');") + ->AddSubBlock(InputUIBlockFactory::MakeForHidden('class', $sClass)) + ->AddSubBlock(InputUIBlockFactory::MakeForHidden('operation', 'bulk_apply_stimulus')) + ->AddSubBlock(InputUIBlockFactory::MakeForHidden('stimulus', $sStimulus)) + ->AddSubBlock(InputUIBlockFactory::MakeForHidden('preview_mode', 1)) + ->AddSubBlock(InputUIBlockFactory::MakeForHidden('filter', utils::HtmlEntities($sFilter))) + ->AddSubBlock(InputUIBlockFactory::MakeForHidden('state', $sState)) + ->AddSubBlock(InputUIBlockFactory::MakeForHidden('selectObject', implode(',', $aSelectObject))) + ->AddSubBlock(InputUIBlockFactory::MakeForHidden('transaction_id', utils::GetNewTransactionId())); - $sURL = "./UI.php?operation=search&filter=".urlencode($sFilter).$oAppContext->GetForLink(true); - $oCancelButton = ButtonUIBlockFactory::MakeForCancel(Dict::S('UI:Button:Cancel'), 'cancel', 'cancel'); - $oCancelButton->SetOnClickJsCode("window.location.href='$sURL'"); - $oForm->AddSubBlock($oCancelButton); + $aContextInputBlocks = $oAppContext->GetForUIForm(); + foreach ($aContextInputBlocks as $oContextInputBlock) { + $oForm->AddSubBlock($oContextInputBlock); + } + // Note: Remove the table if we want fields to occupy the whole width of the container + $oForm->AddHtml('
'); + $oForm->AddHtml($oP->GetDetails($aDetails)); + $oForm->AddHtml('
'); - $oSubmitButton = ButtonUIBlockFactory::MakeForPrimaryAction($sActionLabel, 'submit', 'submit', true); - $oForm->AddSubBlock($oSubmitButton); + $sURL = "./UI.php?operation=search&filter=".urlencode($sFilter).$oAppContext->GetForLink(true); + $oCancelButton = ButtonUIBlockFactory::MakeForCancel(Dict::S('UI:Button:Cancel'), 'cancel', 'cancel'); + $oCancelButton->SetOnClickJsCode("window.location.href='$sURL'"); + $oForm->AddSubBlock($oCancelButton); - $oP->add(<<AddSubBlock($oSubmitButton); + + $oP->add( + <<
HTML - ); + ); - $iFieldsCount = count($aFieldsMap); - $sJsonFieldsMap = json_encode($aFieldsMap); + $iFieldsCount = count($aFieldsMap); + $sJsonFieldsMap = json_encode($aFieldsMap); - $oP->add_script( - <<add_script( + <<add_ready_script( - <<add_ready_script( + <<DisableBreadCrumb(); - $bPreviewMode = utils::ReadPostedParam('preview_mode', false); - $sFilter = utils::ReadPostedParam('filter', '', 'raw_data'); - $sStimulus = utils::ReadPostedParam('stimulus', ''); - $sState = utils::ReadPostedParam('state', ''); - $sSelectObject = utils::ReadPostedParam('selectObject', '', 'raw_data'); - $aSelectObject = explode(',', $sSelectObject); - - if (empty($sFilter) || empty($sStimulus) || empty($sState)) - { - throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state')); - } - $sTransactionId = utils::ReadPostedParam('transaction_id', '', 'transaction_id'); - if (!utils::IsTransactionValid($sTransactionId)) - { - $sUser = UserRights::GetUser(); - IssueLog::Error("UI.php '$operation' : invalid transaction_id ! data: user='$sUser'"); - $oP->p(Dict::S('UI:Error:ObjectAlreadyUpdated')); - } - else - { - // For archiving the modification - $oFilter = DBObjectSearch::unserialize($sFilter); - // Add user filter - $oFilter->UpdateContextFromUser(); - $sClass = $oFilter->GetClass(); - $aObjects = array(); - foreach($aSelectObject as $iId) - { - $aObjects[] = MetaModel::GetObject($sClass, $iId); - } - - $aTransitions = MetaModel::EnumTransitions($sClass, $sState); - $aStimuli = MetaModel::EnumStimuli($sClass); - - $sActionLabel = $aStimuli[$sStimulus]->GetLabel(); - $sActionDetails = $aStimuli[$sStimulus]->GetDescription(); - - $oP->set_title(Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aObjects), $sClass)); - - $oSet = DBObjectSet::FromArray($sClass, $aObjects); - - // For reporting - $aHeaders = array( - 'object' => array('label' => MetaModel::GetName($sClass), 'description' => Dict::S('UI:ModifiedObject')), - 'status' => array('label' => Dict::S('UI:BulkModifyStatus'), 'description' => Dict::S('UI:BulkModifyStatus+')), - 'errors' => array('label' => Dict::S('UI:BulkModifyErrors'), 'description' => Dict::S('UI:BulkModifyErrors+')), - ); - $aRows = array(); - while ($oObj = $oSet->Fetch()) - { - $sError = Dict::S('UI:BulkModifyStatusOk'); - try - { - $aTransitions = $oObj->EnumTransitions(); - $aStimuli = MetaModel::EnumStimuli($sClass); - if (!isset($aTransitions[$sStimulus])) - { - throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel())); - } - else - { - $sActionLabel = $aStimuli[$sStimulus]->GetLabel(); - $sActionDetails = $aStimuli[$sStimulus]->GetDescription(); - $sTargetState = $aTransitions[$sStimulus]['target_state']; - $aExpectedAttributes = $oObj->GetTransitionAttributes($sStimulus /* cureent state */); - $aDetails = array(); - $aErrors = array(); - foreach($aExpectedAttributes as $sAttCode => $iExpectCode) - { - $iFlags = $oObj->GetTransitionFlags($sAttCode, $sStimulus); - if (($iExpectCode & (OPT_ATT_MUSTCHANGE|OPT_ATT_MUSTPROMPT)) || ($oObj->Get($sAttCode) == '') ) - { - $paramValue = utils::ReadPostedParam("attr_$sAttCode", '', 'raw_data'); - if ( ($iFlags & OPT_ATT_SLAVE) && ($paramValue != $oObj->Get($sAttCode)) ) - { - $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode); - $aErrors[] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $oAttDef->GetLabel(), $sAttCode); - unset($aExpectedAttributes[$sAttCode]); - } - } - } - - $oObj->UpdateObjectFromPostedForm('', array_keys($aExpectedAttributes), $aExpectedAttributes); - - if (count($aErrors) == 0) - { - if ($oObj->ApplyStimulus($sStimulus)) - { - list($bResult, $aErrors) = $oObj->CheckToWrite(); - $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusModified') : Dict::S('UI:BulkModifyStatusSkipped'); - if ($bResult) - { - $oObj->DBUpdate(); - } - else - { - $aErrorsToDisplay = array_map(function($sError) { - return utils::HtmlEntities($sError); - }, $aErrors); - $sError = '

'.implode('

',$aErrorsToDisplay)."

\n"; - } - } - else - { - $sStatus = Dict::S('UI:BulkModifyStatusSkipped'); - $sError = '

'.Dict::S('UI:FailedToApplyStimuli')."

\n"; - } - } - else - { - $sStatus = Dict::S('UI:BulkModifyStatusSkipped'); - $sError = '

'.implode('

',$aErrors)."

\n"; - } - } - } - catch(Exception $e) - { - $sError = $e->getMessage(); - $sStatus = Dict::S('UI:BulkModifyStatusSkipped'); - } - $aRows[] = array( - 'object' => $oObj->GetHyperlink(), - 'status' => $sStatus, - 'errors' => $sError, ); } - $oBlock = PanelUIBlockFactory::MakeForClass($sClass, Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aObjects), $sClass)); - $oBlock->SetIcon(MetaModel::GetClassIcon($sClass, false)); + break; + case 'bulk_apply_stimulus': + $oP->DisableBreadCrumb(); + $bPreviewMode = utils::ReadPostedParam('preview_mode', false); + $sFilter = utils::ReadPostedParam('filter', '', 'raw_data'); + $sStimulus = utils::ReadPostedParam('stimulus', ''); + $sState = utils::ReadPostedParam('state', ''); + $sSelectObject = utils::ReadPostedParam('selectObject', '', 'raw_data'); + $aSelectObject = explode(',', $sSelectObject); - $oDataTable = DataTableUIBlockFactory::MakeForStaticData('', $aHeaders,$aRows); - $oBlock->AddSubBlock($oDataTable); - $oP->AddUiBlock($oBlock); - - // Back to the list - $sURL = "./UI.php?operation=search&filter=".urlencode($sFilter).$oAppContext->GetForLink(true); - $oSubmitButton = ButtonUIBlockFactory::MakeForSecondaryAction(Dict::S('UI:Button:Done'), 'submit', 'submit', true); - $oSubmitButton->SetOnClickJsCode("window.location.href='$sURL'"); - $oToolbarButtons = ToolbarUIBlockFactory::MakeStandard(null); - $oToolbarButtons->AddCSSClass('ibo-toolbar--button'); - $oToolbarButtons->AddSubBlock($oSubmitButton); - $oP->AddSubBlock($oToolbarButtons); - } - break; - - case 'stimulus': // Form displayed when applying a stimulus (state change) - $oP->DisableBreadCrumb(); - $sClass = utils::ReadParam('class', '', false, 'class'); - $id = utils::ReadParam('id', ''); - $sStimulus = utils::ReadParam('stimulus', ''); - if ( empty($sClass) || empty($id) || empty($sStimulus) ) // TO DO: check that the class name is valid ! - { - throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'class', 'id', 'stimulus')); - } - $aStimuli = MetaModel::EnumStimuli($sClass); - if ((get_class($aStimuli[$sStimulus]) !== 'StimulusUserAction') || (UserRights::IsStimulusAllowed($sClass, $sStimulus) === UR_ALLOWED_NO)) - { - $sUser = UserRights::GetUser(); - IssueLog::Error("UI.php '$operation' : Stimulus '$sStimulus' not allowed ! data: user='$sUser', class='$sClass'"); - throw new ApplicationException(Dict::S('UI:Error:ActionNotAllowed')); - } - - /** @var \cmdbAbstractObject $oObj */ - $oObj = MetaModel::GetObject($sClass, $id, false); - if ($oObj != null) - { - $aPrefillFormParam = [ - 'user' => Session::Get('auth_user'), - 'context' => $oAppContext->GetAsHash(), - 'stimulus' => $sStimulus, - 'origin' => 'console', - ]; - try { - $bApplyTransition = $oObj->DisplayStimulusForm($oP, $sStimulus, $aPrefillFormParam); + if (empty($sFilter) || empty($sStimulus) || empty($sState)) { + throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state')); } - catch (ApplicationException $e) { - $bApplyTransition = false; - $sMessage = $e->getMessage(); - $sSeverity = 'warning'; - ReloadAndDisplay($oP, $oObj, 'stimulus', $sMessage, $sSeverity); - } - catch (CoreCannotSaveObjectException $e) { - $bApplyTransition = false; - $aIssues = $e->getIssues(); - $sMessage = $e->getHtmlMessage(); - $sSeverity = 'warning'; - ReloadAndDisplay($oP, $oObj, 'stimulus', $sMessage, $sSeverity); - } - if ($bApplyTransition) { - $sMessage = Dict::Format('UI:Class_Object_Updated', MetaModel::GetName(get_class($oObj)), $oObj->GetName()); - $sSeverity = 'ok'; - //transition is ok, whe can display object with transition message - ReloadAndDisplay($oP, $oObj, 'apply_stimulus', $sMessage, $sSeverity); - } - } - else - { - $oP->set_title(Dict::S('UI:ErrorPageTitle')); - $oP->P(Dict::S('UI:ObjectDoesNotExist')); - } - break; - - /////////////////////////////////////////////////////////////////////////////////////////// - - case 'apply_stimulus': // Actual state change - $oP->DisableBreadCrumb(); - $sClass = utils::ReadPostedParam('class', '', 'class'); - $id = utils::ReadPostedParam('id', ''); $sTransactionId = utils::ReadPostedParam('transaction_id', '', 'transaction_id'); - $sStimulus = utils::ReadPostedParam('stimulus', ''); - if ( empty($sClass) || empty($id) || empty($sStimulus) ) // TO DO: check that the class name is valid ! - { - throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'class', 'id', 'stimulus')); - } - /** @var \cmdbAbstractObject $oObj */ - $oObj = MetaModel::GetObject($sClass, $id, false); - if ($oObj != null) - { - $aTransitions = $oObj->EnumTransitions(); - $aStimuli = MetaModel::EnumStimuli($sClass); - $sMessage = ''; - $sSeverity = 'ok'; - $bDisplayDetails = true; - if (!isset($aTransitions[$sStimulus])) - { - throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel())); - } - if (!utils::IsTransactionValid($sTransactionId)) - { + if (!utils::IsTransactionValid($sTransactionId)) { $sUser = UserRights::GetUser(); - IssueLog::Error("UI.php '$operation' : invalid transaction_id ! data: user='$sUser', class='$sClass'"); - $sMessage = Dict::S('UI:Error:ObjectAlreadyUpdated'); - $sSeverity = 'info'; - } - elseif ((get_class($aStimuli[$sStimulus]) !== 'StimulusUserAction') || (UserRights::IsStimulusAllowed($sClass, $sStimulus) === UR_ALLOWED_NO)) - { - $sUser = UserRights::GetUser(); - IssueLog::Error("UI.php '$operation' : Stimulus '$sStimulus' not allowed ! data: user='$sUser', class='$sClass'"); - $sMessage = Dict::S('UI:Error:ActionNotAllowed'); - $sSeverity = 'error'; - } - else - { - $sActionLabel = $aStimuli[$sStimulus]->GetLabel(); - $sActionDetails = $aStimuli[$sStimulus]->GetDescription(); - $sTargetState = $aTransitions[$sStimulus]['target_state']; - $aExpectedAttributes = $oObj->GetTransitionAttributes($sStimulus /*, current state*/); - $aDetails = array(); - $aErrors = array(); - foreach($aExpectedAttributes as $sAttCode => $iExpectCode) - { - $iFlags = $oObj->GetTransitionFlags($sAttCode, $sStimulus); - if (($iExpectCode & (OPT_ATT_MUSTCHANGE|OPT_ATT_MUSTPROMPT)) || ($oObj->Get($sAttCode) == '') ) - { - $paramValue = utils::ReadPostedParam("attr_$sAttCode", '', 'raw_data'); - if ( ($iFlags & OPT_ATT_SLAVE) && ($paramValue != $oObj->Get($sAttCode))) - { - $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode); - $aErrors[] = Dict::Format('UI:AttemptingToChangeASlaveAttribute_Name', $oAttDef->GetLabel()); - unset($aExpectedAttributes[$sAttCode]); - } - } + IssueLog::Error("UI.php '$operation' : invalid transaction_id ! data: user='$sUser'"); + $oP->p(Dict::S('UI:Error:ObjectAlreadyUpdated')); + } else { + // For archiving the modification + $oFilter = DBObjectSearch::unserialize($sFilter); + // Add user filter + $oFilter->UpdateContextFromUser(); + $sClass = $oFilter->GetClass(); + $aObjects = []; + foreach ($aSelectObject as $iId) { + $aObjects[] = MetaModel::GetObject($sClass, $iId); } - $oObj->UpdateObjectFromPostedForm('', array_keys($aExpectedAttributes), $aExpectedAttributes); + $aTransitions = MetaModel::EnumTransitions($sClass, $sState); + $aStimuli = MetaModel::EnumStimuli($sClass); + + $sActionLabel = $aStimuli[$sStimulus]->GetLabel(); + $sActionDetails = $aStimuli[$sStimulus]->GetDescription(); + + $oP->set_title(Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aObjects), $sClass)); + + $oSet = DBObjectSet::FromArray($sClass, $aObjects); + + // For reporting + $aHeaders = [ + 'object' => ['label' => MetaModel::GetName($sClass), 'description' => Dict::S('UI:ModifiedObject')], + 'status' => ['label' => Dict::S('UI:BulkModifyStatus'), 'description' => Dict::S('UI:BulkModifyStatus+')], + 'errors' => ['label' => Dict::S('UI:BulkModifyErrors'), 'description' => Dict::S('UI:BulkModifyErrors+')], + ]; + $aRows = []; + while ($oObj = $oSet->Fetch()) { + $sError = Dict::S('UI:BulkModifyStatusOk'); + try { + $aTransitions = $oObj->EnumTransitions(); + $aStimuli = MetaModel::EnumStimuli($sClass); + if (!isset($aTransitions[$sStimulus])) { + throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel())); + } else { + $sActionLabel = $aStimuli[$sStimulus]->GetLabel(); + $sActionDetails = $aStimuli[$sStimulus]->GetDescription(); + $sTargetState = $aTransitions[$sStimulus]['target_state']; + $aExpectedAttributes = $oObj->GetTransitionAttributes($sStimulus /* cureent state */); + $aDetails = []; + $aErrors = []; + foreach ($aExpectedAttributes as $sAttCode => $iExpectCode) { + $iFlags = $oObj->GetTransitionFlags($sAttCode, $sStimulus); + if (($iExpectCode & (OPT_ATT_MUSTCHANGE | OPT_ATT_MUSTPROMPT)) || ($oObj->Get($sAttCode) == '')) { + $paramValue = utils::ReadPostedParam("attr_$sAttCode", '', 'raw_data'); + if (($iFlags & OPT_ATT_SLAVE) && ($paramValue != $oObj->Get($sAttCode))) { + $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode); + $aErrors[] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $oAttDef->GetLabel(), $sAttCode); + unset($aExpectedAttributes[$sAttCode]); + } + } + } - if (count($aErrors) == 0) - { - $sIssues = ''; - $bApplyStimulus = true; - list($bRes, $aIssues) = $oObj->CheckToWrite(); // Check before trying to write the object - if ($bRes) - { - try - { - $bApplyStimulus = $oObj->ApplyStimulus($sStimulus); // will write the object in the DB - } - catch(CoreException $e) - { - // Rollback to the previous state... by reloading the object from the database and applying the modifications again - $oObj = MetaModel::GetObject(get_class($oObj), $oObj->GetKey()); $oObj->UpdateObjectFromPostedForm('', array_keys($aExpectedAttributes), $aExpectedAttributes); - $sIssues = $e->getMessage(); - } - } - else - { - $sIssues = implode(' ', $aIssues); - } - if (!$bApplyStimulus) - { - $sMessage = Dict::S('UI:FailedToApplyStimuli'); - $sSeverity = 'error'; - - $sOwnershipToken = utils::ReadPostedParam('ownership_token', null, 'raw_data'); - if ($sOwnershipToken !== null) - { - // Release the concurrent lock, if any - iTopOwnershipLock::ReleaseLock(get_class($oObj), $oObj->GetKey(), $sOwnershipToken); + if (count($aErrors) == 0) { + if ($oObj->ApplyStimulus($sStimulus)) { + list($bResult, $aErrors) = $oObj->CheckToWrite(); + $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusModified') : Dict::S('UI:BulkModifyStatusSkipped'); + if ($bResult) { + $oObj->DBUpdate(); + } else { + $aErrorsToDisplay = array_map(function ($sError) { + return utils::HtmlEntities($sError); + }, $aErrors); + $sError = '

'.implode('

', $aErrorsToDisplay)."

\n"; + } + } else { + $sStatus = Dict::S('UI:BulkModifyStatusSkipped'); + $sError = '

'.Dict::S('UI:FailedToApplyStimuli')."

\n"; + } + } else { + $sStatus = Dict::S('UI:BulkModifyStatusSkipped'); + $sError = '

'.implode('

', $aErrors)."

\n"; + } } + } catch (Exception $e) { + $sError = $e->getMessage(); + $sStatus = Dict::S('UI:BulkModifyStatusSkipped'); } - else if ($sIssues != '') - { - $sOwnershipToken = utils::ReadPostedParam('ownership_token', null, 'raw_data'); - if ($sOwnershipToken !== null) - { - // Release the concurrent lock, if any, a new lock will be re-acquired by DisplayStimulusForm below - iTopOwnershipLock::ReleaseLock(get_class($oObj), $oObj->GetKey(), $sOwnershipToken); - } + $aRows[] = [ + 'object' => $oObj->GetHyperlink(), + 'status' => $sStatus, + 'errors' => $sError, + ]; + } + $oBlock = PanelUIBlockFactory::MakeForClass($sClass, Dict::Format('UI:StimulusModify_N_ObjectsOf_Class', $sActionLabel, count($aObjects), $sClass)); + $oBlock->SetIcon(MetaModel::GetClassIcon($sClass, false)); - $bDisplayDetails = false; - // Found issues, explain and give the user a second chance - // - try - { - $oObj->DisplayStimulusForm($oP, $sStimulus); - } - catch(ApplicationException $e) - { - $sMessage = $e->getMessage(); - $sSeverity = 'info'; - } - $sIssueDesc = Dict::Format('UI:ObjectCouldNotBeWritten',$sIssues); - $oP->add_ready_script("CombodoModal.OpenErrorModal('".addslashes($sIssueDesc)."');"); - } - else - { - $sMessage = Dict::Format('UI:Class_Object_Updated', MetaModel::GetName(get_class($oObj)), $oObj->GetName()); - $sSeverity = 'ok'; - utils::RemoveTransaction($sTransactionId); - $bLockEnabled = MetaModel::GetConfig()->Get('concurrent_lock_enabled'); - if ($bLockEnabled) - { - // Release the concurrent lock, if any - $sOwnershipToken = utils::ReadPostedParam('ownership_token', null, 'raw_data'); - if ($sOwnershipToken !== null) - { - // We're done, let's release the lock - iTopOwnershipLock::ReleaseLock(get_class($oObj), $oObj->GetKey(), $sOwnershipToken); + $oDataTable = DataTableUIBlockFactory::MakeForStaticData('', $aHeaders, $aRows); + $oBlock->AddSubBlock($oDataTable); + $oP->AddUiBlock($oBlock); + + // Back to the list + $sURL = "./UI.php?operation=search&filter=".urlencode($sFilter).$oAppContext->GetForLink(true); + $oSubmitButton = ButtonUIBlockFactory::MakeForSecondaryAction(Dict::S('UI:Button:Done'), 'submit', 'submit', true); + $oSubmitButton->SetOnClickJsCode("window.location.href='$sURL'"); + $oToolbarButtons = ToolbarUIBlockFactory::MakeStandard(null); + $oToolbarButtons->AddCSSClass('ibo-toolbar--button'); + $oToolbarButtons->AddSubBlock($oSubmitButton); + $oP->AddSubBlock($oToolbarButtons); + } + break; + + case 'stimulus': // Form displayed when applying a stimulus (state change) + $oP->DisableBreadCrumb(); + $sClass = utils::ReadParam('class', '', false, 'class'); + $id = utils::ReadParam('id', ''); + $sStimulus = utils::ReadParam('stimulus', ''); + if (empty($sClass) || empty($id) || empty($sStimulus)) { // TO DO: check that the class name is valid ! + throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'class', 'id', 'stimulus')); + } + $aStimuli = MetaModel::EnumStimuli($sClass); + if ((get_class($aStimuli[$sStimulus]) !== 'StimulusUserAction') || (UserRights::IsStimulusAllowed($sClass, $sStimulus) === UR_ALLOWED_NO)) { + $sUser = UserRights::GetUser(); + IssueLog::Error("UI.php '$operation' : Stimulus '$sStimulus' not allowed ! data: user='$sUser', class='$sClass'"); + throw new ApplicationException(Dict::S('UI:Error:ActionNotAllowed')); + } + + /** @var \cmdbAbstractObject $oObj */ + $oObj = MetaModel::GetObject($sClass, $id, false); + if ($oObj != null) { + $aPrefillFormParam = [ + 'user' => Session::Get('auth_user'), + 'context' => $oAppContext->GetAsHash(), + 'stimulus' => $sStimulus, + 'origin' => 'console', + ]; + try { + $bApplyTransition = $oObj->DisplayStimulusForm($oP, $sStimulus, $aPrefillFormParam); + } catch (ApplicationException $e) { + $bApplyTransition = false; + $sMessage = $e->getMessage(); + $sSeverity = 'warning'; + ReloadAndDisplay($oP, $oObj, 'stimulus', $sMessage, $sSeverity); + } catch (CoreCannotSaveObjectException $e) { + $bApplyTransition = false; + $aIssues = $e->getIssues(); + $sMessage = $e->getHtmlMessage(); + $sSeverity = 'warning'; + ReloadAndDisplay($oP, $oObj, 'stimulus', $sMessage, $sSeverity); + } + if ($bApplyTransition) { + $sMessage = Dict::Format('UI:Class_Object_Updated', MetaModel::GetName(get_class($oObj)), $oObj->GetName()); + $sSeverity = 'ok'; + //transition is ok, whe can display object with transition message + ReloadAndDisplay($oP, $oObj, 'apply_stimulus', $sMessage, $sSeverity); + } + } else { + $oP->set_title(Dict::S('UI:ErrorPageTitle')); + $oP->P(Dict::S('UI:ObjectDoesNotExist')); + } + break; + + /////////////////////////////////////////////////////////////////////////////////////////// + + case 'apply_stimulus': // Actual state change + $oP->DisableBreadCrumb(); + $sClass = utils::ReadPostedParam('class', '', 'class'); + $id = utils::ReadPostedParam('id', ''); + $sTransactionId = utils::ReadPostedParam('transaction_id', '', 'transaction_id'); + $sStimulus = utils::ReadPostedParam('stimulus', ''); + if (empty($sClass) || empty($id) || empty($sStimulus)) { // TO DO: check that the class name is valid ! + throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'class', 'id', 'stimulus')); + } + /** @var \cmdbAbstractObject $oObj */ + $oObj = MetaModel::GetObject($sClass, $id, false); + if ($oObj != null) { + $aTransitions = $oObj->EnumTransitions(); + $aStimuli = MetaModel::EnumStimuli($sClass); + $sMessage = ''; + $sSeverity = 'ok'; + $bDisplayDetails = true; + if (!isset($aTransitions[$sStimulus])) { + throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel())); + } + if (!utils::IsTransactionValid($sTransactionId)) { + $sUser = UserRights::GetUser(); + IssueLog::Error("UI.php '$operation' : invalid transaction_id ! data: user='$sUser', class='$sClass'"); + $sMessage = Dict::S('UI:Error:ObjectAlreadyUpdated'); + $sSeverity = 'info'; + } elseif ((get_class($aStimuli[$sStimulus]) !== 'StimulusUserAction') || (UserRights::IsStimulusAllowed($sClass, $sStimulus) === UR_ALLOWED_NO)) { + $sUser = UserRights::GetUser(); + IssueLog::Error("UI.php '$operation' : Stimulus '$sStimulus' not allowed ! data: user='$sUser', class='$sClass'"); + $sMessage = Dict::S('UI:Error:ActionNotAllowed'); + $sSeverity = 'error'; + } else { + $sActionLabel = $aStimuli[$sStimulus]->GetLabel(); + $sActionDetails = $aStimuli[$sStimulus]->GetDescription(); + $sTargetState = $aTransitions[$sStimulus]['target_state']; + $aExpectedAttributes = $oObj->GetTransitionAttributes($sStimulus /*, current state*/); + $aDetails = []; + $aErrors = []; + foreach ($aExpectedAttributes as $sAttCode => $iExpectCode) { + $iFlags = $oObj->GetTransitionFlags($sAttCode, $sStimulus); + if (($iExpectCode & (OPT_ATT_MUSTCHANGE | OPT_ATT_MUSTPROMPT)) || ($oObj->Get($sAttCode) == '')) { + $paramValue = utils::ReadPostedParam("attr_$sAttCode", '', 'raw_data'); + if (($iFlags & OPT_ATT_SLAVE) && ($paramValue != $oObj->Get($sAttCode))) { + $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode); + $aErrors[] = Dict::Format('UI:AttemptingToChangeASlaveAttribute_Name', $oAttDef->GetLabel()); + unset($aExpectedAttributes[$sAttCode]); } } } - } - else - { - $sMessage = implode('

', $aErrors); - $sSeverity = 'error'; - } - } - if ($bDisplayDetails) - { - ReloadAndDisplay($oP, $oObj, 'apply_stimulus', $sMessage, $sSeverity); - } - } - else - { - $oP->set_title(Dict::S('UI:ErrorPageTitle')); - $oP->P(Dict::S('UI:ObjectDoesNotExist')); - } - break; - /////////////////////////////////////////////////////////////////////////////////////////// + $oObj->UpdateObjectFromPostedForm('', array_keys($aExpectedAttributes), $aExpectedAttributes); + + if (count($aErrors) == 0) { + $sIssues = ''; + $bApplyStimulus = true; + list($bRes, $aIssues) = $oObj->CheckToWrite(); // Check before trying to write the object + if ($bRes) { + try { + $bApplyStimulus = $oObj->ApplyStimulus($sStimulus); // will write the object in the DB + } catch (CoreException $e) { + // Rollback to the previous state... by reloading the object from the database and applying the modifications again + $oObj = MetaModel::GetObject(get_class($oObj), $oObj->GetKey()); + $oObj->UpdateObjectFromPostedForm('', array_keys($aExpectedAttributes), $aExpectedAttributes); + $sIssues = $e->getMessage(); + } + } else { + $sIssues = implode(' ', $aIssues); + } + + if (!$bApplyStimulus) { + $sMessage = Dict::S('UI:FailedToApplyStimuli'); + $sSeverity = 'error'; + + $sOwnershipToken = utils::ReadPostedParam('ownership_token', null, 'raw_data'); + if ($sOwnershipToken !== null) { + // Release the concurrent lock, if any + iTopOwnershipLock::ReleaseLock(get_class($oObj), $oObj->GetKey(), $sOwnershipToken); + } + } elseif ($sIssues != '') { + $sOwnershipToken = utils::ReadPostedParam('ownership_token', null, 'raw_data'); + if ($sOwnershipToken !== null) { + // Release the concurrent lock, if any, a new lock will be re-acquired by DisplayStimulusForm below + iTopOwnershipLock::ReleaseLock(get_class($oObj), $oObj->GetKey(), $sOwnershipToken); + } + + $bDisplayDetails = false; + // Found issues, explain and give the user a second chance + // + try { + $oObj->DisplayStimulusForm($oP, $sStimulus); + } catch (ApplicationException $e) { + $sMessage = $e->getMessage(); + $sSeverity = 'info'; + } + $sIssueDesc = Dict::Format('UI:ObjectCouldNotBeWritten', $sIssues); + $oP->add_ready_script("CombodoModal.OpenErrorModal('".addslashes($sIssueDesc)."');"); + } else { + $sMessage = Dict::Format('UI:Class_Object_Updated', MetaModel::GetName(get_class($oObj)), $oObj->GetName()); + $sSeverity = 'ok'; + utils::RemoveTransaction($sTransactionId); + $bLockEnabled = MetaModel::GetConfig()->Get('concurrent_lock_enabled'); + if ($bLockEnabled) { + // Release the concurrent lock, if any + $sOwnershipToken = utils::ReadPostedParam('ownership_token', null, 'raw_data'); + if ($sOwnershipToken !== null) { + // We're done, let's release the lock + iTopOwnershipLock::ReleaseLock(get_class($oObj), $oObj->GetKey(), $sOwnershipToken); + } + } + } + } else { + $sMessage = implode('

', $aErrors); + $sSeverity = 'error'; + } + } + if ($bDisplayDetails) { + ReloadAndDisplay($oP, $oObj, 'apply_stimulus', $sMessage, $sSeverity); + } + } else { + $oP->set_title(Dict::S('UI:ErrorPageTitle')); + $oP->P(Dict::S('UI:ObjectDoesNotExist')); + } + break; + + /////////////////////////////////////////////////////////////////////////////////////////// case 'view_relations': // Graphical display of the relations "impact" / "depends on" - require_once(APPROOT.'core/simplegraph.class.inc.php'); - require_once(APPROOT.'core/relationgraph.class.inc.php'); - require_once(APPROOT.'core/displayablegraph.class.inc.php'); - $sClass = utils::ReadParam('class', '', false, 'class'); - $id = utils::ReadParam('id', 0); - $sRelation = utils::ReadParam('relation', 'impact'); - $sDirection = utils::ReadParam('direction', 'down'); - $iGroupingThreshold = utils::ReadParam('g', 5); + require_once(APPROOT.'core/simplegraph.class.inc.php'); + require_once(APPROOT.'core/relationgraph.class.inc.php'); + require_once(APPROOT.'core/displayablegraph.class.inc.php'); + $sClass = utils::ReadParam('class', '', false, 'class'); + $id = utils::ReadParam('id', 0); + $sRelation = utils::ReadParam('relation', 'impact'); + $sDirection = utils::ReadParam('direction', 'down'); + $iGroupingThreshold = utils::ReadParam('g', 5); - $bDirDown = ($sDirection === 'down'); - $oObj = MetaModel::GetObject($sClass, $id); - $iMaxRecursionDepth = MetaModel::GetConfig()->Get('relations_max_depth'); - $aSourceObjects = array($oObj); + $bDirDown = ($sDirection === 'down'); + $oObj = MetaModel::GetObject($sClass, $id); + $iMaxRecursionDepth = MetaModel::GetConfig()->Get('relations_max_depth'); + $aSourceObjects = [$oObj]; - $oP->set_title(MetaModel::GetRelationDescription($sRelation, $bDirDown).' '.$oObj->GetName()); + $oP->set_title(MetaModel::GetRelationDescription($sRelation, $bDirDown).' '.$oObj->GetName()); - $sPageId = "ui-relation-graph-".$sClass.'::'.$id; - $sLabel = $oObj->GetName().' '.MetaModel::GetRelationLabel($sRelation, $bDirDown); - $sDescription = MetaModel::GetRelationDescription($sRelation, $bDirDown).' '.$oObj->GetName(); - $oP->SetBreadCrumbEntry($sPageId, $sLabel, $sDescription); + $sPageId = "ui-relation-graph-".$sClass.'::'.$id; + $sLabel = $oObj->GetName().' '.MetaModel::GetRelationLabel($sRelation, $bDirDown); + $sDescription = MetaModel::GetRelationDescription($sRelation, $bDirDown).' '.$oObj->GetName(); + $oP->SetBreadCrumbEntry($sPageId, $sLabel, $sDescription); - if ($sRelation == 'depends on') { - $sRelation = 'impacts'; - $sDirection = 'up'; - } - if ($sDirection == 'up') { - $oRelGraph = MetaModel::GetRelatedObjectsUp($sRelation, $aSourceObjects, $iMaxRecursionDepth); - } else { - $oRelGraph = MetaModel::GetRelatedObjectsDown($sRelation, $aSourceObjects, $iMaxRecursionDepth); - } + if ($sRelation == 'depends on') { + $sRelation = 'impacts'; + $sDirection = 'up'; + } + if ($sDirection == 'up') { + $oRelGraph = MetaModel::GetRelatedObjectsUp($sRelation, $aSourceObjects, $iMaxRecursionDepth); + } else { + $oRelGraph = MetaModel::GetRelatedObjectsDown($sRelation, $aSourceObjects, $iMaxRecursionDepth); + } + $aResults = $oRelGraph->GetObjectsByClass(); + $oDisplayGraph = DisplayableGraph::FromRelationGraph($oRelGraph, $iGroupingThreshold, ($sDirection == 'down')); + $sTitle = MetaModel::GetRelationDescription($sRelation, $bDirDown).' '.$oObj->GetName(); + $sClassIcon = MetaModel::GetClassIcon($sClass, false); - $aResults = $oRelGraph->GetObjectsByClass(); - $oDisplayGraph = DisplayableGraph::FromRelationGraph($oRelGraph, $iGroupingThreshold, ($sDirection == 'down')); - $sTitle = MetaModel::GetRelationDescription($sRelation, $bDirDown).' '.$oObj->GetName(); - $sClassIcon = MetaModel::GetClassIcon($sClass, false); + $sFirstTab = MetaModel::GetConfig()->Get('impact_analysis_first_tab'); + $bLazyLoading = MetaModel::GetConfig()->Get('impact_analysis_lazy_loading'); + $sContextKey = "itop-config-mgmt/relation_context/$sClass/$sRelation/$sDirection"; - $sFirstTab = MetaModel::GetConfig()->Get('impact_analysis_first_tab'); - $bLazyLoading = MetaModel::GetConfig()->Get('impact_analysis_lazy_loading'); - $sContextKey = "itop-config-mgmt/relation_context/$sClass/$sRelation/$sDirection"; - - // Check if the current object supports Attachments, similar to AttachmentPlugin::IsTargetObject - $sClassForAttachment = null; - $iIdForAttachment = null; - if (class_exists('Attachment')) { - $aAllowedClasses = MetaModel::GetModuleSetting('itop-attachments', 'allowed_classes', array('Ticket')); - foreach ($aAllowedClasses as $sAllowedClass) { - if ($oObj instanceof $sAllowedClass) { - $iIdForAttachment = $id; - $sClassForAttachment = $sClass; + // Check if the current object supports Attachments, similar to AttachmentPlugin::IsTargetObject + $sClassForAttachment = null; + $iIdForAttachment = null; + if (class_exists('Attachment')) { + $aAllowedClasses = MetaModel::GetModuleSetting('itop-attachments', 'allowed_classes', ['Ticket']); + foreach ($aAllowedClasses as $sAllowedClass) { + if ($oObj instanceof $sAllowedClass) { + $iIdForAttachment = $id; + $sClassForAttachment = $sClass; + } } } - } - $oP->AddSubBlock($oDisplayGraph->DisplayFilterBox($oP, $aResults, $bLazyLoading)); - $oPanel = PanelUIBlockFactory::MakeForClass($sClass, $sTitle); - $oPanel->SetIcon($sClassIcon); + $oP->AddSubBlock($oDisplayGraph->DisplayFilterBox($oP, $aResults, $bLazyLoading)); + $oPanel = PanelUIBlockFactory::MakeForClass($sClass, $sTitle); + $oPanel->SetIcon($sClassIcon); - $oP->AddSubBlock($oPanel); - $oP->AddTabContainer('Navigator', '', $oPanel); - $oP->SetCurrentTabContainer('Navigator'); + $oP->AddSubBlock($oPanel); + $oP->AddTabContainer('Navigator', '', $oPanel); + $oP->SetCurrentTabContainer('Navigator'); - // Display the tabs - if ($sFirstTab == 'list') { - DisplayNavigatorListTab($oP, $aResults, $sRelation, $sDirection, $oObj); - $oP->SetCurrentTab('UI:RelationshipGraph'); - $oDisplayGraph->DisplayGraph($oP, $sRelation, $oAppContext, [], $sClassForAttachment, $iIdForAttachment, $sContextKey, array('this' => $oObj), $bLazyLoading); - DisplayNavigatorGroupTab($oP); - } else { - $oP->SetCurrentTab('UI:RelationshipGraph'); - $oDisplayGraph->DisplayGraph($oP, $sRelation, $oAppContext, array(), $sClassForAttachment, $iIdForAttachment, $sContextKey, array('this' => $oObj), $bLazyLoading); - DisplayNavigatorListTab($oP, $aResults, $sRelation, $sDirection, $oObj); - DisplayNavigatorGroupTab($oP); - } + // Display the tabs + if ($sFirstTab == 'list') { + DisplayNavigatorListTab($oP, $aResults, $sRelation, $sDirection, $oObj); + $oP->SetCurrentTab('UI:RelationshipGraph'); + $oDisplayGraph->DisplayGraph($oP, $sRelation, $oAppContext, [], $sClassForAttachment, $iIdForAttachment, $sContextKey, ['this' => $oObj], $bLazyLoading); + DisplayNavigatorGroupTab($oP); + } else { + $oP->SetCurrentTab('UI:RelationshipGraph'); + $oDisplayGraph->DisplayGraph($oP, $sRelation, $oAppContext, [], $sClassForAttachment, $iIdForAttachment, $sContextKey, ['this' => $oObj], $bLazyLoading); + DisplayNavigatorListTab($oP, $aResults, $sRelation, $sDirection, $oObj); + DisplayNavigatorGroupTab($oP); + } - $oP->SetCurrentTab(''); - break; + $oP->SetCurrentTab(''); + break; - /////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////// case 'kill_lock': - $oP->DisableBreadCrumb(); - $sClass = utils::ReadParam('class', '', false, 'class'); - $id = utils::ReadParam('id', ''); - iTopOwnershipLock::KillLock($sClass, $id); - $oObj = MetaModel::GetObject($sClass, $id); - ReloadAndDisplay($oP, $oObj, 'concurrent_lock_killed', Dict::S('UI:ConcurrentLockKilled'), 'info'); - break; + $oP->DisableBreadCrumb(); + $sClass = utils::ReadParam('class', '', false, 'class'); + $id = utils::ReadParam('id', ''); + iTopOwnershipLock::KillLock($sClass, $id); + $oObj = MetaModel::GetObject($sClass, $id); + ReloadAndDisplay($oP, $oObj, 'concurrent_lock_killed', Dict::S('UI:ConcurrentLockKilled'), 'info'); + break; - /////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////// case 'cancel': // An action was cancelled - $oP->DisableBreadCrumb(); - $oP->set_title(Dict::S('UI:OperationCancelled')); - $oP->add('

'.Dict::S('UI:OperationCancelled').'

'); - break; + $oP->DisableBreadCrumb(); + $oP->set_title(Dict::S('UI:OperationCancelled')); + $oP->add('

'.Dict::S('UI:OperationCancelled').'

'); + break; - /////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////// default: // Menu node rendering (templates) - ApplicationMenu::LoadAdditionalMenus(); - $oMenuNode = ApplicationMenu::GetMenuNode(ApplicationMenu::GetMenuIndexById(ApplicationMenu::GetActiveNodeId())); - if (is_object($oMenuNode)) - { - $oMenuNode->RenderContent($oP, $oAppContext->GetAsHash()); - $oP->set_title($oMenuNode->GetLabel()); - } + ApplicationMenu::LoadAdditionalMenus(); + $oMenuNode = ApplicationMenu::GetMenuNode(ApplicationMenu::GetMenuIndexById(ApplicationMenu::GetActiveNodeId())); + if (is_object($oMenuNode)) { + $oMenuNode->RenderContent($oP, $oAppContext->GetAsHash()); + $oP->set_title($oMenuNode->GetLabel()); + } - /////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////// } } DisplayWelcomePopup($oP); $oKPI->ComputeAndReport('Compute page'); $oP->output(); -} -catch (Exception $e) { +} catch (Exception $e) { $oErrorPage = new ErrorPage(Dict::S('UI:PageTitle:FatalError')); if ($e instanceof SecurityException) { $oErrorPage->add("

".Dict::S('UI:SystemIntrusion')."

\n"); @@ -1537,8 +1393,7 @@ catch (Exception $e) { $aData = ($e instanceof CoreException) ? $e->getContextData() : []; $oLog->Set('data', $aData); $oLog->DBInsertNoReload(); - } - catch (Exception $e) { + } catch (Exception $e) { IssueLog::Error("Failed to log issue into the DB"); } } @@ -1548,10 +1403,8 @@ catch (Exception $e) { IssueLog::Debug('UI.php operation='.$sOperationToLog.', error='.$e->getMessage()."\n".$sErrorStackTrace, LogChannels::CONSOLE); } - class UI { - /** * Operation select_for_modify_all * @@ -1606,8 +1459,8 @@ class UI $oFullSetFilter->UpdateContextFromUser(); $aSelectedObj = utils::ReadMultipleSelection($oFullSetFilter); $sCancelUrl = "./UI.php?operation=search&filter=".urlencode($sFilter).$oAppContext->GetForLink(true); - $aContext = array('filter' => utils::EscapeHtml($sFilter)); - cmdbAbstractObject::DisplayBulkModifyForm($oP, $sClass, $aSelectedObj, 'preview_or_modify_all', $sCancelUrl, array(), $aContext); + $aContext = ['filter' => utils::EscapeHtml($sFilter)]; + cmdbAbstractObject::DisplayBulkModifyForm($oP, $sClass, $aSelectedObj, 'preview_or_modify_all', $sCancelUrl, [], $aContext); } /** @@ -1634,16 +1487,15 @@ class UI $sClass = utils::ReadParam('class', '', false, 'class'); $bPreview = utils::ReadParam('preview_mode', ''); $sSelectedObj = utils::ReadParam('selectObj', '', false, 'raw_data'); - if (empty($sClass) || empty($sSelectedObj)) // TO DO: check that the class name is valid ! - { + if (empty($sClass) || empty($sSelectedObj)) { // TO DO: check that the class name is valid ! throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'selectObj')); } $aSelectedObj = explode(',', $sSelectedObj); $sCancelUrl = "./UI.php?operation=search&filter=".urlencode($sFilter).$oAppContext->GetForLink(true); - $aContext = array( + $aContext = [ 'filter' => utils::EscapeHtml($sFilter), 'selectObj' => $sSelectedObj, - ); + ]; cmdbAbstractObject::DoBulkModify($oP, $sClass, $aSelectedObj, 'preview_or_modify_all', $bPreview, $sCancelUrl, $aContext); } -} \ No newline at end of file +} diff --git a/pages/UniversalSearch.php b/pages/UniversalSearch.php index 4debb9552..f2d9b2913 100644 --- a/pages/UniversalSearch.php +++ b/pages/UniversalSearch.php @@ -1,4 +1,5 @@ LinkScriptFromAppRoot("js/forms-json-utils.js"); $oP->LinkScriptFromAppRoot("js/wizardhelper.js"); $oP->LinkScriptFromAppRoot("js/extkeywidget.js"); $oP->LinkScriptFromAppRoot("js/jquery.blockUI.js"); - + // From now on the context is limited to the the selected organization ?? // Now render the content of the page @@ -49,11 +50,9 @@ $sOperation = utils::ReadParam('operation', ''); $oP->SetBreadCrumbEntry('ui-tool-universalsearch', Dict::S('Menu:UniversalSearchMenu'), Dict::S('Menu:UniversalSearchMenu+'), '', 'fas fa-search', iTopWebPage::ENUM_BREADCRUMB_ENTRY_ICON_TYPE_CSS_CLASSES); - - //$sSearchHeaderForceDropdown $sSearchHeaderForceDropdown = '\n"; //end of $sSearchHeaderForceDropdown - -try -{ - if ($sOperation == 'search_form') - { - $sOQL = "SELECT $sClass $sOQLClause"; - $oFilter = DBObjectSearch::FromOQL($sOQL); - } - else - { +try { + if ($sOperation == 'search_form') { + $sOQL = "SELECT $sClass $sOQLClause"; + $oFilter = DBObjectSearch::FromOQL($sOQL); + } else { // Second part: advanced search form: - if (!empty($sFilter)) - { + if (!empty($sFilter)) { $oFilter = DBSearch::unserialize($sFilter); - } - else if (!empty($sClass)) - { + } elseif (!empty($sClass)) { $oFilter = new DBObjectSearch($sClass); } } -} -catch (CoreException $e) -{ +} catch (CoreException $e) { $oFilter = new DBObjectSearch($sClass); $oP->P("".Dict::Format('UI:UniversalSearch:Error', $e->getHtmlDesc()).""); } -if ($oFilter != null) -{ +if ($oFilter != null) { $oSet = new CMDBObjectSet($oFilter); $oBlock = new DisplayBlock($oFilter, 'search', false); $aExtraParams = $oAppContext->GetAsHash(); @@ -110,7 +97,7 @@ if ($oFilter != null) $aExtraParams['submit_on_load'] = false; $oBlock->Display($oP, 0, $aExtraParams); - // Search results + // Search results $oResultBlock = new DisplayBlock($oFilter, 'list', false); $oResultBlock->Display($oP, 1); diff --git a/pages/ajax.render.php b/pages/ajax.render.php index 7a9b97e55..29a916965 100644 --- a/pages/ajax.render.php +++ b/pages/ajax.render.php @@ -1,4 +1,5 @@ add($bRet ? 'Ok' : 'KO'); break; - // ui.searchformforeignkeys + // ui.searchformforeignkeys case 'ShowModalSearchForeignKeys': $oPage->SetContentType('text/html'); $iInputId = utils::ReadParam('iInputId', ''); @@ -180,7 +179,7 @@ try $oWidget->ShowModalSearchForeignKeys($oPage, $sTitle); break; - // ui.searchformforeignkeys + // ui.searchformforeignkeys case 'GetFullListForeignKeysFromSelection': $oPage->SetContentType('application/json'); $oWidget = new UISearchFormForeignKeys($sClass); @@ -188,7 +187,7 @@ try $oWidget->GetFullListForeignKeysFromSelection($oPage, $oFullSetFilter); break; - // ui.searchformforeignkeys + // ui.searchformforeignkeys case 'ListResultsSearchForeignKeys': $oPage->SetContentType('text/html'); $sTargetClass = utils::ReadParam('sTargetClass', '', false, 'class'); @@ -198,7 +197,7 @@ try $oWidget->ListResultsSearchForeignKeys($oPage, $sRemoteClass); break; - // ui.linkswidget + // ui.linkswidget case 'addObjects': $oPage->SetContentType('text/html'); $sAttCode = utils::ReadParam('sAttCode', ''); @@ -215,19 +214,19 @@ try } $oWidget = new UILinksWidget($sClass, $sAttCode, $iInputId, $sSuffix, $bDuplicates); $oAppContext = new ApplicationContext(); - $aPrefillFormParam = array( + $aPrefillFormParam = [ 'user' => Session::Get("auth_user"), 'context' => $oAppContext->GetAsHash(), 'att_code' => $sAttCode, 'origin' => 'console', - 'source_obj' => $oObj - ); - $aAlreadyLinked = utils::ReadParam('aAlreadyLinked', array()); + 'source_obj' => $oObj, + ]; + $aAlreadyLinked = utils::ReadParam('aAlreadyLinked', []); /** @var \DBObject $oObj */ $oWidget->GetObjectPickerDialog($oPage, $oObj, $sJson, $aAlreadyLinked, $aPrefillFormParam); break; - // ui.linkswidget + // ui.linkswidget case 'searchObjectsToAdd': $oPage->SetContentType('text/html'); $sRemoteClass = utils::ReadParam('sRemoteClass', '', false, 'class'); @@ -235,12 +234,12 @@ try $iInputId = utils::ReadParam('iInputId', ''); $sSuffix = utils::ReadParam('sSuffix', ''); $bDuplicates = (utils::ReadParam('bDuplicates', 'false') == 'false') ? false : true; - $aAlreadyLinked = utils::ReadParam('aAlreadyLinked', array()); + $aAlreadyLinked = utils::ReadParam('aAlreadyLinked', []); $oWidget = new UILinksWidget($sClass, $sAttCode, $iInputId, $sSuffix, $bDuplicates); $oWidget->SearchObjectsToAdd($oPage, $sRemoteClass, $aAlreadyLinked); break; - //ui.linksdirectwidget + //ui.linksdirectwidget case 'createObject': $oPage->SetContentType('text/html'); $sClass = utils::ReadParam('class', '', false, 'class'); @@ -258,7 +257,7 @@ try $oWidget->GetObjectCreationDlg($oPage, $sRealClass, $oObj); break; - // ui.linksdirectwidget + // ui.linksdirectwidget case 'getLinksetRow': $oPage = new JsonPage(); $oPage->SetOutputDataOnly(true); @@ -267,16 +266,16 @@ try $sAttCode = utils::ReadParam('att_code', ''); $iInputId = utils::ReadParam('iInputId', ''); $iTempId = utils::ReadParam('tempId', ''); - $aValues = utils::ReadParam('values', array(), false, 'raw_data'); + $aValues = utils::ReadParam('values', [], false, 'raw_data'); $oWidget = new UILinksWidgetDirect($sClass, $sAttCode, $iInputId); $oPage->SetData($oWidget->GetFormRow($oPage, $sRealClass, $aValues, -$iTempId)); break; - // ui.linksdirectwidget + // ui.linksdirectwidget case 'selectObjectsToAdd': $oPage->SetContentType('text/html'); $sClass = utils::ReadParam('class', '', false, 'class'); - $aAlreadyLinked = utils::ReadParam('aAlreadyLinked', array()); + $aAlreadyLinked = utils::ReadParam('aAlreadyLinked', []); $sJson = utils::ReadParam('json', '', false, 'raw_data'); /** @var \DBObject $oObj */ $oObj = null; @@ -290,26 +289,26 @@ try $iCurrObjectId = utils::ReadParam('iObjId', 0); $oPage->SetContentType('text/html'); $oAppContext = new ApplicationContext(); - $aPrefillFormParam = array( + $aPrefillFormParam = [ 'user' => Session::Get('auth_user'), 'context' => $oAppContext->GetAsHash(), 'att_code' => $sAttCode, 'origin' => 'console', 'source_obj' => $oObj, - ); + ]; $aPrefillFormParam['dest_class'] = ($oObj === null ? '' : $oObj->Get($sAttCode)->GetClass()); $oWidget = new UILinksWidgetDirect($sClass, $sAttCode, $iInputId); $oWidget->GetObjectsSelectionDlg($oPage, $oObj, $aAlreadyLinked, $aPrefillFormParam); break; - // ui.linksdirectwidget + // ui.linksdirectwidget case 'searchObjectsToAdd2': $oPage->SetContentType('text/html'); $sClass = utils::ReadParam('class', '', false, 'class'); $sRealClass = utils::ReadParam('real_class', '', false, 'class'); $sAttCode = utils::ReadParam('att_code', ''); $iInputId = utils::ReadParam('iInputId', ''); - $aAlreadyLinked = utils::ReadParam('aAlreadyLinked', array()); + $aAlreadyLinked = utils::ReadParam('aAlreadyLinked', []); $sJson = utils::ReadParam('json', '', false, 'raw_data'); $oObj = null; if ($sJson != '') { @@ -317,19 +316,19 @@ try $oObj = $oWizardHelper->GetTargetObject(); } $oAppContext = new ApplicationContext(); - $aPrefillFormParam = array( + $aPrefillFormParam = [ 'user' => Session::Get('auth_user'), 'context' => $oAppContext->GetAsHash(), 'att_code' => $sAttCode, 'origin' => 'console', 'source_obj' => $oObj, - ); + ]; $aPrefillFormParam['dest_class'] = ($oObj === null ? '' : $oObj->Get($sAttCode)->GetClass()); $oWidget = new UILinksWidgetDirect($sClass, $sAttCode, $iInputId); $oWidget->SearchObjectsToAdd($oPage, $sRealClass, $aAlreadyLinked, $oObj, $aPrefillFormParam); break; - // ui.linksdirectwidget + // ui.linksdirectwidget case 'doAddObjects2': $oPage->SetContentType('text/html'); $oPage->SetContentType('text/html'); @@ -358,9 +357,9 @@ try $oWidget->DoAddObjects($oPage, $oFullSetFilter); break; - //////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////// - // ui.extkeywidget + // ui.extkeywidget case 'searchObjectsToSelect': $oPage->SetContentType('text/html'); $sTargetClass = utils::ReadParam('sTargetClass', '', false, 'class'); @@ -381,7 +380,7 @@ try $oWidget->SearchObjectsToSelect($oPage, $sFilter, $sRemoteClass, $oObj); break; - // ui.extkeywidget: autocomplete + // ui.extkeywidget: autocomplete case 'ac_extkey': $oPage->SetContentType('text/plain'); $sTargetClass = utils::ReadParam('sTargetClass', '', false, 'class'); @@ -404,7 +403,7 @@ try } break; - // ui.extkeywidget + // ui.extkeywidget case 'objectSearchForm': $oPage->SetContentType('text/html'); $sTargetClass = utils::ReadParam('sTargetClass', '', false, 'class'); @@ -425,7 +424,7 @@ try $oWidget->GetSearchDialog($oPage, $sTitle, $oObj); break; - // ui.extkeywidget + // ui.extkeywidget case 'objectCreationForm': $oPage->SetContentType('text/html'); // Retrieving parameters @@ -433,24 +432,24 @@ try $iInputId = utils::ReadParam('iInputId', ''); $sAttCode = utils::ReadParam('sAttCode', ''); $sJson = utils::ReadParam('json', '', false, 'raw_data'); - $bTargetClassSelected = utils::ReadParam('bTargetClassSelected', '', false, 'raw_data'); - // Building form, if target class has child classes we ask the user for the desired leaf class, unless we've already done just that + $bTargetClassSelected = utils::ReadParam('bTargetClassSelected', '', false, 'raw_data'); + // Building form, if target class has child classes we ask the user for the desired leaf class, unless we've already done just that $oWidget = new UIExtKeyWidget($sTargetClass, $iInputId, $sAttCode, false); - if(!$bTargetClassSelected && MetaModel::HasChildrenClasses($sTargetClass)){ + if (!$bTargetClassSelected && MetaModel::HasChildrenClasses($sTargetClass)) { $oWidget->GetClassSelectionForm($oPage); } else { - $aPrefillFormParam = array(); + $aPrefillFormParam = []; if (!empty($sJson)) { $oWizardHelper = WizardHelper::FromJSON($sJson); $oObj = $oWizardHelper->GetTargetObject(); $oAppContext = new ApplicationContext(); - $aPrefillFormParam = array( + $aPrefillFormParam = [ 'user' => Session::Get('auth_user'), 'context' => $oAppContext->GetAsHash(), 'att_code' => $sAttCode, 'source_obj' => $oObj, - 'origin' => 'console' - ); + 'origin' => 'console', + ]; } else { // Search form: no current object $oObj = null; @@ -459,7 +458,7 @@ try } break; - // ui.extkeywidget + // ui.extkeywidget case 'doCreateObject': $oPage->SetContentType('application/json'); $sTargetClass = utils::ReadParam('sTargetClass', '', false, 'class'); @@ -471,7 +470,7 @@ try echo json_encode($aResult); break; - // ui.extkeywidget + // ui.extkeywidget case 'getObjectName': $oPage->SetContentType('application/json'); $sTargetClass = utils::ReadParam('sTargetClass', '', false, 'class'); @@ -481,10 +480,10 @@ try $sFormAttCode = utils::ReadParam('sFormAttCode', null); $oWidget = new UIExtKeyWidget($sTargetClass, $iInputId, '', $bSearchMode); $sName = $oWidget->GetObjectName($iObjectId, $sFormAttCode); - echo json_encode(array('name' => $sName)); + echo json_encode(['name' => $sName]); break; - // ui.extkeywidget + // ui.extkeywidget case 'displayHierarchy': $oPage->SetContentType('text/html'); $sTargetClass = utils::ReadParam('sTargetClass', '', false, 'class'); @@ -504,21 +503,21 @@ try $oWidget->DisplayHierarchy($oPage, $sFilter, $currValue, $oObj); break; - //////////////////////////////////////////////////// + //////////////////////////////////////////////////// - // ui.linkswidget + // ui.linkswidget case 'doAddObjects': $oPage->SetContentType('text/html'); AjaxRenderController::DoAddObjects($oPage, $sClass, $sFilter); break; - // ui.linkswidget + // ui.linkswidget case 'doAddIndirectLinks': $oPage = new JsonPage(); AjaxRenderController::DoAddIndirectLinks($oPage, $sClass, $sFilter); break; - //////////////////////////////////////////////////////////// - /// WizardHelper : see the corresponding PHP class, and JS class + //////////////////////////////////////////////////////////// + /// WizardHelper : see the corresponding PHP class, and JS class case 'wizard_helper_preview': $oPage->SetContentType('text/html'); @@ -542,7 +541,7 @@ try $oObj->Set($sAttCode, $defaultValue); } $sFormPrefix = $oWizardHelper->GetFormPrefix(); - $aExpectedAttributes = ($oWizardHelper->GetStimulus() === null) ? array() : $oObj->GetTransitionAttributes($oWizardHelper->GetStimulus(), $oWizardHelper->GetInitialState()); + $aExpectedAttributes = ($oWizardHelper->GetStimulus() === null) ? [] : $oObj->GetTransitionAttributes($oWizardHelper->GetStimulus(), $oWizardHelper->GetInitialState()); foreach ($oWizardHelper->GetFieldsForAllowedValues() as $sAttCode) { $sId = $oWizardHelper->GetIdForField($sAttCode); if ($sId != '') { @@ -567,8 +566,19 @@ try // Even non-writable fields (like AttributeExternal) can be refreshed $sHTMLValue = "
".$oObj->GetAsHTML($sAttCode)."
"; } else { - $sHTMLValue = cmdbAbstractObject::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $value, - $displayValue, $sId, '', $iFlags, array('this' => $oObj, 'formPrefix' => $sFormPrefix), false); + $sHTMLValue = cmdbAbstractObject::GetFormElementForField( + $oPage, + $sClass, + $sAttCode, + $oAttDef, + $value, + $displayValue, + $sId, + '', + $iFlags, + ['this' => $oObj, 'formPrefix' => $sFormPrefix], + false + ); // Make sure that we immediately validate the field when we reload it $oPage->add_ready_script("$('#$sId').trigger('validate');"); } @@ -576,7 +586,7 @@ try } } } - $oWizardHelper->AddJsForUpdateFields($oPage); + $oWizardHelper->AddJsForUpdateFields($oPage); break; case 'obj_creation_form': @@ -588,21 +598,21 @@ try $sTargetState = utils::ReadParam('target_state', ''); $iTransactionId = utils::ReadParam('transaction_id', '', false, 'transaction_id'); $oObj->Set(MetaModel::GetStateAttributeCode($sClass), $sTargetState); - cmdbAbstractObject::DisplayCreationForm($oPage, $sClass, $oObj, array(), array('action' => utils::GetAbsoluteUrlAppRoot().'pages/UI.php', 'transaction_id' => $iTransactionId)); + cmdbAbstractObject::DisplayCreationForm($oPage, $sClass, $oObj, [], ['action' => utils::GetAbsoluteUrlAppRoot().'pages/UI.php', 'transaction_id' => $iTransactionId]); break; - // DisplayBlock + // DisplayBlock case 'ajax': $oPage->SetContentType('text/html'); if ($sFilter != "") { $sExtraParams = stripslashes(utils::ReadParam('extra_params', '', false, 'raw_data')); - $aExtraParams = array(); + $aExtraParams = []; if (!empty($sExtraParams)) { $aExtraParams = json_decode(str_replace("'", '"', $sExtraParams), true /* associative array */); } // Restore the app context from the ExtraParams $oAppContext = new ApplicationContext(false); // false => don't read the context yet ! - $aContext = array(); + $aContext = []; foreach ($oAppContext->GetNames() as $sName) { $sParamName = 'c['.$sName.']'; if (isset($aExtraParams[$sParamName])) { @@ -615,8 +625,7 @@ try } else { try { $oFilter = DBSearch::unserialize($sFilter); - } - catch (CoreException $e) { + } catch (CoreException $e) { $sFilter = utils::HtmlEntities($sFilter); $oPage->p("Invalid query (invalid filter) : $sFilter"); IssueLog::Error("ajax.render operation='ajax', invalid DBSearch filter param : $sFilter"); @@ -656,7 +665,7 @@ try $oFilter = DBSearch::unserialize($sFilter); } $oDisplayBlock = new DisplayBlock($oFilter, 'pie_chart_ajax', false); - $oDisplayBlock->RenderContent($oPage, array('group_by' => $sGroupBy)); + $oDisplayBlock->RenderContent($oPage, ['group_by' => $sGroupBy]); } else { $oPage->add("\n3d pie\n."); @@ -667,7 +676,7 @@ try $iRefresh = utils::ReadParam('refresh', '-1', false, 'int'); if ($iRefresh != -1) { $oPage->SetContentType('application/json'); - $aParams = utils::ReadParam('params', array(), false, 'raw_data'); + $aParams = utils::ReadParam('params', [], false, 'raw_data'); if ($sFilter != '') { $oFilter = DBObjectSearch::FromOQL($sFilter); $oDisplayBlock = new DisplayBlock($oFilter, 'chart_ajax', false); @@ -707,7 +716,7 @@ try $oPage->add_header("Pragma: public"); $oPage->add_header("Expires: Fri, 17 Jul 1970 05:00:00 GMT"); - $aParams = utils::ReadParam('params', array(), false, 'raw_data'); + $aParams = utils::ReadParam('params', [], false, 'raw_data'); if ($sFilter != '') { $oFilter = DBSearch::unserialize($sFilter); $oDisplayBlock = new DisplayBlock($oFilter, 'chart_ajax', false); @@ -741,7 +750,7 @@ try $oFilter = new DBObjectSearch($sClass); $oFilter->AddCondition($sAttCode, $sName, 'Begins with'); //$oFilter->AddCondition('org_id', $sOrg, '='); - $oSet = new CMDBObjectSet($oFilter, array($sAttCode => true)); + $oSet = new CMDBObjectSet($oFilter, [$sAttCode => true]); while (($iCount < $iMaxCount) && ($oObj = $oSet->fetch())) { $oPage->add($oObj->GetAsHTML($sAttCode)."|".$oObj->GetKey()."\n"); $iCount++; @@ -785,13 +794,13 @@ try $sTableId = utils::ReadParam('_table_id_', null, false, utils::ENUM_SANITIZATION_FILTER_ELEMENT_IDENTIFIER); $sAction = utils::ReadParam('action', ''); $sSelectionMode = utils::ReadParam('selection_mode'); - $sResultListOuterSelector = utils::ReadParam('result_list_outer_selector', null,false, utils::ENUM_SANITIZATION_FILTER_ELEMENT_IDENTIFIER); // actually an Id not a selector - $scssCount = utils::ReadParam('css_count', null,false,utils::ENUM_SANITIZATION_FILTER_ELEMENT_SELECTOR); - $sTableInnerId = utils::ReadParam('table_inner_id', null,false, utils::ENUM_SANITIZATION_FILTER_ELEMENT_IDENTIFIER); + $sResultListOuterSelector = utils::ReadParam('result_list_outer_selector', null, false, utils::ENUM_SANITIZATION_FILTER_ELEMENT_IDENTIFIER); // actually an Id not a selector + $scssCount = utils::ReadParam('css_count', null, false, utils::ENUM_SANITIZATION_FILTER_ELEMENT_SELECTOR); + $sTableInnerId = utils::ReadParam('table_inner_id', null, false, utils::ENUM_SANITIZATION_FILTER_ELEMENT_IDENTIFIER); $oFilter = new DBObjectSearch($sClass); $oSet = new CMDBObjectSet($oFilter); - $sHtml = cmdbAbstractObject::GetSearchForm($oPage, $oSet, array( + $sHtml = cmdbAbstractObject::GetSearchForm($oPage, $oSet, [ 'currentId' => $currentId, 'baseClass' => $sRootClass, 'action' => $sAction, @@ -799,8 +808,8 @@ try 'selection_mode' => $sSelectionMode, 'result_list_outer_selector' => $sResultListOuterSelector, 'cssCount' => $scssCount, - 'table_inner_id' => $sTableInnerId - )); + 'table_inner_id' => $sTableInnerId, + ]); $oPage->add($sHtml); break; @@ -835,7 +844,7 @@ try // Invalidate temporary objects TemporaryObjectManager::GetInstance()->CancelAllTemporaryObjects($iTransactionId); - IssueLog::Trace('on_form_cancel', $sObjClass, array( + IssueLog::Trace('on_form_cancel', $sObjClass, [ '$iObjKey' => $iObjKey, '$sTransactionId' => $iTransactionId, '$sTempId' => $sTempId, @@ -843,7 +852,7 @@ try '$sUser' => UserRights::GetUser(), 'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'], 'REQUEST_URI' => @$_SERVER['REQUEST_URI'], - )); + ]); break; @@ -888,18 +897,16 @@ try $sDashboardFile = RuntimeDashboard::GetDashboardFileFromRelativePath($sDashboardFileRelative); $oDashboard = RuntimeDashboard::GetDashboard($sDashboardFile, $sDashboardId); - $aResult = array('error' => ''); + $aResult = ['error' => '']; if (!is_null($oDashboard)) { try { $oDoc = utils::ReadPostedDocument('dashboard_upload_file'); $oDashboard->FromXml($oDoc->GetData()); $oDashboard->Save(); - } - catch (DOMException $e) { - $aResult = array('error' => Dict::S('UI:Error:InvalidDashboardFile')); - } - catch (Exception $e) { - $aResult = array('error' => $e->getMessage()); + } catch (DOMException $e) { + $aResult = ['error' => Dict::S('UI:Error:InvalidDashboardFile')]; + } catch (Exception $e) { + $aResult = ['error' => $e->getMessage()]; } } else { $aResult['error'] = 'Dashboard id="'.$sDashboardId.'" not found.'; @@ -915,11 +922,11 @@ try appUserPreferences::UnsetPref('display_original_dashboard_'.$sDashboardId); appUserPreferences::SetPref('display_original_dashboard_'.$sDashboardId, !$bStandardSelected); - $aExtraParams = utils::ReadParam('extra_params', array(), false, 'raw_data'); + $aExtraParams = utils::ReadParam('extra_params', [], false, 'raw_data'); $sDashboardFile = utils::ReadParam('file', '', false, 'raw_data'); $sReloadURL = utils::ReadParam('reload_url', '', false, utils::ENUM_SANITIZATION_FILTER_URL); $oDashboard = RuntimeDashboard::GetDashboard($sDashboardFile, $sDashboardId); - $aResult = array('error' => ''); + $aResult = ['error' => '']; if (!is_null($oDashboard)) { if (!empty($sReloadURL)) { $oDashboard->SetReloadURL($sReloadURL); @@ -931,11 +938,11 @@ try case 'reload_dashboard': $oPage->SetContentType('text/html'); $sDashboardId = utils::ReadParam('dashboard_id', '', false, 'raw_data'); - $aExtraParams = utils::ReadParam('extra_params', array(), false, 'raw_data'); + $aExtraParams = utils::ReadParam('extra_params', [], false, 'raw_data'); $sDashboardFile = utils::ReadParam('file', '', false, 'raw_data'); $sReloadURL = utils::ReadParam('reload_url', '', false, utils::ENUM_SANITIZATION_FILTER_URL); $oDashboard = RuntimeDashboard::GetDashboard($sDashboardFile, $sDashboardId); - $aResult = array('error' => ''); + $aResult = ['error' => '']; if (!is_null($oDashboard)) { if (!empty($sReloadURL)) { $oDashboard->SetReloadURL($sReloadURL); @@ -947,16 +954,16 @@ try case 'save_dashboard': $sDashboardId = utils::ReadParam('dashboard_id', '', false, 'context_param'); - $aExtraParams = utils::ReadParam('extra_params', array(), false, 'raw_data'); + $aExtraParams = utils::ReadParam('extra_params', [], false, 'raw_data'); $sReloadURL = utils::ReadParam('reload_url', '', false, utils::ENUM_SANITIZATION_FILTER_URL); appUserPreferences::SetPref('display_original_dashboard_'.$sDashboardId, false); $sJSExtraParams = json_encode($aExtraParams); - $aParams = array(); + $aParams = []; $aParams['layout_class'] = utils::ReadParam('layout_class', ''); $aParams['title'] = utils::ReadParam('title', '', false, 'raw_data'); $aParams['auto_reload'] = utils::ReadParam('auto_reload', false); $aParams['auto_reload_sec'] = utils::ReadParam('auto_reload_sec', 300); - $aParams['cells'] = utils::ReadParam('cells', array(), false, 'raw_data'); + $aParams['cells'] = utils::ReadParam('cells', [], false, 'raw_data'); $oDashboard = new RuntimeDashboard($sDashboardId); $oDashboard->FromParams($aParams); @@ -1013,11 +1020,11 @@ EOF case 'render_dashboard': $sDashboardId = utils::ReadParam('dashboard_id', '', false, 'raw_data'); - $aExtraParams = utils::ReadParam('extra_params', array(), false, 'raw_data'); - $aParams = array(); + $aExtraParams = utils::ReadParam('extra_params', [], false, 'raw_data'); + $aParams = []; $aParams['layout_class'] = utils::ReadParam('layout_class', ''); $aParams['title'] = utils::ReadParam('title', '', false, 'raw_data'); - $aParams['cells'] = utils::ReadParam('cells', array(), false, 'raw_data'); + $aParams['cells'] = utils::ReadParam('cells', [], false, 'raw_data'); $aParams['auto_reload'] = utils::ReadParam('auto_reload', false); $aParams['auto_reload_sec'] = utils::ReadParam('auto_reload_sec', 300); $sReloadURL = utils::ReadParam('reload_url', '', false, utils::ENUM_SANITIZATION_FILTER_URL); @@ -1029,7 +1036,7 @@ EOF case 'dashboard_editor': $sId = utils::ReadParam('id', '', false, 'context_param'); - $aExtraParams = utils::ReadParam('extra_params', array(), false, 'raw_data'); + $aExtraParams = utils::ReadParam('extra_params', [], false, 'raw_data'); $aExtraParams['dashboard_div_id'] = utils::Sanitize($sId, '', 'element_identifier'); $sDashboardFile = utils::ReadParam('file', '', false, 'string'); $sReloadURL = utils::ReadParam('reload_url', '', false, utils::ENUM_SANITIZATION_FILTER_URL); @@ -1069,7 +1076,7 @@ EOF $oPage->add_script("$('#dashlet_$sDashletId').html('$sHtml');"); // in ajax web page add_script has the same effect as add_ready_script // but is executed BEFORE all 'ready_scripts' $oForm = $oDashlet->GetForm(); // Rebuild the form since the values/content changed - $oForm->SetSubmitParams(utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php', array('operation' => 'update_dashlet_property')); + $oForm->SetSubmitParams(utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php', ['operation' => 'update_dashlet_property']); $sHtml = addslashes($oForm->RenderAsPropertySheet($oPage, true /* bReturnHtml */, '.itop-dashboard')); $sHtml = str_replace("\n", '', $sHtml); $sHtml = str_replace("\r", '', $sHtml); @@ -1080,7 +1087,7 @@ EOF case 'update_dashlet_property': require_once(APPROOT.'application/forms.class.inc.php'); require_once(APPROOT.'application/dashlet.class.inc.php'); - $aExtraParams = utils::ReadParam('extra_params', array(), false, utils::ENUM_SANITIZATION_FILTER_RAW_DATA); + $aExtraParams = utils::ReadParam('extra_params', [], false, utils::ENUM_SANITIZATION_FILTER_RAW_DATA); $aParams = utils::ReadParam('params', [], false, utils::ENUM_SANITIZATION_FILTER_RAW_DATA); // raw_data because we need different filter depending on the options $sDashletClass = utils::Sanitize($aParams['attr_dashlet_class'], DashletUnknown::class, utils::ENUM_SANITIZATION_FILTER_PHP_CLASS); // Dashlet PHP class or DashletUnknown if impl isn't present in the installed extensions $sDashletType = utils::Sanitize($aParams['attr_dashlet_type'], '', utils::ENUM_SANITIZATION_FILTER_PHP_CLASS); // original Dashlet PHP class, could be non-existing on the iTop instance (XML definition loading) @@ -1096,7 +1103,7 @@ EOF $aValues = $oForm->ReadParams(); // hash array: 'xxx' => 'new_value' $aCurrentValues = $aValues; - $aUpdatedDecoded = array(); + $aUpdatedDecoded = []; foreach ($aUpdatedProperties as $sProp) { $sDecodedProp = str_replace('attr_', '', $sProp); // Remove the attr_ prefix // Set the previous value @@ -1112,28 +1119,28 @@ EOF $aUpdatedDecoded[] = $sDecodedProp; } - $oDashlet->FromParams($aCurrentValues); - $sPrevClass = get_class($oDashlet); - $oDashlet = $oDashlet->Update($aValues, $aUpdatedDecoded); - $sNewClass = get_class($oDashlet); - if ($sNewClass != $sPrevClass) { - $oPage->add_ready_script("$('#dashlet_$sDashletId').dashlet('option', {dashlet_class: '$sNewClass'});"); + $oDashlet->FromParams($aCurrentValues); + $sPrevClass = get_class($oDashlet); + $oDashlet = $oDashlet->Update($aValues, $aUpdatedDecoded); + $sNewClass = get_class($oDashlet); + if ($sNewClass != $sPrevClass) { + $oPage->add_ready_script("$('#dashlet_$sDashletId').dashlet('option', {dashlet_class: '$sNewClass'});"); + } + if ($oDashlet->IsRedrawNeeded()) { + $oBlock = $oDashlet->DoRender($oPage, true, false, $aExtraParams); + $sHtml = ConsoleBlockRenderer::RenderBlockTemplateInPage($oPage, $oBlock); + $sHtml = json_encode($sHtml); + $oPage->add_script("$('#dashlet_$sDashletId').html({$sHtml});"); + } + if ($oDashlet->IsFormRedrawNeeded()) { + $oForm = $oDashlet->GetForm(); // Rebuild the form since the values/content changed + $oForm->SetSubmitParams(utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php', ['operation' => 'update_dashlet_property', 'extra_params' => $aExtraParams]); + $sHtml = $oForm->RenderAsPropertySheet($oPage, true, '.itop-dashboard'); + $sHtml = json_encode($sHtml); + $oPage->add_script("$('#dashlet_properties_$sDashletId').html({$sHtml});"); + } } - if ($oDashlet->IsRedrawNeeded()) { - $oBlock = $oDashlet->DoRender($oPage, true, false, $aExtraParams); - $sHtml = ConsoleBlockRenderer::RenderBlockTemplateInPage($oPage, $oBlock); - $sHtml= json_encode($sHtml); - $oPage->add_script("$('#dashlet_$sDashletId').html({$sHtml});"); - } - if ($oDashlet->IsFormRedrawNeeded()) { - $oForm = $oDashlet->GetForm(); // Rebuild the form since the values/content changed - $oForm->SetSubmitParams(utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php', array('operation' => 'update_dashlet_property', 'extra_params' => $aExtraParams)); - $sHtml = $oForm->RenderAsPropertySheet($oPage, true, '.itop-dashboard'); - $sHtml= json_encode($sHtml); - $oPage->add_script("$('#dashlet_properties_$sDashletId').html({$sHtml});"); - } - } - break; + break; case 'dashlet_creation_dlg': $sOQL = utils::ReadParam('oql', '', false, 'raw_data'); @@ -1221,9 +1228,10 @@ EOF 'base/layouts/navigation-menu/menu-node' ); - $MenuNameEscaped = utils::HtmlEntities($aValues['name']); - // Important: Mind the back ticks to avoid line breaks to break the JS - $oPage->add_script(<<add_script( + <<GetClass(); $sNeedleFormat = isset($aAccelerators[$sClassName]['needle']) ? $aAccelerators[$sClassName]['needle'] : '%$needle$%'; $sNeedle = str_replace('$needle$', $sFullText, $sNeedleFormat); - $aParams = array('needle' => $sNeedle); + $aParams = ['needle' => $sNeedle]; } else { $sClassName = $sClassSpec; $oFilter = new DBObjectSearch($sClassName); - $aParams = array(); + $aParams = []; foreach ($aFullTextNeedles as $sSearchText) { $oFilter->AddCondition_FullText($sSearchText); @@ -1367,9 +1375,9 @@ JS if ($iTune > 0) { $fStartedClass = microtime(true); } - $oSet = new DBObjectSet($oFilter, array(), $aParams); + $oSet = new DBObjectSet($oFilter, [], $aParams); if (array_key_exists($sClassName, $aAccelerators) && array_key_exists('attributes', $aAccelerators[$sClassName])) { - $oSet->OptimizeColumnLoad(array($oFilter->GetClassAlias() => $aAccelerators[$sClassName]['attributes'])); + $oSet->OptimizeColumnLoad([$oFilter->GetClassAlias() => $aAccelerators[$sClassName]['attributes']]); } $sFullTextJS = addslashes($sFullText); @@ -1388,13 +1396,12 @@ JS }); EOF; - $sEnlargeButton = ''; if ($bEnableEnlarge) { $sEnlargeButton = " "; } if ($oSet->Count() > 0) { - $aLeafs = array(); + $aLeafs = []; while ($oObj = $oSet->Fetch()) { if (get_class($oObj) == $sClassName) { $aLeafs[] = $oObj->GetKey(); @@ -1416,7 +1423,7 @@ EOF; $oBlock = new DisplayBlock($oLeafsFilter, 'list', false); $sBlockId = 'global_search_'.$sClassName; $oPage->add('
'); - $oBlock->RenderContent($oPage, array('table_id' => $sBlockId, 'currentId' => $sBlockId)); + $oBlock->RenderContent($oPage, ['table_id' => $sBlockId, 'currentId' => $sBlockId]); $oPage->add("
\n"); $oPage->add("
\n"); $oPage->p(' '); // Some space ? @@ -1492,7 +1499,7 @@ EOF if (preg_match('/^"(.*)"$/', $sFullText, $aMatches)) { // The text is surrounded by double-quotes, remove the quotes and treat it as one single expression - $aFullTextNeedles = array($aMatches[1]); + $aFullTextNeedles = [$aMatches[1]]; } else { // Split the text on the blanks and treat this as a search for AND AND $aFullTextNeedles = explode(' ', $sFullText); @@ -1508,7 +1515,7 @@ EOF $oPage->add("

".MetaModel::GetClassIcon($sClass)." ".Dict::Format('UI:Search:Count_ObjectsOf_Class_Found', $oSet->Count(), Metamodel::GetName($sClass))."

\n"); $oPage->add("
\n"); if ($oSet->Count() > 0) { - $aLeafs = array(); + $aLeafs = []; while ($oObj = $oSet->Fetch()) { if (get_class($oObj) == $sClass) { $aLeafs[] = $oObj->GetKey(); @@ -1520,7 +1527,7 @@ EOF $oBlock = new DisplayBlock($oLeafsFilter, 'list', false); $sBlockId = 'global_search_'.$sClass; $oPage->add('
'); - $oBlock->RenderContent($oPage, array('table_id' => $sBlockId, 'currentId' => $sBlockId)); + $oBlock->RenderContent($oPage, ['table_id' => $sBlockId, 'currentId' => $sBlockId]); $oPage->add('
'); $oPage->P(' '); // Some space ? // Hide "no object found" @@ -1548,10 +1555,10 @@ EOF $sPageOrientation = utils::ReadParam('o', 'L'); $sTitle = utils::ReadParam('title', '', false, 'raw_data'); $sPositions = utils::ReadParam('positions', null, false, 'raw_data'); - $aExcludedClasses = utils::ReadParam('excluded_classes', array(), false, 'raw_data'); + $aExcludedClasses = utils::ReadParam('excluded_classes', [], false, 'raw_data'); $bIncludeList = (bool)utils::ReadParam('include_list', false); $sComments = utils::ReadParam('comments', '', false, 'raw_data'); - $aContexts = utils::ReadParam('contexts', array(), false, 'raw_data'); + $aContexts = utils::ReadParam('contexts', [], false, 'raw_data'); $sContextKey = utils::ReadParam('context_key', '', false, 'raw_data'); $aPositions = null; if ($sPositions != null) { @@ -1559,8 +1566,8 @@ EOF } // Get the list of source objects - $aSources = utils::ReadParam('sources', array(), false, 'raw_data'); - $aSourceObjects = array(); + $aSources = utils::ReadParam('sources', [], false, 'raw_data'); + $aSourceObjects = []; foreach ($aSources as $sClass => $aIDs) { $oSearch = new DBObjectSearch($sClass); $oSearch->AddCondition('id', $aIDs, 'IN'); @@ -1575,8 +1582,8 @@ EOF } // Get the list of excluded objects - $aExcluded = utils::ReadParam('excluded', array(), false, 'raw_data'); - $aExcludedObjects = array(); + $aExcluded = utils::ReadParam('excluded', [], false, 'raw_data'); + $aExcludedObjects = []; foreach ($aExcluded as $sClass => $aIDs) { $oSearch = new DBObjectSearch($sClass); $oSearch->AddCondition('id', $aIDs, 'IN'); @@ -1613,7 +1620,7 @@ EOF $oGraph->UpdatePositions($aPositions); } - $aGroups = array(); + $aGroups = []; $oIterator = new RelationTypeIterator($oGraph, 'Node'); foreach ($oIterator as $oNode) { if ($oNode instanceof DisplayableGroupNode) { @@ -1625,14 +1632,14 @@ EOF if ($bIncludeList) { // Then the lists of objects (one table per finalclass) - $aResults = array(); + $aResults = []; $oIterator = new RelationTypeIterator($oRelGraph, 'Node'); foreach ($oIterator as $oNode) { $oObj = $oNode->GetProperty('object'); // Some nodes (Redundancy Nodes and Group) do not contain an object if ($oObj) { $sObjClass = get_class($oObj); if (!array_key_exists($sObjClass, $aResults)) { - $aResults[$sObjClass] = array(); + $aResults[$sObjClass] = []; } $aResults[$sObjClass][] = $oObj; } @@ -1652,7 +1659,7 @@ EOF $oTitle = new Html(" ".Dict::Format('UI:Search:Count_ObjectsOf_Class_Found', $oSet->Count(), Metamodel::GetName($sListClass)));*/ $oTitle = new Html(Dict::Format('UI:Search:Count_ObjectsOf_Class_Found', $oSet->Count(), Metamodel::GetName($sListClass))); $oPage->AddSubBlock(TitleUIBlockFactory::MakeStandard($oTitle, 2)); - $oPage->AddSubBlock(cmdbAbstractObject::GetDataTableFromDBObjectSet($oSet, array('table_id' => $sSourceClass.'_'.$sRelation.'_'.$sDirection.'_'.$sListClass))); + $oPage->AddSubBlock(cmdbAbstractObject::GetDataTableFromDBObjectSet($oSet, ['table_id' => $sSourceClass.'_'.$sRelation.'_'.$sDirection.'_'.$sListClass])); } // Then the content of the groups (one table per group) @@ -1686,10 +1693,10 @@ EOF $oDoc = new ormDocument($sPDF, 'application/pdf', $sTitle.'.pdf'); $oAttachment->Set('contents', $oDoc); $iAttachmentId = $oAttachment->DBInsert(); - $aRet = array( + $aRet = [ 'status' => 'ok', 'att_id' => $iAttachmentId, - ); + ]; $oPage->SetData($aRet); } break; @@ -1702,17 +1709,17 @@ EOF $sDirection = utils::ReadParam('direction', 'down'); $iGroupingThreshold = utils::ReadParam('g', 5); $sPositions = utils::ReadParam('positions', null, false, 'raw_data'); - $aExcludedClasses = utils::ReadParam('excluded_classes', array(), false, 'raw_data'); - $aContexts = utils::ReadParam('contexts', array(), false, 'raw_data'); - $sContextKey = utils::ReadParam('context_key', array(), false, 'raw_data'); + $aExcludedClasses = utils::ReadParam('excluded_classes', [], false, 'raw_data'); + $aContexts = utils::ReadParam('contexts', [], false, 'raw_data'); + $sContextKey = utils::ReadParam('context_key', [], false, 'raw_data'); $aPositions = null; if ($sPositions != null) { $aPositions = json_decode($sPositions, true); } // Get the list of source objects - $aSources = utils::ReadParam('sources', array(), false, 'raw_data'); - $aSourceObjects = array(); + $aSources = utils::ReadParam('sources', [], false, 'raw_data'); + $aSourceObjects = []; foreach ($aSources as $sClass => $aIDs) { $oSearch = new DBObjectSearch($sClass); $oSearch->AddCondition('id', $aIDs, 'IN'); @@ -1723,8 +1730,8 @@ EOF } // Get the list of excluded objects - $aExcluded = utils::ReadParam('excluded', array(), false, 'raw_data'); - $aExcludedObjects = array(); + $aExcluded = utils::ReadParam('excluded', [], false, 'raw_data'); + $aExcludedObjects = []; foreach ($aExcluded as $sClass => $aIDs) { $oSearch = new DBObjectSearch($sClass); $oSearch->AddCondition('id', $aIDs, 'IN'); @@ -1772,12 +1779,12 @@ EOF $oSearch->SetShowObsoleteData(utils::ShowObsoleteData()); $oPage->AddUiBlock(TitleUIBlockFactory::MakeNeutral(Dict::Format('UI:RelationGroupNumber_N', (1 + $idx)), 1, "relation_group_$idx")); $oBlock = new DisplayBlock($oSearch, 'list'); - $oBlock->Display($oPage, 'group_'.$iBlock++, array( + $oBlock->Display($oPage, 'group_'.$iBlock++, [ 'surround_with_panel' => true, 'panel_class' => $sListClass, 'panel_title' => Dict::Format('UI:Search:Count_ObjectsOf_Class_Found', count($aDefinition['keys']), Metamodel::GetName($sListClass)), 'panel_icon' => MetaModel::GetClassIcon($sListClass, false), - )); + ]); } break; @@ -1789,13 +1796,13 @@ EOF $oSearch->AddCondition('id', $aKeys, 'IN'); $oSearch->SetShowObsoleteData(utils::ShowObsoleteData()); $oBlock = new DisplayBlock($oSearch, 'list'); - $oBlock->Display($oPage, 'list_'.$iBlock++, array( + $oBlock->Display($oPage, 'list_'.$iBlock++, [ 'table_id' => 'ImpactAnalysis_'.$sListClass, 'surround_with_panel' => true, 'panel_class' => $sListClass, 'panel_title' => Dict::Format('UI:Search:Count_ObjectsOf_Class_Found', count($aKeys), Metamodel::GetName($sListClass)), 'panel_icon' => MetaModel::GetClassIcon($sListClass, false), - )); + ]); } break; @@ -1822,8 +1829,8 @@ EOF $oExtKeyToRemote = MetaModel::GetAttributeDef($oAttDef->GetLinkedClass(), $sExtKeyToRemote); $sRemoteClass = $oExtKeyToRemote->GetTargetClass(); $oSet = $oTicket->Get($sAttCode); - $aSourceObjects = array(); - $aExcludedObjects = array(); + $aSourceObjects = []; + $aExcludedObjects = []; while ($oLnk = $oSet->Fetch()) { if ($oLnk->Get($sImpactAttCode) == 'manual') { $aSourceObjects[] = MetaModel::GetObject($sRemoteClass, $oLnk->Get($sExtKeyToRemote)); @@ -1847,7 +1854,7 @@ EOF $sContextKey = 'itop-tickets/relation_context/'.$sClass.'/'.$sRelation.'/'.$sDirection; $oAppContext = new ApplicationContext(); $oPage->AddSubBlock($oGraph->DisplayFilterBox($oPage, $aResults)); - $oGraph->DisplayGraph($oPage, $sRelation, $oAppContext, $aExcludedObjects, $sClass, $iId, $sContextKey, array('this' => $oTicket)); + $oGraph->DisplayGraph($oPage, $sRelation, $oAppContext, $aExcludedObjects, $sClass, $iId, $sContextKey, ['this' => $oTicket]); break; case 'export_build': @@ -1887,7 +1894,7 @@ EOF $oExporter->Cleanup(); } } - $aResult = array('code' => 'error', 'percentage' => 100, 'message' => Dict::S('Core:BulkExport:ExportCancelledByUser')); + $aResult = ['code' => 'error', 'percentage' => 100, 'message' => Dict::S('Core:BulkExport:ExportCancelledByUser')]; $oPage->add(json_encode($aResult)); break; @@ -1912,7 +1919,7 @@ EOF $oPage->add(json_encode($aResult)); break; - // Important: Only from the backoffice AND logged in + // Important: Only from the backoffice AND logged in case 'acquire_lock': $sObjClass = utils::ReadParam('obj_class', '', false, 'class'); $iObjKey = (int)utils::ReadParam('obj_key', 0, false, 'integer'); @@ -1981,7 +1988,7 @@ EOF $oPage->SetOutputDataOnly(true); // Image uploaded via CKEditor - $aResult = array( + $aResult = [ 'uploaded' => 0, 'fileName' => '', 'url' => '', @@ -1989,7 +1996,7 @@ EOF 'msg' => '', 'att_id' => 0, 'preview' => 'false', - ); + ]; $sObjClass = stripslashes(utils::ReadParam('obj_class', '', false, 'class')); $sTempId = utils::ReadParam('temp_id', '', false, 'transaction_id'); @@ -2023,7 +2030,7 @@ EOF $aResult['height'] = $aDimensions['height']; } - IssueLog::Trace('InlineImage created', LogChannels::INLINE_IMAGE, array( + IssueLog::Trace('InlineImage created', LogChannels::INLINE_IMAGE, [ '$operation' => $operation, '$aResult' => $aResult, 'secret' => $oAttachment->Get('secret'), @@ -2032,19 +2039,18 @@ EOF 'user' => UserRights::GetUser(), 'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'], 'REQUEST_URI' => @$_SERVER['REQUEST_URI'], - )); + ]); } else { $aResult['error'] = $oDoc->GetFileName().' is not a valid image format.'; } - } - catch (FileUploadException $e) { + } catch (FileUploadException $e) { $aResult['error'] = $e->GetMessage(); } } $oPage->SetData($aResult); break; - /** @noinspection PhpMissingBreakStatementInspection cke_upload_and_browse and cke_browse are chained */ + /** @noinspection PhpMissingBreakStatementInspection cke_upload_and_browse and cke_browse are chained */ case 'cke_upload_and_browse': $sTempId = utils::ReadParam('temp_id', '', false, 'transaction_id'); $sObjClass = utils::ReadParam('obj_class', '', false, 'class'); @@ -2052,12 +2058,14 @@ EOF $oDoc = utils::ReadPostedDocument('upload'); $sDocMimeType = $oDoc->GetMimeType(); if (!InlineImage::IsImage($sDocMimeType)) { - LogErrorMessage('CKE : error when uploading image in ajax.render.php, not an image', - array( + LogErrorMessage( + 'CKE : error when uploading image in ajax.render.php, not an image', + [ 'operation' => 'cke_upload_and_browse', 'class' => $sObjClass, 'ImgMimeType' => $sDocMimeType, - )); + ] + ); } else { $aDimensions = null; $iMaxImageSize = (int)MetaModel::GetConfig()->Get('inline_image_max_storage_width', 0); @@ -2072,7 +2080,7 @@ EOF $oAttachment->Set('secret', sprintf('%06x', mt_rand(0, 0xFFFFFF))); // something not easy to guess $iAttId = $oAttachment->DBInsert(); - IssueLog::Trace('InlineImage created', LogChannels::INLINE_IMAGE, array( + IssueLog::Trace('InlineImage created', LogChannels::INLINE_IMAGE, [ '$operation' => $operation, 'secret' => $oAttachment->Get('secret'), 'temp_id' => $sTempId, @@ -2080,19 +2088,20 @@ EOF 'user' => UserRights::GetUser(), 'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'], 'REQUEST_URI' => @$_SERVER['REQUEST_URI'], - )); + ]); } - } - catch (FileUploadException $e) { - LogErrorMessage('CKE : error when uploading image in ajax.render.php, exception occured', - array( + } catch (FileUploadException $e) { + LogErrorMessage( + 'CKE : error when uploading image in ajax.render.php, exception occured', + [ 'operation' => 'cke_upload_and_browse', 'class' => $sObjClass, 'exceptionMsg' => $e, - )); + ] + ); } - // Fall though !! => browse + // Fall though !! => browse case 'cke_browse': $oPage = new NiceWebPage(Dict::S('UI:BrowseInlineImages')); @@ -2203,7 +2212,7 @@ $('.img-picker').magnificPopup({type: 'image', closeOnContentClick: true }); EOF ); $sOQL = "SELECT InlineImage WHERE ((temp_id = :temp_id) OR (item_class = :obj_class AND item_id = :obj_id))"; - $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array(), array('temp_id' => $sTempId, 'obj_class' => $sClass, 'obj_id' => $iObjectId)); + $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), [], ['temp_id' => $sTempId, 'obj_class' => $sClass, 'obj_id' => $iObjectId]); $oPage->add("
$sAvailableImagesLegend"); if ($oSet->Count() == 0) { @@ -2225,11 +2234,11 @@ EOF case 'custom_fields_update': $oPage = new JsonPage(); $sAttCode = utils::ReadParam('attcode', ''); - $aRequestedFields = utils::ReadParam('requested_fields', array()); + $aRequestedFields = utils::ReadParam('requested_fields', []); $sRequestedFieldsFormPath = utils::ReadParam('form_path', ''); $sJson = utils::ReadParam('json_obj', '', false, 'raw_data'); - $aResult = array(); + $aResult = []; try { $oWizardHelper = WizardHelper::FromJSON($sJson); @@ -2243,26 +2252,24 @@ EOF $aRenderRes = $oRenderer->Render($aRequestedFields); $aResult['form']['updated_fields'] = $aRenderRes; - } - catch (Exception $e) { + } catch (Exception $e) { $aResult['error'] = $e->getMessage(); } $oPage->SetData($aResult); $oPage->SetOutputDataOnly(true); break; - //-------------------------------- - // Preferences - //-------------------------------- - /** @internal */ + //-------------------------------- + // Preferences + //-------------------------------- + /** @internal */ case 'preferences.set_user_picture': $oPage = new JsonPage(); try { $oController = new PreferencesController(); $aResult = $oController->SetUserPicture(); $aResult['success'] = true; - } - catch (Exception $oException) { + } catch (Exception $oException) { $aResult = [ 'success' => false, 'error_message' => $oException->getMessage(), @@ -2271,10 +2278,10 @@ EOF $oPage->SetData($aResult); break; - //-------------------------------- - // Activity panel - //-------------------------------- - /** @internal */ + //-------------------------------- + // Activity panel + //-------------------------------- + /** @internal */ case 'activity_panel.save_state': $oPage = new JsonPage(); try { @@ -2283,8 +2290,7 @@ EOF $aResult = [ 'success' => true, ]; - } - catch (Exception $oException) { + } catch (Exception $oException) { $aResult = [ 'success' => false, 'error_message' => $oException->getMessage(), @@ -2293,14 +2299,13 @@ EOF $oPage->SetData($aResult); break; - /** @internal */ + /** @internal */ case 'activity_panel.add_caselog_entries': $oPage = new JsonPage(); try { $oController = new ActivityPanelController(); $aResult = $oController->AddCaseLogsEntries(); - } - catch (Exception $oException) { + } catch (Exception $oException) { $aResult = [ 'success' => false, 'error_message' => $oException->getMessage(), @@ -2309,14 +2314,13 @@ EOF $oPage->SetData($aResult); break; - /** @internal */ + /** @internal */ case 'activity_panel.load_more_entries': $oPage = new JsonPage(); try { $oController = new ActivityPanelController(); $aResult = $oController->LoadMoreEntries(); - } - catch (Exception $oException) { + } catch (Exception $oException) { $aResult = [ 'success' => false, 'error_message' => $oException->getMessage(), @@ -2325,35 +2329,34 @@ EOF $oPage->SetData($aResult); break; - //-------------------------------- - // Navigation menu - //-------------------------------- + //-------------------------------- + // Navigation menu + //-------------------------------- case 'get_menus_count': $oPage = new JsonPage(); $oPage->SetOutputDataOnly(true); $oAjaxRenderController->GetMenusCount($oPage); break; - //-------------------------------- - // Object - //-------------------------------- - /** @internal */ + //-------------------------------- + // Object + //-------------------------------- + /** @internal */ case 'object.modify': $oController = new ObjectController(); $oPage = $oController->OperationModify(); break; - //-------------------------------- - // WelcomePopupMenu - //-------------------------------- + //-------------------------------- + // WelcomePopupMenu + //-------------------------------- case 'welcome_popup.acknowledge_message': $oPage = new JsonPage(); try { $oController = new WelcomePopupController(); $oController->AcknowledgeMessage(); $aResult = ['success' => true]; - } - catch (Exception $oException) { + } catch (Exception $oException) { $aResult = [ 'success' => false, 'error_message' => $oException->getMessage(), @@ -2374,10 +2377,10 @@ EOF IssueLog::Error($e->getMessage()."\nDebug trace:\n".$e->getTraceAsString()); } -function LogErrorMessage($sMsgPrefix, $aContextInfo) { +function LogErrorMessage($sMsgPrefix, $aContextInfo) +{ $sCurrentUserLogin = UserRights::GetUser(); $sContextInfo = urldecode(http_build_query($aContextInfo, '', ', ')); $sErrorMessage = "$sMsgPrefix - User='$sCurrentUserLogin', $sContextInfo"; IssueLog::Error($sErrorMessage); } - diff --git a/pages/csvimport.php b/pages/csvimport.php index 4213b7937..b033509b1 100644 --- a/pages/csvimport.php +++ b/pages/csvimport.php @@ -1,4 +1,5 @@ AddSubBlock($oOption); - $aValidClasses = array(); - $aClassCategories = array('bizmodel', 'addon/authentication'); + $aValidClasses = []; + $aClassCategories = ['bizmodel', 'addon/authentication']; if ($bAdvanced) { $aClassCategories[] = 'grant_by_profile'; } @@ -115,10 +116,9 @@ try { */ function CountCharsFromSet($sString, $aSet) { - $aResult = array(); + $aResult = []; $aCount = count_chars($sString); - foreach($aSet as $sChar) - { + foreach ($aSet as $sChar) { $aResult[$sChar] = isset($aCount[ord($sChar)]) ? $aCount[ord($sChar)] : 0; } return $aResult; @@ -134,35 +134,33 @@ try { { $iLine = 0; $iMaxLine = 20; // Process max 20 lines to guess the parameters - foreach($aPossibleSeparators as $sSep) - { + foreach ($aPossibleSeparators as $sSep) { $aGuesses[$sSep]['total'] = $aGuesses[$sSep]['max'] = 0; $aGuesses[$sSep]['min'] = 999; } - $aStats = array(); - while(($iLine < count($aCSVData)) && ($iLine < $iMaxLine) ) - { - if (strlen($aCSVData[$iLine]) > 0) - { + $aStats = []; + while (($iLine < count($aCSVData)) && ($iLine < $iMaxLine)) { + if (strlen($aCSVData[$iLine]) > 0) { $aStats[$iLine] = CountCharsFromSet($aCSVData[$iLine], $aPossibleSeparators); } $iLine++; } $iLine = 1; - foreach($aStats as $aLineStats) - { - foreach($aPossibleSeparators as $sSep) - { + foreach ($aStats as $aLineStats) { + foreach ($aPossibleSeparators as $sSep) { $aGuesses[$sSep]['total'] += $aLineStats[$sSep]; - if ($aLineStats[$sSep] > $aGuesses[$sSep]['max']) $aGuesses[$sSep]['max'] = $aLineStats[$sSep]; - if ($aLineStats[$sSep] < $aGuesses[$sSep]['min']) $aGuesses[$sSep]['min'] = $aLineStats[$sSep]; + if ($aLineStats[$sSep] > $aGuesses[$sSep]['max']) { + $aGuesses[$sSep]['max'] = $aLineStats[$sSep]; + } + if ($aLineStats[$sSep] < $aGuesses[$sSep]['min']) { + $aGuesses[$sSep]['min'] = $aLineStats[$sSep]; + } } $iLine++; } - $aScores = array(); - foreach($aGuesses as $sSep => $aData) - { + $aScores = []; + foreach ($aGuesses as $sSep => $aData) { $aScores[$sSep] = $aData['total'] + $aData['max'] - $aData['min']; } arsort($aScores, SORT_NUMERIC); // Sort the array, higher scores first @@ -179,10 +177,10 @@ try { function GuessParameters($sCSVData) { $aData = explode("\n", $sCSVData); - $sSeparator = GuessFromFrequency($aData, array("\t", ',', ';', '|')); // Guess the most frequent (and regular) character on each line - $sQualifier = GuessFromFrequency($aData, array('"', "'")); // Guess the most frequent (and regular) character on each line + $sSeparator = GuessFromFrequency($aData, ["\t", ',', ';', '|']); // Guess the most frequent (and regular) character on each line + $sQualifier = GuessFromFrequency($aData, ['"', "'"]); // Guess the most frequent (and regular) character on each line - return array('separator' => $sSeparator, 'qualifier' => $sQualifier); + return ['separator' => $sSeparator, 'qualifier' => $sQualifier]; } /** @@ -191,10 +189,10 @@ try { * @param string $sClass The class of objects to synchronize * @param integer $iCount The number of objects to synchronize */ - function DisplaySynchroBanner(WebPage $oP, $sClass, $iCount) - { - $oP->AddSubBlock(AlertUIBlockFactory::MakeForInformation(MetaModel::GetClassIcon($sClass)." ".Dict::Format('UI:Title:BulkSynchro_nbItem_ofClass_class', $iCount, MetaModel::GetName($sClass)))); - } + function DisplaySynchroBanner(WebPage $oP, $sClass, $iCount) + { + $oP->AddSubBlock(AlertUIBlockFactory::MakeForInformation(MetaModel::GetClassIcon($sClass)." ".Dict::Format('UI:Title:BulkSynchro_nbItem_ofClass_class', $iCount, MetaModel::GetName($sClass)))); + } /** * Process the CSV data, for real or as a simulation @@ -211,11 +209,11 @@ try { } // CSRF transaction id verification - if(!utils::IsTransactionValid(utils::ReadPostedParam('transaction_id', '', 'raw_data'))){ + if (!utils::IsTransactionValid(utils::ReadPostedParam('transaction_id', '', 'raw_data'))) { throw new CoreException(Dict::S('UI:Error:InvalidToken')); } - $aResult = array(); + $aResult = []; $sCSVData = utils::ReadParam('csvdata', '', false, 'raw_data'); $sCSVDataTruncated = utils::ReadParam('csvdata_truncated', '', false, 'raw_data'); $sSeparator = utils::ReadParam('separator', ',', false, 'raw_data'); @@ -223,23 +221,41 @@ try { $bHeaderLine = (utils::ReadParam('header_line', '0') == 1); $iNbSkippedLines = utils::ReadParam('nb_skipped_lines', '0'); $iBoxSkipLines = utils::ReadParam('box_skiplines', '0'); - $aFieldsMapping = utils::ReadParam('field', array(), false, 'raw_data'); - $aSearchFields = utils::ReadParam('search_field', array(), false, 'field_name'); + $aFieldsMapping = utils::ReadParam('field', [], false, 'raw_data'); + $aSearchFields = utils::ReadParam('search_field', [], false, 'field_name'); $iCurrentStep = $bSimulate ? 4 : 5; $bAdvanced = utils::ReadParam('advanced', 0); $sEncoding = utils::ReadParam('encoding', 'UTF-8'); $sSynchroScope = utils::ReadParam('synchro_scope', '', false, 'raw_data'); - $aSynchroUpdate = utils::ReadParam('synchro_update', array()); + $aSynchroUpdate = utils::ReadParam('synchro_update', []); $sDateTimeFormat = utils::ReadParam('date_time_format', 'default'); $sCustomDateTimeFormat = utils::ReadParam('custom_date_time_format', (string)AttributeDateTime::GetFormat(), false, 'raw_data'); - return CSVImportPageProcessor::ProcessData($iBoxSkipLines, $iNbSkippedLines, $sDateTimeFormat, $sCustomDateTimeFormat, $sClassName, $oPage, $aSynchroUpdate, $sCSVData, $sSeparator, $sTextQualifier, $bHeaderLine, $aResult, $aSearchFields, $aFieldsMapping, $bSimulate, $sCSVDataTruncated, - $iCurrentStep, $sEncoding, - $bAdvanced, $sSynchroScope); + return CSVImportPageProcessor::ProcessData( + $iBoxSkipLines, + $iNbSkippedLines, + $sDateTimeFormat, + $sCustomDateTimeFormat, + $sClassName, + $oPage, + $aSynchroUpdate, + $sCSVData, + $sSeparator, + $sTextQualifier, + $bHeaderLine, + $aResult, + $aSearchFields, + $aFieldsMapping, + $bSimulate, + $sCSVDataTruncated, + $iCurrentStep, + $sEncoding, + $bAdvanced, + $sSynchroScope + ); } - /** * Perform the actual load of the CSV data and display the results * @param WebPage $oPage The web page to display the wizard @@ -285,14 +301,14 @@ try { $sCSVData = utils::ReadParam('csvdata', '', false, 'raw_data'); $sCSVDataTruncated = utils::ReadParam('csvdata_truncated', '', false, 'raw_data'); $sSeparator = utils::ReadParam('separator', ',', false, 'raw_data'); - if ($sSeparator == 'tab') $sSeparator = "\t"; - if ($sSeparator == 'other') - { + if ($sSeparator == 'tab') { + $sSeparator = "\t"; + } + if ($sSeparator == 'other') { $sSeparator = utils::ReadParam('other_separator', ',', false, 'raw_data'); } $sTextQualifier = utils::ReadParam('text_qualifier', '"', false, 'raw_data'); - if ($sTextQualifier == 'other') - { + if ($sTextQualifier == 'other') { $sTextQualifier = utils::ReadParam('other_qualifier', '"', false, 'raw_data'); } $bHeaderLine = (utils::ReadParam('header_line', '0') == 1); @@ -312,7 +328,7 @@ try { $oClassesSelect = SelectUIBlockFactory::MakeForSelect("class_name", "select_class_name"); $oDefaultSelect = SelectOptionUIBlockFactory::MakeForSelectOption("$sClassName", MetaModel::GetName($sClassName), true); $oClassesSelect->AddSubBlock($oDefaultSelect); - $aSynchroUpdate = utils::ReadParam('synchro_update', array()); + $aSynchroUpdate = utils::ReadParam('synchro_update', []); } else { $oClassesSelect = GetClassesSelectUIBlock('class_name', $sClassName, UR_ACTION_BULK_MODIFY, (bool)$bAdvanced); } @@ -360,7 +376,7 @@ try { $oForm->AddSubBlock(InputUIBlockFactory::MakeForHidden("synchro_scope", $sSynchroScope)); $oForm->AddSubBlock(InputUIBlockFactory::MakeForHidden("date_time_format", $sDateTimeFormat)); $oForm->AddSubBlock(InputUIBlockFactory::MakeForHidden("custom_date_time_format", $sCustomDateTimeFormat)); - $oForm->AddSubBlock(InputUIBlockFactory::MakeForHidden("transaction_id", utils::GetNewTransactionId(), "transaction_id")); // adding transaction_id field for next step (simulation) + $oForm->AddSubBlock(InputUIBlockFactory::MakeForHidden("transaction_id", utils::GetNewTransactionId(), "transaction_id")); // adding transaction_id field for next step (simulation) if (!empty($sSynchroScope)) { foreach ($aSynchroUpdate as $sKey => $value) { @@ -382,10 +398,9 @@ try { $('#advanced').on('click', function(ev) { DoReload(); } ); EOF ); - if ($sClassName != '') - { - $aFieldsMapping = utils::ReadParam('field', array(), false, 'raw_data'); - $aSearchFields = utils::ReadParam('search_field', array(), false, 'field_name'); + if ($sClassName != '') { + $aFieldsMapping = utils::ReadParam('field', [], false, 'raw_data'); + $aSearchFields = utils::ReadParam('search_field', [], false, 'field_name'); $sFieldsMapping = addslashes(json_encode($aFieldsMapping)); $sSearchFields = addslashes(json_encode($aSearchFields)); @@ -393,7 +408,7 @@ EOF } $oPage->add_script( -<<IsEmpty()) - { - $sCSVData = $oDocument->GetData(); - } - break; + $oDocument = utils::ReadPostedDocument('csvdata'); + if (!$oDocument->IsEmpty()) { + $sCSVData = $oDocument->GetData(); + } + break; default: - $sCSVData = utils::ReadPostedParam('csvdata', '', 'raw_data'); + $sCSVData = utils::ReadPostedParam('csvdata', '', 'raw_data'); } $sEncoding = utils::ReadParam('encoding', 'UTF-8'); // Compute a subset of the data set, now that we know the charset - if ($sEncoding == 'UTF-8') - { + if ($sEncoding == 'UTF-8') { // Remove the BOM if any - if (substr($sCSVData, 0, 3) == UTF8_BOM) - { + if (substr($sCSVData, 0, 3) == UTF8_BOM) { $sCSVData = substr($sCSVData, 3); } // Clean the input // Todo: warn the user if some characters are lost/substituted $sUTF8Data = iconv('UTF-8', 'UTF-8//IGNORE//TRANSLIT', $sCSVData); - } - else - { + } else { $sUTF8Data = iconv($sEncoding, 'UTF-8//IGNORE//TRANSLIT', $sCSVData); } @@ -661,16 +670,15 @@ EOF $iSkippedLines = utils::ReadParam('nb_skipped_lines', ''); $bBoxSkipLines = utils::ReadParam('box_skiplines', 0); $sTextQualifier = utils::ReadParam('text_qualifier', '', false, 'raw_data'); - if ($sTextQualifier == '') // May be set to an empty value by the previous page - { + if ($sTextQualifier == '') { // May be set to an empty value by the previous page $sTextQualifier = $aGuesses['qualifier']; } - $sOtherTextQualifier = in_array($sTextQualifier, array('"', "'")) ? '' : $sTextQualifier; + $sOtherTextQualifier = in_array($sTextQualifier, ['"', "'"]) ? '' : $sTextQualifier; $bHeaderLine = utils::ReadParam('header_line', 0); $sClassName = utils::ReadParam('class_name', '', false, 'class'); $bAdvanced = utils::ReadParam('advanced', 0); - $aFieldsMapping = utils::ReadParam('field', array(), false, 'raw_data'); - $aSearchFields = utils::ReadParam('search_field', array(), false, 'field_name'); + $aFieldsMapping = utils::ReadParam('field', [], false, 'raw_data'); + $aSearchFields = utils::ReadParam('search_field', [], false, 'field_name'); // Create a truncated version of the data used for the fast preview // Take about 20 lines of data... knowing that some lines may contain carriage returns @@ -700,7 +708,7 @@ EOF $oSet = new DBObjectSet($oSearch); $iCount = $oSet->Count(); DisplaySynchroBanner($oPage, $sClassName, $iCount); - $aSynchroUpdate = utils::ReadParam('synchro_update', array()); + $aSynchroUpdate = utils::ReadParam('synchro_update', []); } $oPanel = TitleUIBlockFactory::MakeForPage(Dict::S('UI:Title:CSVImportStep2')); $oPage->AddSubBlock($oPanel); @@ -708,7 +716,6 @@ EOF $oForm = FormUIBlockFactory::MakeStandard('wizForm'); $oPage->AddSubBlock($oForm); - $oContainer = PanelUIBlockFactory::MakeNeutral(''); $oForm->AddSubBlock($oContainer); @@ -720,20 +727,19 @@ EOF $oFieldSetSeparator = FieldSetUIBlockFactory::MakeStandard(Dict::S('UI:CSVImport:SeparatorCharacter')); $oMulticolumn->AddColumn(ColumnUIBlockFactory::MakeForBlock($oFieldSetSeparator)); - $aSep = array( + $aSep = [ ';' => Dict::S('UI:CSVImport:SeparatorSemicolon+'), ',' => Dict::S('UI:CSVImport:SeparatorComma+'), 'tab' => Dict::S('UI:CSVImport:SeparatorTab+'), - ); + ]; $sSeparator = utils::ReadParam('separator', '', false, 'raw_data'); - if ($sSeparator == '') // May be set to an empty value by the previous page - { + if ($sSeparator == '') { // May be set to an empty value by the previous page $sSeparator = $aGuesses['separator']; } if ($sSeparator == "\t") { $sSeparator = "tab"; } - $sOtherSeparator = in_array($sSeparator, array(',', ';', "\t")) ? '' : $sSeparator; + $sOtherSeparator = in_array($sSeparator, [',', ';', "\t"]) ? '' : $sSeparator; $aSep['other'] = Dict::S('UI:CSVImport:SeparatorOther').' '; foreach ($aSep as $sVal => $sLabel) { @@ -751,10 +757,10 @@ EOF $oFieldSetTextQualifier = FieldSetUIBlockFactory::MakeStandard(Dict::S('UI:CSVImport:TextQualifierCharacter')); $oMulticolumn->AddColumn(ColumnUIBlockFactory::MakeForBlock($oFieldSetTextQualifier)); - $aQualifiers = array( + $aQualifiers = [ '"' => Dict::S('UI:CSVImport:QualifierDoubleQuote+'), '\'' => Dict::S('UI:CSVImport:QualifierSimpleQuote+'), - ); + ]; $aQualifiers['other'] = Dict::S('UI:CSVImport:QualifierOther').' AddSubBlock($oCheckBoxHeader); $oFieldSetCommentsAndHeader->AddSubBlock(new Html('
')); - $oCheckBoxSkip = InputUIBlockFactory::MakeForInputWithLabel(Dict::Format('UI:CSVImport:Skip_N_LinesAtTheBeginning', ''), "box_skiplines", "1", "box_skiplines", - "checkbox"); + $oCheckBoxSkip = InputUIBlockFactory::MakeForInputWithLabel( + Dict::Format('UI:CSVImport:Skip_N_LinesAtTheBeginning', ''), + "box_skiplines", + "1", + "box_skiplines", + "checkbox" + ); $oCheckBoxSkip->GetInput()->AddCSSClass('ibo-input-checkbox'); $oCheckBoxSkip->GetInput()->SetIsChecked(($bBoxSkipLines == 1)); $oCheckBoxSkip->SetBeforeInput(false); @@ -901,9 +912,9 @@ EOF ); } EOF - ); + ); $oPage->add_ready_script( -<<Count(); DisplaySynchroBanner($oPage, $sClassName, $iCount); - $aSynchroUpdate = utils::ReadParam('synchro_update', array()); + $aSynchroUpdate = utils::ReadParam('synchro_update', []); } else { $aSynchroUpdate = null; } @@ -959,8 +970,8 @@ EOF if ($sEncoding == '') { $sEncoding = MetaModel::GetConfig()->Get('csv_file_default_charset'); } - $aFieldsMapping = utils::ReadParam('field', array(), false, 'raw_data'); - $aSearchFields = utils::ReadParam('search_field', array(), false, 'field_name'); + $aFieldsMapping = utils::ReadParam('field', [], false, 'raw_data'); + $aSearchFields = utils::ReadParam('search_field', [], false, 'field_name'); $aPossibleEncodings = utils::GetPossibleEncodings(MetaModel::GetConfig()->GetCSVImportCharsets()); foreach ($aPossibleEncodings as $sIconvCode => $sDisplayName) { @@ -995,7 +1006,6 @@ EOF $oFormPaste = FormUIBlockFactory::MakeStandard(); $oTabPaste->AddSubBlock($oFormPaste); - $sCSVData = utils::ReadParam('csvdata', '', false, utils::ENUM_SANITIZATION_FILTER_STRING); $oTextarea = new TextArea('csvdata', $sCSVData, '', 120, 30); $oTextarea->AddCSSClasses(['ibo-input-text', 'ibo-is-code']); @@ -1065,25 +1075,28 @@ ajax_request = $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.csvimport.php', ); } EOF - ); + ); $oPage->add_ready_script( -<<Get('csv_import_history_display')) - { + if (Utils::GetConfig()->Get('csv_import_history_display')) { $oPage->SetCurrentTabContainer('tabs1'); - $oPage->AddAjaxTab('UI:History:BulkImports', utils::GetAbsoluteUrlAppRoot().'pages/csvimport.php?step=11', true /* bCache */, - null, AjaxTab::ENUM_TAB_PLACEHOLDER_MISC); + $oPage->AddAjaxTab( + 'UI:History:BulkImports', + utils::GetAbsoluteUrlAppRoot().'pages/csvimport.php?step=11', + true /* bCache */, + null, + AjaxTab::ENUM_TAB_PLACEHOLDER_MISC + ); } } - switch($iStep) - { + switch ($iStep) { case 11: // Asynchronous tab $oPage = new AjaxPage(''); @@ -1121,19 +1134,15 @@ EOF } $oPage->output(); -} -catch(CoreException $e) -{ +} catch (CoreException $e) { require_once(APPROOT.'/setup/setuppage.class.inc.php'); $oP = new ErrorPage(Dict::S('UI:PageTitle:FatalError')); $oP->add("

".Dict::S('UI:FatalErrorMessage')."

\n"); $oP->error(Dict::Format('UI:Error_Details', $e->getHtmlDesc())); $oP->output(); - if (MetaModel::IsLogEnabledIssue()) - { - if (MetaModel::IsValidClass('EventIssue')) - { + if (MetaModel::IsLogEnabledIssue()) { + if (MetaModel::IsValidClass('EventIssue')) { $oLog = new EventIssue(); $oLog->Set('message', $e->getMessage()); @@ -1150,19 +1159,15 @@ catch(CoreException $e) // For debugging only //throw $e; -} -catch(Exception $e) -{ +} catch (Exception $e) { require_once(APPROOT.'/setup/setuppage.class.inc.php'); $oP = new ErrorPage(Dict::S('UI:PageTitle:FatalError')); $oP->add("

".Dict::S('UI:FatalErrorMessage')."

\n"); $oP->error(Dict::Format('UI:Error_Details', $e->getMessage())); $oP->output(); - if (MetaModel::IsLogEnabledIssue()) - { - if (MetaModel::IsValidClass('EventIssue')) - { + if (MetaModel::IsLogEnabledIssue()) { + if (MetaModel::IsValidClass('EventIssue')) { $oLog = new EventIssue(); $oLog->Set('message', $e->getMessage()); @@ -1170,7 +1175,7 @@ catch(Exception $e) $oLog->Set('issue', 'PHP Exception'); $oLog->Set('impact', 'Page could not be displayed'); $oLog->Set('callstack', $e->getTrace()); - $oLog->Set('data', array()); + $oLog->Set('data', []); $oLog->DBInsertNoReload(); } diff --git a/pages/graphviz.php b/pages/graphviz.php index 4fa075b5b..403aa5fe1 100644 --- a/pages/graphviz.php +++ b/pages/graphviz.php @@ -1,4 +1,5 @@ p("no lifecycle for this class"); - } - else - { + } else { $aStates = MetaModel::EnumStates($sClass); $aStimuli = MetaModel::EnumStimuli($sClass); $sDotFileContent .= "digraph finite_state_machine { @@ -60,18 +58,15 @@ function GraphvizLifecycle($sClass) node [ fontname=Verdana style=filled fillcolor=\"#ffffff\" ]; edge [ fontname=Verdana ]; "; - $aStatesLinks = array(); - foreach ($aStates as $sStateCode => $aStateDef) - { - $aStatesLinks[$sStateCode] = array('in' => 0, 'out' => 0); + $aStatesLinks = []; + foreach ($aStates as $sStateCode => $aStateDef) { + $aStatesLinks[$sStateCode] = ['in' => 0, 'out' => 0]; } - - foreach ($aStates as $sStateCode => $aStateDef) - { + + foreach ($aStates as $sStateCode => $aStateDef) { $sStateLabel = MetaModel::GetStateLabel($sClass, $sStateCode); $sStateDescription = MetaModel::GetStateDescription($sClass, $sStateCode); - foreach(MetaModel::EnumTransitions($sClass, $sStateCode) as $sStimulusCode => $aTransitionDef) - { + foreach (MetaModel::EnumTransitions($sClass, $sStateCode) as $sStimulusCode => $aTransitionDef) { $aStatesLinks[$sStateCode]['out']++; $aStatesLinks[$aTransitionDef['target_state']]['in']++; $sStimulusLabel = $aStimuli[$sStimulusCode]->GetLabel(); @@ -79,19 +74,14 @@ function GraphvizLifecycle($sClass) $sDotFileContent .= "\t$sStateCode -> {$aTransitionDef['target_state']} [ label=\"".GraphvizEscape($sStimulusLabel)."\"];\n"; } } - foreach($aStates as $sStateCode => $aStateDef) - { - if (($aStatesLinks[$sStateCode]['out'] > 0) || ($aStatesLinks[$sStateCode]['in'] > 0)) - { + foreach ($aStates as $sStateCode => $aStateDef) { + if (($aStatesLinks[$sStateCode]['out'] > 0) || ($aStatesLinks[$sStateCode]['in'] > 0)) { // Show only reachable states $sStateLabel = str_replace(' ', '\n', MetaModel::GetStateLabel($sClass, $sStateCode)); - if ( ($aStatesLinks[$sStateCode]['in'] == 0) || ($aStatesLinks[$sStateCode]['out'] == 0)) - { + if (($aStatesLinks[$sStateCode]['in'] == 0) || ($aStatesLinks[$sStateCode]['out'] == 0)) { // End or Start state, make it look different $sDotFileContent .= "\t$sStateCode [ shape=doublecircle,label=\"".GraphvizEscape($sStateLabel)."\"];\n"; - } - else - { + } else { $sDotFileContent .= "\t$sStateCode [ shape=circle,label=\"".GraphvizEscape($sStateLabel)."\"];\n"; } } @@ -108,39 +98,33 @@ $sModuleDir = dirname($sDeclarationFile); $sImageFilePath = $sModuleDir."/lifecycle/".$sClass.".png"; $sDotExecutable = MetaModel::GetConfig()->Get('graphviz_path'); -if (file_exists($sDotExecutable)) -{ +if (file_exists($sDotExecutable)) { // create the file with Graphviz $sImageFilePath = utils::GetDataPath()."lifecycle/".$sClass.".svg"; - if (!is_dir(utils::GetDataPath())) - { + if (!is_dir(utils::GetDataPath())) { @mkdir(utils::GetDataPath()); } - if (!is_dir(utils::GetDataPath()."lifecycle")) - { + if (!is_dir(utils::GetDataPath()."lifecycle")) { @mkdir(utils::GetDataPath()."lifecycle"); } $sDotDescription = GraphvizLifecycle($sClass); $sDotFilePath = utils::GetDataPath()."lifecycle/{$sClass}.dot"; - + $rFile = @fopen($sDotFilePath, "w"); @fwrite($rFile, $sDotDescription); @fclose($rFile); - $aOutput = array(); + $aOutput = []; $CommandLine = "\"$sDotExecutable\" -v -Tsvg < \"$sDotFilePath\" -o \"$sImageFilePath\" 2>&1"; - + exec($CommandLine, $aOutput, $iRetCode); - if ($iRetCode != 0) - { + if ($iRetCode != 0) { header('Content-type: text/html'); echo "

Error:

"; echo "

The command:

$CommandLine
returned $iRetCode

"; echo "

The output of the command is:

\n".implode("\n", $aOutput)."

"; echo "
"; echo "

Content of the '".basename($sDotFilePath)."' file:

\n$sDotDescription
"; - } - else - { + } else { header('Content-type: image/svg+xml'); header('Content-Disposition: inline; filename="'.$sClass.'.svg"'); readfile($sImageFilePath); @@ -148,9 +132,7 @@ if (file_exists($sDotExecutable)) @unlink($sDotFilePath); // Image file is removed as well as there is no cache system yet @unlink($sImageFilePath); -} -else -{ +} else { header('Content-type: image/png'); header('Content-Disposition: inline; filename="'.$sClass.'.png"'); readfile($sImageFilePath); diff --git a/pages/preferences.php b/pages/preferences.php index 707cf19eb..20480ae5a 100644 --- a/pages/preferences.php +++ b/pages/preferences.php @@ -1,4 +1,5 @@ GenerateUrl(NotificationsCenterController::ROUTE_NAMESPACE.'.display_page', [], true); $oNotificationsBlock->AddSubBlock(new Html('

'.Dict::Format('UI:Preferences:Notifications+', $sNotificationsCenterUrl).'

')); $oContentLayout->AddMainBlock($oNotificationsBlock); - ////////////////////////////////////////////////////////////////////////// // // Favorite Organizations // ////////////////////////////////////////////////////////////////////////// - $oFavoriteOrganizationsBlock = new Panel(Dict::S('UI:FavoriteOrganizations'), array(), 'grey', 'ibo-favorite-organizations'); + $oFavoriteOrganizationsBlock = new Panel(Dict::S('UI:FavoriteOrganizations'), [], 'grey', 'ibo-favorite-organizations'); $oFavoriteOrganizationsBlock->SetSubTitle(Dict::S('UI:FavoriteOrganizations+')); $oFavoriteOrganizationsBlock->AddCSSClass('ibo-datatable-panel'); $oFavoriteOrganizationsForm = new Form(); @@ -212,7 +211,7 @@ JS // ////////////////////////////////////////////////////////////////////////// - $oShortcutsBlock = new BlockShortcuts(Dict::S('Menu:MyShortcuts'), array(), 'grey', 'ibo-shortcuts'); + $oShortcutsBlock = new BlockShortcuts(Dict::S('Menu:MyShortcuts'), [], 'grey', 'ibo-shortcuts'); $oShortcutsBlock->AddCSSClass('ibo-datatable-panel'); $oShortcutsBlock->sIdShortcuts = 'shortcut_list'; @@ -236,12 +235,22 @@ JS $oShortcutsToolBar = ToolbarUIBlockFactory::MakeForButton(); $oShortcutsBlock->AddSubBlock($oShortcutsToolBar); // - Rename button - $oShortcutsRenameButton = ButtonUIBlockFactory::MakeForSecondaryAction(Dict::S('UI:Button:Rename'), null, null, false, - "shortcut_btn_rename"); + $oShortcutsRenameButton = ButtonUIBlockFactory::MakeForSecondaryAction( + Dict::S('UI:Button:Rename'), + null, + null, + false, + "shortcut_btn_rename" + ); $oShortcutsToolBar->AddSubBlock($oShortcutsRenameButton); // - Delete button - $oShortcutsDeleteButton = ButtonUIBlockFactory::MakeForSecondaryAction(Dict::S('UI:Button:Delete'), null, null, false, - "shortcut_btn_delete"); + $oShortcutsDeleteButton = ButtonUIBlockFactory::MakeForSecondaryAction( + Dict::S('UI:Button:Delete'), + null, + null, + false, + "shortcut_btn_delete" + ); $oShortcutsToolBar->AddSubBlock($oShortcutsDeleteButton); } $oContentLayout->AddMainBlock($oShortcutsBlock); @@ -255,26 +264,27 @@ JS $oUser = UserRights::GetUserObject(); /** @var iNewsroomProvider[] $aProviders */ $aProviders = InterfaceDiscovery::GetInstance()->FindItopClasses(iNewsroomProvider::class); - foreach($aProviders as $cProvider) - { + foreach ($aProviders as $cProvider) { $oProvider = new $cProvider(); - if ($oProvider->IsApplicable($oUser)) - { + if ($oProvider->IsApplicable($oUser)) { $iCountProviders++; } } $bNewsroomEnabled = (MetaModel::GetConfig()->Get('newsroom_enabled') !== false); - if ($bNewsroomEnabled && ($iCountProviders > 0)) - { - $oNewsroomBlock = new Panel(Dict::S('UI:Newsroom:Preferences'), array(), 'grey', 'ibo-newsroom'); + if ($bNewsroomEnabled && ($iCountProviders > 0)) { + $oNewsroomBlock = new Panel(Dict::S('UI:Newsroom:Preferences'), [], 'grey', 'ibo-newsroom'); $sNewsroomHtml = ''; $sNewsroomHtml .= ''; $iNewsroomDisplaySize = (int)appUserPreferences::GetPref('newsroom_display_size', iTopNewsroomController::DEFAULT_NEWSROOM_DISPLAY_SIZE); - if ($iNewsroomDisplaySize < iTopNewsroomController::DEFAULT_NEWSROOM_MIN_DISPLAY_SIZE) $iNewsroomDisplaySize = iTopNewsroomController::DEFAULT_NEWSROOM_MIN_DISPLAY_SIZE; - if ($iNewsroomDisplaySize > iTopNewsroomController::DEFAULT_NEWSROOM_MAX_DISPLAY_SIZE) $iNewsroomDisplaySize = iTopNewsroomController::DEFAULT_NEWSROOM_MAX_DISPLAY_SIZE; + if ($iNewsroomDisplaySize < iTopNewsroomController::DEFAULT_NEWSROOM_MIN_DISPLAY_SIZE) { + $iNewsroomDisplaySize = iTopNewsroomController::DEFAULT_NEWSROOM_MIN_DISPLAY_SIZE; + } + if ($iNewsroomDisplaySize > iTopNewsroomController::DEFAULT_NEWSROOM_MAX_DISPLAY_SIZE) { + $iNewsroomDisplaySize = iTopNewsroomController::DEFAULT_NEWSROOM_MAX_DISPLAY_SIZE; + } $sInput = ''; $sIcon = ''; $sNewsroomHtml .= Dict::Format('UI:Newsroom:DisplayAtMost_X_Messages', $sInput, $sIcon); @@ -283,22 +293,16 @@ JS * @var iNewsroomProvider[] $aProviders */ $sAppRootUrl = utils::GetAbsoluteUrlAppRoot(); - foreach($aProviders as $cProvider) - { + foreach ($aProviders as $cProvider) { $oProvider = new $cProvider(); - if ($oProvider->IsApplicable($oUser)) - { + if ($oProvider->IsApplicable($oUser)) { $sUrl = $oProvider->GetPreferencesUrl(); $sProviderClass = get_class($oProvider); $sPreferencesLink = ''; - if ($sUrl !== null) - { - if(substr($sUrl, 0, strlen($sAppRootUrl)) === $sAppRootUrl) - { + if ($sUrl !== null) { + if (substr($sUrl, 0, strlen($sAppRootUrl)) === $sAppRootUrl) { $sTarget = ''; // Internal link, open in the same window - } - else - { + } else { $sTarget = ' target="_blank"'; // External link, open in new window } $sPreferencesLink = ' - '.Dict::S('UI:Newsroom:ConfigurationLink').''; @@ -308,8 +312,10 @@ JS // Forbid disabling internal newsroom provider $sDisabledForHtml = $sProviderClass === iTopNewsroomProvider::class ? 'disabled' : ''; - $sNewsroomHtml .= '
'.$sPreferencesLink.'
'; + $sNewsroomHtml .= '
'.$sPreferencesLink.'
'; } } @@ -319,7 +325,8 @@ JS // - Reset button $oNewsroomResetCacheButton = ButtonUIBlockFactory::MakeForAlternativeDestructiveAction(Dict::S('UI:Newsroom:ResetCache')); - $oNewsroomResetCacheButton->SetOnClickJsCode(<<SetOnClickJsCode( + <<SetOnClickJsCode("window.location.href = '$sURL'"); $oNewsroomToolbar->AddSubBlock($oNewsroomCancelButton); // - Submit button - $oNewsroomSubmitButton = ButtonUIBlockFactory::MakeForPrimaryAction(Dict::S('UI:Button:Apply'), 'operation', - 'apply_newsroom_preferences', true); + $oNewsroomSubmitButton = ButtonUIBlockFactory::MakeForPrimaryAction( + Dict::S('UI:Button:Apply'), + 'operation', + 'apply_newsroom_preferences', + true + ); $oNewsroomToolbar->AddSubBlock($oNewsroomSubmitButton); - $sNewsroomEndHtml = ''; $oNewsroomEndHtmlBlock = new Html($sNewsroomEndHtml); @@ -352,7 +362,7 @@ JS ////////////////////////////////////////////////////////////////////////// // Panel - $oKeyboardShortcutBlock = new Panel(Dict::S('UI:Preferences:PersonalizeKeyboardShortcuts:Title'), array(), 'grey', 'ibo_keyboard_shortcuts'); + $oKeyboardShortcutBlock = new Panel(Dict::S('UI:Preferences:PersonalizeKeyboardShortcuts:Title'), [], 'grey', 'ibo_keyboard_shortcuts'); // Form $oKeyboardShortcutForm = new Form('ibo-form-for-user-interface-preferences'); $oKeyboardShortcutForm->AddSubBlock(InputUIBlockFactory::MakeForHidden('operation', 'apply_keyboard_shortcuts')) @@ -414,7 +424,6 @@ JS $oKeyboardShortcutSubmitButton = ButtonUIBlockFactory::MakeForPrimaryAction(Dict::S('UI:Button:Apply'), 'operation', 'apply_keyboard_shortcuts', true); $oKeyboardShortcutToolbar->AddSubBlock($oKeyboardShortcutSubmitButton); - $oContentLayout->AddMainBlock($oKeyboardShortcutBlock); ////////////////////////////////////////////////////////////////////////// @@ -423,23 +432,20 @@ JS // ////////////////////////////////////////////////////////////////////////// - $oUserPicturePlaceHolderBlock = new Panel(Dict::S('UI:Preferences:ChooseAPlaceholder'), array(), 'grey', 'ibo-user-picture-placeholder'); + $oUserPicturePlaceHolderBlock = new Panel(Dict::S('UI:Preferences:ChooseAPlaceholder'), [], 'grey', 'ibo-user-picture-placeholder'); $sUserPicturesFolderRelPath = 'images/user-pictures/'; - $sUserPicturesFolderAbsPath = APPROOT . $sUserPicturesFolderRelPath; - $sUserPicturesFolderAbsUrl = utils::GetAbsoluteUrlAppRoot() . $sUserPicturesFolderRelPath; + $sUserPicturesFolderAbsPath = APPROOT.$sUserPicturesFolderRelPath; + $sUserPicturesFolderAbsUrl = utils::GetAbsoluteUrlAppRoot().$sUserPicturesFolderRelPath; $sUserDefaultPicture = appUserPreferences::GetPref('user_picture_placeholder', 'default-placeholder.png'); $sUserPicturePlaceHolderHtml = ''; $sUserPicturePlaceHolderHtml .= '

'.Dict::S('UI:Preferences:ChooseAPlaceholder+').'

'; - foreach (scandir($sUserPicturesFolderAbsPath) as $sUserPicture) - { - if ($sUserPicture === '.' || $sUserPicture === '..') - { + foreach (scandir($sUserPicturesFolderAbsPath) as $sUserPicture) { + if ($sUserPicture === '.' || $sUserPicture === '..') { continue; } $sAdditionalClass = ''; - if ($sUserDefaultPicture === $sUserPicture) - { + if ($sUserDefaultPicture === $sUserPicture) { $sAdditionalClass = ' ibo-is-active'; } $sUserPicturePlaceHolderHtml .= ' '; @@ -475,7 +481,7 @@ $('[data-role="ibo-preferences--user-preferences--picture-placeholder--image"]') }); }); JS -); + ); $sUserPicturePlaceHolderHtml .= << @@ -486,8 +492,7 @@ HTML $oContentLayout->AddMainBlock($oUserPicturePlaceHolderBlock); /** @var iPreferencesExtension $oLoginExtensionInstance */ - foreach (MetaModel::EnumPlugins('iPreferencesExtension') as $oPreferencesExtensionInstance) - { + foreach (MetaModel::EnumPlugins('iPreferencesExtension') as $oPreferencesExtensionInstance) { $oPreferencesExtensionInstance->DisplayPreferences($oP); } @@ -505,7 +510,7 @@ HTML function GetLanguageFieldBlock(): iUIBlock { $aAvailableLanguages = Dict::GetLanguages(); - $aSortedLanguages = array(); + $aSortedLanguages = []; foreach ($aAvailableLanguages as $sCode => $aLang) { if (MetaModel::GetConfig()->Get('demo_mode') && ($sCode !== Dict::GetUserLanguage())) { // Demo mode: only the current user language is listed in the available choices @@ -584,10 +589,12 @@ function GetTabsLayoutFieldBlock(): iUIBlock ]; $oSelect = SelectUIBlockFactory::MakeForSelectWithLabel('tab_layout', Dict::S('UI:Preferences:Tabs:Layout:Label')); foreach ($aOptionsValues as $sValue) { - $oSelect->AddSubBlock(SelectOptionUIBlockFactory::MakeForSelectOption( - $sValue, - Dict::S('UI:Preferences:Tabs:Layout:'.ucfirst($sValue)), - $sValue === $sCurrentValue) + $oSelect->AddSubBlock( + SelectOptionUIBlockFactory::MakeForSelectOption( + $sValue, + Dict::S('UI:Preferences:Tabs:Layout:'.ucfirst($sValue)), + $sValue === $sCurrentValue + ) ); } @@ -612,10 +619,12 @@ function GetTabsNavigationFieldBlock(): iUIBlock ]; $oSelect = SelectUIBlockFactory::MakeForSelectWithLabel('tab_scrollable', Dict::S('UI:Preferences:Tabs:Scrollable:Label')); foreach ($aOptionsValues as $sValue => $sDictEntrySuffix) { - $oSelect->AddSubBlock(SelectOptionUIBlockFactory::MakeForSelectOption( - $sValue, - Dict::S('UI:Preferences:Tabs:Scrollable:'.$sDictEntrySuffix), - $sValue === $sCurrentValueAsString) + $oSelect->AddSubBlock( + SelectOptionUIBlockFactory::MakeForSelectOption( + $sValue, + Dict::S('UI:Preferences:Tabs:Scrollable:'.$sDictEntrySuffix), + $sValue === $sCurrentValueAsString + ) ); } @@ -680,7 +689,6 @@ HTML; return new Html($sHtml); } - /** * @return \Combodo\iTop\Application\UI\Base\iUIBlock * @throws \CoreException @@ -719,7 +727,7 @@ function GetToastsPositionFieldBlock(): iUIBlock $sPosition = appUserPreferences::GetPref('toasts_vertical_position', "bottom"); $oSelect = SelectUIBlockFactory::MakeForSelectWithLabel('toasts_vertical_position', Dict::S('UI:Preferences:General:Toasts')); - + $oSelect->AddSubBlock(SelectOptionUIBlockFactory::MakeForSelectOption("bottom", Dict::S('UI:Preferences:General:Toasts:Bottom'), $sPosition === "bottom")); $oSelect->AddSubBlock(SelectOptionUIBlockFactory::MakeForSelectOption("top", Dict::S('UI:Preferences:General:Toasts:Top'), $sPosition === "top")); @@ -756,7 +764,7 @@ try { case 'apply': $oFilter = DBObjectSearch::FromOQL('SELECT Organization'); $sSelectionMode = utils::ReadParam('selectionMode', ''); - $aExceptions = utils::ReadParam('storedSelection', array()); + $aExceptions = utils::ReadParam('storedSelection', []); if (($sSelectionMode == 'negative') && (count($aExceptions) == 0)) { // All Orgs selected appUserPreferences::SetPref('favorite_orgs', null); @@ -818,17 +826,17 @@ try { // - Obsolete data $bShowObsoleteData = (bool)utils::ReadParam('show_obsolete_data', 0); appUserPreferences::SetPref('show_obsolete_data', $bShowObsoleteData); - + // - Summary cards $bShowSummaryCards = (bool)utils::ReadParam('show_summary_cards', 0); appUserPreferences::SetPref('show_summary_cards', $bShowSummaryCards); // - Toast notifications $sToastsVerticalPosition = utils::ReadParam('toasts_vertical_position', "bottom"); - if(utils::IsNotNullOrEmptyString($sToastsVerticalPosition) && in_array($sToastsVerticalPosition, ["bottom", "top"], true)) { + if (utils::IsNotNullOrEmptyString($sToastsVerticalPosition) && in_array($sToastsVerticalPosition, ["bottom", "top"], true)) { appUserPreferences::SetPref('toasts_vertical_position', $sToastsVerticalPosition); } - + // Redirect to force a reload/display of the page in case language has been changed $oAppContext = new ApplicationContext(); $sURL = utils::GetAbsoluteUrlAppRoot().'pages/preferences.php?'.$oAppContext->GetForLink(); @@ -855,7 +863,6 @@ try { break; case 'apply_newsroom_preferences': - $iCountProviders = 0; $oUser = UserRights::GetUserObject(); /** @var iNewsroomProvider[] $aProviders */ @@ -882,29 +889,25 @@ try { } } $bProvidersModified = false; - foreach ($aProviders as $cProvider) - { + foreach ($aProviders as $cProvider) { // Forbid disabling internal newsroom provider if ($cProvider === iTopNewsroomProvider::class) { continue; } $oProvider = new $cProvider(); - if ($oProvider->IsApplicable($oUser)) - { + if ($oProvider->IsApplicable($oUser)) { $sProviderClass = get_class($oProvider); $bProviderEnabled = (utils::ReadParam('newsroom_provider_'.$sProviderClass, 'off') == 'on'); $bCurrentValue = appUserPreferences::GetPref('newsroom_provider_'.$sProviderClass, true); - if ($bCurrentValue != $bProviderEnabled) - { + if ($bCurrentValue != $bProviderEnabled) { // Save the preference only if it differs from the current value $bProvidersModified = true; appUserPreferences::SetPref('newsroom_provider_'.$sProviderClass, $bProviderEnabled); } } } - if ($bProvidersModified) - { + if ($bProvidersModified) { $oPage->add_ready_script( <<SetBreadCrumbEntry('ui-tool-preferences', Dict::S('UI:Preferences'), Dict::S('UI:Preferences'), '', - 'fas fa-user-cog', iTopWebPage::ENUM_BREADCRUMB_ENTRY_ICON_TYPE_CSS_CLASSES); + $oPage->SetBreadCrumbEntry( + 'ui-tool-preferences', + Dict::S('UI:Preferences'), + Dict::S('UI:Preferences'), + '', + 'fas fa-user-cog', + iTopWebPage::ENUM_BREADCRUMB_ENTRY_ICON_TYPE_CSS_CLASSES + ); DisplayPreferences($oPage); } } - + $oPage->output(); -} -catch(CoreException $e) -{ +} catch (CoreException $e) { require_once(APPROOT.'/setup/setuppage.class.inc.php'); $oP = new ErrorPage(Dict::S('UI:PageTitle:FatalError')); - $oP->add("

".Dict::S('UI:FatalErrorMessage')."

\n"); - $oP->error(Dict::Format('UI:Error_Details', $e->getHtmlDesc())); + $oP->add("

".Dict::S('UI:FatalErrorMessage')."

\n"); + $oP->error(Dict::Format('UI:Error_Details', $e->getHtmlDesc())); $oP->output(); - if (MetaModel::IsLogEnabledIssue()) - { - if (MetaModel::IsValidClass('EventIssue')) - { + if (MetaModel::IsLogEnabledIssue()) { + if (MetaModel::IsValidClass('EventIssue')) { $oLog = new EventIssue(); $oLog->Set('message', $e->getMessage()); @@ -953,19 +958,15 @@ catch(CoreException $e) // For debugging only //throw $e; -} -catch(Exception $e) -{ +} catch (Exception $e) { require_once(APPROOT.'/setup/setuppage.class.inc.php'); $oP = new ErrorPage(Dict::S('UI:PageTitle:FatalError')); - $oP->add("

".Dict::S('UI:FatalErrorMessage')."

\n"); - $oP->error(Dict::Format('UI:Error_Details', $e->getMessage())); + $oP->add("

".Dict::S('UI:FatalErrorMessage')."

\n"); + $oP->error(Dict::Format('UI:Error_Details', $e->getMessage())); $oP->output(); - if (MetaModel::IsLogEnabledIssue()) - { - if (MetaModel::IsValidClass('EventIssue')) - { + if (MetaModel::IsLogEnabledIssue()) { + if (MetaModel::IsValidClass('EventIssue')) { $oLog = new EventIssue(); $oLog->Set('message', $e->getMessage()); @@ -973,7 +974,7 @@ catch(Exception $e) $oLog->Set('issue', 'PHP Exception'); $oLog->Set('impact', 'Page could not be displayed'); $oLog->Set('callstack', $e->getTrace()); - $oLog->Set('data', array()); + $oLog->Set('data', []); $oLog->DBInsertNoReload(); } diff --git a/pages/run_query.php b/pages/run_query.php index 40f83eb25..9177b6ff7 100644 --- a/pages/run_query.php +++ b/pages/run_query.php @@ -1,4 +1,5 @@ array( + $aExamples = [ + 'Pedagogic examples' => [ "Person" => "SELECT Person", "Person having an 'A' in their name" => "SELECT Person AS B WHERE B.name LIKE '%A%'", "Organization having a name beginning by 'My'" => "SELECT Organization WHERE name REGEXP '^My .*$'", "Changes planned on new year's day" => "SELECT Change AS ch WHERE ch.start_date >= '2009-12-31' AND ch.end_date <= '2010-01-01'", "IPs in a range" => "SELECT DatacenterDevice AS dev WHERE INET_ATON(dev.managementip) > INET_ATON('10.22.32.224') AND INET_ATON(dev.managementip) < INET_ATON('10.22.32.255')", "Persons below a given root organization" => "SELECT Person AS P JOIN Organization AS Node ON P.org_id = Node.id JOIN Organization AS Root ON Node.parent_id BELOW Root.id WHERE Root.id=1", - ), - 'Usefull examples' => array( + ], + 'Usefull examples' => [ "NW interfaces of equipment in production for customer 'Demo'" => "SELECT PhysicalInterface AS if JOIN DatacenterDevice AS dev ON if.connectableci_id = dev.id WHERE dev.status = 'production' AND dev.organization_name = 'Demo'", "My tickets" => "SELECT Ticket AS t WHERE t.agent_id = :current_contact_id", "People being owner of an active ticket" => "SELECT Person AS p JOIN UserRequest AS u ON u.agent_id = p.id WHERE u.status != 'closed'", "Contracts terminating in the next thirty days" => "SELECT Contract AS c WHERE c.end_date > NOW() AND c.end_date < DATE_ADD(NOW(), INTERVAL 30 DAY)", "Orphan tickets (opened one hour ago, still not assigned)" => "SELECT UserRequest AS u WHERE u.start_date < DATE_SUB(NOW(), INTERVAL 60 MINUTE) AND u.status = 'new'", "Long lasting incidents (duration > 8 hours)" => "SELECT UserRequest AS u WHERE u.close_date > DATE_ADD(u.start_date, INTERVAL 8 HOUR)", - ), - ); + ], + ]; - $aDisplayData = array(); + $aDisplayData = []; $oAppContext = new ApplicationContext(); $sContext = $oAppContext->GetForForm(); foreach ($aExamples as $sTopic => $aQueries) { @@ -81,23 +82,23 @@ function ShowExamples($oP, $sExpression) $oFormButton->AddSubBlock($oButton); $oFormButton->AddSubBlock(new Html($sContext)); //$aDisplayData[$sTopic][] = array( - $aDisplayData[Dict::S('UI:RunQuery:QueryExamples')][] = array( + $aDisplayData[Dict::S('UI:RunQuery:QueryExamples')][] = [ 'desc' => "
".utils::EscapeHtml($sDescription)."
", 'oql' => "
".utils::EscapeHtml($sOql)."
", 'go' => BlockRenderer::RenderBlockTemplates($oFormButton), - ); + ]; } } - $aDisplayConfig = array(); - $aDisplayConfig['desc'] = array( + $aDisplayConfig = []; + $aDisplayConfig['desc'] = [ 'label' => Dict::S('UI:RunQuery:HeaderPurpose'), 'description' => Dict::S('UI:RunQuery:HeaderPurpose+'), - ); - $aDisplayConfig['oql'] = array( + ]; + $aDisplayConfig['oql'] = [ 'label' => Dict::S('UI:RunQuery:HeaderOQLExpression'), 'description' => Dict::S('UI:RunQuery:HeaderOQLExpression+'), - ); - $aDisplayConfig['go'] = array('label' => '', 'description' => ''); + ]; + $aDisplayConfig['go'] = ['label' => '', 'description' => '']; foreach ($aDisplayData as $sTopic => $aQueriesDisplayData) { $bShowOpened = $bUsingExample; @@ -120,8 +121,7 @@ $sEncoding = utils::ReadParam('encoding', 'oql'); ShowExamples($oP, $sExpression); -try -{ +try { if ($sEncoding == 'crypted') { // Translate $sExpression into a oql expression $oFilter = DBObjectSearch::unserialize($sExpression); @@ -129,32 +129,23 @@ try } $oFilter = null; - $aArgs = array(); + $aArgs = []; $sSyntaxError = null; - if (!empty($sExpression)) - { - try - { + if (!empty($sExpression)) { + try { $oFilter = DBObjectSearch::FromOQL($sExpression); - } - catch(Exception $e) - { - if ($e instanceof OqlException) - { + } catch (Exception $e) { + if ($e instanceof OqlException) { $sSyntaxError = $e->getHtmlDesc(); - } - else - { + } else { $sSyntaxError = $e->getMessage(); } } - if ($oFilter) - { - $aArgs = array(); - foreach($oFilter->GetQueryParams() as $sParam => $foo) - { + if ($oFilter) { + $aArgs = []; + foreach ($oFilter->GetQueryParams() as $sParam => $foo) { $value = utils::ReadParam('arg_'.$sParam, null, true, 'raw_data'); if (!is_null($value)) { $aArgs[$sParam] = $value; @@ -180,7 +171,8 @@ try $oQueryTextArea->AddCSSClasses(['ibo-input-text', 'ibo-query-oql', 'ibo-is-code']); $oQueryForm->AddSubBlock($oQueryTextArea); - $oP->add_ready_script(<<add_ready_script( + << 0) { //--- Query arguments $oQueryForm->AddSubBlock(TitleUIBlockFactory::MakeNeutral(Dict::S('UI:RunQuery:QueryArguments'), 3)->AddCSSClass("ibo-collapsible-section--title")); - $oQueryArgsContainer = UIContentBlockUIBlockFactory::MakeStandard(null,['wizContainer']); + $oQueryArgsContainer = UIContentBlockUIBlockFactory::MakeStandard(null, ['wizContainer']); $oQueryForm->AddSubBlock($oQueryArgsContainer); foreach ($aArgs as $sParam => $sValue) { - $oInput = InputUIBlockFactory::MakeStandard("text",'arg_'.$sParam, $sValue); - $oArgInput = \Combodo\iTop\Application\UI\Base\Component\Field\FieldUIBlockFactory::MakeFromObject($sParam,$oInput,Field::ENUM_FIELD_LAYOUT_SMALL); + $oInput = InputUIBlockFactory::MakeStandard("text", 'arg_'.$sParam, $sValue); + $oArgInput = \Combodo\iTop\Application\UI\Base\Component\Field\FieldUIBlockFactory::MakeFromObject($sParam, $oInput, Field::ENUM_FIELD_LAYOUT_SMALL); $oArgInput->AddCSSClass("ibo-field--label-small"); //$oArgInput = InputUIBlockFactory::MakeForInputWithLabel( $sParam, 'arg_'.$sParam, $sValue ); $oQueryArgsContainer->AddSubBlock($oArgInput); @@ -216,10 +208,9 @@ JS $oQueryForm->AddSubBlock($oToolbarButtons); $oToolbarButtons->AddSubBlock($oQuerySubmit); - if ($oFilter) { //--- Query filter - $oPanelResult= PanelUIBlockFactory::MakeWithBrandingSecondaryColor(Dict::S('UI:RunQuery:QueryResults')); + $oPanelResult = PanelUIBlockFactory::MakeWithBrandingSecondaryColor(Dict::S('UI:RunQuery:QueryResults')); $oP->AddSubBlock($oPanelResult); $oResultBlock = new DisplayBlock($oFilter, 'list', false); $oPanelResult->AddSubBlock($oResultBlock->GetDisplay($oP, 'runquery')); @@ -228,10 +219,10 @@ JS //$iCount = $oResultBlock->GetDisplayedCount(); $sPageId = "ui-search-".$oFilter->GetClass(); $sLabel = MetaModel::GetName($oFilter->GetClass()); - $aArgs = array(); + $aArgs = []; foreach (array_merge($_POST, $_GET) as $sKey => $value) { if (is_array($value)) { - $aItems = array(); + $aItems = []; foreach ($value as $sItemKey => $sItemValue) { $aArgs[] = $sKey.'['.$sItemKey.']='.urlencode($sItemValue); } @@ -242,7 +233,6 @@ JS $sUrl = utils::GetAbsoluteUrlAppRoot().'pages/run_query.php?'.implode('&', $aArgs); $oP->SetBreadCrumbEntry($sPageId, $sLabel, $oFilter->ToOQL(true), $sUrl, 'fas fa-terminal', iTopWebPage::ENUM_BREADCRUMB_ENTRY_ICON_TYPE_CSS_CLASSES); - //--- More info $aMoreInfoBlocks = []; @@ -254,14 +244,13 @@ JS $oSerializedQuerySet->AddSubBlock(UIContentBlockUIBlockFactory::MakeForCode($oFilter->serialize())); $aMoreInfoBlocks[] = $oSerializedQuerySet; - $aModifierProperties = MetaModel::MakeModifierProperties($oFilter); // Avoid adding all the fields for counts or "group by" requests - $aCountAttToLoad = array(); + $aCountAttToLoad = []; $sMainClass = null; foreach ($oFilter->GetSelectedClasses() as $sClassAlias => $sClass) { - $aCountAttToLoad[$sClassAlias] = array(); + $aCountAttToLoad[$sClassAlias] = []; if (empty($sMainClass)) { $sMainClass = $sClass; } @@ -279,7 +268,7 @@ JS } // SQL Count - $sSQL = $oFilter->MakeSelectQuery(array(), $aRealArgs, $aCountAttToLoad, null, 0, 0, true); + $sSQL = $oFilter->MakeSelectQuery([], $aRealArgs, $aCountAttToLoad, null, 0, 0, true); $oCountResultQuerySet = new FieldSet(Dict::S('UI:RunQuery:ResultSQLCount')); $oCountResultQuerySet->AddSubBlock(UIContentBlockUIBlockFactory::MakeForCode($sSQL)); $aMoreInfoBlocks[] = $oCountResultQuerySet; @@ -324,13 +313,13 @@ JS $sEscapedExpression = json_encode(utils::EscapeHtml($sFixedExpression)); $oUseSuggestedQueryButton = ButtonUIBlockFactory::MakeForDestructiveAction('Use this query'); $oUseSuggestedQueryButton->SetOnClickJsCode( -<<AddSubBlock($oUseSuggestedQueryButton); + $oSyntaxErrorPanel->AddSubBlock($oUseSuggestedQueryButton); } else { $oSyntaxErrorPanel->AddSubBlock(HtmlFactory::MakeParagraph($e->getHtmlDesc())); } @@ -341,8 +330,7 @@ JS $oSyntaxErrorPanel->AddSubBlock(HtmlFactory::MakeParagraph($e->getMessage())); } } -} -catch (Exception $e) { +} catch (Exception $e) { $oErrorAlert = AlertUIBlockFactory::MakeForFailure( Dict::Format('UI:RunQuery:Error', $e->getMessage()), '
'.$e->getTraceAsString().'
' @@ -352,4 +340,3 @@ catch (Exception $e) { } $oP->output(); - diff --git a/pages/tagadmin.php b/pages/tagadmin.php index 53f88111b..7a4e65fb5 100644 --- a/pages/tagadmin.php +++ b/pages/tagadmin.php @@ -1,4 +1,5 @@ SetBreadCrumbEntry('ui-tool-tag-admin', Dict::S('Menu:TagAdminMenu'), Dict::S('Menu:TagAdminMenu+'), '', 'fas fa-tags', iTopWebPage::ENUM_BREADCRUMB_ENTRY_ICON_TYPE_CSS_CLASSES); $sSearchHeaderForceDropdown = '\n"; - try - { - if ($sOperation == 'search_form') - { + try { + if ($sOperation == 'search_form') { $sOQL = "SELECT $sClass $sOQLClause"; $oFilter = DBObjectSearch::FromOQL($sOQL); - } - else - { + } else { // Second part: advanced search form: - if (!empty($sFilter)) - { + if (!empty($sFilter)) { $oFilter = DBSearch::unserialize($sFilter); - } - else if (!empty($sClass)) - { + } elseif (!empty($sClass)) { $oFilter = new DBObjectSearch($sClass); } } - } - catch (CoreException $e) - { + } catch (CoreException $e) { $oFilter = new DBObjectSearch($sClass); $oP->P("".Dict::Format('UI:TagSetFieldData:Error', $e->getHtmlDesc()).""); } - if (!empty($oFilter)) - { + if (!empty($oFilter)) { $oSearchContext = new ContextTag(ContextTag::TAG_OBJECT_SEARCH); $oSet = new CMDBObjectSet($oFilter); @@ -120,9 +107,7 @@ try // Menu node $sFilter = $oFilter->ToOQL(); $oP->add("\n\n"); - } - else - { + } else { $oP->add("

"); $oP->add(Dict::S('UI:TagAdminMenu:NoTags')); $oP->add("

"); @@ -130,9 +115,7 @@ try $oP->add("
\n"); $oP->output(); -} -catch (Exception $e) -{ +} catch (Exception $e) { require_once(APPROOT.'setup/setuppage.class.inc.php'); $oP = new ErrorPage(Dict::S('UI:PageTitle:FatalError')); diff --git a/setup/applicationinstaller.class.inc.php b/setup/applicationinstaller.class.inc.php index 0c52898e0..ca6293565 100644 --- a/setup/applicationinstaller.class.inc.php +++ b/setup/applicationinstaller.class.inc.php @@ -1,4 +1,5 @@ oParams->Get('target_env', ''); - if ($sTargetEnvironment !== '') - { + if ($sTargetEnvironment !== '') { return $sTargetEnvironment; } @@ -100,17 +100,12 @@ class ApplicationInstaller $sStep = ''; $sStepLabel = ''; $iOverallStatus = self::OK; - do - { - if ($bVerbose) - { - if ($sStep != '') - { + do { + if ($bVerbose) { + if ($sStep != '') { echo "$sStepLabel\n"; echo "Executing '$sStep'\n"; - } - else - { + } else { echo "Starting the installation...\n"; } } @@ -118,11 +113,9 @@ class ApplicationInstaller $sStep = $aRes['next-step']; $sStepLabel = $aRes['next-step-label']; $sMessage = $aRes['message']; - if ($bVerbose) - { - switch ($aRes['status']) - { - case self::OK; + if ($bVerbose) { + switch ($aRes['status']) { + case self::OK: echo "Ok. ".$aRes['percentage-completed']." % done.\n"; break; @@ -142,11 +135,8 @@ class ApplicationInstaller echo $aRes['percentage-completed']." % done.\n"; break; } - } - else - { - switch ($aRes['status']) - { + } else { + switch ($aRes['status']) { case self::ERROR: $iOverallStatus = self::ERROR; break; @@ -155,8 +145,7 @@ class ApplicationInstaller break; } } - } - while(($aRes['status'] != self::ERROR) && ($aRes['next-step'] != '')); + } while (($aRes['status'] != self::ERROR) && ($aRes['next-step'] != '')); return ($iOverallStatus == self::OK); } @@ -167,8 +156,7 @@ class ApplicationInstaller $sConfigFile = APPCONF.$sTargetEnvironment.'/'.ITOP_CONFIG_FILE; try { $oConfig = new Config($sConfigFile); - } - catch (Exception $e) { + } catch (Exception $e) { return null; } @@ -189,21 +177,19 @@ class ApplicationInstaller */ public function ExecuteStep($sStep = '', $sInstallComment = null) { - try - { + try { $fStart = microtime(true); SetupLog::Info("##### STEP {$sStep} start"); $this->EnterReadOnlyMode(); - switch ($sStep) - { + switch ($sStep) { case '': - $aResult = array( + $aResult = [ 'status' => self::OK, 'message' => '', 'percentage-completed' => 0, 'next-step' => 'copy', 'next-step-label' => 'Copying data model files', - ); + ]; // Log the parameters... $oDoc = new DOMDocument('1.0', 'UTF-8'); @@ -217,8 +203,7 @@ class ApplicationInstaller // Save the response file as a stand-alone file as well $sFileName = 'install-'.date('Y-m-d'); $index = 0; - while (file_exists(APPROOT.'log/'.$sFileName.'.xml')) - { + while (file_exists(APPROOT.'log/'.$sFileName.'.xml')) { $index++; $sFileName = 'install-'.date('Y-m-d').'-'.$index; } @@ -233,18 +218,15 @@ class ApplicationInstaller self::DoCopy($aCopies); $sReport = "Copying..."; - $aResult = array( + $aResult = [ 'status' => self::OK, 'message' => $sReport, - ); - if (isset($aPreinstall['backup'])) - { + ]; + if (isset($aPreinstall['backup'])) { $aResult['next-step'] = 'backup'; $aResult['next-step-label'] = 'Performing a backup of the database'; $aResult['percentage-completed'] = 20; - } - else - { + } else { $aResult['next-step'] = 'compile'; $aResult['next-step-label'] = 'Compiling the data model'; $aResult['percentage-completed'] = 20; @@ -262,13 +244,13 @@ class ApplicationInstaller $sMySQLBinDir = $this->oParams->Get('mysql_bindir', null); self::DoBackup($oTempConfig, $sDestination, $sSourceConfigFile, $sMySQLBinDir); - $aResult = array( + $aResult = [ 'status' => self::OK, 'message' => "Created backup", 'next-step' => 'compile', 'next-step-label' => 'Compiling the data model', 'percentage-completed' => 20, - ); + ]; break; case 'compile': @@ -277,7 +259,7 @@ class ApplicationInstaller $sExtensionDir = $this->oParams->Get('extensions_dir', 'extensions'); $sTargetEnvironment = $this->GetTargetEnv(); $sTargetDir = $this->GetTargetDir(); - $aMiscOptions = $this->oParams->Get('options', array()); + $aMiscOptions = $this->oParams->Get('options', []); $bUseSymbolicLinks = null; if ((isset($aMiscOptions['symlinks']) && $aMiscOptions['symlinks'])) { @@ -290,36 +272,49 @@ class ApplicationInstaller } $aParamValues = $this->oParams->GetParamForConfigArray(); - self::DoCompile($aSelectedModules, $sSourceDir, $sExtensionDir, $sTargetDir, $sTargetEnvironment, - $bUseSymbolicLinks, $aParamValues); + self::DoCompile( + $aSelectedModules, + $sSourceDir, + $sExtensionDir, + $sTargetDir, + $sTargetEnvironment, + $bUseSymbolicLinks, + $aParamValues + ); - $aResult = array( + $aResult = [ 'status' => self::OK, 'message' => '', 'next-step' => 'db-schema', 'next-step-label' => 'Updating database schema', 'percentage-completed' => 40, - ); + ]; break; case 'db-schema': - $aSelectedModules = $this->oParams->Get('selected_modules', array()); + $aSelectedModules = $this->oParams->Get('selected_modules', []); $sTargetEnvironment = $this->GetTargetEnv(); $sTargetDir = $this->GetTargetDir(); $aParamValues = $this->oParams->GetParamForConfigArray(); $bOldAddon = $this->oParams->Get('old_addon', false); $sUrl = $this->oParams->Get('url', ''); - self::DoUpdateDBSchema($aSelectedModules, $sTargetDir, $aParamValues, $sTargetEnvironment, - $bOldAddon, $sUrl); + self::DoUpdateDBSchema( + $aSelectedModules, + $sTargetDir, + $aParamValues, + $sTargetEnvironment, + $bOldAddon, + $sUrl + ); - $aResult = array( + $aResult = [ 'status' => self::OK, 'message' => '', 'next-step' => 'after-db-create', 'next-step-label' => 'Creating profiles', 'percentage-completed' => 60, - ); + ]; break; case 'after-db-create': @@ -330,19 +325,27 @@ class ApplicationInstaller $sAdminUser = $aAdminParams['user']; $sAdminPwd = $aAdminParams['pwd']; $sAdminLanguage = $aAdminParams['language']; - $aSelectedModules = $this->oParams->Get('selected_modules', array()); + $aSelectedModules = $this->oParams->Get('selected_modules', []); $bOldAddon = $this->oParams->Get('old_addon', false); - self::AfterDBCreate($sTargetDir, $aParamValues, $sAdminUser, $sAdminPwd, $sAdminLanguage, - $aSelectedModules, $sTargetEnvironment, $bOldAddon); + self::AfterDBCreate( + $sTargetDir, + $aParamValues, + $sAdminUser, + $sAdminPwd, + $sAdminLanguage, + $aSelectedModules, + $sTargetEnvironment, + $bOldAddon + ); - $aResult = array( + $aResult = [ 'status' => self::OK, 'message' => '', 'next-step' => 'load-data', 'next-step-label' => 'Loading data', 'percentage-completed' => 80, - ); + ]; break; case 'load-data': @@ -353,16 +356,22 @@ class ApplicationInstaller $bOldAddon = $this->oParams->Get('old_addon', false); $bSampleData = ($this->oParams->Get('sample_data', 0) == 1); - self::DoLoadFiles($aSelectedModules, $sTargetDir, $aParamValues, $sTargetEnvironment, $bOldAddon, - $bSampleData); + self::DoLoadFiles( + $aSelectedModules, + $sTargetDir, + $aParamValues, + $sTargetEnvironment, + $bOldAddon, + $bSampleData + ); - $aResult = array( + $aResult = [ 'status' => self::INFO, 'message' => 'All data loaded', 'next-step' => 'create-config', 'next-step-label' => 'Creating the configuration File', 'percentage-completed' => 99, - ); + ]; break; case 'create-config': @@ -371,51 +380,56 @@ class ApplicationInstaller $sPreviousConfigFile = $this->oParams->Get('previous_configuration_file', ''); $sDataModelVersion = $this->oParams->Get('datamodel_version', '0.0.0'); $bOldAddon = $this->oParams->Get('old_addon', false); - $aSelectedModuleCodes = $this->oParams->Get('selected_modules', array()); - $aSelectedExtensionCodes = $this->oParams->Get('selected_extensions', array()); + $aSelectedModuleCodes = $this->oParams->Get('selected_modules', []); + $aSelectedExtensionCodes = $this->oParams->Get('selected_extensions', []); $aParamValues = $this->oParams->GetParamForConfigArray(); - self::DoCreateConfig($sTargetDir, $sPreviousConfigFile, $sTargetEnvironment, $sDataModelVersion, - $bOldAddon, $aSelectedModuleCodes, $aSelectedExtensionCodes, $aParamValues, $sInstallComment); + self::DoCreateConfig( + $sTargetDir, + $sPreviousConfigFile, + $sTargetEnvironment, + $sDataModelVersion, + $bOldAddon, + $aSelectedModuleCodes, + $aSelectedExtensionCodes, + $aParamValues, + $sInstallComment + ); - $aResult = array( + $aResult = [ 'status' => self::INFO, 'message' => 'Configuration file created', 'next-step' => '', 'next-step-label' => 'Completed', 'percentage-completed' => 100, - ); + ]; $this->ExitReadOnlyMode(); break; - default: - $aResult = array( + $aResult = [ 'status' => self::ERROR, 'message' => '', 'next-step' => '', 'next-step-label' => "Unknown setup step '$sStep'.", 'percentage-completed' => 100, - ); + ]; break; } - } - catch (Exception $e) - { - $aResult = array( + } catch (Exception $e) { + $aResult = [ 'status' => self::ERROR, 'message' => $e->getMessage(), 'next-step' => '', 'next-step-label' => '', 'percentage-completed' => 100, - ); + ]; SetupLog::Error('An exception occurred: '.$e->getMessage().' at line '.$e->getLine().' in file '.$e->getFile()); $idx = 0; // Log the call stack, but not the parameters since they may contain passwords or other sensitive data SetupLog::Ok("Call stack:"); - foreach ($e->getTrace() as $aTrace) - { + foreach ($e->getTrace() as $aTrace) { $sLine = empty($aTrace['line']) ? "" : $aTrace['line']; $sFile = empty($aTrace['file']) ? "" : $aTrace['file']; $sClass = empty($aTrace['class']) ? "" : $aTrace['class']; @@ -425,9 +439,7 @@ class ApplicationInstaller SetupLog::Ok("#$idx $sFile($sLine): $sVerb(...)"); $idx++; } - } - finally - { + } finally { $fDuration = round(microtime(true) - $fStart, 2); SetupLog::Info("##### STEP {$sStep} duration: {$fDuration}s"); } @@ -437,13 +449,11 @@ class ApplicationInstaller private function EnterReadOnlyMode() { - if ($this->GetTargetEnv() != 'production') - { + if ($this->GetTargetEnv() != 'production') { return; } - if (SetupUtils::IsInReadOnlyMode()) - { + if (SetupUtils::IsInReadOnlyMode()) { return; } @@ -452,25 +462,21 @@ class ApplicationInstaller private function ExitReadOnlyMode() { - if ($this->GetTargetEnv() != 'production') - { + if ($this->GetTargetEnv() != 'production') { return; } - if (!SetupUtils::IsInReadOnlyMode()) - { + if (!SetupUtils::IsInReadOnlyMode()) { return; } SetupUtils::ExitReadOnlyMode(); } - protected static function DoCopy($aCopies) { - $aReports = array(); - foreach ($aCopies as $aCopy) - { + $aReports = []; + foreach ($aCopies as $aCopy) { $sSource = $aCopy['source']; $sDestination = APPROOT.$aCopy['destination']; @@ -479,12 +485,9 @@ class ApplicationInstaller SetupUtils::copydir($sSource, $sDestination); $aReports[] = "'{$aCopy['source']}' to '{$aCopy['destination']}' (OK)"; } - if (count($aReports) > 0) - { + if (count($aReports) > 0) { $sReport = "Copies: ".count($aReports).': '.implode('; ', $aReports); - } - else - { + } else { $sReport = "No file copy"; } return $sReport; @@ -513,7 +516,6 @@ class ApplicationInstaller $oBackup->CreateCompressedBackup($sTargetFile, $sSourceConfigFile); } - /** * @param array $aSelectedModules * @param string $sSourceDir @@ -542,28 +544,24 @@ class ApplicationInstaller } $sSourcePath = APPROOT.$sSourceDir; - $aDirsToScan = array($sSourcePath); + $aDirsToScan = [$sSourcePath]; $sExtensionsPath = APPROOT.$sExtensionDir; - if (is_dir($sExtensionsPath)) - { + if (is_dir($sExtensionsPath)) { // if the extensions dir exists, scan it for additional modules as well $aDirsToScan[] = $sExtensionsPath; } $sExtraPath = APPROOT.'/data/'.$sEnvironment.'-modules/'; - if (is_dir($sExtraPath)) - { + if (is_dir($sExtraPath)) { // if the extra dir exists, scan it for additional modules as well $aDirsToScan[] = $sExtraPath; } $sTargetPath = APPROOT.$sTargetDir; - if (!is_dir($sSourcePath)) - { + if (!is_dir($sSourcePath)) { throw new Exception("Failed to find the source directory '$sSourcePath', please check the rights of the web server"); } $bIsAlreadyInMaintenanceMode = SetupUtils::IsInMaintenanceMode(); - if (($sEnvironment == 'production') && !$bIsAlreadyInMaintenanceMode) - { + if (($sEnvironment == 'production') && !$bIsAlreadyInMaintenanceMode) { $sConfigFilePath = utils::GetConfigFilePath($sEnvironment); if (is_file($sConfigFilePath)) { $oConfig = new Config($sConfigFilePath); @@ -578,21 +576,15 @@ class ApplicationInstaller SetupUtils::EnterMaintenanceMode($oConfig); } - if (!is_dir($sTargetPath)) - { - if (!mkdir($sTargetPath)) - { + if (!is_dir($sTargetPath)) { + if (!mkdir($sTargetPath)) { throw new Exception("Failed to create directory '$sTargetPath', please check the rights of the web server"); - } - else - { + } else { // adjust the rights if and only if the directory was just created // owner:rwx user/group:rx chmod($sTargetPath, 0755); } - } - else if (substr($sTargetPath, 0, strlen(APPROOT)) == APPROOT) - { + } elseif (substr($sTargetPath, 0, strlen(APPROOT)) == APPROOT) { // If the directory is under the root folder - as expected - let's clean-it before compiling SetupUtils::tidydir($sTargetPath); } @@ -603,25 +595,21 @@ class ApplicationInstaller $oFactory->LoadModule($oDictModule); $sDeltaFile = APPROOT.'core/datamodel.core.xml'; - if (file_exists($sDeltaFile)) - { + if (file_exists($sDeltaFile)) { $oCoreModule = new MFCoreModule('core', 'Core Module', $sDeltaFile); $oFactory->LoadModule($oCoreModule); } $sDeltaFile = APPROOT.'application/datamodel.application.xml'; - if (file_exists($sDeltaFile)) - { + if (file_exists($sDeltaFile)) { $oApplicationModule = new MFCoreModule('application', 'Application Module', $sDeltaFile); $oFactory->LoadModule($oApplicationModule); } $aModules = $oFactory->FindModules(); - foreach($aModules as $oModule) - { + foreach ($aModules as $oModule) { $sModule = $oModule->GetName(); - if (in_array($sModule, $aSelectedModules)) - { + if (in_array($sModule, $aSelectedModules)) { $oFactory->LoadModule($oModule); } } @@ -629,8 +617,7 @@ class ApplicationInstaller $oFactory->SaveToFile(utils::GetDataPath().'datamodel-'.$sEnvironment.'.xml'); $sDeltaFile = utils::GetDataPath().$sEnvironment.'.delta.xml'; - if (file_exists($sDeltaFile)) - { + if (file_exists($sDeltaFile)) { $oDelta = new MFDeltaModule($sDeltaFile); $oFactory->LoadModule($oDelta); $oFactory->SaveToFile(utils::GetDataPath().'datamodel-'.$sEnvironment.'-with-delta.xml'); @@ -648,8 +635,7 @@ class ApplicationInstaller // Special case to patch a ugly patch in itop-config-mgmt $sFileToPatch = $sTargetPath.'/itop-config-mgmt-1.0.0/model.itop-config-mgmt.php'; - if (file_exists($sFileToPatch)) - { + if (file_exists($sFileToPatch)) { $sContent = file_get_contents($sFileToPatch); $sContent = str_replace("require_once(APPROOT.'modules/itop-welcome-itil/model.itop-welcome-itil.php');", "//\n// The line below is no longer needed in iTop 2.0 -- patched by the setup program\n// require_once(APPROOT.'modules/itop-welcome-itil/model.itop-welcome-itil.php');", $sContent); @@ -660,13 +646,11 @@ class ApplicationInstaller // Set an "Instance UUID" identifying this machine based on a file located in the data directory $sInstanceUUIDFile = utils::GetDataPath().'instance.txt'; SetupUtils::builddir(utils::GetDataPath()); - if (!file_exists($sInstanceUUIDFile)) - { + if (!file_exists($sInstanceUUIDFile)) { $sIntanceUUID = utils::CreateUUID('filesystem'); file_put_contents($sInstanceUUIDFile, $sIntanceUUID); } - if (($sEnvironment == 'production') && !$bIsAlreadyInMaintenanceMode) - { + if (($sEnvironment == 'production') && !$bIsAlreadyInMaintenanceMode) { SetupUtils::ExitMaintenanceMode(); } } @@ -698,8 +682,7 @@ class ApplicationInstaller $oConfig = new Config(); $oConfig->UpdateFromParams($aParamValues, $sModulesDir); - if ($bOldAddon) - { + if ($bOldAddon) { // Old version of the add-on for backward compatibility with pre-2.0 data models $oConfig->SetAddons([]); } @@ -715,39 +698,32 @@ class ApplicationInstaller // priv_internalUser caused troubles because MySQL transforms table names to lower case under Windows // This becomes an issue when moving your installation data to/from Windows // Starting 2.0, all table names must be lowercase - if ($sMode != 'install') - { + if ($sMode != 'install') { SetupLog::Info("Renaming '{$sDBPrefix}priv_internalUser' into '{$sDBPrefix}priv_internaluser' (lowercase)"); // This command will have no effect under Windows... // and it has been written in two steps so as to make it work under windows! CMDBSource::SelectDB($sDBName); - try - { + try { $sRepair = "RENAME TABLE `{$sDBPrefix}priv_internalUser` TO `{$sDBPrefix}priv_internaluser_other`, `{$sDBPrefix}priv_internaluser_other` TO `{$sDBPrefix}priv_internaluser`"; CMDBSource::Query($sRepair); - } - catch (Exception $e) - { + } catch (Exception $e) { SetupLog::Info("Renaming '{$sDBPrefix}priv_internalUser' failed (already done in a previous upgrade?)"); } // let's remove the records in priv_change which have no counterpart in priv_changeop SetupLog::Info("Cleanup of '{$sDBPrefix}priv_change' to remove orphan records"); CMDBSource::SelectDB($sDBName); - try - { + try { $sTotalCount = "SELECT COUNT(*) FROM `{$sDBPrefix}priv_change`"; $iTotalCount = (int)CMDBSource::QueryToScalar($sTotalCount); SetupLog::Info("There is a total of $iTotalCount records in {$sDBPrefix}priv_change."); $sOrphanCount = "SELECT COUNT(c.id) FROM `{$sDBPrefix}priv_change` AS c left join `{$sDBPrefix}priv_changeop` AS o ON c.id = o.changeid WHERE o.id IS NULL"; $iOrphanCount = (int)CMDBSource::QueryToScalar($sOrphanCount); - SetupLog::Info("There are $iOrphanCount useless records in {$sDBPrefix}priv_change (".sprintf('%.2f', ((100.0*$iOrphanCount)/$iTotalCount))."%)"); - if ($iOrphanCount > 0) - { + SetupLog::Info("There are $iOrphanCount useless records in {$sDBPrefix}priv_change (".sprintf('%.2f', ((100.0 * $iOrphanCount) / $iTotalCount))."%)"); + if ($iOrphanCount > 0) { //N°3793 - if ($iOrphanCount > 100000) - { + if ($iOrphanCount > 100000) { SetupLog::Info("There are too much useless records ($iOrphanCount) in {$sDBPrefix}priv_change. Cleanup cannot be done during setup."); } else { SetupLog::Info("Removing the orphan records..."); @@ -755,14 +731,10 @@ class ApplicationInstaller CMDBSource::Query($sCleanup); SetupLog::Info("Cleanup completed successfully."); } - } - else - { + } else { SetupLog::Info("Ok, nothing to cleanup."); } - } - catch (Exception $e) - { + } catch (Exception $e) { SetupLog::Info("Cleanup of orphan records in `{$sDBPrefix}priv_change` failed: ".$e->getMessage()); } @@ -773,15 +745,13 @@ class ApplicationInstaller $aAvailableModules = $oProductionEnv->AnalyzeInstallation(MetaModel::GetConfig(), APPROOT.$sModulesDir); $oProductionEnv->CallInstallerHandlers($aAvailableModules, $aSelectedModules, 'BeforeDatabaseCreation'); - if(!$oProductionEnv->CreateDatabaseStructure(MetaModel::GetConfig(), $sMode)) - { + if (!$oProductionEnv->CreateDatabaseStructure(MetaModel::GetConfig(), $sMode)) { throw new Exception("Failed to create/upgrade the database structure for environment '$sTargetEnvironment'"); } // Set a DBProperty with a unique ID to identify this instance of iTop $sUUID = DBProperty::GetProperty('database_uuid', ''); - if ($sUUID === '') - { + if ($sUUID === '') { $sUUID = utils::CreateUUID('database'); DBProperty::SetProperty('database_uuid', $sUUID, 'Installation/upgrade of '.ITOP_APPLICATION, 'Unique ID of this '.ITOP_APPLICATION.' Database'); } @@ -790,12 +760,10 @@ class ApplicationInstaller // Let's initialize the field with 'interactive' for all records were it's null // Then check if some records should hold a different value, based on a pattern matching in the userinfo field CMDBSource::SelectDB($sDBName); - try - { + try { $sCount = "SELECT COUNT(*) FROM `{$sDBPrefix}priv_change` WHERE `origin` IS NULL"; $iCount = (int)CMDBSource::QueryToScalar($sCount); - if ($iCount > 0) - { + if ($iCount > 0) { SetupLog::Info("Initializing '{$sDBPrefix}priv_change.origin' ($iCount records to update)"); // By default all uninitialized values are considered as 'interactive' @@ -810,13 +778,11 @@ class ApplicationInstaller $sInit = "UPDATE `{$sDBPrefix}priv_change` SET `origin` = 'csv-interactive' WHERE `userinfo` LIKE '%(CSV)' AND origin = 'interactive'"; CMDBSource::Query($sInit); - // Syncho data sources were identified by the comment at the end // Unfortunately the comment is localized, so we have to search for all possible patterns $sCurrentLanguage = Dict::GetUserLanguage(); - $aSuffixes = array(); - foreach(array_keys(Dict::GetLanguages()) as $sLangCode) - { + $aSuffixes = []; + foreach (array_keys(Dict::GetLanguages()) as $sLangCode) { Dict::SetUserLanguage($sLangCode); $sSuffix = CMDBSource::Quote('%'.Dict::S('Core:SyncDataExchangeComment')); $aSuffixes[$sSuffix] = true; @@ -828,26 +794,20 @@ class ApplicationInstaller CMDBSource::Query($sInit); SetupLog::Info("Initialization of '{$sDBPrefix}priv_change.origin' completed."); - } - else - { + } else { SetupLog::Info("'{$sDBPrefix}priv_change.origin' already initialized, nothing to do."); } - } - catch (Exception $e) - { + } catch (Exception $e) { SetupLog::Error("Initializing '{$sDBPrefix}priv_change.origin' failed: ".$e->getMessage()); } // priv_async_task now has a 'status' field to distinguish between the various statuses rather than just relying on the date columns // Let's initialize the field with 'planned' or 'error' for all records were it's null CMDBSource::SelectDB($sDBName); - try - { + try { $sCount = "SELECT COUNT(*) FROM `{$sDBPrefix}priv_async_task` WHERE `status` IS NULL"; $iCount = (int)CMDBSource::QueryToScalar($sCount); - if ($iCount > 0) - { + if ($iCount > 0) { SetupLog::Info("Initializing '{$sDBPrefix}priv_async_task.status' ($iCount records to update)"); $sInit = "UPDATE `{$sDBPrefix}priv_async_task` SET `status` = 'planned' WHERE (`status` IS NULL) AND (`started` IS NULL)"; @@ -857,14 +817,10 @@ class ApplicationInstaller CMDBSource::Query($sInit); SetupLog::Info("Initialization of '{$sDBPrefix}priv_async_task.status' completed."); - } - else - { + } else { SetupLog::Info("'{$sDBPrefix}priv_async_task.status' already initialized, nothing to do."); } - } - catch (Exception $e) - { + } catch (Exception $e) { SetupLog::Error("Initializing '{$sDBPrefix}priv_async_task.status' failed: ".$e->getMessage()); } @@ -884,10 +840,15 @@ class ApplicationInstaller } protected static function AfterDBCreate( - $sModulesDir, $aParamValues, $sAdminUser, $sAdminPwd, $sAdminLanguage, $aSelectedModules, $sTargetEnvironment, + $sModulesDir, + $aParamValues, + $sAdminUser, + $sAdminPwd, + $sAdminLanguage, + $aSelectedModules, + $sTargetEnvironment, $bOldAddon - ) - { + ) { /** * @since 3.2.0 move the ContextTag init at the very beginning of the method * @noinspection PhpUnusedLocalVariableInspection @@ -899,8 +860,7 @@ class ApplicationInstaller $oConfig = new Config(); $oConfig->UpdateFromParams($aParamValues, $sModulesDir); - if ($bOldAddon) - { + if ($bOldAddon) { // Old version of the add-on for backward compatibility with pre-2.0 data models $oConfig->SetAddons([]); } @@ -917,14 +877,10 @@ class ApplicationInstaller $oProductionEnv->UpdatePredefinedObjects(); - if($sMode == 'install') - { - if (!self::CreateAdminAccount(MetaModel::GetConfig(), $sAdminUser, $sAdminPwd, $sAdminLanguage)) - { + if ($sMode == 'install') { + if (!self::CreateAdminAccount(MetaModel::GetConfig(), $sAdminUser, $sAdminPwd, $sAdminLanguage)) { throw(new Exception("Failed to create the administrator account '$sAdminUser'")); - } - else - { + } else { SetupLog::Info("Administrator account '$sAdminUser' created."); } } @@ -942,21 +898,21 @@ class ApplicationInstaller { SetupLog::Info('CreateAdminAccount'); - if (UserRights::CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage)) - { + if (UserRights::CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage)) { return true; - } - else - { + } else { return false; } } protected static function DoLoadFiles( - $aSelectedModules, $sModulesDir, $aParamValues, $sTargetEnvironment = 'production', $bOldAddon = false, + $aSelectedModules, + $sModulesDir, + $aParamValues, + $sTargetEnvironment = 'production', + $bOldAddon = false, $bSampleData = false - ) - { + ) { /** * @since 3.2.0 move the ContextTag init at the very beginning of the method * @noinspection PhpUnusedLocalVariableInspection @@ -966,8 +922,7 @@ class ApplicationInstaller $oConfig = new Config(); $oConfig->UpdateFromParams($aParamValues, $sModulesDir); - if ($bOldAddon) - { + if ($bOldAddon) { // Old version of the add-on for backward compatibility with pre-2.0 data models $oConfig->SetAddons([]); } @@ -975,8 +930,7 @@ class ApplicationInstaller $oProductionEnv = new RunTimeEnvironment($sTargetEnvironment); //Load the MetaModel if needed (asynchronous mode) - if (!self::$bMetaModelStarted) - { + if (!self::$bMetaModelStarted) { $oProductionEnv->InitDataModel($oConfig, false); // load data model and connect to the database self::$bMetaModelStarted = true; // No need to reload the final MetaModel in case the installer runs synchronously @@ -985,7 +939,7 @@ class ApplicationInstaller $aAvailableModules = $oProductionEnv->AnalyzeInstallation($oConfig, APPROOT.$sModulesDir); $oProductionEnv->LoadData($aAvailableModules, $aSelectedModules, $bSampleData); - // Perform after dbload setup tasks here + // Perform after dbload setup tasks here // $oProductionEnv->CallInstallerHandlers($aAvailableModules, $aSelectedModules, 'AfterDataLoad'); } @@ -1007,8 +961,15 @@ class ApplicationInstaller * @throws \Exception */ protected static function DoCreateConfig( - $sModulesDir, $sPreviousConfigFile, $sTargetEnvironment, $sDataModelVersion, $bOldAddon, $aSelectedModuleCodes, - $aSelectedExtensionCodes, $aParamValues, $sInstallComment = null + $sModulesDir, + $sPreviousConfigFile, + $sTargetEnvironment, + $sDataModelVersion, + $bOldAddon, + $aSelectedModuleCodes, + $aSelectedExtensionCodes, + $aParamValues, + $sInstallComment = null ) { /** * @since 3.2.0 move the ContextTag init at the very beginning of the method @@ -1020,22 +981,16 @@ class ApplicationInstaller $sMode = $aParamValues['mode']; $bPreserveModuleSettings = false; - if ($sMode == 'upgrade') - { - try - { + if ($sMode == 'upgrade') { + try { $oOldConfig = new Config($sPreviousConfigFile); $oConfig = clone($oOldConfig); $bPreserveModuleSettings = true; - } - catch(Exception $e) - { + } catch (Exception $e) { // In case the previous configuration is corrupted... start with a blank new one $oConfig = new Config(); } - } - else - { + } else { $oConfig = new Config(); // To preserve backward compatibility while upgrading to 2.0.3 (when tracking_level_linked_set_default has been introduced) // the default value on upgrade differs from the default value at first install @@ -1045,8 +1000,7 @@ class ApplicationInstaller $oConfig->Set('access_mode', ACCESS_FULL); // Final config update: add the modules $oConfig->UpdateFromParams($aParamValues, $sModulesDir, $bPreserveModuleSettings); - if ($bOldAddon) - { + if ($bOldAddon) { // Old version of the add-on for backward compatibility with pre-2.0 data models $oConfig->SetAddons([]); } @@ -1055,14 +1009,12 @@ class ApplicationInstaller $oProductionEnv = new RunTimeEnvironment($sTargetEnvironment); $oProductionEnv->InitDataModel($oConfig, true); // load data model and connect to the database - if (!$oProductionEnv->RecordInstallation($oConfig, $sDataModelVersion, $aSelectedModuleCodes, $aSelectedExtensionCodes, $sInstallComment)) - { + if (!$oProductionEnv->RecordInstallation($oConfig, $sDataModelVersion, $aSelectedModuleCodes, $aSelectedExtensionCodes, $sInstallComment)) { throw new Exception("Failed to record the installation information"); } // Make sure the root configuration directory exists - if (!file_exists(APPCONF)) - { + if (!file_exists(APPCONF)) { mkdir(APPCONF); chmod(APPCONF, 0770); // RWX for owner and group, nothing for others SetupLog::Info("Created configuration directory: ".APPCONF); diff --git a/setup/backup.class.inc.php b/setup/backup.class.inc.php index 3d02e0ebe..c2214f7d4 100644 --- a/setup/backup.class.inc.php +++ b/setup/backup.class.inc.php @@ -1,9 +1,10 @@ sDBSubName = $oConfig->get('db_subname'); } - /** * Create a normalized backup name, depending on the current date/time and Database * @@ -225,26 +222,23 @@ class DBBackup * * @param string $sSourceConfigFile * @param string $sTmpFolder - * @param bool $bSkipSQLDumpForTesting + * @param bool $bSkipSQLDumpForTesting * * @return array list of files to archive * @throws \Exception */ protected function PrepareFilesToBackup($sSourceConfigFile, $sTmpFolder, $bSkipSQLDumpForTesting = false) { - $aRet = array(); - if (is_dir($sTmpFolder)) - { + $aRet = []; + if (is_dir($sTmpFolder)) { SetupUtils::rrmdir($sTmpFolder); } $this->LogInfo("backup: creating tmp dir '$sTmpFolder'"); @mkdir($sTmpFolder, 0777, true); - if (is_null($sSourceConfigFile)) - { + if (is_null($sSourceConfigFile)) { $sSourceConfigFile = MetaModel::GetConfig()->GetLoadedFile(); } - if (!empty($sSourceConfigFile)) - { + if (!empty($sSourceConfigFile)) { $sFile = $sTmpFolder.'/config-itop.php'; $this->LogInfo("backup: adding resource '$sSourceConfigFile'"); @copy($sSourceConfigFile, $sFile); // During unattended install config file may be absent @@ -252,16 +246,14 @@ class DBBackup } $sDeltaFile = utils::GetDataPath().utils::GetCurrentEnvironment().'.delta.xml'; - if (file_exists($sDeltaFile)) - { + if (file_exists($sDeltaFile)) { $sFile = $sTmpFolder.'/delta.xml'; $this->LogInfo("backup: adding resource '$sDeltaFile'"); copy($sDeltaFile, $sFile); $aRet[] = $sFile; } $sExtraDir = utils::GetDataPath().utils::GetCurrentEnvironment().'-modules/'; - if (is_dir($sExtraDir)) - { + if (is_dir($sExtraDir)) { $sModules = utils::GetCurrentEnvironment().'-modules'; $sFile = $sTmpFolder.'/'.$sModules; $this->LogInfo("backup: adding resource '$sExtraDir'"); @@ -270,38 +262,31 @@ class DBBackup } $aExtraFiles = []; - if (MetaModel::GetConfig() !== null) // During unattended install config file may be absent - { + if (MetaModel::GetConfig() !== null) { // During unattended install config file may be absent $aExtraFiles = MetaModel::GetModuleSetting('itop-backup', 'extra_files', []); } - foreach (InterfaceDiscovery::GetInstance()->FindItopClasses(iBackupExtraFilesExtension::class) as $sExtensionClass) - { + foreach (InterfaceDiscovery::GetInstance()->FindItopClasses(iBackupExtraFilesExtension::class) as $sExtensionClass) { /** @var iBackupExtraFilesExtension $oExtensionInstance */ $oExtensionInstance = new $sExtensionClass(); $aExtraFiles = array_merge($aExtraFiles, $oExtensionInstance->GetExtraFilesRelPaths()); } - foreach($aExtraFiles as $sExtraFileOrDir) - { - if(!file_exists(APPROOT.'/'.$sExtraFileOrDir)) { + foreach ($aExtraFiles as $sExtraFileOrDir) { + if (!file_exists(APPROOT.'/'.$sExtraFileOrDir)) { continue; // Ignore non-existing files } $sExtraFullPath = utils::RealPath(APPROOT.'/'.$sExtraFileOrDir, APPROOT); - if ($sExtraFullPath === false) - { + if ($sExtraFullPath === false) { throw new Exception("Backup: Aborting, resource '$sExtraFileOrDir'. Considered as UNSAFE because not inside the iTop directory."); } - if (is_dir($sExtraFullPath)) - { + if (is_dir($sExtraFullPath)) { $sFile = $sTmpFolder.'/'.$sExtraFileOrDir; $this->LogInfo("backup: adding directory '$sExtraFileOrDir'"); SetupUtils::copydir($sExtraFullPath, $sFile); $aRet[] = $sFile; - } - elseif (file_exists($sExtraFullPath)) - { + } elseif (file_exists($sExtraFullPath)) { $sFile = $sTmpFolder.'/'.$sExtraFileOrDir; $this->LogInfo("backup: adding file '$sExtraFileOrDir'"); @mkdir(dirname($sFile), 0755, true); @@ -309,8 +294,7 @@ class DBBackup $aRet[] = $sFile; } } - if (!$bSkipSQLDumpForTesting) - { + if (!$bSkipSQLDumpForTesting) { $sDataFile = $sTmpFolder.'/itop-dump.sql'; $this->DoBackup($sDataFile); $aRet[] = $sDataFile; @@ -344,19 +328,16 @@ class DBBackup $this->DBConnect(); $sTables = ''; - if ($this->sDBSubName != '') - { + if ($this->sDBSubName != '') { // This instance of iTop uses a prefix for the tables, so there may be other tables in the database // Let's explicitely list all the tables and views to dump $aTables = $this->EnumerateTables(); - if (count($aTables) == 0) - { + if (count($aTables) == 0) { // No table has been found with the given prefix throw new BackupException("No table has been found with the given prefix"); } - $aEscapedTables = array(); - foreach ($aTables as $sTable) - { + $aEscapedTables = []; + foreach ($aTables as $sTable) { $aEscapedTables[] = self::EscapeShellArg($sTable); } $sTables = implode(' ', $aEscapedTables); @@ -391,39 +372,32 @@ EOF; file_put_contents($sMySQLDumpCnfFile, $sMySQLDumpCnf, LOCK_EX); // Note: opt implicitly sets lock-tables... which cancels the benefit of single-transaction! - // skip-lock-tables compensates and allows for writes during a backup - $sCommand = "$sMySQLDump --defaults-extra-file=\"$sMySQLDumpCnfFile\" --opt --skip-lock-tables --default-character-set=" . $sMysqldumpCharset . " --add-drop-database --single-transaction --host=$sHost $sPortAndTransportOptions --user=$sUser $sTlsOptions --result-file=$sTmpFileName $sDBName $sTables 2>&1"; - $sCommandDisplay = "$sMySQLDump --defaults-extra-file=\"$sMySQLDumpCnfFile\" --opt --skip-lock-tables --default-character-set=" . $sMysqldumpCharset . " --add-drop-database --single-transaction --host=$sHost $sPortAndTransportOptions --user=xxxxx $sTlsOptions --result-file=$sTmpFileName $sDBName $sTables"; + // skip-lock-tables compensates and allows for writes during a backup + $sCommand = "$sMySQLDump --defaults-extra-file=\"$sMySQLDumpCnfFile\" --opt --skip-lock-tables --default-character-set=".$sMysqldumpCharset." --add-drop-database --single-transaction --host=$sHost $sPortAndTransportOptions --user=$sUser $sTlsOptions --result-file=$sTmpFileName $sDBName $sTables 2>&1"; + $sCommandDisplay = "$sMySQLDump --defaults-extra-file=\"$sMySQLDumpCnfFile\" --opt --skip-lock-tables --default-character-set=".$sMysqldumpCharset." --add-drop-database --single-transaction --host=$sHost $sPortAndTransportOptions --user=xxxxx $sTlsOptions --result-file=$sTmpFileName $sDBName $sTables"; // Now run the command for real $this->LogInfo("backup: generate data file with command: $sCommandDisplay"); - $aOutput = array(); + $aOutput = []; $iRetCode = 0; exec($sCommand, $aOutput, $iRetCode); @unlink($sMySQLDumpCnfFile); - foreach ($aOutput as $sLine) - { + foreach ($aOutput as $sLine) { $this->LogInfo("mysqldump said: $sLine"); } - if ($iRetCode != 0) - { + if ($iRetCode != 0) { // Cleanup residual output (Happens with Error 2020: Got packet bigger than 'maxallowedpacket' bytes...) - if (file_exists($sBackupFileName)) - { + if (file_exists($sBackupFileName)) { unlink($sBackupFileName); } $this->LogError("Failed to execute: $sCommandDisplay. The command returned:$iRetCode"); - foreach ($aOutput as $sLine) - { + foreach ($aOutput as $sLine) { $this->LogError("mysqldump said: $sLine"); } - if (count($aOutput) == 1) - { + if (count($aOutput) == 1) { $sMoreInfo = trim($aOutput[0]); - } - else - { + } else { $sMoreInfo = "Check the log files 'log/setup.log' or 'log/error.log' for more information."; } throw new BackupException("Failed to execute mysqldump: ".$sMoreInfo); @@ -439,8 +413,7 @@ EOF; */ public function DownloadBackup($sFile) { - if (!file_exists($sFile)) - { + if (!file_exists($sFile)) { throw new InvalidParameterException('Invalid file path'); } @@ -473,25 +446,27 @@ EOF; $sTlsEnabled = $oConfig->Get('db_tls.enabled'); $sTlsCA = $oConfig->Get('db_tls.ca'); - try - { - $oMysqli = CMDBSource::GetMysqliInstance($sServer, $sUser, $sPwd, $sSource, $sTlsEnabled, $sTlsCA, - false); + try { + $oMysqli = CMDBSource::GetMysqliInstance( + $sServer, + $sUser, + $sPwd, + $sSource, + $sTlsEnabled, + $sTlsCA, + false + ); - if ($oMysqli->connect_errno) - { + if ($oMysqli->connect_errno) { $sHost = is_null($this->iDBPort) ? $this->sDBHost : $this->sDBHost.' on port '.$this->iDBPort; - throw new MySQLException('Could not connect to the DB server '.$oMysqli->connect_errno.' (mysql errno: '.$oMysqli->connect_error, array('host' => $sHost, 'user' => $sUser)); - } - if (!$oMysqli->select_db($this->sDBName)) - { + throw new MySQLException('Could not connect to the DB server '.$oMysqli->connect_errno.' (mysql errno: '.$oMysqli->connect_error, ['host' => $sHost, 'user' => $sUser]); + } + if (!$oMysqli->select_db($this->sDBName)) { throw new BackupException("The database '$this->sDBName' does not seem to exist"); } return $oMysqli; - } - catch (MySQLException $e) - { + } catch (MySQLException $e) { throw new BackupException($e->getMessage()); } } @@ -504,28 +479,22 @@ EOF; protected function EnumerateTables() { $oMysqli = $this->DBConnect(); - if ($this->sDBSubName != '') - { + if ($this->sDBSubName != '') { $oResult = $oMysqli->query("SHOW TABLES LIKE '{$this->sDBSubName}%'"); - } - else - { + } else { $oResult = $oMysqli->query("SHOW TABLES"); } - if (!$oResult) - { + if (!$oResult) { throw new BackupException("Failed to execute the SHOW TABLES query: ".$oMysqli->error); } - $aTables = array(); - while ($aRow = $oResult->fetch_row()) - { + $aTables = []; + while ($aRow = $oResult->fetch_row()) { $aTables[] = $aRow[0]; } return $aTables; } - /** * @param Config $oConfig * @@ -541,25 +510,18 @@ EOF; public static function GetMysqlCliTlsOptions($oConfig) { $bDbTlsEnabled = $oConfig->Get('db_tls.enabled'); - if (!$bDbTlsEnabled) - { + if (!$bDbTlsEnabled) { return ''; } $sTlsOptions = ''; // Mysql 5.7.11 and upper deprecated --ssl and uses --ssl-mode instead - if (CMDBSource::IsSslModeDBVersion()) - { - if(empty($oConfig->Get('db_tls.ca'))) - { + if (CMDBSource::IsSslModeDBVersion()) { + if (empty($oConfig->Get('db_tls.ca'))) { $sTlsOptions .= ' --ssl-mode=REQUIRED'; - } - else - { + } else { $sTlsOptions .= ' --ssl-mode=VERIFY_CA'; } - } - else - { + } else { $sTlsOptions .= ' --ssl'; } @@ -582,8 +544,7 @@ EOF; */ private static function GetMysqliCliSingleOption($sCliArgName, $sData) { - if (empty($sData)) - { + if (empty($sData)) { return ''; } @@ -613,7 +574,7 @@ EOF; $sPortOption = self::GetMysqliCliSingleOption('port', $iPort); $sTransportOptions = ' --protocol=tcp'; - return $sPortOption . $sTransportOptions; + return $sPortOption.$sTransportOptions; } if (is_null($iPort)) { @@ -632,8 +593,7 @@ EOF; { if (empty($sMySQLBinDir)) { $sMySQLCommand = $sCmd; - } - else { + } else { $sMySQLBinDir = escapeshellcmd($sMySQLBinDir); $sMySQLCommand = '"'.$sMySQLBinDir.'/$sCmd"'; if (!file_exists($sMySQLCommand)) { @@ -666,15 +626,12 @@ class TarGzArchive implements BackupArchive { // remove leading and tailing / $sFile = trim($sFile, "/ \t\n\r\0\x0B"); - if ($this->aFiles === null) - { + if ($this->aFiles === null) { // Initial load $this->buildFileList(); } - foreach ($this->aFiles as $aArchFile) - { - if ($aArchFile['filename'] == $sFile) - { + foreach ($this->aFiles as $aArchFile) { + if ($aArchFile['filename'] == $sFile) { return true; } } @@ -691,15 +648,12 @@ class TarGzArchive implements BackupArchive { // remove leading and tailing / $sDirectory = trim($sDirectory, "/ \t\n\r\0\x0B"); - if ($this->aFiles === null) - { + if ($this->aFiles === null) { // Initial load $this->buildFileList(); } - foreach ($this->aFiles as $aArchFile) - { - if (($aArchFile['typeflag'] == 5) && ($aArchFile['filename'] == $sDirectory)) - { + foreach ($this->aFiles as $aArchFile) { + if (($aArchFile['typeflag'] == 5) && ($aArchFile['filename'] == $sDirectory)) { return true; } } @@ -764,4 +718,3 @@ class TarGzArchive implements BackupArchive $this->aFiles = $this->oArchive->listContent(); } } - diff --git a/setup/compiler.class.inc.php b/setup/compiler.class.inc.php index 5a6ac60f7..918cf7f49 100644 --- a/setup/compiler.class.inc.php +++ b/setup/compiler.class.inc.php @@ -1,4 +1,5 @@ getLineNo().')'; - } - parent::__construct($message, $code, $previous); - } + /** + * Overrides the Exception default constructor to automatically add informations about the concerned node (path and + * line number) + * + * @param string $message + * @param $code + * @param $previous + * @param DesignElement|null $node DOMNode causing the DOMFormatException + */ + public function __construct($message, $code = 0, $previous = null, DesignElement $node = null) + { + if ($node !== null) { + $message .= ' ('.MFDocument::GetItopNodePath($node).' at line '.$node->getLineNo().')'; + } + parent::__construct($message, $code, $previous); + } } /** * Compiler class - */ + */ class MFCompiler { - const DATA_PRECOMPILED_FOLDER = 'data'.DIRECTORY_SEPARATOR.'precompiled_styles'.DIRECTORY_SEPARATOR; + public const DATA_PRECOMPILED_FOLDER = 'data'.DIRECTORY_SEPARATOR.'precompiled_styles'.DIRECTORY_SEPARATOR; /** * @var string @@ -108,7 +106,7 @@ class MFCompiler * @var string * @since 2.7.5 3.0.0 N°4020 */ - const REBUILD_HKEYS_NEVER = APPROOT.'data/.setup-rebuild-hkeys-never'; + public const REBUILD_HKEYS_NEVER = APPROOT.'data/.setup-rebuild-hkeys-never'; /** @var \ModelFactory */ protected $oFactory; @@ -316,31 +314,24 @@ class MFCompiler SetupUtils::builddir($sTempTargetDir); // Here is the directory } - try - { + try { $this->DoCompile($sTempTargetDir, $sFinalTargetDir, $oP = null, $bUseSymbolicLinks); - } - catch (Exception $e) - { - if ($sTempTargetDir != $sFinalTargetDir) - { + } catch (Exception $e) { + if ($sTempTargetDir != $sFinalTargetDir) { // Cleanup the temporary directory SetupUtils::rrmdir($sTempTargetDir); } - if (($this->sEnvironment == 'production') && !$bIsAlreadyInMaintenanceMode) - { + if (($this->sEnvironment == 'production') && !$bIsAlreadyInMaintenanceMode) { SetupUtils::ExitMaintenanceMode(); } throw $e; } - if ($sTempTargetDir != $sFinalTargetDir) - { + if ($sTempTargetDir != $sFinalTargetDir) { // Move the results to the target directory SetupUtils::movedir($sTempTargetDir, $sFinalTargetDir); } - if (($this->sEnvironment == 'production') && !$bIsAlreadyInMaintenanceMode) - { + if (($this->sEnvironment == 'production') && !$bIsAlreadyInMaintenanceMode) { SetupUtils::ExitMaintenanceMode(); } @@ -348,18 +339,15 @@ class MFCompiler // In case of bad luck (this happens **sometimes** - see N. 550), we may analyze the database structure // with the previous datamodel still loaded (in opcode cache) and thus fail to create the new fields // Finally the application crashes (because of the missing field) when the cache gets updated - if (function_exists('opcache_reset')) - { + if (function_exists('opcache_reset')) { // Zend opcode cache opcache_reset(); } - if (function_exists('apc_clear_cache')) - { + if (function_exists('apc_clear_cache')) { // old style APC apc_clear_cache(); } } - /** * Perform the actual "Compilation" of all modules @@ -371,15 +359,14 @@ class MFCompiler */ protected function DoCompile($sTempTargetDir, $sFinalTargetDir, $oP = null, $bUseSymbolicLinks = false) { - $aAllClasses = array(); // flat list of classes - $aModulesInfo = array(); // Hash array of module_name => array('version' => string, 'root_dir' => string) + $aAllClasses = []; // flat list of classes + $aModulesInfo = []; // Hash array of module_name => array('version' => string, 'root_dir' => string) // Determine the target modules for the MENUS // - $aMenuNodes = array(); - $aMenusByModule = array(); - foreach ($this->oFactory->GetNodes('menus/menu') as $oMenuNode) - { + $aMenuNodes = []; + $aMenusByModule = []; + foreach ($this->oFactory->GetNodes('menus/menu') as $oMenuNode) { $sMenuId = $oMenuNode->getAttribute('id'); $aMenuNodes[$sMenuId] = $oMenuNode; @@ -409,7 +396,7 @@ class MFCompiler // List root classes // - $this->aRootClasses = array(); + $this->aRootClasses = []; foreach ($this->oFactory->ListRootClasses() as $oClass) { $this->Log("Root class (with child classes): ".$oClass->getAttribute('id')); $this->aRootClasses[$oClass->getAttribute('id')] = $oClass; @@ -422,8 +409,8 @@ class MFCompiler // Compile, module by module // $aModules = $this->oFactory->GetLoadedModules(); - $aDataModelFiles = array(); - $aWebservicesFiles = array(); + $aDataModelFiles = []; + $aWebservicesFiles = []; $iStart = strlen(realpath(APPROOT)); $sRelFinalTargetDir = substr($sFinalTargetDir, strlen(APPROOT)); @@ -452,32 +439,26 @@ class MFCompiler $sRelativeDir = $sModuleName; $sRealRelativeDir = $sModuleName; } - $aModulesInfo[$sModuleName] = array('root_dir' => $sRealRelativeDir, 'version' => $sModuleVersion); + $aModulesInfo[$sModuleName] = ['root_dir' => $sRealRelativeDir, 'version' => $sModuleVersion]; $sCompiledCode = ''; $oConstants = $this->oFactory->ListConstants($sModuleName); - if ($oConstants->length > 0) - { - foreach($oConstants as $oConstant) - { + if ($oConstants->length > 0) { + foreach ($oConstants as $oConstant) { $sCompiledCode .= $this->CompileConstant($oConstant)."\n"; } } $oEvents = $this->oFactory->ListEvents($sModuleName); - if ($oEvents->length > 0) - { - foreach($oEvents as $oEvent) - { + if ($oEvents->length > 0) { + foreach ($oEvents as $oEvent) { $sCompiledCode .= $this->CompileEvent($oEvent, $sModuleName)."\n"; } } - if (array_key_exists($sModuleName, $this->aSnippets)) - { - foreach( $this->aSnippets[$sModuleName]['before'] as $aSnippet) - { + if (array_key_exists($sModuleName, $this->aSnippets)) { + foreach ($this->aSnippets[$sModuleName]['before'] as $aSnippet) { $sCompiledCode .= "\n"; $sCompiledCode .= "/**\n"; $sCompiledCode .= " * Snippet: {$aSnippet['snippet_id']}\n"; @@ -486,26 +467,18 @@ class MFCompiler } } - $oClasses = $this->oFactory->ListClasses($sModuleName); $iClassCount = $oClasses->length; - if ($iClassCount == 0) - { + if ($iClassCount == 0) { $this->Log("Found module without classes declared: $sModuleName"); - } - else - { + } else { /** @var \MFElement $oClass */ - foreach($oClasses as $oClass) - { + foreach ($oClasses as $oClass) { $sClass = $oClass->getAttribute("id"); $aAllClasses[] = $sClass; - try - { + try { $sCompiledCode .= $this->CompileClass($oClass, $sTempTargetDir, $sFinalTargetDir, $sRelativeDir); - } - catch (DOMFormatException $e) - { + } catch (DOMFormatException $e) { $sMessage = "Failed to process class '$sClass', "; if (!empty($sModuleRootDir)) { $sMessage .= "from '$sModuleRootDir': "; @@ -516,12 +489,9 @@ class MFCompiler } } - if (!array_key_exists($sModuleName, $aMenusByModule)) - { + if (!array_key_exists($sModuleName, $aMenusByModule)) { $this->Log("Found module without menus declared: $sModuleName"); - } - else - { + } else { $sMenuCreationClass = 'MenuCreation_'.preg_replace('/[^A-Za-z0-9_]/', '_', $sModuleName); $sCompiledCode .= <<GetId()}' (location : '$sModuleRootDir') contains an unknown menuId : '$sMenuId'"); } - if ($oMenuNode->getAttribute("xsi:type") == 'MenuGroup') - { + if ($oMenuNode->getAttribute("xsi:type") == 'MenuGroup') { // Note: this algorithm is wrong // 1 - the module may appear empty in the current module, while children are defined in other modules // 2 - check recursively that child nodes are not empty themselves @@ -573,43 +539,33 @@ EOF; // a- browse the modules and build the menu tree // b- browse the tree and blacklist empty menus // c- before compiling, discard if blacklisted - if (!in_array($oMenuNode->getAttribute("id"), $aParentMenus)) - { + if (!in_array($oMenuNode->getAttribute("id"), $aParentMenus)) { // Discard empty menu groups continue; } } - try - { + try { /** @var iTopWebPage $oP */ $aMenuLines = $this->CompileMenu($oMenuNode, $sTempTargetDir, $sFinalTargetDir, $sRelativeDir, $oP); - } - catch (DOMFormatException $e) - { + } catch (DOMFormatException $e) { throw new Exception("Failed to process menu '$sMenuId', from '$sModuleRootDir': ".$e->getMessage()); } $sParent = $oMenuNode->GetChildText('parent', null); - if (($oMenuNode->GetChildText('enable_admin_only') == '1') || isset($aAdminMenus[$sParent])) - { + if (($oMenuNode->GetChildText('enable_admin_only') == '1') || isset($aAdminMenus[$sParent])) { $aMenuLinesForAdmins = array_merge($aMenuLinesForAdmins, $aMenuLines); $aAdminMenus[$oMenuNode->getAttribute("id")] = true; - } - else - { + } else { $aMenuLinesForAll = array_merge($aMenuLinesForAll, $aMenuLines); } } $sIndent = "\t\t"; - foreach ($aMenuLinesForAll as $sPHPLine) - { + foreach ($aMenuLinesForAll as $sPHPLine) { $sCompiledCode .= $sIndent.$sPHPLine."\n"; } - if (count($aMenuLinesForAdmins) > 0) - { + if (count($aMenuLinesForAdmins) > 0) { $sCompiledCode .= $sIndent."if (UserRights::IsAdministrator())\n"; $sCompiledCode .= $sIndent."{\n"; - foreach ($aMenuLinesForAdmins as $sPHPLine) - { + foreach ($aMenuLinesForAdmins as $sPHPLine) { $sCompiledCode .= $sIndent."\t".$sPHPLine."\n"; } $sCompiledCode .= $sIndent."}\n"; @@ -624,15 +580,12 @@ EOF; // User rights // - if ($sModuleName == $sUserRightsModule) - { + if ($sModuleName == $sUserRightsModule) { $sCompiledCode .= $this->CompileUserRights($oUserRightsNode); } - if (array_key_exists($sModuleName, $this->aSnippets)) - { - foreach( $this->aSnippets[$sModuleName]['after'] as $aSnippet) - { + if (array_key_exists($sModuleName, $this->aSnippets)) { + foreach ($this->aSnippets[$sModuleName]['after'] as $aSnippet) { $sCompiledCode .= "\n"; $sCompiledCode .= "/**\n"; $sCompiledCode .= " * Snippet: {$aSnippet['snippet_id']}\n"; @@ -640,15 +593,13 @@ EOF; $sCompiledCode .= $aSnippet['content']."\n"; } } - + // Create (overwrite if existing) the compiled file // - if (strlen($sCompiledCode) > 0) - { + if (strlen($sCompiledCode) > 0) { // We have compiled something: write the code somewhere // - if (strlen($sModuleRootDir) > 0) - { + if (strlen($sModuleRootDir) > 0) { // Write the code into the given module as model..php // $sModelFileName = 'model.'.$sModuleName.'.php'; @@ -656,9 +607,7 @@ EOF; $this->WritePHPFile($sResultFile, $sModuleName, $sModuleVersion, $sCompiledCode); // In case the model file wasn't present in the module file, we're adding it ! (N°4875) $oModule->AddFileToInclude('business', $sModelFileName); - } - else - { + } else { // Write the code into core/main.php // $this->sMainPHPCode .= @@ -675,8 +624,7 @@ EOF; } // files to include (PHP datamodels) - foreach($oModule->GetFilesToInclude('business') as $sRelFileName) - { + foreach ($oModule->GetFilesToInclude('business') as $sRelFileName) { if (file_exists("{$sTempTargetDir}/{$sRelativeDir}/{$sRelFileName}")) { $aDataModelFiles[] = "MetaModel::IncludeModule(MODULESROOT.'/$sRelativeDir/$sRelFileName');"; } else { @@ -718,8 +666,7 @@ PHP; // Compile the dictionaries -out of the modules // $sDictDir = $sTempTargetDir.'/dictionaries'; - if (!is_dir($sDictDir)) - { + if (!is_dir($sDictDir)) { $this->Log("Creating directory $sDictDir"); mkdir($sDictDir, 0777, true); } @@ -733,10 +680,8 @@ PHP; $oBrandingNode = $this->oFactory->GetNodes('branding')->item(0); $this->CompileBranding($oBrandingNode, $sTempTargetDir, $sFinalTargetDir); - if (array_key_exists('_core_', $this->aSnippets)) - { - foreach( $this->aSnippets['_core_']['before'] as $aSnippet) - { + if (array_key_exists('_core_', $this->aSnippets)) { + foreach ($this->aSnippets['_core_']['before'] as $aSnippet) { $this->sMainPHPCode .= "\n"; $this->sMainPHPCode .= "/**\n"; $this->sMainPHPCode .= " * Snippet: {$aSnippet['snippet_id']}\n"; @@ -744,7 +689,7 @@ PHP; $this->sMainPHPCode .= $aSnippet['content']."\n"; } } - + // Compile the portals /** @var \MFElement $oPortalsNode */ $oPortalsNode = $this->oFactory->GetNodes('/itop_design/portals')->item(0); @@ -758,11 +703,9 @@ PHP; /** @var \MFElement $oParametersNode */ $oParametersNode = $this->oFactory->GetNodes('/itop_design/module_parameters')->item(0); $this->CompileParameters($oParametersNode, $sTempTargetDir, $sFinalTargetDir); - - if (array_key_exists('_core_', $this->aSnippets)) - { - foreach( $this->aSnippets['_core_']['after'] as $aSnippet) - { + + if (array_key_exists('_core_', $this->aSnippets)) { + foreach ($this->aSnippets['_core_']['after'] as $aSnippet) { $this->sMainPHPCode .= "\n"; $this->sMainPHPCode .= "/**\n"; $this->sMainPHPCode .= " * Snippet: {$aSnippet['snippet_id']}\n"; @@ -771,14 +714,12 @@ PHP; } } - if (count($this->aRelations) > 0) - { + if (count($this->aRelations) > 0) { $this->sMainPHPCode .= "\n"; $this->sMainPHPCode .= "/**\n"; $this->sMainPHPCode .= " * Relations\n"; $this->sMainPHPCode .= " */\n"; - foreach($this->aRelations as $sRelationCode => $aData) - { + foreach ($this->aRelations as $sRelationCode => $aData) { $sRelCodeSafe = addslashes($sRelationCode); $this->sMainPHPCode .= "MetaModel::RegisterRelation('$sRelCodeSafe');\n"; } @@ -792,7 +733,7 @@ PHP; $sCurrDate = date(DATE_ISO8601); // Autoload $sPHPFile = $sTempTargetDir.'/autoload.php'; - $sPHPFileContent = + $sPHPFileContent = << $value) - { - if (is_null($value)) - { + foreach ($aItems as $key => $value) { + if (is_null($value)) { $aTransformed[] = $key; - } - else - { - if (is_array($value)) - { + } else { + if (is_array($value)) { $this->ArrayOfItemsToZList($value); } $aTransformed[$key] = $value; @@ -848,29 +783,26 @@ EOF * Helper to format the flags for an attribute, in a given state * @param object $oAttNode DOM node containing the information to build the flags * Returns string PHP flags, based on the OPT_ATT_ constants, or empty (meaning 0, can be omitted) - */ + */ protected function FlagsToPHP($oAttNode) { - static $aNodeAttributeToFlag = array( + static $aNodeAttributeToFlag = [ 'mandatory' => 'OPT_ATT_MANDATORY', 'read_only' => 'OPT_ATT_READONLY', 'must_prompt' => 'OPT_ATT_MUSTPROMPT', 'must_change' => 'OPT_ATT_MUSTCHANGE', 'hidden' => 'OPT_ATT_HIDDEN', - ); - - $aFlags = array(); - foreach ($aNodeAttributeToFlag as $sNodeAttribute => $sFlag) - { + ]; + + $aFlags = []; + foreach ($aNodeAttributeToFlag as $sNodeAttribute => $sFlag) { $bFlag = ($oAttNode->GetOptionalElement($sNodeAttribute) != null); - if ($bFlag) - { + if ($bFlag) { $aFlags[] = $sFlag; } } - if (empty($aFlags)) - { - $aFlags[] = 'OPT_ATT_NORMAL'; // When no flag is defined, reset the state to "normal" + if (empty($aFlags)) { + $aFlags[] = 'OPT_ATT_NORMAL'; // When no flag is defined, reset the state to "normal" } $sRes = implode(' | ', $aFlags); return $sRes; @@ -886,31 +818,29 @@ EOF */ protected function TrackingLevelToPHP($sAttType, $sTrackingLevel) { - static $aXmlToPHP_Links = array( + static $aXmlToPHP_Links = [ 'none' => 'LINKSET_TRACKING_NONE', 'list' => 'LINKSET_TRACKING_LIST', 'details' => 'LINKSET_TRACKING_DETAILS', 'all' => 'LINKSET_TRACKING_ALL', - ); - - static $aXmlToPHP_Others = array( + ]; + + static $aXmlToPHP_Others = [ 'none' => 'ATTRIBUTE_TRACKING_NONE', 'all' => 'ATTRIBUTE_TRACKING_ALL', - ); + ]; - switch ($sAttType) - { - case 'AttributeLinkedSetIndirect': - case 'AttributeLinkedSet': - $aXmlToPHP = $aXmlToPHP_Links; - break; + switch ($sAttType) { + case 'AttributeLinkedSetIndirect': + case 'AttributeLinkedSet': + $aXmlToPHP = $aXmlToPHP_Links; + break; - default: - $aXmlToPHP = $aXmlToPHP_Others; + default: + $aXmlToPHP = $aXmlToPHP_Others; } - if (!array_key_exists($sTrackingLevel, $aXmlToPHP)) - { + if (!array_key_exists($sTrackingLevel, $aXmlToPHP)) { throw new DOMFormatException("Tracking level: unknown value '$sTrackingLevel', expecting a value in {".implode(', ', array_keys($aXmlToPHP))."}"); } return $aXmlToPHP[$sTrackingLevel]; @@ -926,22 +856,20 @@ EOF */ protected function EditModeToPHP($sEditMode) { - static $aXmlToPHP = array( + static $aXmlToPHP = [ 'none' => 'LINKSET_EDITMODE_NONE', 'add_only' => 'LINKSET_EDITMODE_ADDONLY', 'actions' => 'LINKSET_EDITMODE_ACTIONS', 'in_place' => 'LINKSET_EDITMODE_INPLACE', 'add_remove' => 'LINKSET_EDITMODE_ADDREMOVE', - ); - - if (!array_key_exists($sEditMode, $aXmlToPHP)) - { + ]; + + if (!array_key_exists($sEditMode, $aXmlToPHP)) { throw new DOMFormatException("Edit mode: unknown value '$sEditMode'"); } return $aXmlToPHP[$sEditMode]; } - /** * Helper to format the edit-when for direct linkset * @@ -952,55 +880,41 @@ EOF */ protected function EditWhenToPHP($sEditWhen): string { - static $aXmlToPHP = array( + static $aXmlToPHP = [ 'never' => 'LINKSET_EDITWHEN_NEVER', 'on_host_edition' => 'LINKSET_EDITWHEN_ON_HOST_EDITION', 'on_host_display' => 'LINKSET_EDITWHEN_ON_HOST_DISPLAY', 'always' => 'LINKSET_EDITWHEN_ALWAYS', - ); + ]; - if (!array_key_exists($sEditWhen, $aXmlToPHP)) - { + if (!array_key_exists($sEditWhen, $aXmlToPHP)) { throw new DOMFormatException("Edit mode: unknown value '$sEditWhen'"); } return $aXmlToPHP[$sEditWhen]; } - + /** * Format a path (file or url) as an absolute path or relative to the module or the app - */ + */ protected function PathToPHP($sPath, $sModuleRelativeDir, $bIsUrl = false) { - if ($sPath == '') - { + if ($sPath == '') { $sPHP = "''"; - } - elseif (substr($sPath, 0, 2) == '$$') - { + } elseif (substr($sPath, 0, 2) == '$$') { // Absolute $sPHP = self::QuoteForPHP(substr($sPath, 2)); - } - elseif (substr($sPath, 0, 1) == '$') - { + } elseif (substr($sPath, 0, 1) == '$') { // Relative to the application - if ($bIsUrl) - { + if ($bIsUrl) { $sPHP = "utils::GetAbsoluteUrlAppRoot().".self::QuoteForPHP(substr($sPath, 1)); - } - else - { + } else { $sPHP = "APPROOT.".self::QuoteForPHP(substr($sPath, 1)); } - } - else - { + } else { // Relative to the module - if ($bIsUrl) - { + if ($bIsUrl) { $sPHP = "utils::GetAbsoluteUrlModulePage('$sModuleRelativeDir', ".self::QuoteForPHP($sPath).")"; - } - else - { + } else { $sPHP = "__DIR__.'/$sPath'"; } } @@ -1020,14 +934,10 @@ EOF protected function GetPropString($oNode, string $sTag, string $sDefault = null, bool $bAddQuotes = true) { $val = $oNode->GetChildText($sTag); - if (is_null($val)) - { - if (is_null($sDefault)) - { + if (is_null($val)) { + if (is_null($sDefault)) { return null; - } - else - { + } else { $val = $sDefault; } } @@ -1050,18 +960,15 @@ EOF protected function GetMandatoryPropString($oNode, string $sTag, bool $bAddQuotes = true) { $val = $oNode->GetChildText($sTag); - if (!is_null($val) && ($val !== '')) - { + if (!is_null($val) && ($val !== '')) { if ($bAddQuotes) { return "'".$val."'"; } else { return $val; } - } - else - { + } else { throw new DOMFormatException("missing (or empty) mandatory tag '$sTag' under the tag '".$oNode->nodeName."'"); - } + } } /** @@ -1075,12 +982,10 @@ EOF { $sValue = $this->GetPropBoolean($oNode, $sTag, $bDefault); - if ($sValue == null) - { + if ($sValue == null) { return null; } - if ($sValue == 'true') - { + if ($sValue == 'true') { return true; } @@ -1098,14 +1003,10 @@ EOF protected function GetPropBoolean($oNode, $sTag, $bDefault = null) { $val = $oNode->GetChildText($sTag); - if (is_null($val)) - { - if (is_null($bDefault)) - { + if (is_null($val)) { + if (is_null($bDefault)) { return null; - } - else - { + } else { return $bDefault ? 'true' : 'false'; } } @@ -1122,8 +1023,7 @@ EOF protected function GetMandatoryPropBoolean($oNode, $sTag) { $val = $oNode->GetChildText($sTag); - if (is_null($val)) - { + if (is_null($val)) { throw new DOMFormatException("missing (or empty) mandatory tag '$sTag' under the tag '".$oNode->nodeName."'"); } return $val == 'true' ? 'true' : 'false'; @@ -1132,14 +1032,10 @@ EOF protected function GetPropNumber($oNode, $sTag, $nDefault = null) { $val = $oNode->GetChildText($sTag); - if (is_null($val)) - { - if (is_null($nDefault)) - { + if (is_null($val)) { + if (is_null($nDefault)) { return null; - } - else - { + } else { $val = $nDefault; } } @@ -1156,8 +1052,7 @@ EOF protected function GetMandatoryPropNumber($oNode, $sTag) { $val = $oNode->GetChildText($sTag); - if (is_null($val)) - { + if (is_null($val)) { throw new DOMFormatException("missing (or empty) mandatory tag '$sTag' under the tag '".$oNode->nodeName."'"); } return (string)$val; @@ -1165,18 +1060,15 @@ EOF /** * Adds quotes and escape characters - */ + */ protected function QuoteForPHP($sStr, $bSimpleQuotes = false) { $sStr = $sStr ?? ''; - if ($bSimpleQuotes) - { - $sEscaped = str_replace(array('\\', "'"), array('\\\\', "\\'"), $sStr); + if ($bSimpleQuotes) { + $sEscaped = str_replace(['\\', "'"], ['\\\\', "\\'"], $sStr); $sRet = "'$sEscaped'"; - } - else - { - $sEscaped = str_replace(array('\\', '"', "\n"), array('\\\\', '\\"', '\\n'), $sStr); + } else { + $sEscaped = str_replace(['\\', '"', "\n"], ['\\\\', '\\"', '\\n'], $sStr); $sRet = '"'.$sEscaped.'"'; } return $sRet; @@ -1250,7 +1142,6 @@ EOF $sOutput .= " )\n"; $sOutput .= ");\n"; - return $sOutput; } @@ -1260,47 +1151,37 @@ EOF $sType = $oConstant->getAttribute('xsi:type'); $sText = $oConstant->GetText(null); - switch ($sType) - { - case 'integer': - if (is_null($sText)) - { - // No data given => null - $sScalar = 'null'; - } - else - { - $sScalar = (string)(int)$sText; - } - break; - - case 'float': - if (is_null($sText)) - { - // No data given => null - $sScalar = 'null'; - } - else - { - $sScalar = (string)(float)$sText; - } - break; - - case 'bool': - if (is_null($sText)) - { - // No data given => null - $sScalar = 'null'; - } - else - { - $sScalar = ($sText == 'true') ? 'true' : 'false'; - } - break; + switch ($sType) { + case 'integer': + if (is_null($sText)) { + // No data given => null + $sScalar = 'null'; + } else { + $sScalar = (string)(int)$sText; + } + break; - case 'string': - default: - $sScalar = $this->QuoteForPHP($sText, true); + case 'float': + if (is_null($sText)) { + // No data given => null + $sScalar = 'null'; + } else { + $sScalar = (string)(float)$sText; + } + break; + + case 'bool': + if (is_null($sText)) { + // No data given => null + $sScalar = 'null'; + } else { + $sScalar = ($sText == 'true') ? 'true' : 'false'; + } + break; + + case 'string': + default: + $sScalar = $this->QuoteForPHP($sText, true); } $sPHPDefine = "define('$sName', $sScalar);"; return $sPHPDefine; @@ -1325,7 +1206,7 @@ EOF // Class characteristics // - $aClassParams = array(); + $aClassParams = []; $aClassParams['category'] = $this->GetPropString($oProperties, 'category', ''); $aClassParams['key_type'] = "'autoincrement'"; if ((bool)$this->GetPropNumber($oProperties, 'is_link', 0)) { @@ -1343,7 +1224,7 @@ EOF $oNameAttributes = $oNaming->GetUniqueElement('attributes'); /** @var \DOMNodeList $oAttributes */ $oAttributes = $oNameAttributes->getElementsByTagName('attribute'); - $aNameAttCodes = array(); + $aNameAttCodes = []; /** @var \MFElement $oAttribute */ foreach ($oAttributes as $oAttribute) { $aNameAttCodes[] = $oAttribute->getAttribute('id'); @@ -1357,7 +1238,7 @@ EOF if ($oComplementaryNameAttributes = $oNaming->GetOptionalElement('complementary_attributes')) { /** @var \DOMNodeList $oAttributes */ $oComplementaryAttributes = $oComplementaryNameAttributes->getElementsByTagName('attribute'); - $aComplementaryNameAttCodes = array(); + $aComplementaryNameAttCodes = []; /** @var \MFElement $oAttribute */ foreach ($oComplementaryAttributes as $oComplementaryAttribute) { $aComplementaryNameAttCodes[] = $oComplementaryAttribute->getAttribute('id'); @@ -1397,7 +1278,7 @@ EOF // Reconcialiation if ($oReconciliation = $oProperties->GetOptionalElement('reconciliation')) { $oReconcAttributes = $oReconciliation->getElementsByTagName('attribute'); - $aReconcAttCodes = array(); + $aReconcAttCodes = []; foreach ($oReconcAttributes as $oAttribute) { $aReconcAttCodes[] = $oAttribute->getAttribute('id'); } @@ -1430,12 +1311,11 @@ EOF $sCss .= $aClassStyleData['scss']; } - $oOrder = $oProperties->GetOptionalElement('order'); if ($oOrder) { $oColumnsNode = $oOrder->GetUniqueElement('columns'); $oColumns = $oColumnsNode->getElementsByTagName('column'); - $aSortColumns = array(); + $aSortColumns = []; foreach ($oColumns as $oColumn) { $aSortColumns[] = "'".$oColumn->getAttribute('id')."' => ".(($oColumn->getAttribute('ascending') == 'true') ? 'true' : 'false'); } @@ -1444,11 +1324,9 @@ EOF } } - if ($oIndexes = $oProperties->GetOptionalElement('indexes')) - { - $aIndexes = array(); - foreach($oIndexes->getElementsByTagName('index') as $oIndex) - { + if ($oIndexes = $oProperties->GetOptionalElement('indexes')) { + $aIndexes = []; + foreach ($oIndexes->getElementsByTagName('index') as $oIndex) { $sIndexId = $oIndex->getAttribute('id'); /** @var DesignElement $oAttributes */ $oAttributes = $oIndex->GetUniqueElement('attributes'); @@ -1492,8 +1370,7 @@ PHP; } } - if (!empty($sEvents)) - { + if (!empty($sEvents)) { $sMethods .= <<GetOptionalElement('uniqueness_rules')) { - $aUniquenessRules = array(); + $aUniquenessRules = []; /** @var \MFElement $oUniquenessSingleRule */ foreach ($oUniquenessRules->GetElementsByTagName('rule') as $oUniquenessSingleRule) { $sCurrentRuleId = $oUniquenessSingleRule->getAttribute('id'); $oAttributes = $oUniquenessSingleRule->GetUniqueElement('attributes', false); if ($oAttributes) { - $aUniquenessAttributes = array(); + $aUniquenessAttributes = []; foreach ($oAttributes->getElementsByTagName('attribute') as $oAttribute) { $aUniquenessAttributes[] = $oAttribute->getAttribute('id'); } @@ -1535,8 +1412,11 @@ EOF; $aUniquenessRules[$sCurrentRuleId]['filter'] = $oUniquenessSingleRule->GetChildText('filter'); $aUniquenessRules[$sCurrentRuleId]['disabled'] = $this->GetPropBooleanConverted($oUniquenessSingleRule, 'disabled', null); - $aUniquenessRules[$sCurrentRuleId]['is_blocking'] = $this->GetPropBooleanConverted($oUniquenessSingleRule, 'is_blocking', - null); + $aUniquenessRules[$sCurrentRuleId]['is_blocking'] = $this->GetPropBooleanConverted( + $oUniquenessSingleRule, + 'is_blocking', + null + ); } // we will check for rules validity later as for now we don't have objects hierarchy (see \MetaModel::InitClasses) @@ -1554,37 +1434,29 @@ EOF; // Fields // $oFields = $oClass->GetOptionalElement('fields'); - if ($oFields) - { + if ($oFields) { $this->CompileFiles($oFields, $sTempTargetDir.'/'.$sModuleRelativeDir, $sFinalTargetDir.'/'.$sModuleRelativeDir, ''); } $sAttributes = ''; - $aTagFieldsInfo = array(); + $aTagFieldsInfo = []; /** @var \DOMElement $oField */ - foreach($this->oFactory->ListFields($oClass) as $oField) - { - try - { + foreach ($this->oFactory->ListFields($oClass) as $oField) { + try { // $oField $sAttCode = $oField->getAttribute('id'); $sAttType = $oField->getAttribute('xsi:type'); - $aParameters = $this->CompileAttribute($sAttType, $oField, $sModuleRelativeDir, $sClass, $sAttCode, $sCss, $aTagFieldsInfo, $sTempTargetDir); - $aParams = array(); - foreach($aParameters as $sKey => $sValue) - { - if (!is_null($sValue)) - { + $aParams = []; + foreach ($aParameters as $sKey => $sValue) { + if (!is_null($sValue)) { $aParams[] = '"'.$sKey.'"=>'.$sValue; } } $sParams = implode(', ', $aParams); $sAttributes .= " MetaModel::Init_AddAttribute(new $sAttType(\"$sAttCode\", array($sParams)));\n"; - } - catch(Exception $e) - { + } catch (Exception $e) { throw new DOMFormatException("Field: '$sAttCode', (type: $sAttType), ".$e->getMessage()); } } @@ -1599,61 +1471,54 @@ EOF; $sLifecycle .= "\t\t//\n"; $oStimuli = $oLifecycle->GetUniqueElement('stimuli'); - foreach ($oStimuli->getElementsByTagName('stimulus') as $oStimulus) - { + foreach ($oStimuli->getElementsByTagName('stimulus') as $oStimulus) { $sStimulus = $oStimulus->getAttribute('id'); $sStimulusClass = $oStimulus->getAttribute('xsi:type'); $sLifecycle .= " MetaModel::Init_DefineStimulus(new ".$sStimulusClass."(\"".$sStimulus."\", array()));\n"; } $oHighlightScale = $oLifecycle->GetUniqueElement('highlight_scale', false); - if ($oHighlightScale) - { + if ($oHighlightScale) { $sHighlightScale = "\t\t// Higlight Scale\n"; $sHighlightScale .= " MetaModel::Init_DefineHighlightScale( array(\n"; $this->CompileFiles($oHighlightScale, $sTempTargetDir.'/'.$sModuleRelativeDir, $sFinalTargetDir.'/'.$sModuleRelativeDir, ''); - foreach ($oHighlightScale->getElementsByTagName('item') as $oItem) - { + foreach ($oHighlightScale->getElementsByTagName('item') as $oItem) { $sItemCode = $oItem->getAttribute('id'); $fRank = (float)$oItem->GetChildText('rank'); $sColor = $oItem->GetChildText('color'); - if (($sIcon = $oItem->GetChildText('icon')) && (strlen($sIcon) > 0)) - { + if (($sIcon = $oItem->GetChildText('icon')) && (strlen($sIcon) > 0)) { $sIcon = $sModuleRelativeDir.'/'.$sIcon; $sIcon = "utils::GetAbsoluteUrlModulesRoot().'$sIcon'"; - } - else - { + } else { $sIcon = "''"; } - switch($sColor) - { + switch ($sColor) { // Known PHP constants: keep the literal value as-is case 'HILIGHT_CLASS_CRITICAL': case 'HIGHLIGHT_CLASS_CRITICAL': - $sColor = 'HILIGHT_CLASS_CRITICAL'; - break; + $sColor = 'HILIGHT_CLASS_CRITICAL'; + break; case 'HILIGHT_CLASS_OK': case 'HIGHLIGHT_CLASS_OK': - $sColor = 'HILIGHT_CLASS_OK'; - break; + $sColor = 'HILIGHT_CLASS_OK'; + break; case 'HIGHLIGHT_CLASS_WARNING': case 'HILIGHT_CLASS_WARNING': - $sColor = 'HILIGHT_CLASS_WARNING'; - break; + $sColor = 'HILIGHT_CLASS_WARNING'; + break; case 'HIGHLIGHT_CLASS_NONE': case 'HILIGHT_CLASS_NONE': - $sColor = 'HILIGHT_CLASS_NONE'; - break; + $sColor = 'HILIGHT_CLASS_NONE'; + break; default: - // Future extension, specify your own color?? - $sColor = "'".addslashes($sColor)."'"; + // Future extension, specify your own color?? + $sColor = "'".addslashes($sColor)."'"; } $sHighlightScale .= " '$sItemCode' => array('rank' => $fRank, 'color' => $sColor, 'icon' => $sIcon),\n"; @@ -1662,62 +1527,48 @@ EOF; } $oStates = $oLifecycle->GetUniqueElement('states'); - $aStatesDependencies = array(); - $aStates = array(); - foreach ($oStates->getElementsByTagName('state') as $oState) - { + $aStatesDependencies = []; + $aStates = []; + foreach ($oStates->getElementsByTagName('state') as $oState) { $aStatesDependencies[$oState->getAttribute('id')] = $oState->GetChildText('inherit_flags_from', ''); $aStates[$oState->getAttribute('id')] = $oState; } - $aStatesOrder = array(); - while (count($aStatesOrder) < count($aStatesDependencies)) - { + $aStatesOrder = []; + while (count($aStatesOrder) < count($aStatesDependencies)) { $iResolved = 0; - foreach($aStatesDependencies as $sState => $sInheritFrom) - { - if (is_null($sInheritFrom)) - { + foreach ($aStatesDependencies as $sState => $sInheritFrom) { + if (is_null($sInheritFrom)) { // Already recorded as resolved continue; - } - elseif ($sInheritFrom == '') - { + } elseif ($sInheritFrom == '') { // Resolved $aStatesOrder[$sState] = $sInheritFrom; $aStatesDependencies[$sState] = null; $iResolved++; - } - elseif (isset($aStatesOrder[$sInheritFrom])) - { + } elseif (isset($aStatesOrder[$sInheritFrom])) { // Resolved $aStatesOrder[$sState] = $sInheritFrom; $aStatesDependencies[$sState] = null; $iResolved++; } } - if ($iResolved == 0) - { + if ($iResolved == 0) { // No change on this loop -> there are unmet dependencies - $aRemainingDeps = array(); - foreach($aStatesDependencies as $sState => $sParentState) - { - if (strlen($sParentState) > 0) - { + $aRemainingDeps = []; + foreach ($aStatesDependencies as $sState => $sParentState) { + if (strlen($sParentState) > 0) { $aRemainingDeps[] = $sState.' ('.$sParentState.')'; } } throw new DOMFormatException("Could not solve inheritance for states: ".implode(', ', $aRemainingDeps)); } } - foreach ($aStatesOrder as $sState => $foo) - { + foreach ($aStatesOrder as $sState => $foo) { $oState = $aStates[$sState]; $oInitialStatePath = $oState->GetOptionalElement('initial_state_path'); - if ($oInitialStatePath) - { - $aInitialStatePath = array(); - foreach ($oInitialStatePath->getElementsByTagName('state_ref') as $oIntermediateState) - { + if ($oInitialStatePath) { + $aInitialStatePath = []; + foreach ($oInitialStatePath->getElementsByTagName('state_ref') as $oIntermediateState) { $aInitialStatePath[] = "'".$oIntermediateState->GetText()."'"; } $sInitialStatePath = 'Array('.implode(', ', $aInitialStatePath).')'; @@ -1729,11 +1580,9 @@ EOF; $sAttributeInherit = $oState->GetChildText('inherit_flags_from', ''); $sLifecycle .= " \"attribute_inherit\" => '$sAttributeInherit',\n"; $oHighlight = $oState->GetUniqueElement('highlight', false); - if ($oHighlight) - { + if ($oHighlight) { $sCode = $oHighlight->GetChildText('code', ''); - if ($sCode != '') - { + if ($sCode != '') { $sLifecycle .= " 'highlight' => array('code' => '$sCode'),\n"; } @@ -1742,52 +1591,42 @@ EOF; $sLifecycle .= " \"attribute_list\" => array(\n"; $oFlags = $oState->GetUniqueElement('flags'); - foreach ($oFlags->getElementsByTagName('attribute') as $oAttributeNode) - { + foreach ($oFlags->getElementsByTagName('attribute') as $oAttributeNode) { $sFlags = $this->FlagsToPHP($oAttributeNode); - if (strlen($sFlags) > 0) - { + if (strlen($sFlags) > 0) { $sAttCode = $oAttributeNode->GetAttribute('id'); $sLifecycle .= " '$sAttCode' => $sFlags,\n"; } } $sLifecycle .= " ),\n"; - if (!is_null($oInitialStatePath)) - { + if (!is_null($oInitialStatePath)) { $sLifecycle .= " \"initial_state_path\" => $sInitialStatePath,\n"; } $sLifecycle .= " )\n"; $sLifecycle .= " );\n"; $oTransitions = $oState->GetUniqueElement('transitions'); - foreach ($oTransitions->getElementsByTagName('transition') as $oTransition) - { + foreach ($oTransitions->getElementsByTagName('transition') as $oTransition) { $sStimulus = $oTransition->getAttribute('id'); $sTargetState = $oTransition->GetChildText('target'); $oActions = $oTransition->GetUniqueElement('actions'); - $aVerbs = array(); - foreach ($oActions->getElementsByTagName('action') as $oAction) - { + $aVerbs = []; + foreach ($oActions->getElementsByTagName('action') as $oAction) { $sVerb = $oAction->GetChildText('verb'); $oParams = $oAction->GetOptionalElement('params'); - $aActionParams = array(); - if ($oParams) - { + $aActionParams = []; + if ($oParams) { $oParamNodes = $oParams->getElementsByTagName('param'); - foreach($oParamNodes as $oParam) - { + foreach ($oParamNodes as $oParam) { $sParamType = $oParam->getAttribute('xsi:type'); - if ($sParamType == '') - { + if ($sParamType == '') { $sParamType = 'string'; } $aActionParams[] = "array('type' => '$sParamType', 'value' => ".self::QuoteForPHP($oParam->textContent).")"; } - } - else - { + } else { // Old (pre 2.1.0) format, when no parameter is specified, assume 1 parameter: reference sStimulusCode $aActionParams[] = "array('type' => 'reference', 'value' => 'sStimulusCode')"; } @@ -1796,28 +1635,25 @@ EOF; } $sActions = implode(', ', $aVerbs); - $sLifecycle .= " MetaModel::Init_DefineTransition(\"$sState\", \"$sStimulus\", array(\n"; - $sLifecycle .= " \"target_state\"=>\"$sTargetState\",\n"; - $sLifecycle .= " \"actions\"=>array($sActions),\n"; - $sLifecycle .= " \"user_restriction\"=>null,\n"; - $sLifecycle .= " \"attribute_list\"=>array(\n"; + $sLifecycle .= " MetaModel::Init_DefineTransition(\"$sState\", \"$sStimulus\", array(\n"; + $sLifecycle .= " \"target_state\"=>\"$sTargetState\",\n"; + $sLifecycle .= " \"actions\"=>array($sActions),\n"; + $sLifecycle .= " \"user_restriction\"=>null,\n"; + $sLifecycle .= " \"attribute_list\"=>array(\n"; $oFlags = $oTransition->GetOptionalElement('flags'); - if($oFlags !== null) - { - foreach ($oFlags->getElementsByTagName('attribute') as $oAttributeNode) - { - $sFlags = $this->FlagsToPHP($oAttributeNode); - if (strlen($sFlags) > 0) - { - $sAttCode = $oAttributeNode->GetAttribute('id'); - $sLifecycle .= " '$sAttCode' => $sFlags,\n"; - } - } - } + if ($oFlags !== null) { + foreach ($oFlags->getElementsByTagName('attribute') as $oAttributeNode) { + $sFlags = $this->FlagsToPHP($oAttributeNode); + if (strlen($sFlags) > 0) { + $sAttCode = $oAttributeNode->GetAttribute('id'); + $sLifecycle .= " '$sAttCode' => $sFlags,\n"; + } + } + } - $sLifecycle .= " )\n"; - $sLifecycle .= " ));\n"; + $sLifecycle .= " )\n"; + $sLifecycle .= " ));\n"; } } } @@ -1898,17 +1734,14 @@ EOF; // Relations // $oRelations = $oClass->GetOptionalElement('relations'); - if ($oRelations) - { - $aRelations = array(); - foreach($oRelations->getElementsByTagName('relation') as $oRelation) - { + if ($oRelations) { + $aRelations = []; + foreach ($oRelations->getElementsByTagName('relation') as $oRelation) { $sRelationId = $oRelation->getAttribute('id'); - $this->aRelations[$sRelationId] = array('id' => $sRelationId); + $this->aRelations[$sRelationId] = ['id' => $sRelationId]; $oNeighbours = $oRelation->GetUniqueElement('neighbours'); - foreach($oNeighbours->getElementsByTagName('neighbour') as $oNeighbour) - { + foreach ($oNeighbours->getElementsByTagName('neighbour') as $oNeighbour) { $sNeighbourId = $oNeighbour->getAttribute('id'); $sDirection = $oNeighbour->GetChildText('direction', 'both'); @@ -1916,12 +1749,10 @@ EOF; $sQueryDown = $oNeighbour->GetChildText('query_down'); $sQueryUp = $oNeighbour->GetChildText('query_up'); - if (($sQueryDown == '') && ($sAttribute == '')) - { + if (($sQueryDown == '') && ($sAttribute == '')) { throw new DOMFormatException("Relation '$sRelationId/$sNeighbourId': either a query or an attribute must be specified"); } - if (($sQueryDown != '') && ($sAttribute != '')) - { + if (($sQueryDown != '') && ($sAttribute != '')) { throw new DOMFormatException("Relation '$sRelationId/$sNeighbourId': both a query and and attribute have been specified... which one should be used?"); } @@ -1932,7 +1763,7 @@ EOF; } elseif ($sDirection != 'down') { throw new DOMFormatException("Relation '$sRelationId/$sNeighbourId': unknown direction ($sDirection), expecting 'both' or 'down'"); } - $aRelations[$sRelationId][$sNeighbourId] = array( + $aRelations[$sRelationId][$sNeighbourId] = [ '_legacy_' => false, 'sDirection' => $sDirection, 'sDefinedInClass' => $sClass, @@ -1940,7 +1771,7 @@ EOF; 'sQueryDown' => $sQueryDown, 'sQueryUp' => $sQueryUp, 'sAttribute' => $sAttribute, - ); + ]; } } @@ -1948,12 +1779,10 @@ EOF; $sMethods .= "\t{\n"; $sMethods .= "\t\tswitch (\$sRelCode)\n"; $sMethods .= "\t\t{\n"; - foreach ($aRelations as $sRelationId => $aRelationData) - { + foreach ($aRelations as $sRelationId => $aRelationData) { $sMethods .= "\t\tcase '$sRelationId':\n"; $sMethods .= "\t\t\t\$aRels = array(\n"; - foreach ($aRelationData as $sNeighbourId => $aData) - { + foreach ($aRelationData as $sNeighbourId => $aData) { //$sData = str_replace("\n", "\n\t\t\t\t", var_export($aData, true)); $sData = var_export($aData, true); $sMethods .= "\t\t\t\t'$sNeighbourId' => $sData,\n"; @@ -1973,21 +1802,16 @@ EOF; $bIsAbstractClass = ($oProperties->GetChildText('abstract') == 'true'); $oPhpParent = $oClass->GetUniqueElement('php_parent', false); $aRequiredFiles = []; - if ($oPhpParent) - { + if ($oPhpParent) { $sParentClass = $oPhpParent->GetChildText('name', ''); - if ($sParentClass == '') - { + if ($sParentClass == '') { throw new Exception("Failed to process class '".$oClass->getAttribute('id')."', missing required tag 'name' under 'php_parent'."); } $sIncludeFile = $oPhpParent->GetChildText('file', ''); - if ($sIncludeFile != '') - { + if ($sIncludeFile != '') { $aRequiredFiles[] = $sIncludeFile; } - } - else - { + } else { $sParentClass = $oClass->GetChildText('parent', 'DBObject'); } $sInitMethodCalls = @@ -2003,20 +1827,19 @@ EOF; $sPHP .= $this->GeneratePhpCodeForClass($sClassName, $sParentClass, $sClassParams, $sInitMethodCalls, $bIsAbstractClass, $sMethods, $aRequiredFiles, $sCodeComment); // N°931 generates TagFieldData classes for AttributeTag fields - if (!empty($aTagFieldsInfo)) - { + if (!empty($aTagFieldsInfo)) { $sTagClassParentClass = "TagSetFieldData"; - $aTagClassParams = array - ( + $aTagClassParams = + [ 'category' => 'bizmodel', 'key_type' => 'autoincrement', - 'name_attcode' => array('label'), + 'name_attcode' => ['label'], 'state_attcode' => '', - 'reconc_keys' => array('code'), + 'reconc_keys' => ['code'], 'db_table' => '', // no need to have a corresponding table : this class exists only for rights, no additional field 'db_key_field' => 'id', 'db_finalclass_field' => 'finalclass', - ); + ]; $sTagInitMethodCalls = << 'label', )); EOF - ; - foreach ($aTagFieldsInfo as $sTagFieldName) - { + ; + foreach ($aTagFieldsInfo as $sTagFieldName) { $sTagClassName = static::GetTagDataClassName($sClassName, $sTagFieldName); $sTagClassParams = var_export($aTagClassParams, true); $sPHP .= $this->GeneratePhpCodeForClass($sTagClassName, $sTagClassParentClass, $sTagClassParams, $sTagInitMethodCalls); @@ -2062,13 +1884,11 @@ EOF { $aParameters = []; - $aDependencies = array(); + $aDependencies = []; $oDependencies = $oField->GetOptionalElement('dependencies'); - if (!is_null($oDependencies)) - { + if (!is_null($oDependencies)) { $oDepNodes = $oDependencies->getElementsByTagName('attribute'); - foreach($oDepNodes as $oDepAttribute) - { + foreach ($oDepNodes as $oDepAttribute) { $aDependencies[] = "'".$oDepAttribute->getAttribute('id')."'"; } } @@ -2260,17 +2080,17 @@ EOF $oXMLDoc->save($sTempTargetDir.'/'.$sFileName); $aParameters['definition_file'] = "'".str_replace("'", "\\'", $sFileName)."'"; } - } else if($sAttType == 'AttributeClass'){ + } elseif ($sAttType == 'AttributeClass') { $this->CompileCommonProperty('sql', $oField, $aParameters, $sModuleRelativeDir); $this->CompileCommonProperty('is_null_allowed', $oField, $aParameters, $sModuleRelativeDir, false); $this->CompileCommonProperty('default_value', $oField, $aParameters, $sModuleRelativeDir, ''); $this->CompileCommonProperty('allowed_values', $oField, $aParameters, $sModuleRelativeDir); - $aParameters['class_category'] = $this->GetPropString($oField, 'class_category', ''); + $aParameters['class_category'] = $this->GetPropString($oField, 'class_category', ''); $aParameters['more_values'] = $this->GetPropString($oField, 'more_values', ''); $aParameters['depends_on'] = $sDependencies; - $aParameters['class_exclusion_list'] = $this->GetPropString($oField, 'class_exclusion_list', null); + $aParameters['class_exclusion_list'] = $this->GetPropString($oField, 'class_exclusion_list', null); - }else { + } else { $this->CompileCommonProperty('sql', $oField, $aParameters, $sModuleRelativeDir); $this->CompileCommonProperty('is_null_allowed', $oField, $aParameters, $sModuleRelativeDir, false); $this->CompileCommonProperty('default_value', $oField, $aParameters, $sModuleRelativeDir, ''); @@ -2337,19 +2157,19 @@ EOF break; case 'edit_when': $sEditWhen = $oField->GetChildText('edit_when'); - if(!is_null($sEditWhen)){ + if (!is_null($sEditWhen)) { $aParameters['edit_when'] = $this->EditWhenToPHP($sEditWhen); } break; case 'mappings': $oMappings = $oField->GetUniqueElement('mappings'); $oMappingNodes = $oMappings->getElementsByTagName('mapping'); - $aMapping = array(); + $aMapping = []; foreach ($oMappingNodes as $oMapping) { $sMappingId = $oMapping->getAttribute('id'); $sMappingAttCode = $oMapping->GetChildText('attcode'); $aMapping[$sMappingId]['attcode'] = $sMappingAttCode; - $aMapping[$sMappingId]['values'] = array(); + $aMapping[$sMappingId]['values'] = []; $oMetaValues = $oMapping->GetUniqueElement('metavalues'); foreach ($oMetaValues->getElementsByTagName('metavalue') as $oMetaValue) { $sMetaValue = $oMetaValue->getAttribute('id'); @@ -2373,7 +2193,7 @@ EOF case 'states': $oStates = $oField->GetUniqueElement('states'); $oStateNodes = $oStates->getElementsByTagName('state'); - $aStates = array(); + $aStates = []; foreach ($oStateNodes as $oState) { $aStates[] = '"'.$oState->GetAttribute('id').'"'; } @@ -2382,7 +2202,7 @@ EOF case 'thresholds': $oThresholds = $oField->GetUniqueElement('thresholds'); $oThresholdNodes = $oThresholds->getElementsByTagName('threshold'); - $aThresholds = array(); + $aThresholds = []; foreach ($oThresholdNodes as $oThreshold) { $iPercent = (int)$oThreshold->getAttribute('id'); @@ -2396,10 +2216,10 @@ EOF $oActions = $oThreshold->GetUniqueElement('actions'); $oActionNodes = $oActions->getElementsByTagName('action'); - $aActions = array(); + $aActions = []; foreach ($oActionNodes as $oAction) { $oParams = $oAction->GetOptionalElement('params'); - $aActionParams = array(); + $aActionParams = []; if ($oParams) { $oParamNodes = $oParams->getElementsByTagName('param'); foreach ($oParamNodes as $oParam) { @@ -2533,9 +2353,9 @@ EOF $sCode = $this->GetMandatoryPropString($oValue, 'code', false); $sRankAsString = $this->GetPropNumber($oValue, 'rank'); // Consider value as ranked only if it is the desired sort type, this is to avoid issues if a node is left when sort type isn't "rank" - if (utils::IsNotNullOrEmptyString($sRankAsString) && ($sSortType === static::ENUM_ATTRIBUTE_ENUM_SORT_TYPE_RANK)){ + if (utils::IsNotNullOrEmptyString($sRankAsString) && ($sSortType === static::ENUM_ATTRIBUTE_ENUM_SORT_TYPE_RANK)) { $aValuesWithRank[$sCode] = (float) $sRankAsString; - } else { + } else { $aValuesWithoutRank[$sCode] = true; } @@ -2564,6 +2384,7 @@ EOF // Default language (fallback -eg. english- if no dict entry for the current language -eg. italian-) can change at anytime in the configuration file -eg. from english to french- // if that was to happen, users would not understand why they have labels from in english instead of french, which would cause support questions / investigations. $sLocalizedSortAsPHPParam = ', true'; + // no break default: // Sort values by their code ksort($aValuesWithoutRank); @@ -2740,10 +2561,10 @@ CSS; // - Convert SCSS variable to CSS variable use as SCSS variable cannot be used elsewhere than during SCSS compiling // Note: We check the $sXXXColorForCSS instead of the $sXXXColorForOrm because its value has been altered. if ($bHasMainColor && (stripos($sMainColorForCss, '$') === 0)) { - $sMainColorForOrm = "'var($sMainColorCssVariableName)'"; + $sMainColorForOrm = "'var($sMainColorCssVariableName)'"; } if ($bHasComplementaryColor && (stripos($sComplementaryColorForCss, '$') === 0)) { - $sComplementaryColorForOrm = "'var($sComplementaryColorCssVariableName)'"; + $sComplementaryColorForOrm = "'var($sComplementaryColorCssVariableName)'"; } $aData['orm_style_instantiation'] = "$sOrmStylePrefix new ormStyle($sCssRegularClassForOrm, $sCssAlternativeClassForOrm, $sMainColorForOrm, $sComplementaryColorForOrm, $sDecorationClasses, $sIconRelPath)"; @@ -2757,7 +2578,6 @@ CSS; return 'TagSetFieldDataFor_'.$sTagSuffix; } - /** * @param \MFElement $oMenu * @param string $sTempTargetDir @@ -2777,134 +2597,116 @@ CSS; $sMenuClass = $oMenu->getAttribute("xsi:type"); $sParent = $oMenu->GetChildText('parent', null); - if ($sParent) - { + if ($sParent) { $sParentSpec = "\$__comp_menus__['$sParent']->GetIndex()"; - } - else - { + } else { $sParentSpec = '-1'; } $fRank = (float) $oMenu->GetChildText('rank'); - if ($sEnableClass = $oMenu->GetChildText('enable_class')) - { + if ($sEnableClass = $oMenu->GetChildText('enable_class')) { $sEnableAction = $oMenu->GetChildText('enable_action', 'UR_ACTION_MODIFY'); $sEnablePermission = $oMenu->GetChildText('enable_permission', 'UR_ALLOWED_YES'); $sEnableStimulus = $oMenu->GetChildText('enable_stimulus'); - if ($sEnableStimulus != null) - { + if ($sEnableStimulus != null) { $sOptionalEnableParams = ", '$sEnableClass', $sEnableAction, $sEnablePermission, '$sEnableStimulus'"; - } - else - { + } else { $sOptionalEnableParams = ", '$sEnableClass', $sEnableAction, $sEnablePermission, null"; } - } - else - { + } else { $sOptionalEnableParams = ", null, UR_ACTION_MODIFY, UR_ALLOWED_YES, null"; } - switch($sMenuClass) - { - case 'WebPageMenuNode': - $sUrl = $oMenu->GetChildText('url'); - $sUrlSpec = $this->PathToPHP($sUrl, $sModuleRelativeDir, true /* Url */); - $bIsLinkInNewWindow = $this->GetPropBooleanConverted($oMenu, 'in_new_window', false); - if ($bIsLinkInNewWindow) - { - $sOptionalEnableParams .= ', true'; - } - $sNewMenu = "new WebPageMenuNode('$sMenuId', $sUrlSpec, $sParentSpec, $fRank {$sOptionalEnableParams});"; - break; - - case 'DashboardMenuNode': - $sTemplateFile = $oMenu->GetChildText('definition_file', ''); - if ($sTemplateFile != '') - { - $sTemplateSpec = $this->PathToPHP($sTemplateFile, $sModuleRelativeDir); - } - else - { - $oDashboardDefinition = $oMenu->GetOptionalElement('definition'); - if ($oDashboardDefinition == null) - { - throw(new DOMFormatException('Missing definition for Dashboard menu "'.$sMenuId.'" expecting either a tag "definition_file" or "definition".')); + switch ($sMenuClass) { + case 'WebPageMenuNode': + $sUrl = $oMenu->GetChildText('url'); + $sUrlSpec = $this->PathToPHP($sUrl, $sModuleRelativeDir, true /* Url */); + $bIsLinkInNewWindow = $this->GetPropBooleanConverted($oMenu, 'in_new_window', false); + if ($bIsLinkInNewWindow) { + $sOptionalEnableParams .= ', true'; } - $sFileName = strtolower(str_replace(array(':', '/', '\\', '*'), '_', $sMenuId)).'_dashboard.xml'; - $sTemplateSpec = $this->PathToPHP($sFileName, $sModuleRelativeDir); + $sNewMenu = "new WebPageMenuNode('$sMenuId', $sUrlSpec, $sParentSpec, $fRank {$sOptionalEnableParams});"; + break; - $oXMLDoc = new DOMDocument('1.0', 'UTF-8'); - $oXMLDoc->formatOutput = true; // indent (must be loaded with option LIBXML_NOBLANKS) - $oXMLDoc->preserveWhiteSpace = true; // otherwise the formatOutput option would have no effect + case 'DashboardMenuNode': + $sTemplateFile = $oMenu->GetChildText('definition_file', ''); + if ($sTemplateFile != '') { + $sTemplateSpec = $this->PathToPHP($sTemplateFile, $sModuleRelativeDir); + } else { + $oDashboardDefinition = $oMenu->GetOptionalElement('definition'); + if ($oDashboardDefinition == null) { + throw(new DOMFormatException('Missing definition for Dashboard menu "'.$sMenuId.'" expecting either a tag "definition_file" or "definition".')); + } + $sFileName = strtolower(str_replace([':', '/', '\\', '*'], '_', $sMenuId)).'_dashboard.xml'; + $sTemplateSpec = $this->PathToPHP($sFileName, $sModuleRelativeDir); - $oRootNode = $oXMLDoc->createElement('dashboard'); // make sure that the document is not empty - $oRootNode->setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance"); - $oXMLDoc->appendChild($oRootNode); - foreach ($oDashboardDefinition->childNodes as $oNode) - { - $oDefNode = $oXMLDoc->importNode($oNode, true); // layout, cells, etc Nodes and below - $oRootNode->appendChild($oDefNode); + $oXMLDoc = new DOMDocument('1.0', 'UTF-8'); + $oXMLDoc->formatOutput = true; // indent (must be loaded with option LIBXML_NOBLANKS) + $oXMLDoc->preserveWhiteSpace = true; // otherwise the formatOutput option would have no effect + + $oRootNode = $oXMLDoc->createElement('dashboard'); // make sure that the document is not empty + $oRootNode->setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance"); + $oXMLDoc->appendChild($oRootNode); + foreach ($oDashboardDefinition->childNodes as $oNode) { + $oDefNode = $oXMLDoc->importNode($oNode, true); // layout, cells, etc Nodes and below + $oRootNode->appendChild($oDefNode); + } + $oXMLDoc->save($sTempTargetDir.'/'.$sModuleRelativeDir.'/'.$sFileName); } - $oXMLDoc->save($sTempTargetDir.'/'.$sModuleRelativeDir.'/'.$sFileName); - } - $sNewMenu = "new DashboardMenuNode('$sMenuId', $sTemplateSpec, $sParentSpec, $fRank {$sOptionalEnableParams});"; - break; - - case 'ShortcutContainerMenuNode': - $sNewMenu = "new ShortcutContainerMenuNode('$sMenuId', $sParentSpec, $fRank {$sOptionalEnableParams});"; - break; - - case 'OQLMenuNode': - $sOQL = self::QuoteForPHP($oMenu->GetChildText('oql')); - $bSearch = ($oMenu->GetChildText('do_search') == '1') ? 'true' : 'false'; - $sSearchFormOpenXML = $oMenu->GetChildText('search_form_open'); - switch($sSearchFormOpenXML) - { - case '1': - $sSearchFormOpen = 'true'; + $sNewMenu = "new DashboardMenuNode('$sMenuId', $sTemplateSpec, $sParentSpec, $fRank {$sOptionalEnableParams});"; break; - - case '0': - $sSearchFormOpen = 'false'; + + case 'ShortcutContainerMenuNode': + $sNewMenu = "new ShortcutContainerMenuNode('$sMenuId', $sParentSpec, $fRank {$sOptionalEnableParams});"; break; - - default: - $sSearchFormOpen = 'true'; - } - $sNewMenu = "new OQLMenuNode('$sMenuId', $sOQL, $sParentSpec, $fRank, $bSearch {$sOptionalEnableParams}, $sSearchFormOpen);"; - break; - case 'NewObjectMenuNode': - $sClass = $oMenu->GetChildText('class'); - $sNewMenu = "new NewObjectMenuNode('$sMenuId', '$sClass', $sParentSpec, $fRank {$sOptionalEnableParams});"; - break; + case 'OQLMenuNode': + $sOQL = self::QuoteForPHP($oMenu->GetChildText('oql')); + $bSearch = ($oMenu->GetChildText('do_search') == '1') ? 'true' : 'false'; + $sSearchFormOpenXML = $oMenu->GetChildText('search_form_open'); + switch ($sSearchFormOpenXML) { + case '1': + $sSearchFormOpen = 'true'; + break; - case 'SearchMenuNode': - $sClass = $oMenu->GetChildText('class'); - $sNewMenu = "new SearchMenuNode('$sMenuId', '$sClass', $sParentSpec, $fRank, null {$sOptionalEnableParams});"; - break; + case '0': + $sSearchFormOpen = 'false'; + break; - case 'TemplateMenuNode': - $sNewMenu = "new TemplateMenuNode('$sMenuId', '', $sParentSpec, $fRank {$sOptionalEnableParams});"; - break; + default: + $sSearchFormOpen = 'true'; + } + $sNewMenu = "new OQLMenuNode('$sMenuId', $sOQL, $sParentSpec, $fRank, $bSearch {$sOptionalEnableParams}, $sSearchFormOpen);"; + break; - case 'MenuGroup': - $oStyleNode = $oMenu->GetOptionalElement('style'); - // Note: We use '' as the default value to ease the MenuGroup::__construct() call as we would have to make a different processing to not put the quotes around the parameter in case of null. - $sDecorationClasses = ($oStyleNode === null) ? '' : $oStyleNode->GetChildText('decoration_classes', ''); + case 'NewObjectMenuNode': + $sClass = $oMenu->GetChildText('class'); + $sNewMenu = "new NewObjectMenuNode('$sMenuId', '$sClass', $sParentSpec, $fRank {$sOptionalEnableParams});"; + break; - $sNewMenu = "new MenuGroup('$sMenuId', $fRank, '$sDecorationClasses' {$sOptionalEnableParams});"; - break; + case 'SearchMenuNode': + $sClass = $oMenu->GetChildText('class'); + $sNewMenu = "new SearchMenuNode('$sMenuId', '$sClass', $sParentSpec, $fRank, null {$sOptionalEnableParams});"; + break; - default: - $sNewMenu = "new $sMenuClass('$sMenuId', $fRank {$sOptionalEnableParams});"; + case 'TemplateMenuNode': + $sNewMenu = "new TemplateMenuNode('$sMenuId', '', $sParentSpec, $fRank {$sOptionalEnableParams});"; + break; + + case 'MenuGroup': + $oStyleNode = $oMenu->GetOptionalElement('style'); + // Note: We use '' as the default value to ease the MenuGroup::__construct() call as we would have to make a different processing to not put the quotes around the parameter in case of null. + $sDecorationClasses = ($oStyleNode === null) ? '' : $oStyleNode->GetChildText('decoration_classes', ''); + + $sNewMenu = "new MenuGroup('$sMenuId', $fRank, '$sDecorationClasses' {$sOptionalEnableParams});"; + break; + + default: + $sNewMenu = "new $sMenuClass('$sMenuId', $fRank {$sOptionalEnableParams});"; } - $aPHPMenu = array("\$__comp_menus__['$sMenuId'] = $sNewMenu"); - if ($sAutoReload = $oMenu->GetChildText('auto_reload')) - { + $aPHPMenu = ["\$__comp_menus__['$sMenuId'] = $sNewMenu"]; + if ($sAutoReload = $oMenu->GetChildText('auto_reload')) { $sAutoReload = self::QuoteForPHP($sAutoReload); $aPHPMenu[] = "\$__comp_menus__['$sMenuId']->SetParameters(array('auto_reload' => $sAutoReload));"; } @@ -2916,52 +2718,42 @@ CSS; */ protected function CumulateGrant(&$aGrants, $sKey, $bGrant) { - if (isset($aGrants[$sKey])) - { - if (!$bGrant) - { + if (isset($aGrants[$sKey])) { + if (!$bGrant) { $aGrants[$sKey] = false; } - } - else - { + } else { $aGrants[$sKey] = $bGrant; } } protected function CompileUserRights($oUserRightsNode) { - static $aActionsInShort = array( + static $aActionsInShort = [ 'read' => 'r', 'bulk read' => 'br', 'write' => 'w', 'bulk write' => 'bw', 'delete' => 'd', 'bulk delete' => 'bd', - ); + ]; // Preliminary : create an index so that links will be taken into account implicitely - $aLinkToClasses = array(); + $aLinkToClasses = []; $oClasses = $this->oFactory->ListAllClasses(); - foreach($oClasses as $oClass) - { + foreach ($oClasses as $oClass) { $bIsLink = false; $oProperties = $oClass->GetOptionalElement('properties'); - if ($oProperties) - { + if ($oProperties) { $bIsLink = (bool) $this->GetPropNumber($oProperties, 'is_link', 0); } - if ($bIsLink) - { - foreach($this->oFactory->ListFields($oClass) as $oField) - { + if ($bIsLink) { + foreach ($this->oFactory->ListFields($oClass) as $oField) { $sAttType = $oField->getAttribute('xsi:type'); - - if (($sAttType == 'AttributeExternalKey') || ($sAttType == 'AttributeHierarchicalKey')) - { + + if (($sAttType == 'AttributeExternalKey') || ($sAttType == 'AttributeHierarchicalKey')) { $sOnTargetDel = $oField->GetChildText('on_target_delete'); - if (($sOnTargetDel == 'DEL_AUTO') || ($sOnTargetDel == 'DEL_SILENT') || ($sOnTargetDel == 'DEL_NONE')) - { + if (($sOnTargetDel == 'DEL_AUTO') || ($sOnTargetDel == 'DEL_SILENT') || ($sOnTargetDel == 'DEL_NONE')) { $sTargetClass = $oField->GetChildText('target_class'); $aLinkToClasses[$oClass->getAttribute('id')][] = $sTargetClass; } @@ -2972,17 +2764,15 @@ CSS; // Groups // - $aGroupClasses = array(); + $aGroupClasses = []; $oGroups = $oUserRightsNode->GetUniqueElement('groups'); - foreach($oGroups->getElementsByTagName('group') as $oGroup) - { + foreach ($oGroups->getElementsByTagName('group') as $oGroup) { $sGroupId = $oGroup->getAttribute("id"); - $aClasses = array(); + $aClasses = []; $oClasses = $oGroup->GetUniqueElement('classes'); - foreach($oClasses->getElementsByTagName('class') as $oClass) - { - + foreach ($oClasses->getElementsByTagName('class') as $oClass) { + $sClass = $oClass->getAttribute("id"); $aClasses[] = $sClass; @@ -2995,65 +2785,52 @@ CSS; // Profiles and grants // - $aProfiles = array(); + $aProfiles = []; // Hardcode the administrator profile - $aProfiles[1] = array( + $aProfiles[1] = [ 'name' => 'Administrator', 'description' => 'Has the rights on everything (bypassing any control)', - ); + ]; - $aGrants = array(); + $aGrants = []; $oProfiles = $oUserRightsNode->GetUniqueElement('profiles'); - foreach($oProfiles->getElementsByTagName('profile') as $oProfile) - { + foreach ($oProfiles->getElementsByTagName('profile') as $oProfile) { $iProfile = $oProfile->getAttribute("id"); $sName = $oProfile->GetChildText('name'); $sDescription = $oProfile->GetChildText('description'); $oGroups = $oProfile->GetUniqueElement('groups'); - foreach($oGroups->getElementsByTagName('group') as $oGroup) - { + foreach ($oGroups->getElementsByTagName('group') as $oGroup) { $sGroupId = $oGroup->getAttribute("id"); $oActions = $oGroup->GetUniqueElement('actions'); - foreach($oActions->getElementsByTagName('action') as $oAction) - { + foreach ($oActions->getElementsByTagName('action') as $oAction) { $sAction = $oAction->getAttribute("id"); - if (strpos($sAction, 'action:') === 0) - { + if (strpos($sAction, 'action:') === 0) { $sType = 'action'; $sActionCode = substr($sAction, strlen('action:')); $sActionCode = $aActionsInShort[$sActionCode]; - } - else - { + } else { $sType = 'stimulus'; $sActionCode = substr($sAction, strlen('stimulus:')); } $sGrant = $oAction->GetText(); $bGrant = ($sGrant == 'allow'); - - if ($sGroupId == '*') - { - $aGrantClasses = array('*'); - } - else - { + + if ($sGroupId == '*') { + $aGrantClasses = ['*']; + } else { if (array_key_exists($sGroupId, $aGroupClasses) === false) { SetupLog::Error("Profile \"$sName\" relies on group \"$sGroupId\" but it does not seem to be present in the DM yet (did you forgot a dependency in your module?)"); } $aGrantClasses = $aGroupClasses[$sGroupId]; } - foreach ($aGrantClasses as $sClass) - { - if ($sType == 'stimulus') - { + foreach ($aGrantClasses as $sClass) { + if ($sType == 'stimulus') { $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'_s_'.$sActionCode, $bGrant); $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'+_s_'.$sActionCode, $bGrant); // subclasses inherit this grant - } - else - { + } else { $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'_'.$sActionCode, $bGrant); $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'+_'.$sActionCode, $bGrant); // subclasses inherit this grant } @@ -3061,10 +2838,10 @@ CSS; } } - $aProfiles[$iProfile] = array( + $aProfiles[$iProfile] = [ 'name' => $sName, 'description' => $sDescription, - ); + ]; } $sProfiles = var_export($aProfiles, true); @@ -3222,24 +2999,22 @@ class ProfilesConfig } EOF; - return $sPHP; + return $sPHP; } // function CompileUserRights protected function CompileDictionaries($oDictionaries, $sTempTargetDir, $sFinalTargetDir) { - $aLanguages = array(); - foreach($oDictionaries as $oDictionaryNode) - { + $aLanguages = []; + foreach ($oDictionaries as $oDictionaryNode) { $sLang = $oDictionaryNode->getAttribute('id'); $sEnglishLanguageDesc = $oDictionaryNode->GetChildText('english_description'); $sLocalizedLanguageDesc = $oDictionaryNode->GetChildText('localized_description'); - $aLanguages[$sLang] = array('description' => $sEnglishLanguageDesc, 'localized_description' => $sLocalizedLanguageDesc); + $aLanguages[$sLang] = ['description' => $sEnglishLanguageDesc, 'localized_description' => $sLocalizedLanguageDesc]; - $aEntriesPHP = array(); + $aEntriesPHP = []; $oEntries = $oDictionaryNode->GetUniqueElement('entries'); /** @var MFElement $oEntry */ - foreach ($oEntries->getElementsByTagName('entry') as $oEntry) - { + foreach ($oEntries->getElementsByTagName('entry') as $oEntry) { $sStringCode = $oEntry->getAttribute('id'); $sValue = $oEntry->GetText(''); $aEntriesPHP[] = "\t'$sStringCode' => ".self::QuoteForPHP(self::FilterDictString($sValue), true).","; @@ -3272,15 +3047,14 @@ Dict::SetLanguagesList( $sLanguagesDump ); EOF; - + file_put_contents($sLanguagesFile, $sLanguagesFileContent); } protected static function FilterDictString(string $s): string { - if (strpos($s, '~') !== false) - { - return str_replace(array('~~', '~*'), '', $s); + if (strpos($s, '~') !== false) { + return str_replace(['~~', '~*'], '', $s); } return $s; } @@ -3299,18 +3073,15 @@ EOF; protected function CompileFiles($oNode, $sTempTargetDir, $sFinalTargetDir, $sRelativePath) { $oFileRefs = $oNode->GetNodes(".//fileref"); - foreach ($oFileRefs as $oFileRef) - { + foreach ($oFileRefs as $oFileRef) { $sFileId = $oFileRef->getAttribute('ref'); - if ($sFileId !== '') - { + if ($sFileId !== '') { $sQuotedFileId = DesignDocument::XPathQuote($sFileId); $oNodes = $this->oFactory->GetNodes("/itop_design/files/file[@id=$sQuotedFileId]"); - if ($oNodes->length == 0) - { + if ($oNodes->length == 0) { throw new DOMFormatException('Could not find the file with ref '.$sFileId); } - + $sName = $oNodes->item(0)->GetChildText('name'); $sData = base64_decode($oNodes->item(0)->GetChildText('data')); $aPathInfo = pathinfo($sName); @@ -3318,20 +3089,18 @@ EOF; $sFilePath = $sTempTargetDir.'/images/'.$sFile; @mkdir($sTempTargetDir.'/images'); file_put_contents($sFilePath, $sData); - if (!file_exists($sFilePath)) - { + if (!file_exists($sFilePath)) { throw new Exception('Could not write icon file '.$sFilePath); } $oParentNode = $oFileRef->parentNode; $oParentNode->removeChild($oFileRef); - + $oTextNode = $oParentNode->ownerDocument->createTextNode($sRelativePath.'/images/'.$sFile); $oParentNode->appendChild($oTextNode); } } } - /** * @param \MFElement $oBrandingNode * @param string $sTempTargetDir @@ -3346,12 +3115,11 @@ EOF; $sIcon = trim($oBrandingNode->GetChildText($sNodeName) ?? ''); if (strlen($sIcon) > 0) { $sSourceFile = $sTempTargetDir.'/'.$sIcon; - $aIconName=explode(".", $sIcon); - $sIconExtension=$aIconName[count($aIconName)-1]; + $aIconName = explode(".", $sIcon); + $sIconExtension = $aIconName[count($aIconName) - 1]; $sTargetFile = '/branding/'.$sTargetFile.'.'.$sIconExtension; - if (!file_exists($sSourceFile)) - { + if (!file_exists($sSourceFile)) { throw new Exception("Branding $sNodeName: could not find the file $sIcon ($sSourceFile)"); } @@ -3376,17 +3144,16 @@ EOF; // Note: During compilation, we don't have access to "env-xxx", so we have to set several imports paths: // - The CSS directory for the native imports (eg. "../css/css-variables.scss") // - The SCSS from modules - $aImportsPaths = array( + $aImportsPaths = [ APPROOT.'css/', APPROOT.'css/backoffice/main.scss', $sTempTargetDir.'/', - ); + ]; // Build compiled themes folder $sThemesRelDirPath = 'branding/themes/'; $sThemesAbsDirPath = $sTempTargetDir.$sThemesRelDirPath; - if(!is_dir($sThemesAbsDirPath)) - { + if (!is_dir($sThemesAbsDirPath)) { SetupUtils::builddir($sThemesAbsDirPath); } @@ -3399,21 +3166,21 @@ EOF; // Parsing theme from common theme node /** @var \MFElement $oThemesCommonNodes */ $oThemesCommonNodes = $oBrandingNode->GetUniqueElement('themes_common', false); - $aThemesCommonParameters = array( - 'variables' => array(), - 'variable_imports' => array(), - 'utility_imports' => array(), - 'stylesheets' => array(), - ); - - if($oThemesCommonNodes !== null) { + $aThemesCommonParameters = [ + 'variables' => [], + 'variable_imports' => [], + 'utility_imports' => [], + 'stylesheets' => [], + ]; + + if ($oThemesCommonNodes !== null) { /** @var \DOMNodeList $oThemesCommonVariables */ $oThemesCommonVariables = $oThemesCommonNodes->GetNodes('variables/variable'); foreach ($oThemesCommonVariables as $oVariable) { $sVariableId = $oVariable->getAttribute('id'); $aThemesCommonParameters['variables'][$sVariableId] = $oVariable->GetText(); } - + /** @var \DOMNodeList $oThemesCommonImports */ $oThemesCommonImports = $oThemesCommonNodes->GetNodes('imports/import'); foreach ($oThemesCommonImports as $oImport) { @@ -3427,7 +3194,7 @@ EOF; SetupLog::Warning('CompileThemes: Theme common has an import (#'.$sImportId.') without explicit xsi:type, it will be ignored. Check Datamodel XML Reference to fix it.'); } } - + // Stylesheets // - Manually added in the XML /** @var \DOMNodeList $oThemesCommonStylesheets */ @@ -3439,18 +3206,17 @@ EOF; } // Parsing themes from DM - $aThemes = array(); + $aThemes = []; /** @var \DOMNodeList $oThemeNodes */ $oThemeNodes = $oBrandingNode->GetNodes('themes/theme'); - foreach($oThemeNodes as $oTheme) - { + foreach ($oThemeNodes as $oTheme) { $sThemeId = $oTheme->getAttribute('id'); - $aThemeParameters = array( - 'variables' => array(), - 'variable_imports' => array(), - 'utility_imports' => array(), - 'stylesheets' => array(), - ); + $aThemeParameters = [ + 'variables' => [], + 'variable_imports' => [], + 'utility_imports' => [], + 'stylesheets' => [], + ]; /** @var \DOMNodeList $oVariables */ $oVariables = $oTheme->GetNodes('variables/variable'); @@ -3477,8 +3243,7 @@ EOF; // - Manually added in the XML /** @var \DOMNodeList $oStylesheets */ $oStylesheets = $oTheme->GetNodes('stylesheets/stylesheet'); - foreach($oStylesheets as $oStylesheet) - { + foreach ($oStylesheets as $oStylesheet) { $sStylesheetId = $oStylesheet->getAttribute('id'); $aThemeParameters['stylesheets'][$sStylesheetId] = $oStylesheet->GetText(); } @@ -3488,11 +3253,11 @@ EOF; // - Overload default values with module ones foreach ($aThemeParameters as $sThemeParameterName => $aThemeParameter) { - if(array_key_exists($sThemeParameterName, $aThemesCommonParameters)){ + if (array_key_exists($sThemeParameterName, $aThemesCommonParameters)) { $aThemeParameters[$sThemeParameterName] = array_merge($aThemeParameter, $aThemesCommonParameters[$sThemeParameterName]); } } - + $aThemes[$sThemeId] = [ 'theme_parameters' => $aThemeParameters, 'precompiled_stylesheet' => $oTheme->GetChildText('precompiled_stylesheet', ''), @@ -3500,36 +3265,33 @@ EOF; } // Force to have a default theme if none in the DM - if(empty($aThemes)) - { + if (empty($aThemes)) { $aDefaultThemeInfo = ThemeHandler::GetDefaultThemeInformation(); $aDefaultThemeInfo['parameters']['stylesheets'][$sDmStylesheetId] = $sThemesRelDirPath.$sDmStylesheetFilename; $aThemes[$aDefaultThemeInfo['name']] = $aDefaultThemeInfo['parameters']; } - $sPostCompilationPrecompiledThemeFolder = APPROOT . self::DATA_PRECOMPILED_FOLDER; - if (! is_dir($sPostCompilationPrecompiledThemeFolder)){ + $sPostCompilationPrecompiledThemeFolder = APPROOT.self::DATA_PRECOMPILED_FOLDER; + if (! is_dir($sPostCompilationPrecompiledThemeFolder)) { mkdir($sPostCompilationPrecompiledThemeFolder); } // Compile themes $fStart = microtime(true); - foreach($aThemes as $sThemeId => $aThemeInfos) - { + foreach ($aThemes as $sThemeId => $aThemeInfos) { $aThemeParameters = $aThemeInfos['theme_parameters']; $sPrecompiledStylesheet = $aThemeInfos['precompiled_stylesheet']; $sThemeDir = $sThemesAbsDirPath.$sThemeId; - if(!is_dir($sThemeDir)) - { + if (!is_dir($sThemeDir)) { SetupUtils::builddir($sThemeDir); } // Check if a precompiled version of the theme is supplied - $sPostCompilationLatestPrecompiledFile = $sPostCompilationPrecompiledThemeFolder . $sThemeId . ".css"; + $sPostCompilationLatestPrecompiledFile = $sPostCompilationPrecompiledThemeFolder.$sThemeId.".css"; $sPrecompiledFileToUse = $this->UseLatestPrecompiledFile($sTempTargetDir, $sPrecompiledStylesheet, $sPostCompilationLatestPrecompiledFile, $sThemeId); - if ($sPrecompiledFileToUse != null){ + if ($sPrecompiledFileToUse != null) { copy($sPrecompiledFileToUse, $sThemeDir.'/main.css'); // Make sure that the copy of the precompiled file is older than any other files to force a validation of the signature touch($sThemeDir.'/main.css', 1577836800 /* 2020-01-01 00:00:00 */); @@ -3541,7 +3303,7 @@ EOF; $bHasCompiled = static::$oThemeHandlerService->CompileTheme($sThemeId, true, $this->sCompilationTimeStamp, $aThemeParameters, $aImportsPaths, $sTempTargetDir); if ($bHasCompiled) { - if (utils::GetConfig()->Get('theme.enable_precompilation')){ + if (utils::GetConfig()->Get('theme.enable_precompilation')) { /*if (utils::IsDevelopmentEnvironment() && ! empty(trim($sPrecompiledStylesheet))) //N°4438 - Disable (temporary) copy of precompiled stylesheets after setup { //help developers to detect & push theme precompilation changes $sInitialPrecompiledFilePath = null; @@ -3569,10 +3331,11 @@ EOF; SetupLog::Info("No theme '$sThemeId' compilation was required during setup."); } } - $this->Log(sprintf('Themes compilation took: %.3f ms for %d themes.', (microtime(true) - $fStart)*1000.0, count($aThemes))); + $this->Log(sprintf('Themes compilation took: %.3f ms for %d themes.', (microtime(true) - $fStart) * 1000.0, count($aThemes))); } - public static function SetThemeHandlerService(ThemeHandlerService $oThemeHandlerService): void { + public static function SetThemeHandlerService(ThemeHandlerService $oThemeHandlerService): void + { self::$oThemeHandlerService = $oThemeHandlerService; } @@ -3586,35 +3349,36 @@ EOF; * * @return string : file path of latest precompiled file to use for setup */ - public function UseLatestPrecompiledFile(string $sTempTargetDir, string $sPrecompiledFileUri, $sPostCompilationLatestPrecompiledFile, $sThemeId) : ?string { + public function UseLatestPrecompiledFile(string $sTempTargetDir, string $sPrecompiledFileUri, $sPostCompilationLatestPrecompiledFile, $sThemeId): ?string + { if (! utils::GetConfig()->Get('theme.enable_precompilation')) { return null; } $bDataXmlPrecompiledFileExists = false; clearstatcache(); - if (!empty($sPrecompiledFileUri)){ - $sDataXmlProvidedPrecompiledFile = $sTempTargetDir . DIRECTORY_SEPARATOR . $sPrecompiledFileUri; + if (!empty($sPrecompiledFileUri)) { + $sDataXmlProvidedPrecompiledFile = $sTempTargetDir.DIRECTORY_SEPARATOR.$sPrecompiledFileUri; $bDataXmlPrecompiledFileExists = file_exists($sDataXmlProvidedPrecompiledFile) ; - if (!$bDataXmlPrecompiledFileExists){ + if (!$bDataXmlPrecompiledFileExists) { SetupLog::Warning("Missing defined theme '$sThemeId' precompiled file configured with: '$sPrecompiledFileUri'"); } else { - $sSourceDir = APPROOT . utils::GetConfig()->Get('source_dir'); + $sSourceDir = APPROOT.utils::GetConfig()->Get('source_dir'); $aDirToCheck = [ $sSourceDir, - APPROOT . DIRECTORY_SEPARATOR . 'extensions/', + APPROOT.DIRECTORY_SEPARATOR.'extensions/', ]; $iDataXmlFileLastModified = 0; - foreach ($aDirToCheck as $sDir){ - $sCurrentFile = $sDir . DIRECTORY_SEPARATOR . $sPrecompiledFileUri; - if (is_file($sCurrentFile)){ + foreach ($aDirToCheck as $sDir) { + $sCurrentFile = $sDir.DIRECTORY_SEPARATOR.$sPrecompiledFileUri; + if (is_file($sCurrentFile)) { $iDataXmlFileLastModified = max($iDataXmlFileLastModified, @filemtime($sCurrentFile)); } } - if ($iDataXmlFileLastModified == 0){ + if ($iDataXmlFileLastModified == 0) { SetupLog::Warning("Missing defined theme '$sThemeId' precompiled file in datamodels/X.x or extensions directory configured with: '$sPrecompiledFileUri'. That should not happen!"); $bDataXmlPrecompiledFileExists = false; } @@ -3624,17 +3388,17 @@ EOF; $bPostCompilationPrecompiledFileExists = file_exists($sPostCompilationLatestPrecompiledFile); - if (!$bDataXmlPrecompiledFileExists && !$bPostCompilationPrecompiledFileExists){ + if (!$bDataXmlPrecompiledFileExists && !$bPostCompilationPrecompiledFileExists) { return null; } - if (!$bDataXmlPrecompiledFileExists){ + if (!$bDataXmlPrecompiledFileExists) { $sPrecompiledFileToUse = $sPostCompilationLatestPrecompiledFile; - } else if (!$bPostCompilationPrecompiledFileExists){ + } elseif (!$bPostCompilationPrecompiledFileExists) { $sPrecompiledFileToUse = $sDataXmlProvidedPrecompiledFile; - } else{ + } else { $iPostCompilationFileLastModified = @filemtime($sPostCompilationLatestPrecompiledFile); - SetupLog::Debug("Theme '$sThemeId' check mtime between data XML file " . $iDataXmlFileLastModified . " and latest postcompilation file: " . $iPostCompilationFileLastModified); + SetupLog::Debug("Theme '$sThemeId' check mtime between data XML file ".$iDataXmlFileLastModified." and latest postcompilation file: ".$iPostCompilationFileLastModified); $sPrecompiledFileToUse = $iDataXmlFileLastModified > $iPostCompilationFileLastModified ? $sDataXmlProvidedPrecompiledFile : $sPostCompilationLatestPrecompiledFile; } @@ -3655,21 +3419,20 @@ EOF; { // Enable relative paths SetupUtils::builddir($sTempTargetDir.'/branding'); - if ($oBrandingNode) - { + if ($oBrandingNode) { // Transform file refs into files in the images folder $this->CompileFiles($oBrandingNode, $sTempTargetDir.'/branding', $sFinalTargetDir.'/branding', 'branding'); $aDataBranding = []; - $aLogosToCompile = [ - ['sNodeName' => 'login_logo', 'sTargetFile' => 'login-logo', 'sType' => Branding::ENUM_LOGO_TYPE_LOGIN_LOGO], - ['sNodeName' => 'main_logo', 'sTargetFile' => 'main-logo-full', 'sType' => Branding::ENUM_LOGO_TYPE_MAIN_LOGO_FULL], - ['sNodeName' => 'main_logo_compact', 'sTargetFile' => 'main-logo-compact', 'sType' => Branding::ENUM_LOGO_TYPE_MAIN_LOGO_COMPACT], - ['sNodeName' => 'portal_logo', 'sTargetFile' => 'portal-logo', 'sType' => Branding::ENUM_LOGO_TYPE_PORTAL_LOGO], - ['sNodeName' => 'login_favicon', 'sTargetFile' => 'login_favicon', 'sType' => Branding::ENUM_LOGO_TYPE_LOGIN_FAVICON], - ['sNodeName' => 'main_favicon', 'sTargetFile' => 'main_favicon', 'sType' => Branding::ENUM_LOGO_TYPE_MAIN_FAVICON], - ['sNodeName' => 'portal_favicon', 'sTargetFile' => 'portal_favicon', 'sType' => Branding::ENUM_LOGO_TYPE_PORTAL_FAVICON], - ]; + $aLogosToCompile = [ + ['sNodeName' => 'login_logo', 'sTargetFile' => 'login-logo', 'sType' => Branding::ENUM_LOGO_TYPE_LOGIN_LOGO], + ['sNodeName' => 'main_logo', 'sTargetFile' => 'main-logo-full', 'sType' => Branding::ENUM_LOGO_TYPE_MAIN_LOGO_FULL], + ['sNodeName' => 'main_logo_compact', 'sTargetFile' => 'main-logo-compact', 'sType' => Branding::ENUM_LOGO_TYPE_MAIN_LOGO_COMPACT], + ['sNodeName' => 'portal_logo', 'sTargetFile' => 'portal-logo', 'sType' => Branding::ENUM_LOGO_TYPE_PORTAL_LOGO], + ['sNodeName' => 'login_favicon', 'sTargetFile' => 'login_favicon', 'sType' => Branding::ENUM_LOGO_TYPE_LOGIN_FAVICON], + ['sNodeName' => 'main_favicon', 'sTargetFile' => 'main_favicon', 'sType' => Branding::ENUM_LOGO_TYPE_MAIN_FAVICON], + ['sNodeName' => 'portal_favicon', 'sTargetFile' => 'portal_favicon', 'sType' => Branding::ENUM_LOGO_TYPE_PORTAL_FAVICON], + ]; foreach ($aLogosToCompile as $aLogo) { $sLogo = $this->CompileLogo($oBrandingNode, $sTempTargetDir, $sFinalTargetDir, $aLogo['sNodeName'], $aLogo['sTargetFile']); if ($sLogo != null) { @@ -3685,12 +3448,11 @@ EOF; file_put_contents($sWorkingPath.'/branding/logos.json', json_encode($aDataBranding)); // Cleanup the images directory (eventually made by CompileFiles) - if (file_exists($sTempTargetDir.'/branding/images')) - { + if (file_exists($sTempTargetDir.'/branding/images')) { SetupUtils::rrmdir($sTempTargetDir.'/branding/images'); } - // Compile themes + // Compile themes $this->CompileThemes($oBrandingNode, $sTempTargetDir); } } @@ -3702,40 +3464,34 @@ EOF; */ protected function CompilePortals($oPortalsNode, $sTempTargetDir, $sFinalTargetDir) { - if ($oPortalsNode) - { + if ($oPortalsNode) { // Create some static PHP data in /core/main.php $oPortals = $oPortalsNode->GetNodes('portal'); - $aPortalsConfig = array(); - foreach($oPortals as $oPortal) - { + $aPortalsConfig = []; + foreach ($oPortals as $oPortal) { $sPortalId = $oPortal->getAttribute('id'); - $aPortalsConfig[$sPortalId] = array(); + $aPortalsConfig[$sPortalId] = []; $aPortalsConfig[$sPortalId]['rank'] = (float)$oPortal->GetChildText('rank', 0); $aPortalsConfig[$sPortalId]['handler'] = $oPortal->GetChildText('handler', 'PortalDispatcher'); $aPortalsConfig[$sPortalId]['url'] = $oPortal->GetChildText('url', 'portal/index.php'); $oAllow = $oPortal->GetOptionalElement('allow'); - $aPortalsConfig[$sPortalId]['allow'] = array(); - if ($oAllow) - { - foreach($oAllow->GetNodes('profile') as $oProfile) - { + $aPortalsConfig[$sPortalId]['allow'] = []; + if ($oAllow) { + foreach ($oAllow->GetNodes('profile') as $oProfile) { $aPortalsConfig[$sPortalId]['allow'][] = $oProfile->getAttribute('id'); } } $oDeny = $oPortal->GetOptionalElement('deny'); - $aPortalsConfig[$sPortalId]['deny'] = array(); - if ($oDeny) - { - foreach($oDeny->GetNodes('profile') as $oProfile) - { + $aPortalsConfig[$sPortalId]['deny'] = []; + if ($oDeny) { + foreach ($oDeny->GetNodes('profile') as $oProfile) { $aPortalsConfig[$sPortalId]['deny'][] = $oProfile->getAttribute('id'); } - } + } } - - uasort($aPortalsConfig, array(get_class($this), 'SortOnRank')); - + + uasort($aPortalsConfig, [get_class($this), 'SortOnRank']); + $this->sMainPHPCode .= "\n"; $this->sMainPHPCode .= "/**\n"; $this->sMainPHPCode .= " * Portal(s) definition(s) extracted from the XML definition at compile time\n"; @@ -3767,18 +3523,16 @@ EOF; */ protected function CompileParameters($oParametersNode, $sTempTargetDir, $sFinalTargetDir) { - if ($oParametersNode) - { + if ($oParametersNode) { // Create some static PHP data in /core/main.php $oParameters = $oParametersNode->GetNodes('parameters'); - $aParametersConfig = array(); - foreach($oParameters as $oParams) - { + $aParametersConfig = []; + foreach ($oParameters as $oParams) { $sModuleId = $oParams->getAttribute('id'); $oParamsReader = new MFParameters($oParams); $aParametersConfig[$sModuleId] = $oParamsReader->GetAll(); } - + $this->sMainPHPCode .= "\n"; $this->sMainPHPCode .= "/**\n"; $this->sMainPHPCode .= " * Modules parameters extracted from the XML definition at compile time\n"; @@ -3806,12 +3560,10 @@ EOF; */ protected function CompileModuleDesigns($oDesigns, $sTempTargetDir, $sFinalTargetDir) { - if ($oDesigns) - { + if ($oDesigns) { SetupUtils::builddir($sTempTargetDir.'/core/module_designs/images'); $this->CompileFiles($oDesigns, $sTempTargetDir.'/core/module_designs', $sFinalTargetDir.'/core/module_designs', 'core/module_designs'); - foreach ($oDesigns->GetNodes('module_design') as $oDesign) - { + foreach ($oDesigns->GetNodes('module_design') as $oDesign) { $oDoc = new ModuleDesign(); $oClone = $oDoc->importNode($oDesign->cloneNode(true), true); $oDoc->appendChild($oClone); @@ -3826,58 +3578,44 @@ EOF; protected function LoadSnippets() { $oSnippets = $this->oFactory->GetNodes('/itop_design/snippets/snippet'); - foreach($oSnippets as $oSnippet) - { + foreach ($oSnippets as $oSnippet) { $sSnippetId = $oSnippet->getAttribute('id'); $sPlacement = $oSnippet->GetChildText('placement', null); - if ($sPlacement == 'core') - { + if ($sPlacement == 'core') { $sModuleId = '_core_'; - } - else if ($sPlacement == 'module') - { + } elseif ($sPlacement == 'module') { $sModuleId = $oSnippet->GetChildText('module', null); - if ($sModuleId == null) - { + if ($sModuleId == null) { throw new DOMFormatException("Invalid definition for snippet id='$sSnippetId' with placement=module. Missing '' tag."); } - } - else if ($sPlacement === 'null') - { + } elseif ($sPlacement === 'null') { throw new DOMFormatException("Invalid definition for snippet id='$sSnippetId'. Missing tag."); - } - else - { + } else { throw new DOMFormatException("Invalid definition for snippet id='$sSnippetId'. Incorrect value '$sPlacement' for tag. The allowed values are either 'core' or 'module'."); } - if (!array_key_exists($sModuleId, $this->aSnippets)) - { - $this->aSnippets[$sModuleId] = array('before' => array(), 'after' => array()); + if (!array_key_exists($sModuleId, $this->aSnippets)) { + $this->aSnippets[$sModuleId] = ['before' => [], 'after' => []]; } $fOrder = (float) $oSnippet->GetChildText('rank', 0); $sContent = $oSnippet->GetChildText('content', ''); - if ($fOrder < 0) - { - $this->aSnippets[$sModuleId]['before'][] = array( + if ($fOrder < 0) { + $this->aSnippets[$sModuleId]['before'][] = [ 'rank' => $fOrder, 'content' => $sContent, 'snippet_id' => $sSnippetId, - ); - } - else - { - $this->aSnippets[$sModuleId]['after'][] = array( + ]; + } else { + $this->aSnippets[$sModuleId]['after'][] = [ 'rank' => $fOrder, 'content' => $sContent, 'snippet_id' => $sSnippetId, - ); + ]; } } - foreach($this->aSnippets as $sModuleId => $void) - { - uasort($this->aSnippets[$sModuleId]['before'], array(get_class($this), 'SortOnRank')); - uasort($this->aSnippets[$sModuleId]['after'], array(get_class($this), 'SortOnRank')); + foreach ($this->aSnippets as $sModuleId => $void) { + uasort($this->aSnippets[$sModuleId]['before'], [get_class($this), 'SortOnRank']); + uasort($this->aSnippets[$sModuleId]['after'], [get_class($this), 'SortOnRank']); } } @@ -3929,14 +3667,14 @@ EOF; $sContext = '["'.implode('", "', $aContexts).'"]'; } - $aEventListeners[] = array( + $aEventListeners[] = [ 'event_name' => $sEventName, 'callback' => $sCallback, 'content' => $sCallbackFct, 'rank' => $fRank, 'source' => $sEventSource, 'context' => $sContext, - ); + ]; } if (empty($aEventListeners)) { @@ -3967,13 +3705,13 @@ $sRegister PHP; $fOrder = 0; - $this->aSnippets[$sModuleId]['after'][] = array( + $this->aSnippets[$sModuleId]['after'][] = [ 'rank' => $fOrder, 'content' => $sContent, 'snippet_id' => $sClassName, - ); + ]; foreach ($this->aSnippets as $sModuleId => $void) { - uasort($this->aSnippets[$sModuleId]['after'], array(get_class($this), 'SortOnRank')); + uasort($this->aSnippets[$sModuleId]['after'], [get_class($this), 'SortOnRank']); } } @@ -4008,7 +3746,6 @@ PHP; return $aDefinition; } - /** * @throws \DOMFormatException * @since 3.1.0 N°6040 @@ -4075,7 +3812,6 @@ PHP; return $this->aDynamicAttributeDefinitions[$sAttributeName]['properties']; } - /** * We can't use var_export() as we need to output some PHP code, for example `utils::GetAbsoluteUrlModulesRoot()` calls * @@ -4085,9 +3821,8 @@ PHP; */ private function GetAssociativeArrayAsPhpCode($aAssocArray) { - $aArrayPhp = array(); - foreach ($aAssocArray as $sKey => $sPHPValue) - { + $aArrayPhp = []; + foreach ($aAssocArray as $sKey => $sPHPValue) { $aArrayPhp[] = " '$sKey' => $sPHPValue,"; } $sArrayPhp = implode("\n", $aArrayPhp); @@ -4120,17 +3855,13 @@ PHP; ) { $sPHP = "\n\n$sCodeComment\n"; - foreach ($aRequiredFiles as $sIncludeFile) - { + foreach ($aRequiredFiles as $sIncludeFile) { $sPHP .= "\nrequire_once('$sIncludeFile');\n"; } - if ($bIsAbstractClass) - { + if ($bIsAbstractClass) { $sPHP .= 'abstract class '.$sClassName; - } - else - { + } else { $sPHP .= 'class '.$sClassName; } $sPHP .= " extends $sParentClassName\n"; @@ -4162,8 +3893,8 @@ EOF; private function GeneratePhpCodeForZlist(string $sListCode, DOMNode $oListNode): string { $aAttributes = $oListNode->GetNodeAsArrayOfItems(); - if(!is_array($aAttributes)) { - $aAttributes = array(); + if (!is_array($aAttributes)) { + $aAttributes = []; } $this->ArrayOfItemsToZList($aAttributes); @@ -4192,13 +3923,11 @@ EOF; */ protected function WriteFile($sFilename, $sContent, $flags = null) { - if (is_file($sFilename) || is_link($sFilename)) - { + if (is_file($sFilename) || is_link($sFilename)) { @unlink($sFilename); } $ret = file_put_contents($sFilename, $sContent, $flags ?? 0); - if ($ret === false) - { + if ($ret === false) { $iLen = strlen($sContent); $fFree = @disk_free_space(dirname($sFilename)); $aErr = error_get_last(); @@ -4312,15 +4041,11 @@ XML; */ protected function WritePHPFile($sResultFile, $sModuleName, $sModuleVersion, $sCompiledCode) { - if (is_file($sResultFile)) - { + if (is_file($sResultFile)) { $this->Log("Updating $sResultFile for module $sModuleName in version $sModuleVersion"); - } - else - { + } else { $sResultDir = dirname($sResultFile); - if (!is_dir($sResultDir)) - { + if (!is_dir($sResultDir)) { $this->Log("Creating directory $sResultDir"); mkdir($sResultDir, 0777, true); } @@ -4353,8 +4078,7 @@ EOF; private static function RemoveSurroundingQuotes($sValue) { - if (utils::StartsWith($sValue, '\'') && utils::EndsWith($sValue, '\'')) - { + if (utils::StartsWith($sValue, '\'') && utils::EndsWith($sValue, '\'')) { $sValue = substr($sValue, 1, -1); } diff --git a/setup/extensionsmap.class.inc.php b/setup/extensionsmap.class.inc.php index 0e8fca1eb..5ac374521 100644 --- a/setup/extensionsmap.class.inc.php +++ b/setup/extensionsmap.class.inc.php @@ -12,9 +12,9 @@ require_once(APPROOT.'/setup/moduleinstaller.class.inc.php'); */ class iTopExtension { - const SOURCE_WIZARD = 'datamodels'; - const SOURCE_MANUAL = 'extensions'; - const SOURCE_REMOTE = 'data'; + public const SOURCE_WIZARD = 'datamodels'; + public const SOURCE_MANUAL = 'extensions'; + public const SOURCE_REMOTE = 'data'; /** * @var string @@ -103,12 +103,12 @@ class iTopExtension $this->bMarkedAsChosen = false; $this->sVersion = ITOP_VERSION; $this->sInstalledVersion = ''; - $this->aModules = array(); - $this->aModuleVersion = array(); - $this->aModuleInfo = array(); + $this->aModules = []; + $this->aModuleVersion = []; + $this->aModuleInfo = []; $this->sSourceDir = ''; $this->bVisible = true; - $this->aMissingDependencies = array(); + $this->aMissingDependencies = []; } /** @@ -146,18 +146,16 @@ class iTopExtensionsMap */ protected $aScannedDirs; - public function __construct($sFromEnvironment = 'production', $bNormalizeOldExtensions = true, $aExtraDirs = array()) + public function __construct($sFromEnvironment = 'production', $bNormalizeOldExtensions = true, $aExtraDirs = []) { - $this->aExtensions = array(); - $this->aScannedDirs = array(); + $this->aExtensions = []; + $this->aScannedDirs = []; $this->ScanDisk($sFromEnvironment); - foreach($aExtraDirs as $sDir) - { + foreach ($aExtraDirs as $sDir) { $this->ReadDir($sDir, iTopExtension::SOURCE_REMOTE); } $this->CheckDependencies($sFromEnvironment); - if ($bNormalizeOldExtensions) - { + if ($bNormalizeOldExtensions) { $this->NormalizeOldExtensions(); } } @@ -170,9 +168,10 @@ class iTopExtensionsMap */ protected function ScanDisk($sEnvironment) { - if (!$this->ReadInstallationWizard(APPROOT.'/datamodels/2.x') && !$this->ReadInstallationWizard(APPROOT.'/datamodels/2.x')) - { - if(!$this->ReadDir(APPROOT.'/datamodels/2.x', iTopExtension::SOURCE_WIZARD)) $this->ReadDir(APPROOT.'/datamodels/1.x', iTopExtension::SOURCE_WIZARD); + if (!$this->ReadInstallationWizard(APPROOT.'/datamodels/2.x') && !$this->ReadInstallationWizard(APPROOT.'/datamodels/2.x')) { + if (!$this->ReadDir(APPROOT.'/datamodels/2.x', iTopExtension::SOURCE_WIZARD)) { + $this->ReadDir(APPROOT.'/datamodels/1.x', iTopExtension::SOURCE_WIZARD); + } } $this->ReadDir(APPROOT.'/extensions', iTopExtension::SOURCE_MANUAL); $this->ReadDir(APPROOT.'/data/'.$sEnvironment.'-modules', iTopExtension::SOURCE_REMOTE); @@ -186,17 +185,16 @@ class iTopExtensionsMap */ protected function ReadInstallationWizard($sDir) { - if (!is_readable($sDir.'/installation.xml')) return false; + if (!is_readable($sDir.'/installation.xml')) { + return false; + } $oXml = new XMLParameters($sDir.'/installation.xml'); - foreach($oXml->Get('steps') as $aStepInfo) - { - if (array_key_exists('options', $aStepInfo)) - { + foreach ($oXml->Get('steps') as $aStepInfo) { + if (array_key_exists('options', $aStepInfo)) { $this->ProcessWizardChoices($aStepInfo['options']); } - if (array_key_exists('alternatives', $aStepInfo)) - { + if (array_key_exists('alternatives', $aStepInfo)) { $this->ProcessWizardChoices($aStepInfo['alternatives']); } } @@ -210,26 +208,20 @@ class iTopExtensionsMap */ protected function ProcessWizardChoices($aChoices) { - foreach($aChoices as $aChoiceInfo) - { - if (array_key_exists('extension_code', $aChoiceInfo)) - { + foreach ($aChoices as $aChoiceInfo) { + if (array_key_exists('extension_code', $aChoiceInfo)) { $oExtension = new iTopExtension(); $oExtension->sCode = $aChoiceInfo['extension_code']; $oExtension->sLabel = $aChoiceInfo['title']; - if (array_key_exists('modules', $aChoiceInfo)) - { + if (array_key_exists('modules', $aChoiceInfo)) { // Some wizard choices are not associated with any module $oExtension->aModules = $aChoiceInfo['modules']; } - if (array_key_exists('sub_options', $aChoiceInfo)) - { - if (array_key_exists('options', $aChoiceInfo['sub_options'])) - { + if (array_key_exists('sub_options', $aChoiceInfo)) { + if (array_key_exists('options', $aChoiceInfo['sub_options'])) { $this->ProcessWizardChoices($aChoiceInfo['sub_options']['options']); } - if (array_key_exists('alternatives', $aChoiceInfo['sub_options'])) - { + if (array_key_exists('alternatives', $aChoiceInfo['sub_options'])) { $this->ProcessWizardChoices($aChoiceInfo['sub_options']['alternatives']); } } @@ -246,19 +238,14 @@ class iTopExtensionsMap */ protected function AddExtension(iTopExtension $oNewExtension) { - foreach($this->aExtensions as $key => $oExtension) - { - if ($oExtension->sCode == $oNewExtension->sCode) - { - if (version_compare($oNewExtension->sVersion, $oExtension->sVersion, '>')) - { + foreach ($this->aExtensions as $key => $oExtension) { + if ($oExtension->sCode == $oNewExtension->sCode) { + if (version_compare($oNewExtension->sVersion, $oExtension->sVersion, '>')) { // This "new" extension is "newer" than the previous one, let's replace the previous one unset($this->aExtensions[$key]); $this->aExtensions[$oNewExtension->sCode.'/'.$oNewExtension->sVersion] = $oNewExtension; return; - } - else - { + } else { // This "new" extension is not "newer" than the previous one, let's ignore it return; } @@ -274,9 +261,9 @@ class iTopExtensionsMap * * @return \iTopExtension|null */ - public function Get(string $sExtensionCode):?iTopExtension + public function Get(string $sExtensionCode): ?iTopExtension { - foreach($this->aExtensions as $oExtension) { + foreach ($this->aExtensions as $oExtension) { if ($oExtension->sCode === $sExtensionCode) { return $oExtension; } @@ -295,17 +282,17 @@ class iTopExtensionsMap */ protected function ReadDir($sSearchDir, $sSource, $sParentExtensionId = null) { - if (!is_readable($sSearchDir)) return false; + if (!is_readable($sSearchDir)) { + return false; + } $hDir = opendir($sSearchDir); - if ($hDir !== false) - { - if ($sParentExtensionId == null) - { + if ($hDir !== false) { + if ($sParentExtensionId == null) { // We're not recursing, let's add the directory to the list of scanned dirs $this->aScannedDirs[] = $sSearchDir; } $sExtensionId = null; - $aSubDirectories = array(); + $aSubDirectories = []; // First check if there is an extension.xml file in this directory if (is_readable($sSearchDir.'/extension.xml')) { @@ -324,22 +311,17 @@ class iTopExtensionsMap $this->AddExtension($oExtension); } // Then scan the other files and subdirectories - while (($sFile = readdir($hDir)) !== false) - { - if (($sFile !== '.') && ($sFile !== '..')) - { - $aMatches = array(); - if (is_dir($sSearchDir.'/'.$sFile)) - { + while (($sFile = readdir($hDir)) !== false) { + if (($sFile !== '.') && ($sFile !== '..')) { + $aMatches = []; + if (is_dir($sSearchDir.'/'.$sFile)) { // Recurse after parsing all the regular files $aSubDirectories[] = $sSearchDir.'/'.$sFile; - } - else if (preg_match('/^module\.(.*).php$/i', $sFile, $aMatches)) - { + } elseif (preg_match('/^module\.(.*).php$/i', $sFile, $aMatches)) { // Found a module try { $aModuleInfo = ModuleFileReader::GetInstance()->ReadModuleFileInformation($sSearchDir.'/'.$sFile); - } catch(ModuleFileReaderException $e){ + } catch (ModuleFileReaderException $e) { continue; } // If we are not already inside a formal extension, then the module itself is considered @@ -358,15 +340,13 @@ class iTopExtensionsMap $this->aExtensions[$sParentExtensionId]->aModules[] = $sModuleName; $this->aExtensions[$sParentExtensionId]->aModuleVersion[$sModuleName] = $sModuleVersion; $this->aExtensions[$sParentExtensionId]->aModuleInfo[$sModuleName] = $aModuleInfo[ModuleFileReader::MODULE_INFO_CONFIG]; - } - else { + } else { // Not already inside an folder containing an 'extension.xml' file // Ignore non-visible modules and auto-select ones, since these are never prompted // as a choice to the end-user $bVisible = true; - if (!$aModuleInfo[ModuleFileReader::MODULE_INFO_CONFIG]['visible'] || isset($aModuleInfo[ModuleFileReader::MODULE_INFO_CONFIG]['auto_select'])) - { + if (!$aModuleInfo[ModuleFileReader::MODULE_INFO_CONFIG]['visible'] || isset($aModuleInfo[ModuleFileReader::MODULE_INFO_CONFIG]['auto_select'])) { $bVisible = false; } @@ -379,7 +359,7 @@ class iTopExtensionsMap $oExtension->sSource = $sSource; $oExtension->bMandatory = $aModuleInfo[ModuleFileReader::MODULE_INFO_CONFIG]['mandatory']; $oExtension->sMoreInfoUrl = $aModuleInfo[ModuleFileReader::MODULE_INFO_CONFIG]['doc.more_information']; - $oExtension->aModules = array($sModuleName); + $oExtension->aModules = [$sModuleName]; $oExtension->aModuleVersion[$sModuleName] = $sModuleVersion; $oExtension->aModuleInfo[$sModuleName] = $aModuleInfo[ModuleFileReader::MODULE_INFO_CONFIG]; $oExtension->sSourceDir = $sSearchDir; @@ -394,10 +374,9 @@ class iTopExtensionsMap } } closedir($hDir); - foreach($aSubDirectories as $sDir) - { + foreach ($aSubDirectories as $sDir) { // Recurse inside the subdirectories - $this->ReadDir($sDir, $sSource, $sExtensionId); + $this->ReadDir($sDir, $sSource, $sExtensionId); } return true; } @@ -412,38 +391,28 @@ class iTopExtensionsMap */ protected function CheckDependencies($sFromEnvironment) { - $aSearchDirs = array(); + $aSearchDirs = []; - if (is_dir(APPROOT.'/datamodels/2.x')) - { + if (is_dir(APPROOT.'/datamodels/2.x')) { $aSearchDirs[] = APPROOT.'/datamodels/2.x'; - } - else if (is_dir(APPROOT.'/datamodels/1.x')) - { + } elseif (is_dir(APPROOT.'/datamodels/1.x')) { $aSearchDirs[] = APPROOT.'/datamodels/1.x'; } $aSearchDirs = array_merge($aSearchDirs, $this->aScannedDirs); - try - { + try { $aAllModules = ModuleDiscovery::GetAvailableModules($aSearchDirs, true); - } - catch(MissingDependencyException $e) - { + } catch (MissingDependencyException $e) { // Some modules have missing dependencies // Let's check what is the impact at the "extensions" level - foreach($this->aExtensions as $sKey => $oExtension) - { - foreach($oExtension->aModules as $sModuleName) - { - if (array_key_exists($sModuleName, $oExtension->aModuleVersion)) - { + foreach ($this->aExtensions as $sKey => $oExtension) { + foreach ($oExtension->aModules as $sModuleName) { + if (array_key_exists($sModuleName, $oExtension->aModuleVersion)) { // This information is not available for pseudo modules defined in the installation wizard, but let's ignore them $sVersion = $oExtension->aModuleVersion[$sModuleName]; $sModuleId = $sModuleName.'/'.$sVersion; - if (array_key_exists($sModuleId, $e->aModulesInfo)) - { + if (array_key_exists($sModuleId, $e->aModulesInfo)) { // The extension actually contains a module which has unmet dependencies $aModuleInfo = $e->aModulesInfo[$sModuleId]; $this->aExtensions[$sKey]->aMissingDependencies = array_merge($oExtension->aMissingDependencies, $aModuleInfo['dependencies']); @@ -471,17 +440,14 @@ class iTopExtensionsMap */ public function MarkAsChosen($sExtensionCode, $bMark = true) { - foreach($this->aExtensions as $oExtension) - { - if ($oExtension->sCode == $sExtensionCode) - { + foreach ($this->aExtensions as $oExtension) { + if ($oExtension->sCode == $sExtensionCode) { $oExtension->bMarkedAsChosen = $bMark; break; } } } - /** * Tells if a given extension(code) is marked as chosen * @param string $sExtensionCode @@ -489,10 +455,8 @@ class iTopExtensionsMap */ public function IsMarkedAsChosen($sExtensionCode) { - foreach($this->aExtensions as $oExtension) - { - if ($oExtension->sCode == $sExtensionCode) - { + foreach ($this->aExtensions as $oExtension) { + if ($oExtension->sCode == $sExtensionCode) { return $oExtension->bMarkedAsChosen; } } @@ -507,10 +471,8 @@ class iTopExtensionsMap */ protected function SetInstalledVersion($sExtensionCode, $sInstalledVersion) { - foreach($this->aExtensions as $oExtension) - { - if ($oExtension->sCode == $sExtensionCode) - { + foreach ($this->aExtensions as $oExtension) { + if ($oExtension->sCode == $sExtensionCode) { $oExtension->sInstalledVersion = $sInstalledVersion; break; } @@ -523,11 +485,9 @@ class iTopExtensionsMap */ public function GetChoices() { - $aResult = array(); - foreach($this->aExtensions as $oExtension) - { - if ($oExtension->bMarkedAsChosen) - { + $aResult = []; + foreach ($this->aExtensions as $oExtension) { + if ($oExtension->bMarkedAsChosen) { $aResult[] = $oExtension; } } @@ -541,24 +501,19 @@ class iTopExtensionsMap */ public function LoadChoicesFromDatabase(Config $oConfig) { - try - { - $aInstalledExtensions = array(); - if (CMDBSource::DBName() === null) - { + try { + $aInstalledExtensions = []; + if (CMDBSource::DBName() === null) { CMDBSource::InitFromConfig($oConfig); } $sLatestInstallationDate = CMDBSource::QueryToScalar("SELECT max(installed) FROM ".$oConfig->Get('db_subname')."priv_extension_install"); $aInstalledExtensions = CMDBSource::QueryToArray("SELECT * FROM ".$oConfig->Get('db_subname')."priv_extension_install WHERE installed = '".$sLatestInstallationDate."'"); - } - catch (MySQLException $e) - { + } catch (MySQLException $e) { // No database or erroneous information return false; } - foreach($aInstalledExtensions as $aDBInfo) - { + foreach ($aInstalledExtensions as $aDBInfo) { $this->MarkAsChosen($aDBInfo['code']); $this->SetInstalledVersion($aDBInfo['code'], $aDBInfo['version']); } @@ -573,15 +528,14 @@ class iTopExtensionsMap public function IsExtensionObsoletedByAnother(iTopExtension $oExtension) { // Complex extensions (more than 1 module) are never considered as obsolete - if (count($oExtension->aModules) != 1) return null; + if (count($oExtension->aModules) != 1) { + return null; + } - foreach($this->GetAllExtensions() as $oOtherExtension) - { - if (($oOtherExtension->sSourceDir != $oExtension->sSourceDir) && ($oOtherExtension->sSource != iTopExtension::SOURCE_WIZARD)) - { + foreach ($this->GetAllExtensions() as $oOtherExtension) { + if (($oOtherExtension->sSourceDir != $oExtension->sSourceDir) && ($oOtherExtension->sSource != iTopExtension::SOURCE_WIZARD)) { if (array_key_exists($oExtension->sCode, $oOtherExtension->aModuleVersion) && - (version_compare($oOtherExtension->aModuleVersion[$oExtension->sCode], $oExtension->sVersion, '>=')) ) - { + (version_compare($oOtherExtension->aModuleVersion[$oExtension->sCode], $oExtension->sVersion, '>='))) { // Found another extension containing a more recent version of the extension/module return $oOtherExtension; } @@ -602,21 +556,22 @@ class iTopExtensionsMap public function NormalizeOldExtensions($sInSourceOnly = iTopExtension::SOURCE_MANUAL) { $aSignatures = $this->GetOldExtensionsSignatures(); - foreach($aSignatures as $sExtensionCode => $aExtensionSignatures) { + foreach ($aSignatures as $sExtensionCode => $aExtensionSignatures) { $bFound = false; - foreach($aExtensionSignatures['versions'] as $sVersion => $aModules) { + foreach ($aExtensionSignatures['versions'] as $sVersion => $aModules) { $bInstalled = true; - foreach($aModules as $sModuleId) { - if(!$this->ModuleIsPresent($sModuleId, $sInSourceOnly)) { + foreach ($aModules as $sModuleId) { + if (!$this->ModuleIsPresent($sModuleId, $sInSourceOnly)) { $bFound = false; break; // One missing module is enough to determine that the extension/version is not present - } - else { + } else { $bInstalled = $bInstalled && $this->ModuleIsInstalled($sModuleId, $sInSourceOnly); $bFound = true; } } - if ($bFound) break; // The current version matches the signature + if ($bFound) { + break; + } // The current version matches the signature } if ($bFound) { @@ -626,12 +581,12 @@ class iTopExtensionsMap $oExtension->sSource = $sInSourceOnly; $oExtension->sDescription = $aExtensionSignatures['description']; $oExtension->sVersion = $sVersion; - $oExtension->aModules = array(); + $oExtension->aModules = []; if ($bInstalled) { $oExtension->sInstalledVersion = $sVersion; $oExtension->bMarkedAsChosen = true; } - foreach($aModules as $sModuleId) { + foreach ($aModules as $sModuleId) { list($sModuleName, $sModuleVersion) = ModuleDiscovery::GetModuleName($sModuleId); $oExtension->aModules[] = $sModuleName; $oExtension->aModuleInfo[$sModuleName] = $this->aExtensions[$sModuleId]->aModuleInfo[$sModuleName]; @@ -662,7 +617,7 @@ class iTopExtensionsMap { return (array_key_exists($sModuleIdToFind, $this->aExtensions) && ($this->aExtensions[$sModuleIdToFind]->sSource == $sInSourceOnly) && - ($this->aExtensions[$sModuleIdToFind]->sInstalledVersion !== '') ); + ($this->aExtensions[$sModuleIdToFind]->sInstalledVersion !== '')); } /** @@ -675,12 +630,10 @@ class iTopExtensionsMap { $bChosen = false; - foreach($this->GetAllExtensions() as $oExtension) - { + foreach ($this->GetAllExtensions() as $oExtension) { if (($oExtension->sSource == $sInSourceOnly) && ($oExtension->bMarkedAsChosen == true) && - (array_key_exists($sModuleNameToFind, $oExtension->aModuleVersion))) - { + (array_key_exists($sModuleNameToFind, $oExtension->aModuleVersion))) { return true; } } @@ -694,8 +647,7 @@ class iTopExtensionsMap */ protected function ReplaceModulesByNormalizedExtension($aModules, iTopExtension $oNewExtension) { - foreach($aModules as $sModuleId) - { + foreach ($aModules as $sModuleId) { unset($this->aExtensions[$sModuleId]); } $this->AddExtension($oNewExtension); @@ -709,636 +661,636 @@ class iTopExtensionsMap protected function GetOldExtensionsSignatures() { // Generated by the Factory using the page export_component_versions_for_normalisation.php - return array ( + return [ 'combodo-approval-process-light' => - array ( + [ 'label' => 'Approval process light', 'description' => 'Approve a request via a simple email', 'versions' => - array ( + [ '1.0.1' => - array ( + [ 0 => 'approval-base/2.1.0', 1 => 'combodo-approval-light/1.0.1', - ), + ], '1.0.2' => - array ( + [ 0 => 'approval-base/2.1.1', 1 => 'combodo-approval-light/1.0.2', - ), + ], '1.0.3' => - array ( + [ 0 => 'approval-base/2.1.2', 1 => 'combodo-approval-light/1.0.2', - ), + ], '1.1.0' => - array ( + [ 0 => 'approval-base/2.2.2', 1 => 'combodo-approval-light/1.0.2', - ), + ], '1.1.1' => - array ( + [ 0 => 'approval-base/2.2.3', 1 => 'combodo-approval-light/1.0.2', - ), + ], '1.1.2' => - array ( + [ 0 => 'approval-base/2.2.6', 1 => 'combodo-approval-light/1.0.2', - ), + ], '1.1.3' => - array ( + [ 0 => 'approval-base/2.2.6', 1 => 'combodo-approval-light/1.0.3', - ), + ], '1.2.0' => - array ( + [ 0 => 'approval-base/2.3.0', 1 => 'combodo-approval-light/1.0.3', - ), + ], '1.2.1' => - array ( + [ 0 => 'approval-base/2.4.0', 1 => 'combodo-approval-light/1.0.4', - ), + ], '1.3.0' => - array ( + [ 0 => 'approval-base/2.4.2', 1 => 'combodo-approval-light/1.1.1', - ), + ], '1.3.1' => - array ( + [ 0 => 'approval-base/2.5.0', 1 => 'combodo-approval-light/1.1.1', - ), + ], '1.3.2' => - array ( + [ 0 => 'approval-base/2.5.0', 1 => 'combodo-approval-light/1.1.2', - ), + ], '1.2.2' => - array ( + [ 0 => 'approval-base/2.4.2', 1 => 'combodo-approval-light/1.0.5', - ), + ], '1.3.3' => - array ( + [ 0 => 'approval-base/2.5.1', 1 => 'combodo-approval-light/1.1.2', - ), + ], '1.3.4' => - array ( + [ 0 => 'approval-base/2.5.2', 1 => 'combodo-approval-light/1.1.2', - ), + ], '1.3.5' => - array ( + [ 0 => 'approval-base/2.5.3', 1 => 'combodo-approval-light/1.1.2', - ), + ], '1.4.0' => - array ( + [ 0 => 'approval-base/2.5.3', 1 => 'combodo-approval-light/1.1.2', 2 => 'itop-approval-portal/1.0.0', - ), - ), - ), + ], + ], + ], 'combodo-approval-process-automation' => - array ( + [ 'label' => 'Approval process automation', 'description' => 'Control your approval process with predefined rules based on service catalog', 'versions' => - array ( + [ '1.0.1' => - array ( + [ 0 => 'approval-base/2.1.0', 1 => 'combodo-approval-extended/1.0.2', - ), + ], '1.0.2' => - array ( + [ 0 => 'approval-base/2.1.1', 1 => 'combodo-approval-extended/1.0.4', - ), + ], '1.0.3' => - array ( + [ 0 => 'approval-base/2.1.2', 1 => 'combodo-approval-extended/1.0.4', - ), + ], '1.1.0' => - array ( + [ 0 => 'approval-base/2.2.2', 1 => 'combodo-approval-extended/1.0.4', - ), + ], '1.1.1' => - array ( + [ 0 => 'approval-base/2.2.3', 1 => 'combodo-approval-extended/1.0.4', - ), + ], '1.1.2' => - array ( + [ 0 => 'approval-base/2.2.6', 1 => 'combodo-approval-extended/1.0.5', - ), + ], '1.1.3' => - array ( + [ 0 => 'approval-base/2.2.6', 1 => 'combodo-approval-extended/1.0.6', - ), + ], '1.2.0' => - array ( + [ 0 => 'approval-base/2.3.0', 1 => 'combodo-approval-extended/1.0.7', - ), + ], '1.2.1' => - array ( + [ 0 => 'approval-base/2.4.0', 1 => 'combodo-approval-extended/1.0.8', - ), + ], '1.3.0' => - array ( + [ 0 => 'approval-base/2.4.2', 1 => 'combodo-approval-extended/1.2.1', - ), + ], '1.3.1' => - array ( + [ 0 => 'approval-base/2.5.0', 1 => 'combodo-approval-extended/1.2.1', - ), + ], '1.3.2' => - array ( + [ 0 => 'approval-base/2.5.0', 1 => 'combodo-approval-extended/1.2.2', - ), + ], '1.2.2' => - array ( + [ 0 => 'approval-base/2.4.2', 1 => 'combodo-approval-extended/1.0.9', - ), + ], '1.3.3' => - array ( + [ 0 => 'approval-base/2.5.1', 1 => 'combodo-approval-extended/1.2.3', - ), + ], '1.3.4' => - array ( + [ 0 => 'approval-base/2.5.2', 1 => 'combodo-approval-extended/1.2.3', - ), + ], '1.3.5' => - array ( + [ 0 => 'approval-base/2.5.3', 1 => 'combodo-approval-extended/1.2.3', - ), + ], '1.4.0' => - array ( + [ 0 => 'approval-base/2.5.3', 1 => 'combodo-approval-extended/1.2.3', 3 => 'itop-approval-portal/1.0.0', - ), - ), - ), + ], + ], + ], 'combodo-predefined-response-models' => - array ( + [ 'label' => 'Predefined response models', 'description' => 'Pick common answers from a list of predefined replies grouped by categories to update tickets log', 'versions' => - array ( + [ '1.0.0' => - array ( + [ 0 => 'precanned-replies/1.0.0', 1 => 'precanned-replies-pro/1.0.0', - ), + ], '1.0.1' => - array ( + [ 0 => 'precanned-replies/1.0.1', 1 => 'precanned-replies-pro/1.0.1', - ), + ], '1.0.2' => - array ( + [ 0 => 'precanned-replies/1.0.2', 1 => 'precanned-replies-pro/1.0.1', - ), + ], '1.0.3' => - array ( + [ 0 => 'precanned-replies/1.0.3', 1 => 'precanned-replies-pro/1.0.1', - ), + ], '1.0.4' => - array ( + [ 0 => 'precanned-replies/1.0.3', 1 => 'precanned-replies-pro/1.0.2', - ), + ], '1.0.5' => - array ( + [ 0 => 'precanned-replies/1.0.4', 1 => 'precanned-replies-pro/1.0.2', - ), + ], '1.1.0' => - array ( + [ 0 => 'precanned-replies/1.1.0', 1 => 'precanned-replies-pro/1.0.2', - ), + ], '1.1.1' => - array ( + [ 0 => 'precanned-replies/1.1.1', 1 => 'precanned-replies-pro/1.0.2', - ), - ), - ), + ], + ], + ], 'combodo-customized-request-forms' => - array ( + [ 'label' => 'Customized request forms', 'description' => 'Define personalized request forms based on the service catalog. Add extra fields for a given type of request.', 'versions' => - array ( + [ '1.0.1' => - array ( + [ 0 => 'templates-base/2.1.1', 1 => 'itop-request-template/1.0.0', - ), + ], '1.0.2' => - array ( + [ 0 => 'templates-base/2.1.2', 1 => 'itop-request-template/1.0.0', - ), + ], '1.0.3' => - array ( + [ 0 => 'templates-base/2.1.2', 1 => 'itop-request-template/1.0.1', - ), + ], '1.0.4' => - array ( + [ 0 => 'templates-base/2.1.3', 1 => 'itop-request-template/1.0.1', - ), + ], '1.0.5' => - array ( + [ 0 => 'templates-base/2.1.4', 1 => 'itop-request-template/1.0.1', - ), + ], '2.0.0' => - array ( + [ 0 => 'templates-base/3.0.0', 1 => 'itop-request-template/2.0.0', 2 => 'itop-request-template-portal/1.0.0', - ), + ], '2.0.1' => - array ( + [ 0 => 'templates-base/3.0.1', 1 => 'itop-request-template/2.0.0', 2 => 'itop-request-template-portal/1.0.0', - ), + ], '2.0.2' => - array ( + [ 0 => 'templates-base/3.0.2', 1 => 'itop-request-template/2.0.0', 2 => 'itop-request-template-portal/1.0.0', - ), + ], '2.0.3' => - array ( + [ 0 => 'templates-base/3.0.4', 1 => 'itop-request-template/2.0.0', 2 => 'itop-request-template-portal/1.0.0', - ), + ], '2.0.4' => - array ( + [ 0 => 'templates-base/3.0.5', 1 => 'itop-request-template/2.0.0', 2 => 'itop-request-template-portal/1.0.0', - ), + ], '2.0.5' => - array ( + [ 0 => 'templates-base/3.0.6', 1 => 'itop-request-template/2.0.0', 2 => 'itop-request-template-portal/1.0.0', - ), + ], '2.0.6' => - array ( + [ 0 => 'templates-base/3.0.8', 1 => 'itop-request-template/2.0.0', 2 => 'itop-request-template-portal/1.0.0', - ), + ], '2.0.7' => - array ( + [ 0 => 'templates-base/3.0.9', 1 => 'itop-request-template/2.0.0', 2 => 'itop-request-template-portal/1.0.0', - ), + ], '2.0.8' => - array ( + [ 0 => 'templates-base/3.0.12', 1 => 'itop-request-template/2.0.0', 2 => 'itop-request-template-portal/1.0.0', - ), - ), - ), + ], + ], + ], 'combodo-sla-considering-business-hours' => - array ( + [ 'label' => 'SLA considering business hours', 'description' => 'Compute SLAs taking into account service coverage window and holidays', 'versions' => - array ( + [ '2.0.1' => - array ( + [ 0 => 'combodo-sla-computation/2.0.1', 1 => 'combodo-coverage-windows-computation/2.0.0', - ), + ], '2.1.0' => - array ( + [ 0 => 'combodo-sla-computation/2.1.0', 1 => 'combodo-coverage-windows-computation/2.0.0', - ), + ], '2.1.1' => - array ( + [ 0 => 'combodo-sla-computation/2.1.1', 1 => 'combodo-coverage-windows-computation/2.0.0', - ), + ], '2.1.2' => - array ( + [ 0 => 'combodo-sla-computation/2.1.2', 1 => 'combodo-coverage-windows-computation/2.0.0', - ), + ], '2.1.3' => - array ( + [ 0 => 'combodo-sla-computation/2.1.2', 1 => 'combodo-coverage-windows-computation/2.0.1', - ), + ], '2.0.2' => - array ( + [ 0 => 'combodo-sla-computation/2.0.1', 1 => 'combodo-coverage-windows-computation/2.0.1', - ), + ], '2.1.4' => - array ( + [ 0 => 'combodo-sla-computation/2.1.3', 1 => 'combodo-coverage-windows-computation/2.0.1', - ), + ], '2.1.5' => - array ( + [ 0 => 'combodo-sla-computation/2.1.5', 1 => 'combodo-coverage-windows-computation/2.0.1', - ), + ], '2.1.6' => - array ( + [ 0 => 'combodo-sla-computation/2.1.5', 1 => 'combodo-coverage-windows-computation/2.0.2', - ), + ], '2.1.7' => - array ( + [ 0 => 'combodo-sla-computation/2.1.6', 1 => 'combodo-coverage-windows-computation/2.0.2', - ), + ], '2.1.8' => - array ( + [ 0 => 'combodo-sla-computation/2.1.7', 1 => 'combodo-coverage-windows-computation/2.0.2', - ), + ], '2.1.9' => - array ( + [ 0 => 'combodo-sla-computation/2.1.8', 1 => 'combodo-coverage-windows-computation/2.0.2', - ), - ), - ), + ], + ], + ], 'combodo-mail-to-ticket-automation' => - array ( + [ 'label' => 'Mail to ticket automation', 'description' => 'Scan several mailboxes to create or update tickets.', 'versions' => - array ( + [ '2.6.0' => - array ( + [ 0 => 'combodo-email-synchro/2.6.0', 1 => 'itop-standard-email-synchro/2.6.0', - ), + ], '2.6.1' => - array ( + [ 0 => 'combodo-email-synchro/2.6.1', 1 => 'itop-standard-email-synchro/2.6.0', - ), + ], '2.6.2' => - array ( + [ 0 => 'combodo-email-synchro/2.6.2', 1 => 'itop-standard-email-synchro/2.6.0', - ), + ], '2.6.3' => - array ( + [ 0 => 'combodo-email-synchro/2.6.2', 1 => 'itop-standard-email-synchro/2.6.1', - ), + ], '2.6.4' => - array ( + [ 0 => 'combodo-email-synchro/2.6.3', 1 => 'itop-standard-email-synchro/2.6.2', - ), + ], '2.6.5' => - array ( + [ 0 => 'combodo-email-synchro/2.6.4', 1 => 'itop-standard-email-synchro/2.6.2', - ), + ], '2.6.6' => - array ( + [ 0 => 'combodo-email-synchro/2.6.5', 1 => 'itop-standard-email-synchro/2.6.3', - ), + ], '2.6.7' => - array ( + [ 0 => 'combodo-email-synchro/2.6.6', 1 => 'itop-standard-email-synchro/2.6.4', - ), + ], '2.6.8' => - array ( + [ 0 => 'combodo-email-synchro/2.6.7', 1 => 'itop-standard-email-synchro/2.6.4', - ), + ], '2.6.9' => - array ( + [ 0 => 'combodo-email-synchro/2.6.8', 1 => 'itop-standard-email-synchro/2.6.5', - ), + ], '2.6.10' => - array ( + [ 0 => 'combodo-email-synchro/2.6.9', 1 => 'itop-standard-email-synchro/2.6.6', - ), + ], '2.6.11' => - array ( + [ 0 => 'combodo-email-synchro/2.6.10', 1 => 'itop-standard-email-synchro/2.6.6', - ), + ], '2.6.12' => - array ( + [ 0 => 'combodo-email-synchro/2.6.11', 1 => 'itop-standard-email-synchro/2.6.6', - ), + ], '3.0.0' => - array ( + [ 0 => 'combodo-email-synchro/3.0.0', 1 => 'itop-standard-email-synchro/3.0.0', - ), + ], '3.0.1' => - array ( + [ 0 => 'combodo-email-synchro/3.0.1', 1 => 'itop-standard-email-synchro/3.0.1', - ), + ], '3.0.2' => - array ( + [ 0 => 'combodo-email-synchro/3.0.2', 1 => 'itop-standard-email-synchro/3.0.1', - ), + ], '3.0.3' => - array ( + [ 0 => 'combodo-email-synchro/3.0.3', 1 => 'itop-standard-email-synchro/3.0.3', - ), + ], '3.0.4' => - array ( + [ 0 => 'combodo-email-synchro/3.0.3', 1 => 'itop-standard-email-synchro/3.0.4', - ), + ], '3.0.5' => - array ( + [ 0 => 'combodo-email-synchro/3.0.4', 1 => 'itop-standard-email-synchro/3.0.4', - ), + ], '3.0.6' => - array ( + [ 0 => 'combodo-email-synchro/3.0.5', 1 => 'itop-standard-email-synchro/3.0.4', - ), + ], '3.0.7' => - array ( + [ 0 => 'combodo-email-synchro/3.0.5', 1 => 'itop-standard-email-synchro/3.0.5', - ), - ), - ), + ], + ], + ], 'combodo-configurator-for-automatic-object-creation' => - array ( + [ 'label' => 'Configurator for automatic object creation', 'description' => 'Templating based on existing objects.', 'versions' => - array ( + [ '1.0.13' => - array ( + [ 1 => 'itop-stencils/1.0.6', - ), - ), - ), + ], + ], + ], 'combodo-user-actions-configurator' => - array ( + [ 'label' => 'User actions configurator', 'description' => 'Configure user actions to simplify and automate processes (e.g. create an incident from a CI).', 'versions' => - array ( + [ '1.0.0' => - array ( + [ 0 => 'itop-object-copier/1.0.0', - ), + ], '1.0.1' => - array ( + [ 0 => 'itop-object-copier/1.0.1', - ), + ], '1.0.2' => - array ( + [ 0 => 'itop-object-copier/1.0.2', - ), + ], '1.0.3' => - array ( + [ 0 => 'itop-object-copier/1.0.3', - ), + ], '1.1.0' => - array ( + [ 0 => 'itop-object-copier/1.1.0', - ), + ], '1.1.1' => - array ( + [ 0 => 'itop-object-copier/1.1.1', - ), + ], '1.1.2' => - array ( + [ 0 => 'itop-object-copier/1.1.2', - ), + ], '1.1.3' => - array ( + [ 0 => 'itop-object-copier/1.1.3', - ), + ], '1.1.4' => - array ( + [ 0 => 'itop-object-copier/1.1.4', - ), + ], '1.1.5' => - array ( + [ 0 => 'itop-object-copier/1.1.5', - ), + ], '1.1.6' => - array ( + [ 0 => 'itop-object-copier/1.1.6', - ), + ], '1.1.7' => - array ( + [ 0 => 'itop-object-copier/1.1.7', - ), + ], '1.1.8' => - array ( + [ 0 => 'itop-object-copier/1.1.8', - ), - ), - ), + ], + ], + ], 'combodo-send-updates-by-email' => - array ( + [ 'label' => 'Send updates by email', 'description' => 'Send an email to pre-configured contacts when a ticket log is updated.', 'versions' => - array ( + [ '1.0.1' => - array ( + [ 0 => 'email-reply/1.0.1', - ), + ], '1.0.3' => - array ( + [ 0 => 'email-reply/1.0.3', - ), + ], '1.1.1' => - array ( + [ 0 => 'email-reply/1.1.1', - ), + ], '1.1.2' => - array ( + [ 0 => 'email-reply/1.1.2', - ), + ], '1.1.3' => - array ( + [ 0 => 'email-reply/1.1.3', - ), + ], '1.1.4' => - array ( + [ 0 => 'email-reply/1.1.4', - ), + ], '1.1.5' => - array ( + [ 0 => 'email-reply/1.1.5', - ), + ], '1.1.6' => - array ( + [ 0 => 'email-reply/1.1.6', - ), + ], '1.1.7' => - array ( + [ 0 => 'email-reply/1.1.7', - ), + ], // 1.1.8 was never released '1.1.9' => - array ( + [ 0 => 'email-reply/1.1.9', - ), + ], '1.1.10' => - array ( + [ 0 => 'email-reply/1.1.10', - ), - ), - ), - ); + ], + ], + ], + ]; } } diff --git a/setup/itopdesignformat.class.inc.php b/setup/itopdesignformat.class.inc.php index ec8d7d257..92fb11edd 100644 --- a/setup/itopdesignformat.class.inc.php +++ b/setup/itopdesignformat.class.inc.php @@ -1,4 +1,5 @@ array( + public static $aVersions = [ + '1.0' => [ 'previous' => null, 'go_to_previous' => null, 'next' => '1.1', 'go_to_next' => 'From10To11', - ), - '1.1' => array( + ], + '1.1' => [ 'previous' => '1.0', 'go_to_previous' => 'From11To10', 'next' => '1.2', 'go_to_next' => 'From11To12', - ), - '1.2' => array( + ], + '1.2' => [ 'previous' => '1.1', 'go_to_previous' => 'From12To11', 'next' => '1.3', 'go_to_next' => 'From12To13', - ), - '1.3' => array( // iTop >= 2.2.0 - 'previous' => '1.2', - 'go_to_previous' => 'From13To12', - 'next' => '1.4', - 'go_to_next' => 'From13To14', - ), - '1.4' => array( // iTop >= 2.4.0 - 'previous' => '1.3', - 'go_to_previous' => 'From14To13', - 'next' => '1.5', - 'go_to_next' => 'From14To15', - ), - '1.5' => array( // iTop >= 2.5.0 - 'previous' => '1.4', - 'go_to_previous' => 'From15To14', - 'next' => '1.6', - 'go_to_next' => 'From15To16', - ), - '1.6' => array( // iTop >= 2.6.0 - 'previous' => '1.5', - 'go_to_previous' => 'From16To15', - 'next' => '1.7', - 'go_to_next' => 'From16To17', - ), - '1.7' => array( // iTop >= 2.7.0 - 'previous' => '1.6', - 'go_to_previous' => 'From17To16', - 'next' => '3.0', - 'go_to_next' => 'From17To30', - ), - '3.0' => array( + ], + '1.3' => [ // iTop >= 2.2.0 + 'previous' => '1.2', + 'go_to_previous' => 'From13To12', + 'next' => '1.4', + 'go_to_next' => 'From13To14', + ], + '1.4' => [ // iTop >= 2.4.0 + 'previous' => '1.3', + 'go_to_previous' => 'From14To13', + 'next' => '1.5', + 'go_to_next' => 'From14To15', + ], + '1.5' => [ // iTop >= 2.5.0 + 'previous' => '1.4', + 'go_to_previous' => 'From15To14', + 'next' => '1.6', + 'go_to_next' => 'From15To16', + ], + '1.6' => [ // iTop >= 2.6.0 + 'previous' => '1.5', + 'go_to_previous' => 'From16To15', + 'next' => '1.7', + 'go_to_next' => 'From16To17', + ], + '1.7' => [ // iTop >= 2.7.0 + 'previous' => '1.6', + 'go_to_previous' => 'From17To16', + 'next' => '3.0', + 'go_to_next' => 'From17To30', + ], + '3.0' => [ 'previous' => '1.7', 'go_to_previous' => 'From30To17', 'next' => '3.1', 'go_to_next' => 'From30To31', - ), - '3.1' => array( + ], + '3.1' => [ 'previous' => '3.0', 'go_to_previous' => 'From31To30', 'next' => '3.2', 'go_to_next' => 'From31To32', - ), - '3.2' => array( + ], + '3.2' => [ 'previous' => '3.1', 'go_to_previous' => 'From32To31', 'next' => '3.3', 'go_to_next' => 'From32To33', - ), - '3.3' => array( + ], + '3.3' => [ 'previous' => '3.2', 'go_to_previous' => 'From33To32', 'next' => null, 'go_to_next' => null, - ), - ); + ], + ]; /** * The Document to work on @@ -154,10 +154,10 @@ class iTopDesignFormat */ protected function LogError($sMessage) { - $this->aLog[] = array( + $this->aLog[] = [ 'severity' => 'Error', 'msg' => $sMessage, - ); + ]; $this->bStatus = false; } @@ -167,10 +167,10 @@ class iTopDesignFormat */ protected function LogWarning($sMessage) { - $this->aLog[] = array( + $this->aLog[] = [ 'severity' => 'Warning', 'msg' => $sMessage, - ); + ]; } /** @@ -179,10 +179,10 @@ class iTopDesignFormat */ protected function LogInfo($sMessage) { - $this->aLog[] = array( + $this->aLog[] = [ 'severity' => 'Info', 'msg' => $sMessage, - ); + ]; } /** @@ -213,11 +213,9 @@ class iTopDesignFormat */ public function GetErrors() { - $aErrors = array(); - foreach ($this->aLog as $aLogEntry) - { - if ($aLogEntry['severity'] == 'Error') - { + $aErrors = []; + foreach ($this->aLog as $aLogEntry) { + if ($aLogEntry['severity'] == 'Error') { $aErrors[] = $aLogEntry['msg']; } } @@ -229,11 +227,9 @@ class iTopDesignFormat */ public function GetWarnings() { - $aErrors = array(); - foreach ($this->aLog as $aLogEntry) - { - if ($aLogEntry['severity'] == 'Warning') - { + $aErrors = []; + foreach ($this->aLog as $aLogEntry) { + if ($aLogEntry['severity'] == 'Warning') { $aErrors[] = $aLogEntry['msg']; } } @@ -290,7 +286,9 @@ class iTopDesignFormat */ public static function GetItopNodePath($oNode) { - if ($oNode instanceof DOMDocument) return ''; + if ($oNode instanceof DOMDocument) { + return ''; + } $sId = $oNode->getAttribute('id'); $sNodeDesc = ($sId != '') ? $oNode->nodeName.'['.$sId.']' : $oNode->nodeName; @@ -325,13 +323,12 @@ class iTopDesignFormat */ public function Convert($sTargetVersion = ITOP_DESIGN_LATEST_VERSION, $oFactory = null) { - $this->aLog = array(); + $this->aLog = []; $this->bStatus = true; try { $sVersion = $this->GetVersion(); - } - catch (iTopXmlException $e) { + } catch (iTopXmlException $e) { $this->LogError($e->getMessage()); return $this->bStatus; @@ -340,8 +337,7 @@ class iTopDesignFormat $this->LogInfo("Converting from $sVersion to $sTargetVersion"); try { $this->DoConvert($sVersion, $sTargetVersion, $oFactory); - } - catch (Exception|Error $e) { + } catch (Exception|Error $e) { $this->LogError($e->getMessage()); return false; @@ -367,17 +363,14 @@ class iTopDesignFormat */ protected function DoConvert($sFrom, $sTo, $oFactory = null) { - if ($sFrom == $sTo) - { + if ($sFrom == $sTo) { return; } - if (!array_key_exists($sFrom, self::$aVersions)) - { + if (!array_key_exists($sFrom, self::$aVersions)) { $this->LogError("Unknown source format version: $sFrom"); return; } - if (!array_key_exists($sTo, self::$aVersions)) - { + if (!array_key_exists($sTo, self::$aVersions)) { $this->LogError("Unknown target format version: $sTo"); return; // unknown versions are not supported } @@ -385,29 +378,25 @@ class iTopDesignFormat $aVersionIds = array_keys(self::$aVersions); $iFrom = array_search($sFrom, $aVersionIds); $iTo = array_search($sTo, $aVersionIds); - if ($iFrom < $iTo) - { + if ($iFrom < $iTo) { // This is an upgrade $sIntermediate = self::$aVersions[$sFrom]['next']; $sTransform = self::$aVersions[$sFrom]['go_to_next']; $this->LogInfo("Upgrading from $sFrom to $sIntermediate ($sTransform)"); - } - else - { + } else { // This is a downgrade $sIntermediate = self::$aVersions[$sFrom]['previous']; $sTransform = self::$aVersions[$sFrom]['go_to_previous']; $this->LogInfo("Downgrading from $sFrom to $sIntermediate ($sTransform)"); } // Transform to the intermediate format - $aCallSpec = array($this, $sTransform); + $aCallSpec = [$this, $sTransform]; try { call_user_func($aCallSpec, $oFactory); // Recurse $this->DoConvert($sIntermediate, $sTo, $oFactory); - } - catch (Exception $e) { + } catch (Exception $e) { $this->LogError($e->getMessage()); } } @@ -442,8 +431,7 @@ class iTopDesignFormat // which don't already have one $oXPath = new DOMXPath($this->oDocument); $oNodeList = $oXPath->query('/itop_design/classes//class/lifecycle/states/state/transitions/transition/stimulus'); - foreach ($oNodeList as $oNode) - { + foreach ($oNodeList as $oNode) { $oNode->parentNode->SetAttribute('id', $oNode->textContent); $this->DeleteNode($oNode); } @@ -451,8 +439,7 @@ class iTopDesignFormat // Adjust the XML to transparently add an id (=percent) on all thresholds of stopwatches // which don't already have one $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@xsi:type='AttributeStopWatch']/thresholds/threshold/percent"); - foreach ($oNodeList as $oNode) - { + foreach ($oNodeList as $oNode) { $oNode->parentNode->SetAttribute('id', $oNode->textContent); $this->DeleteNode($oNode); } @@ -460,16 +447,12 @@ class iTopDesignFormat // Adjust the XML to transparently add an id (=action:) on all allowed actions (profiles) // which don't already have one $oNodeList = $oXPath->query('/itop_design/user_rights/profiles/profile/groups/group/actions/action'); - foreach ($oNodeList as $oNode) - { - if ($oNode->getAttribute('id') == '') - { - $oNode->SetAttribute('id', 'action:' . $oNode->getAttribute('xsi:type')); + foreach ($oNodeList as $oNode) { + if ($oNode->getAttribute('id') == '') { + $oNode->SetAttribute('id', 'action:'.$oNode->getAttribute('xsi:type')); $oNode->removeAttribute('xsi:type'); - } - elseif ($oNode->getAttribute('xsi:type') == 'stimulus') - { - $oNode->SetAttribute('id', 'stimulus:' . $oNode->getAttribute('id')); + } elseif ($oNode->getAttribute('xsi:type') == 'stimulus') { + $oNode->SetAttribute('id', 'stimulus:'.$oNode->getAttribute('id')); $oNode->removeAttribute('xsi:type'); } } @@ -477,10 +460,8 @@ class iTopDesignFormat // Adjust the XML to transparently add an id (=value) on all values of an enum which don't already have one. // This enables altering an enum for just adding/removing one value, intead of redefining the whole list of values. $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@xsi:type='AttributeEnum']/values/value"); - foreach ($oNodeList as $oNode) - { - if ($oNode->getAttribute('id') == '') - { + foreach ($oNodeList as $oNode) { + if ($oNode->getAttribute('id') == '') { $oNode->SetAttribute('id', $oNode->textContent); } } @@ -496,10 +477,8 @@ class iTopDesignFormat // Move the id down to a stimulus node on all life-cycle transitions $oXPath = new DOMXPath($this->oDocument); $oNodeList = $oXPath->query('/itop_design/classes//class/lifecycle/states/state/transitions/transition[@id]'); - foreach ($oNodeList as $oNode) - { - if ($oXPath->query('descendant-or-self::*[@_delta or @_rename_from]', $oNode)->length > 0) - { + foreach ($oNodeList as $oNode) { + if ($oXPath->query('descendant-or-self::*[@_delta or @_rename_from]', $oNode)->length > 0) { $this->LogError('Alterations have been defined under the node: '.self::GetItopNodePath($oNode)); } $oStimulus = $oNode->ownerDocument->createElement('stimulus', $oNode->getAttribute('id')); @@ -509,10 +488,8 @@ class iTopDesignFormat // Move the id down to a percent node on all thresholds $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@xsi:type='AttributeStopWatch']/thresholds/threshold[@id]"); - foreach ($oNodeList as $oNode) - { - if ($oXPath->query('descendant-or-self::*[@_delta or @_rename_from]', $oNode)->length > 0) - { + foreach ($oNodeList as $oNode) { + if ($oXPath->query('descendant-or-self::*[@_delta or @_rename_from]', $oNode)->length > 0) { $this->LogError('Alterations have been defined under the node: '.self::GetItopNodePath($oNode)); } $oStimulus = $oNode->ownerDocument->createElement('percent', $oNode->getAttribute('id')); @@ -522,21 +499,16 @@ class iTopDesignFormat // Restore the type and id on profile/actions $oNodeList = $oXPath->query('/itop_design/user_rights/profiles/profile/groups/group/actions/action'); - foreach ($oNodeList as $oNode) - { - if ($oXPath->query('descendant-or-self::*[@_delta or @_rename_from]', $oNode)->length > 0) - { + foreach ($oNodeList as $oNode) { + if ($oXPath->query('descendant-or-self::*[@_delta or @_rename_from]', $oNode)->length > 0) { $this->LogError('Alterations have been defined under the node: '.self::GetItopNodePath($oNode)); } - if (substr($oNode->getAttribute('id'), 0, strlen('action')) == 'action') - { + if (substr($oNode->getAttribute('id'), 0, strlen('action')) == 'action') { // The id has the form 'action:' $sActionCode = substr($oNode->getAttribute('id'), strlen('action:')); $oNode->removeAttribute('id'); $oNode->setAttribute('xsi:type', $sActionCode); - } - else - { + } else { // The id has the form 'stimulus:' $sStimulusCode = substr($oNode->getAttribute('id'), strlen('stimulus:')); $oNode->setAttribute('id', $sStimulusCode); @@ -546,10 +518,8 @@ class iTopDesignFormat // Remove the id on all enum values $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@xsi:type='AttributeEnum']/values/value[@id]"); - foreach ($oNodeList as $oNode) - { - if ($oXPath->query('descendant-or-self::*[@_delta or @_rename_from]', $oNode)->length > 0) - { + foreach ($oNodeList as $oNode) { + if ($oXPath->query('descendant-or-self::*[@_delta or @_rename_from]', $oNode)->length > 0) { $this->LogError('Alterations have been defined under the node: '.self::GetItopNodePath($oNode)); } $oNode->removeAttribute('id'); @@ -577,8 +547,7 @@ class iTopDesignFormat // Transform ObjectKey attributes into Integer // $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@xsi:type='AttributeObjectKey']"); - foreach ($oNodeList as $oNode) - { + foreach ($oNodeList as $oNode) { $oNode->setAttribute('xsi:type', 'AttributeInteger'); // The property class_attcode is left there (doing no harm) $this->LogWarning('The attribute '.self::GetItopNodePath($oNode).' has been degraded into an integer attribute. Any OQL query using this attribute will fail.'); @@ -587,37 +556,32 @@ class iTopDesignFormat // Remove Redundancy settings attributes (no redundancy could be defined in the previous format) // $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@xsi:type='AttributeRedundancySettings']"); - foreach ($oNodeList as $oNode) - { + foreach ($oNodeList as $oNode) { $this->LogWarning('The attribute '.self::GetItopNodePath($oNode).' is of no use and must be removed.'); $this->DeleteNode($oNode); } // Later: transform the relations into code (iif defined as an SQL query) $oNodeList = $oXPath->query('/itop_design/classes//class/relations'); - foreach ($oNodeList as $oNode) - { + foreach ($oNodeList as $oNode) { $this->LogWarning('The relations defined in '.self::GetItopNodePath($oNode).' will be lost.'); $this->DeleteNode($oNode); } $oNodeList = $oXPath->query('/itop_design/portal'); - foreach ($oNodeList as $oNode) - { + foreach ($oNodeList as $oNode) { $this->LogWarning('Portal definition will be lost.'); $this->DeleteNode($oNode); } $oNodeList = $oXPath->query('/itop_design/module_parameters'); - foreach ($oNodeList as $oNode) - { + foreach ($oNodeList as $oNode) { $this->LogWarning('Module parameters will be lost.'); $this->DeleteNode($oNode); } $oNodeList = $oXPath->query('/itop_design/snippets'); - foreach ($oNodeList as $oNode) - { + foreach ($oNodeList as $oNode) { $this->LogWarning('Code snippets will be lost.'); $this->DeleteNode($oNode); } @@ -642,8 +606,7 @@ class iTopDesignFormat $oXPath = new DOMXPath($this->oDocument); $oNodeList = $oXPath->query('/itop_design/module_designs/module_design'); - foreach ($oNodeList as $oNode) - { + foreach ($oNodeList as $oNode) { $this->LogWarning('The module design defined in '.self::GetItopNodePath($oNode).' will be lost.'); $this->DeleteNode($oNode); } @@ -651,8 +614,7 @@ class iTopDesignFormat // Remove MetaEnum attributes // $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@xsi:type='AttributeMetaEnum']"); - foreach ($oNodeList as $oNode) - { + foreach ($oNodeList as $oNode) { $this->LogWarning('The attribute '.self::GetItopNodePath($oNode).' is irrelevant and must be removed.'); $this->DeleteNode($oNode); } @@ -660,8 +622,7 @@ class iTopDesignFormat // Remove CustomFields attributes // $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@xsi:type='AttributeCustomFields']"); - foreach ($oNodeList as $oNode) - { + foreach ($oNodeList as $oNode) { $this->LogWarning('The attribute '.self::GetItopNodePath($oNode).' is irrelevant and must be removed.'); $this->DeleteNode($oNode); } @@ -669,8 +630,7 @@ class iTopDesignFormat // Remove Image attributes // $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@xsi:type='AttributeImage']"); - foreach ($oNodeList as $oNode) - { + foreach ($oNodeList as $oNode) { $this->LogWarning('The attribute '.self::GetItopNodePath($oNode).' is irrelevant and must be removed.'); $this->DeleteNode($oNode); } @@ -678,8 +638,7 @@ class iTopDesignFormat // Discard _delta="if_exists" // $oNodeList = $oXPath->query("//*[@_delta='if_exists']"); - foreach ($oNodeList as $oNode) - { + foreach ($oNodeList as $oNode) { $this->LogWarning('The flag _delta="if_exists" on '.self::GetItopNodePath($oNode).' is irrelevant and must be replaced by _delta="must_exist".'); $oNode->setAttribute('_delta', 'must_exist'); } @@ -707,13 +666,11 @@ class iTopDesignFormat // $oNodeList = $oXPath->query("/itop_design/classes//class/fields/field[@_delta='force']"); $iCount = 0; - foreach ($oNodeList as $oNode) - { + foreach ($oNodeList as $oNode) { $oNode->setAttribute('_delta', 'define'); $iCount++; } - if ($iCount > 0) - { + if ($iCount > 0) { $this->LogWarning('The attribute _delta="force" is not supported, converted to _delta="define" ('.$iCount.' instances processed).'); } @@ -721,8 +678,7 @@ class iTopDesignFormat // $oNodeList = $oXPath->query("/itop_design/classes//class/lifecycle/states/state/transitions/transition/flags"); $this->LogWarning('Before removing flags nodes'); - foreach ($oNodeList as $oNode) - { + foreach ($oNodeList as $oNode) { $this->LogWarning('Attribute flags '.self::GetItopNodePath($oNode).' is irrelevant on transition and must be removed.'); $this->DeleteNode($oNode); } @@ -741,8 +697,7 @@ class iTopDesignFormat // $sPath = "/itop_design/menus/menu[@xsi:type!='MenuGroup' and @xsi:type!='TemplateMenuNode']"; $oNodeList = $oXPath->query("$sPath/enable_class | $sPath/enable_action | $sPath/enable_permission | $sPath/enable_stimulus"); - foreach ($oNodeList as $oNode) - { + foreach ($oNodeList as $oNode) { $this->LogWarning('Node '.self::GetItopNodePath($oNode).' is irrelevant in this version, it will be ignored. Use enable_admin_only instead.'); } } @@ -792,14 +747,16 @@ class iTopDesignFormat protected function From16To17($oFactory) { // N°2275 Clean branding node (move "define" from collection to logos or theme, noe that any other nodes will be seen as "merge") - $this->CleanDefineOnCollectionNode('/itop_design/branding', - '*[self::main_logo or self::login_logo or self::portal_logo]|themes/theme'); + $this->CleanDefineOnCollectionNode( + '/itop_design/branding', + '*[self::main_logo or self::login_logo or self::portal_logo]|themes/theme' + ); // N°2275 Clean portal form properties node (move "define" from collection to each property) $this->CleanDefineOnCollectionNode('/itop_design/module_designs/module_design[@id="itop-portal"]/forms/form/properties', '*'); // N°2806 Clean legacy portal constants - $aConstantsIDsToRemove = array( + $aConstantsIDsToRemove = [ 'PORTAL_POWER_USER_PROFILE', 'PORTAL_SERVICECATEGORY_QUERY', 'PORTAL_SERVICE_SUBCATEGORY_QUERY', @@ -829,9 +786,8 @@ class iTopDesignFormat 'PORTAL_USERREQUEST_DETAILS_ZLIST', 'PORTAL_USERREQUEST_DISPLAY_QUERY', 'PORTAL_USERREQUEST_DISPLAY_POWERUSER_QUERY', - ); - foreach($aConstantsIDsToRemove as $sConstantIDToRemove) - { + ]; + foreach ($aConstantsIDsToRemove as $sConstantIDToRemove) { $sXPath = '/itop_design/constants/constant[@id="'.$sConstantIDToRemove.'"]'; $this->RemoveNodeFromXPath($sXPath); } @@ -920,12 +876,12 @@ class iTopDesignFormat $oNode->setAttribute('id', 'ibo-page-banner--background-color'); } - $oNodeList = $oXPath->query( '/itop_design/branding/themes/theme[@id="test-red"]/variables/variable[@id="backoffice-environment-banner-text-color"]'); + $oNodeList = $oXPath->query('/itop_design/branding/themes/theme[@id="test-red"]/variables/variable[@id="backoffice-environment-banner-text-color"]'); foreach ($oNodeList as $oNode) { $oNode->setAttribute('id', 'ibo-page-banner--text-color'); } - $oNodeList = $oXPath->query( '/itop_design/branding/themes/theme[@id="test-red"]/variables/variable[@id="backoffice-environment-banner-text-content"]'); + $oNodeList = $oXPath->query('/itop_design/branding/themes/theme[@id="test-red"]/variables/variable[@id="backoffice-environment-banner-text-content"]'); foreach ($oNodeList as $oNode) { $oNode->setAttribute('id', 'ibo-page-banner--text-content'); } @@ -1152,8 +1108,7 @@ class iTopDesignFormat $oXPath = new DOMXPath($this->oDocument); $oNodeList = $oXPath->query($sPath); - foreach ($oNodeList as $oNode) - { + foreach ($oNodeList as $oNode) { $this->LogWarning('Node '.self::GetItopNodePath($oNode).' is irrelevant in this version, it will be removed.'); $this->DeleteNode($oNode); } @@ -1175,17 +1130,14 @@ class iTopDesignFormat // Iterate over collections $oCollectionNodeList = $oXPath->query($sCollectionXPath); /** @var \DOMElement $oCollectionNode */ - foreach ($oCollectionNodeList as $oCollectionNode) - { + foreach ($oCollectionNodeList as $oCollectionNode) { // Move _delta="define" from collection to items - if (($oCollectionNode->hasAttribute('_delta')) && ($oCollectionNode->getAttribute('_delta') === "define")) - { + if (($oCollectionNode->hasAttribute('_delta')) && ($oCollectionNode->getAttribute('_delta') === "define")) { $oCollectionNode->removeAttribute('_delta'); $oItemNodeList = $oXPath->query($sItemsRelativeXPath, $oCollectionNode); /** @var \DOMElement $oItemNode */ - foreach ($oItemNodeList as $oItemNode) - { + foreach ($oItemNodeList as $oItemNode) { $oItemNode->setAttribute('_delta', 'define'); } } diff --git a/setup/modelfactory.class.inc.php b/setup/modelfactory.class.inc.php index d2b56e801..b1919b41d 100644 --- a/setup/modelfactory.class.inc.php +++ b/setup/modelfactory.class.inc.php @@ -1,4 +1,5 @@ sId = $sId; [$this->sName, $this->sVersion] = ModuleDiscovery::GetModuleName($sId); - if (strlen($this->sVersion) == 0) - { + if (strlen($this->sVersion) == 0) { $this->sVersion = '1.0.0'; } $this->sRootDir = $sRootDir; $this->sLabel = $sLabel; - $this->aDataModels = array(); + $this->aDataModels = []; $this->bAutoSelect = $bAutoSelect; $this->sAutoSelect = 'false'; - $this->aFilesToInclude = array('addons' => array(), 'business' => array(), 'webservices' => array(),); + $this->aFilesToInclude = ['addons' => [], 'business' => [], 'webservices' => [],]; if (is_null($sRootDir)) { return; } // Scan the module's root directory to find the datamodel(*).xml files - if ($hDir = opendir($sRootDir)) - { + if ($hDir = opendir($sRootDir)) { // This is the correct way to loop over the directory. (according to the documentation) - while (($sFile = readdir($hDir)) !== false) - { - if (preg_match('/^datamodel(.*)\.xml$/i', $sFile, $aMatches)) - { + while (($sFile = readdir($hDir)) !== false) { + if (preg_match('/^datamodel(.*)\.xml$/i', $sFile, $aMatches)) { $this->aDataModels[] = $this->sRootDir.'/'.$aMatches[0]; } } @@ -211,7 +208,6 @@ class MFModule } } - /** * @return string */ @@ -275,7 +271,7 @@ class MFModule */ public function ListClasses() { - return array(); + return []; } /** @@ -283,17 +279,16 @@ class MFModule */ public function GetDictionaryFiles() { - $aDictionaries = array(); - foreach (array($this->sRootDir, $this->sRootDir.'/dictionaries') as $sRootDir) - { - if ($hDir = @opendir($sRootDir)) - { - while (($sFile = readdir($hDir)) !== false) - { - $aMatches = array(); - if (preg_match("/^[^\\.]+.dict.".$this->sName.'.php$/i', $sFile, - $aMatches)) // Dictionary files are named like .dict..php - { + $aDictionaries = []; + foreach ([$this->sRootDir, $this->sRootDir.'/dictionaries'] as $sRootDir) { + if ($hDir = @opendir($sRootDir)) { + while (($sFile = readdir($hDir)) !== false) { + $aMatches = []; + if (preg_match( + "/^[^\\.]+.dict.".$this->sName.'.php$/i', + $sFile, + $aMatches + )) { // Dictionary files are named like .dict..php $aDictionaries[] = $sRootDir.'/'.$sFile; } } @@ -375,8 +370,8 @@ class MFDeltaModule extends MFModule parent::__construct('datamodel-delta', '', 'Additional Delta'); $this->sName = 'delta'; $this->sVersion = '1.0'; - $this->aDataModels = array($sDeltaFile); - $this->aFilesToInclude = array('addons' => array(), 'business' => array(), 'webservices' => array(),); + $this->aDataModels = [$sDeltaFile]; + $this->aFilesToInclude = ['addons' => [], 'business' => [], 'webservices' => [],]; } /** @@ -408,7 +403,7 @@ class MFDeltaModule extends MFModule */ public function GetDictionaryFiles() { - return array(); + return []; } } @@ -431,8 +426,8 @@ class MFCoreModule extends MFModule parent::__construct($sName, '', $sLabel); $this->sName = $sName; $this->sVersion = '1.0'; - $this->aDataModels = array($sDeltaFile); - $this->aFilesToInclude = array('addons' => array(), 'business' => array(), 'webservices' => array(),); + $this->aDataModels = [$sDeltaFile]; + $this->aFilesToInclude = ['addons' => [], 'business' => [], 'webservices' => [],]; } /** @@ -456,7 +451,7 @@ class MFCoreModule extends MFModule */ public function GetDictionaryFiles() { - return array(); + return []; } } @@ -479,8 +474,8 @@ class MFDictModule extends MFModule parent::__construct($sName, $sRootDir, $sLabel); $this->sName = $sName; $this->sVersion = '1.0'; - $this->aDataModels = array(); - $this->aFilesToInclude = array('addons' => array(), 'business' => array(), 'webservices' => array(),); + $this->aDataModels = []; + $this->aFilesToInclude = ['addons' => [], 'business' => [], 'webservices' => [],]; } /** @@ -506,22 +501,19 @@ class MFDictModule extends MFModule */ public function GetDictionaryFiles($sDir = null) { - $aDictionaries = array(); + $aDictionaries = []; $sDictionaryFilePattern = '*dictionary.itop.*.php'; - if($sDir === null) - { + if ($sDir === null) { $sDir = $this->sRootDir; } - if ($hDir = opendir($sDir)) - { + if ($hDir = opendir($sDir)) { // Matching files $aDictionaries = glob($sDir.'/'.$sDictionaryFilePattern); // Directories to scan - foreach(glob($sDir.'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $sSubDir) - { + foreach (glob($sDir.'/*', GLOB_ONLYDIR | GLOB_NOSORT) as $sSubDir) { /** @noinspection SlowArrayOperationsInLoopInspection */ $aDictionaries = array_merge($aDictionaries, $this->GetDictionaryFiles($sSubDir)); } @@ -531,7 +523,6 @@ class MFDictModule extends MFModule } } - /** * ModelFactory: the class that manages the in-memory representation of the XML MetaModel * @@ -556,13 +547,12 @@ class ModelFactory protected $aRootDirs; protected $oDOMDocument; protected $oRoot; - static protected $aWellKnownParents = array('DBObject', 'CMDBObject', 'cmdbAbstractObject'); - static protected $aLoadedModules; - static protected $aLoadErrors; + protected static $aWellKnownParents = ['DBObject', 'CMDBObject', 'cmdbAbstractObject']; + protected static $aLoadedModules; + protected static $aLoadErrors; protected $aDict; protected $aDictKeys; - /** * ModelFactory constructor. * @@ -571,10 +561,10 @@ class ModelFactory * * @throws \Exception */ - public function __construct($aRootDirs, $aRootNodeExtensions = array()) + public function __construct($aRootDirs, $aRootNodeExtensions = []) { - $this->aDict = array(); - $this->aDictKeys = array(); + $this->aDict = []; + $this->aDictKeys = []; $this->aRootDirs = $aRootDirs; $this->oDOMDocument = new MFDocument(); $this->oRoot = $this->oDOMDocument->CreateElement('itop_design'); @@ -588,8 +578,7 @@ class ModelFactory $oDictionaries = $this->oDOMDocument->CreateElement('dictionaries'); $this->oRoot->appendChild($oDictionaries); - foreach (self::$aWellKnownParents as $sWellKnownParent) - { + foreach (self::$aWellKnownParents as $sWellKnownParent) { $this->AddWellKnownParent($oClasses, $sWellKnownParent); } $oMenus = $this->oDOMDocument->CreateElement('menus'); @@ -600,13 +589,12 @@ class ModelFactory $oEvents = $this->oDOMDocument->CreateElement('events'); $this->oRoot->appendChild($oEvents); - foreach ($aRootNodeExtensions as $sElementName) - { + foreach ($aRootNodeExtensions as $sElementName) { $oElement = $this->oDOMDocument->CreateElement($sElementName); $this->oRoot->appendChild($oElement); } - self::$aLoadedModules = array(); - self::$aLoadErrors = array(); + self::$aLoadedModules = []; + self::$aLoadErrors = []; libxml_use_internal_errors(true); } @@ -620,8 +608,7 @@ class ModelFactory */ public function Dump($oNode = null, $bReturnRes = false) { - if (is_null($oNode)) - { + if (is_null($oNode)) { $oNode = $this->oRoot; } @@ -637,9 +624,8 @@ class ModelFactory $this->oRoot = $this->oDOMDocument->firstChild; $oModules = $this->oRoot->getElementsByTagName('loaded_modules')->item(0); - self::$aLoadedModules = array(); - foreach ($oModules->getElementsByTagName('module') as $oModuleNode) - { + self::$aLoadedModules = []; + foreach ($oModules->getElementsByTagName('module') as $oModuleNode) { $sId = $oModuleNode->getAttribute('id'); $sRootDir = $oModuleNode->GetChildText('root_dir'); $sLabel = $oModuleNode->GetChildText('label'); @@ -751,8 +737,12 @@ class ModelFactory $oParentNode = $oSubClassNode->parentNode; $iLine = ModelFactory::GetXMLLineNumber($oParentNode); $sItopNodePath = DesignDocument::GetItopNodePath($oParentNode); - throw new MFException("$sItopNodePath at line $iLine: _delta=\"$sParentDeltaSpec\" not supported for classes in hierarchy", - MFException::NOT_FOUND, $iLine, $sItopNodePath); + throw new MFException( + "$sItopNodePath at line $iLine: _delta=\"$sParentDeltaSpec\" not supported for classes in hierarchy", + MFException::NOT_FOUND, + $iLine, + $sItopNodePath + ); } } @@ -810,8 +800,12 @@ class ModelFactory if (is_null($oNodeForTargetParent)) { $iLine = ModelFactory::GetXMLLineNumber($oSourceParentClassNode); $sItopNodePath = DesignDocument::GetItopNodePath($oSourceParentClassNode); - throw new MFException($sItopNodePath." at line $iLine: invalid parent class '$sParentClassName'", - MFException::NOT_FOUND, $iLine, $sItopNodePath); + throw new MFException( + $sItopNodePath." at line $iLine: invalid parent class '$sParentClassName'", + MFException::NOT_FOUND, + $iLine, + $sItopNodePath + ); } $oNextParentSibling = $oNodeForTargetParent->nextSibling; if ($oNextParentSibling) { @@ -841,8 +835,12 @@ class ModelFactory if ($bMustExist) { $iLine = ModelFactory::GetXMLLineNumber($oSourceNode); $sItopNodePath = DesignDocument::GetItopNodePath($oSourceNode); - throw new MFException($sItopNodePath.' at line '.$iLine.': could not be found or marked as removed', - MFException::NOT_FOUND, $iLine, $sItopNodePath); + throw new MFException( + $sItopNodePath.' at line '.$iLine.': could not be found or marked as removed', + MFException::NOT_FOUND, + $iLine, + $sItopNodePath + ); } if ($bIfExists) { // Do not continue deeper @@ -851,8 +849,13 @@ class ModelFactory if (!$bSpecifiedMerge && $sMode === self::LOAD_DELTA_MODE_STRICT && ($sSearchId !== '' || is_null($oSourceNode->GetFirstElementChild()))) { $iLine = ModelFactory::GetXMLLineNumber($oSourceNode); $sItopNodePath = DesignDocument::GetItopNodePath($oSourceNode); - throw new MFException($sItopNodePath.' at line '.$iLine.': could not be found or marked as removed (strict mode)', - MFException::NOT_FOUND, $iLine, $sItopNodePath, 'strict mode'); + throw new MFException( + $sItopNodePath.' at line '.$iLine.': could not be found or marked as removed (strict mode)', + MFException::NOT_FOUND, + $iLine, + $sItopNodePath, + 'strict mode' + ); } // Ignore renaming non-existant node @@ -903,8 +906,13 @@ class ModelFactory if ($sMode === self::LOAD_DELTA_MODE_STRICT && !$oSourceNode->hasAttribute('_rename_from') && trim($oSourceNode->GetText('')) !== '') { $iLine = ModelFactory::GetXMLLineNumber($oSourceNode); $sItopNodePath = DesignDocument::GetItopNodePath($oSourceNode); - throw new MFException($sItopNodePath.' at line '.$iLine.': cannot be modified without _delta flag (strict mode)', - MFException::AMBIGUOUS_LEAF, $iLine, $sItopNodePath, 'strict mode'); + throw new MFException( + $sItopNodePath.' at line '.$iLine.': cannot be modified without _delta flag (strict mode)', + MFException::AMBIGUOUS_LEAF, + $iLine, + $sItopNodePath, + 'strict mode' + ); } else { // Lax mode: same as redefine // Replace the existing node by the given node - copy child nodes as well @@ -980,12 +988,20 @@ class ModelFactory $iLine = $this->GetXMLLineNumber($oSourceNode); if ($oTargetNode == null) { - throw new MFException($sPath.' at line '.$iLine.": could not be deleted (not found)", MFException::COULD_NOT_BE_DELETED, - $iLine, $sPath); + throw new MFException( + $sPath.' at line '.$iLine.": could not be deleted (not found)", + MFException::COULD_NOT_BE_DELETED, + $iLine, + $sPath + ); } if ($oTargetNode->IsRemoved()) { - throw new MFException($sPath.' at line '.$iLine.": could not be deleted (already marked as deleted)", - MFException::ALREADY_DELETED, $iLine, $sPath); + throw new MFException( + $sPath.' at line '.$iLine.": could not be deleted (already marked as deleted)", + MFException::ALREADY_DELETED, + $iLine, + $sPath + ); } $oTargetNode->Delete(); break; @@ -993,8 +1009,13 @@ class ModelFactory default: $sPath = MFDocument::GetItopNodePath($oSourceNode); $iLine = $this->GetXMLLineNumber($oSourceNode); - throw new MFException($sPath.' at line '.$iLine.": unexpected value for attribute _delta: '".$sDeltaSpec."'", - MFException::INVALID_DELTA, $iLine, $sPath, $sDeltaSpec); + throw new MFException( + $sPath.' at line '.$iLine.": unexpected value for attribute _delta: '".$sDeltaSpec."'", + MFException::INVALID_DELTA, + $iLine, + $sPath, + $sDeltaSpec + ); } if ($oTargetNode && $oTargetNode->parentNode) { @@ -1036,7 +1057,7 @@ class ModelFactory } $oSubClassNodes = $this->GetChildClasses($oClassNode); - foreach($oSubClassNodes as $oSubClassNode) { + foreach ($oSubClassNodes as $oSubClassNode) { // Put the subclass before the parent classes to delete in reverse order $this->DeleteSubClasses($oSubClassNode, false); } @@ -1078,10 +1099,9 @@ class ModelFactory * * @throws \Exception */ - public function LoadModule(MFModule $oModule, $aLanguages = array()) + public function LoadModule(MFModule $oModule, $aLanguages = []) { - try - { + try { $aDataModels = $oModule->GetDataModelFiles(); $sModuleName = $oModule->GetName(); self::$aLoadedModules[] = $oModule; @@ -1095,71 +1115,56 @@ class ModelFactory $oModules = $this->oRoot->getElementsByTagName('loaded_modules')->item(0); $oModules->appendChild($oModuleNode); - foreach ($aDataModels as $sXmlFile) - { + foreach ($aDataModels as $sXmlFile) { $oDocument = new MFDocument(); libxml_clear_errors(); $oDocument->load($sXmlFile); $aErrors = libxml_get_errors(); - if (count($aErrors) > 0) - { + if (count($aErrors) > 0) { throw new Exception($this->GetXMLErrorMessage($aErrors)); } $oXPath = new DOMXPath($oDocument); $oNodeList = $oXPath->query('/itop_design/classes//class'); - foreach ($oNodeList as $oNode) - { - if ($oNode->getAttribute('_created_in') == '') - { + foreach ($oNodeList as $oNode) { + if ($oNode->getAttribute('_created_in') == '') { $oNode->SetAttribute('_created_in', $sModuleName); } } $oNodeList = $oXPath->query('/itop_design/constants/constant'); - foreach ($oNodeList as $oNode) - { - if ($oNode->getAttribute('_created_in') == '') - { + foreach ($oNodeList as $oNode) { + if ($oNode->getAttribute('_created_in') == '') { $oNode->SetAttribute('_created_in', $sModuleName); } } $oNodeList = $oXPath->query('/itop_design/events/event'); - foreach ($oNodeList as $oNode) - { - if ($oNode->getAttribute('_created_in') == '') - { + foreach ($oNodeList as $oNode) { + if ($oNode->getAttribute('_created_in') == '') { $oNode->SetAttribute('_created_in', $sModuleName); } } $oNodeList = $oXPath->query('/itop_design/menus/menu'); - foreach ($oNodeList as $oNode) - { - if ($oNode->getAttribute('_created_in') == '') - { + foreach ($oNodeList as $oNode) { + if ($oNode->getAttribute('_created_in') == '') { $oNode->SetAttribute('_created_in', $sModuleName); } } $oUserRightsNode = $oXPath->query('/itop_design/user_rights')->item(0); - if ($oUserRightsNode) - { - if ($oUserRightsNode->getAttribute('_created_in') == '') - { + if ($oUserRightsNode) { + if ($oUserRightsNode->getAttribute('_created_in') == '') { $oUserRightsNode->SetAttribute('_created_in', $sModuleName); } } $oAlteredNodes = $oXPath->query('/itop_design//*[@_delta]'); - if ($oAlteredNodes->length > 0) - { - foreach ($oAlteredNodes as $oAlteredNode) - { + if ($oAlteredNodes->length > 0) { + foreach ($oAlteredNodes as $oAlteredNode) { $oAlteredNode->SetAttribute('_altered_in', $sModuleName); } } $oFormat = new iTopDesignFormat($oDocument); - if (!$oFormat->Convert()) - { + if (!$oFormat->Convert()) { $sError = implode(', ', $oFormat->GetErrors()); throw new Exception("Cannot load module $sModuleName, failed to upgrade to datamodel format of: $sXmlFile. Reason(s): $sError"); } @@ -1171,40 +1176,36 @@ class ModelFactory $aDictionaries = $oModule->GetDictionaryFiles(); $sPHPFile = 'undefined'; - try - { + try { $this->ResetTempDictionary(); - foreach ($aDictionaries as $sPHPFile) - { + foreach ($aDictionaries as $sPHPFile) { $sDictFileContents = file_get_contents($sPHPFile); - $sDictFileContents = str_replace(array('<'.'?'.'php', '?'.'>'), '', $sDictFileContents); + $sDictFileContents = str_replace(['<'.'?'.'php', '?'.'>'], '', $sDictFileContents); $sDictFileContents = str_replace('Dict::Add', '$this->AddToTempDictionary', $sDictFileContents); eval($sDictFileContents); } - foreach ($this->aDict as $sLanguageCode => $aDictDefinition) - { - if ((count($aLanguages) > 0) && !in_array($sLanguageCode, $aLanguages)) - { + foreach ($this->aDict as $sLanguageCode => $aDictDefinition) { + if ((count($aLanguages) > 0) && !in_array($sLanguageCode, $aLanguages)) { // skip some languages if the parameter says so continue; } $this->IntegrateDictEntriesIntoXML($sLanguageCode, $aDictDefinition); } - } catch (Exception|Error $e) // Error can occurs on eval() calls - { - throw new DictException('Failed to load dictionary file "' . $sPHPFile . '"', [ - 'exception_class' => get_class($e), - 'exception_msg' => $e->getMessage(), - ]); - } - } - catch (Exception $e) { - $aLoadedModuleNames = array(); + } catch (Exception|Error $e) { // Error can occurs on eval() calls + throw new DictException('Failed to load dictionary file "'.$sPHPFile.'"', [ + 'exception_class' => get_class($e), + 'exception_msg' => $e->getMessage(), + ]); + } + } catch (Exception $e) { + $aLoadedModuleNames = []; foreach (self::$aLoadedModules as $oLoadedModule) { $aLoadedModuleNames[] = $oLoadedModule->GetName().':'.$oLoadedModule->GetVersion(); } - throw new Exception('Error loading module "'.$oModule->GetName().'": '.$e->getMessage().' - Loaded modules: '.implode(', ', - $aLoadedModuleNames)); + throw new Exception('Error loading module "'.$oModule->GetName().'": '.$e->getMessage().' - Loaded modules: '.implode( + ', ', + $aLoadedModuleNames + )); } } @@ -1225,8 +1226,10 @@ class ModelFactory $oDictionaries->AddChildNode($oXmlDict); $oXmlEntries = $this->oDOMDocument->CreateElement('english_description', $aDictDefinition['english_description']); $oXmlDict->appendChild($oXmlEntries); - $oXmlEntries = $this->oDOMDocument->CreateElement('localized_description', - $aDictDefinition['localized_description']); + $oXmlEntries = $this->oDOMDocument->CreateElement( + 'localized_description', + $aDictDefinition['localized_description'] + ); $oXmlDict->appendChild($oXmlEntries); $oXmlEntries = $this->oDOMDocument->CreateElement('entries'); $oXmlDict->appendChild($oXmlEntries); @@ -1264,20 +1267,18 @@ class ModelFactory { $this->aDict[$sLanguageCode]['english_description'] = $sEnglishLanguageDesc; $this->aDict[$sLanguageCode]['localized_description'] = $sLocalizedLanguageDesc; - if (!array_key_exists('entries', $this->aDict[$sLanguageCode])) - { - $this->aDict[$sLanguageCode]['entries'] = array(); + if (!array_key_exists('entries', $this->aDict[$sLanguageCode])) { + $this->aDict[$sLanguageCode]['entries'] = []; } - foreach ($aEntries as $sKey => $sValue) - { + foreach ($aEntries as $sKey => $sValue) { $this->aDict[$sLanguageCode]['entries'][$sKey] = $sValue; } } protected function ResetTempDictionary() { - $this->aDict = array(); + $this->aDict = []; } /** @@ -1288,8 +1289,7 @@ class ModelFactory protected function GetXMLErrorMessage($aErrors) { $sMessage = "Data model source file ({$aErrors[0]->file}) could not be loaded : \n"; - foreach ($aErrors as $oXmlError) - { + foreach ($aErrors as $oXmlError) { // XML messages already ends with \n $sMessage .= $oXmlError->message; } @@ -1302,39 +1302,31 @@ class ModelFactory * * @return MFModule[] */ - function GetLoadedModules($bExcludeWorkspace = true) + public function GetLoadedModules($bExcludeWorkspace = true) { - if ($bExcludeWorkspace) - { - $aModules = array(); - foreach (self::$aLoadedModules as $oModule) - { - if (!$oModule instanceof MFWorkspace) - { + if ($bExcludeWorkspace) { + $aModules = []; + foreach (self::$aLoadedModules as $oModule) { + if (!$oModule instanceof MFWorkspace) { $aModules[] = $oModule; } } - } - else - { + } else { $aModules = self::$aLoadedModules; } return $aModules; } - /** * @param $sModuleName * * @return mixed|null */ - function GetModule($sModuleName) + public function GetModule($sModuleName) { - foreach (self::$aLoadedModules as $oModule) - { - if ($oModule->GetName() == $sModuleName) - { + foreach (self::$aLoadedModules as $oModule) { + if ($oModule->GetName() == $sModuleName) { return $oModule; } } @@ -1391,16 +1383,12 @@ class ModelFactory */ public function AddClass(DOMNode $oClassNode, $sModuleName) { - if ($oClassNode->hasAttribute('id')) - { + if ($oClassNode->hasAttribute('id')) { $sClassName = $oClassNode->GetAttribute('id'); - } - else - { + } else { throw new Exception('ModelFactory::AddClass: Cannot add a class with no name'); } - if ($this->ClassNameExists($oClassNode->getAttribute('id'))) - { + if ($this->ClassNameExists($oClassNode->getAttribute('id'))) { throw new Exception("ModelFactory::AddClass: Cannot add the already existing class $sClassName"); } $sParentClass = $oClassNode->GetChildText('parent', ''); @@ -1449,7 +1437,7 @@ $sHeader EOF - ; + ; } /** @@ -1501,8 +1489,7 @@ EOF public function ListAllClasses($bIncludeMetas = false) { $sXPath = "/itop_design/classes/class[@id]"; - if ($bIncludeMetas === true) - { + if ($bIncludeMetas === true) { $sXPath .= "|/itop_design/meta/classes/class[@id]"; } @@ -1549,8 +1536,7 @@ EOF $oClassNode = $this->GetNodes("/itop_design/classes/class[@id='$sClassName']")->item(0); // If not, check if class among exposed meta classes (PHP classes) - if (is_null($oClassNode) && ($bIncludeMetas === true)) - { + if (is_null($oClassNode) && ($bIncludeMetas === true)) { /** @var \MFElement|null $oClassNode */ $oClassNode = $this->GetNodes("/itop_design/meta/classes/class[@id='$sClassName']")->item(0); } @@ -1594,15 +1580,13 @@ EOF */ public function GetField($sClassName, $sAttCode) { - if (!$this->ClassNameExists($sClassName)) - { + if (!$this->ClassNameExists($sClassName)) { return null; } $oClassNode = $this->GetClass($sClassName); /** @var \MFElement|null $oFieldNode */ $oFieldNode = $this->GetNodes("fields/field[@id='$sAttCode']", $oClassNode)->item(0); - if (($oFieldNode == null) && ($sParentClass = $oClassNode->GetChildText('parent'))) - { + if (($oFieldNode == null) && ($sParentClass = $oClassNode->GetChildText('parent'))) { return $this->GetField($sParentClass, $sAttCode); } @@ -1663,7 +1647,6 @@ EOF return $this->oRoot->ListChanges(); } - /** * Import the node into the delta * @@ -1776,8 +1759,7 @@ EOF { // Search into the deleted node as well! $oNodeSet = $this->oDOMDocument->GetNodes("//*[@$sAttribute='$sPreviousValue']", null, false); - foreach ($oNodeSet as $oTouchedNode) - { + foreach ($oNodeSet as $oTouchedNode) { $oTouchedNode->setAttribute($sAttribute, $sNewValue); } } @@ -1791,41 +1773,31 @@ EOF * @return \MFDocument * @throws \Exception */ - public function GetDeltaDocument($aNodesToIgnore = array(), $aAttributes = null) + public function GetDeltaDocument($aNodesToIgnore = [], $aAttributes = null) { $oDelta = new MFDocument(); - foreach ($this->ListChanges() as $oAlteredNode) - { + foreach ($this->ListChanges() as $oAlteredNode) { $this->ImportNodeAndPathDelta($oDelta, $oAlteredNode); } - foreach ($aNodesToIgnore as $sXPath) - { + foreach ($aNodesToIgnore as $sXPath) { $oNodesToRemove = $oDelta->GetNodes($sXPath); - foreach ($oNodesToRemove as $oNode) - { - if ($oNode instanceof DOMAttr) - { + foreach ($oNodesToRemove as $oNode) { + if ($oNode instanceof DOMAttr) { $oNode->ownerElement->removeAttributeNode($oNode); - } - else - { + } else { $oNode->parentNode->removeChild($oNode); } } } $oNodesToClean = $oDelta->GetNodes('/itop_design//*[@_altered_in]'); - foreach ($oNodesToClean as $oNode) - { + foreach ($oNodesToClean as $oNode) { $oNode->removeAttribute('_altered_in'); } - if ($aAttributes != null) - { - foreach ($aAttributes as $sAttribute => $value) - { - if ($oDelta->documentElement) // yes, this may happen when still no change has been performed (and a module has been selected for installation) - { + if ($aAttributes != null) { + foreach ($aAttributes as $sAttribute => $value) { + if ($oDelta->documentElement) { // yes, this may happen when still no change has been performed (and a module has been selected for installation) $oDelta->documentElement->setAttribute($sAttribute, $value); } } @@ -1843,7 +1815,7 @@ EOF * @return string * @throws \Exception */ - public function GetDelta($aNodesToIgnore = array(), $aAttributes = null) + public function GetDelta($aNodesToIgnore = [], $aAttributes = null) { $oDelta = $this->GetDeltaDocument($aNodesToIgnore, $aAttributes); @@ -1860,24 +1832,19 @@ EOF public function FindModules() { $aAvailableModules = ModuleDiscovery::GetAvailableModules($this->aRootDirs); - $aResult = array(); - foreach ($aAvailableModules as $sId => $aModule) - { + $aResult = []; + foreach ($aAvailableModules as $sId => $aModule) { $oModule = new MFModule($sId, $aModule['root_dir'], $aModule['label'], isset($aModule['auto_select'])); - if (isset($aModule['auto_select'])) - { + if (isset($aModule['auto_select'])) { $oModule->SetAutoSelect($aModule['auto_select']); } - if (isset($aModule['datamodel']) && is_array($aModule['datamodel'])) - { + if (isset($aModule['datamodel']) && is_array($aModule['datamodel'])) { $oModule->SetFilesToInclude($aModule['datamodel'], 'business'); } - if (isset($aModule['webservice']) && is_array($aModule['webservice'])) - { + if (isset($aModule['webservice']) && is_array($aModule['webservice'])) { $oModule->SetFilesToInclude($aModule['webservice'], 'webservices'); } - if (isset($aModule['addons']) && is_array($aModule['addons'])) - { + if (isset($aModule['addons']) && is_array($aModule['addons'])) { $oModule->SetFilesToInclude($aModule['addons'], 'addons'); } $aResult[] = $oModule; @@ -1903,7 +1870,8 @@ EOF /** * @return mixed */ - public function GetRootDirs() { + public function GetRootDirs() + { return $this->aRootDirs; } @@ -1966,17 +1934,14 @@ class MFElement extends Combodo\iTop\DesignElement public function GetUniqueElement($sTagName, $bMustExist = true) { $oNode = null; - foreach ($this->childNodes as $oChildNode) - { + foreach ($this->childNodes as $oChildNode) { /** @var MFElement $oChildNode */ - if (($oChildNode->nodeName == $sTagName) && !$oChildNode->IsRemoved()) - { + if (($oChildNode->nodeName == $sTagName) && !$oChildNode->IsRemoved()) { $oNode = $oChildNode; break; } } - if ($bMustExist && is_null($oNode)) - { + if ($bMustExist && is_null($oNode)) { $sXPath = DesignDocument::GetItopNodePath($this); throw new DOMFormatException("Missing unique tag: $sTagName in: $sXPath"); } @@ -2001,45 +1966,33 @@ class MFElement extends Combodo\iTop\DesignElement public function GetNodeAsArrayOfItems($sElementName = 'items') { $oItems = $this->GetOptionalElement($sElementName); - if ($oItems) - { - $res = array(); - $aRanks = array(); - foreach ($oItems->childNodes as $oItem) - { - if ($oItem instanceof DOMElement) - { + if ($oItems) { + $res = []; + $aRanks = []; + foreach ($oItems->childNodes as $oItem) { + if ($oItem instanceof DOMElement) { // When an attribute is missing - if ($oItem->hasAttribute('id')) - { + if ($oItem->hasAttribute('id')) { $key = $oItem->getAttribute('id'); - if (array_key_exists($key, $res)) - { + if (array_key_exists($key, $res)) { // Houston! $sXPath = DesignDocument::GetItopNodePath($this); throw new DOMFormatException("id '$key' already used in $sXPath", 0, null, $oItem); } $res[$key] = $oItem->GetNodeAsArrayOfItems(); - } - else - { + } else { $res[] = $oItem->GetNodeAsArrayOfItems(); } $sRank = $oItem->GetChildText('rank'); - if ($sRank != '') - { + if ($sRank != '') { $aRanks[] = (float)$sRank; - } - else - { + } else { $aRanks[] = count($aRanks) > 0 ? max($aRanks) + 1 : 0; } array_multisort($aRanks, $res); } } - } - else - { + } else { $res = $this->GetText(); } @@ -2053,25 +2006,20 @@ class MFElement extends Combodo\iTop\DesignElement */ protected static function AddItemToNode($oXmlDoc, $oXMLNode, $itemValue) { - if (is_array($itemValue)) - { + if (is_array($itemValue)) { $oXmlItems = $oXmlDoc->CreateElement('items'); $oXMLNode->appendChild($oXmlItems); - foreach ($itemValue as $key => $item) - { + foreach ($itemValue as $key => $item) { $oXmlItem = $oXmlDoc->CreateElement('item'); $oXmlItems->appendChild($oXmlItem); - if (is_string($key)) - { + if (is_string($key)) { $oXmlItem->SetAttribute('key', $key); } self::AddItemToNode($oXmlDoc, $oXmlItem, $item); } - } - else - { + } else { $oXmlText = $oXmlDoc->CreateTextNode((string)$itemValue); $oXMLNode->appendChild($oXmlText); } @@ -2082,17 +2030,14 @@ class MFElement extends Combodo\iTop\DesignElement */ protected function DeleteChildren() { - while (isset($this->firstChild)) - { - if ($this->firstChild instanceof MFElement) - { + while (isset($this->firstChild)) { + if ($this->firstChild instanceof MFElement) { $this->firstChild->DeleteChildren(); } $this->removeChild($this->firstChild); } } - /** * Check if the current node is under a node 'added' or 'altered' * Usage: In such a case, the change must not be tracked @@ -2102,10 +2047,8 @@ class MFElement extends Combodo\iTop\DesignElement public function IsInDefinition() { // Iterate through the parents: reset the flag if any of them has a flag set - for ($oParent = $this; $oParent instanceof MFElement; $oParent = $oParent->parentNode) - { - if ($oParent->GetAlteration() != '') - { + for ($oParent = $this; $oParent instanceof MFElement; $oParent = $oParent->parentNode) { + if ($oParent->GetAlteration() != '') { return true; } } @@ -2123,10 +2066,8 @@ class MFElement extends Combodo\iTop\DesignElement public function IsAlteredByModule($aModules) { // Iterate through the parents: reset the flag if any of them has a flag set - for ($oParent = $this; $oParent instanceof MFElement; $oParent = $oParent->parentNode) - { - if (in_array($oParent->getAttribute('_altered_in'), $aModules)) - { + for ($oParent = $this; $oParent instanceof MFElement; $oParent = $oParent->parentNode) { + if (in_array($oParent->getAttribute('_altered_in'), $aModules)) { return true; } } @@ -2151,10 +2092,8 @@ class MFElement extends Combodo\iTop\DesignElement */ public function AddTrace() { - if (!is_null(self::$aTraceAttributes)) - { - foreach (self::$aTraceAttributes as $sAttribute => $value) - { + if (!is_null(self::$aTraceAttributes)) { + foreach (self::$aTraceAttributes as $sAttribute => $value) { $this->setAttribute($sAttribute, $value); } } @@ -2175,8 +2114,7 @@ class MFElement extends Combodo\iTop\DesignElement $oNode->AddTrace(); $oExisting = $this->_FindChildNode($oNode); - if ($oExisting) - { + if ($oExisting) { if (!$oExisting->IsRemoved()) { $sPath = MFDocument::GetItopNodePath($oNode); $iLine = ModelFactory::GetXMLLineNumber($oNode); @@ -2189,14 +2127,11 @@ EOF; } $oExisting->ReplaceWithSingleNode($oNode); $sFlag = 'replaced'; - } - else - { + } else { $this->appendChild($oNode); $sFlag = 'added'; } - if (!$this->IsInDefinition()) - { + if (!$this->IsInDefinition()) { $oNode->SetAlteration($sFlag); } } @@ -2219,20 +2154,27 @@ EOF; $oNode->AddTrace(); $oExisting = $this->_FindChildNode($oNode, $sSearchId); - if (!$oExisting) - { + if (!$oExisting) { $sPath = MFDocument::GetItopNodePath($this)."/".$oNode->tagName.(empty($sSearchId) ? '' : "[$sSearchId]"); $iLine = ModelFactory::GetXMLLineNumber($oNode); - throw new MFException($sPath." at line $iLine: could not be modified (not found)", MFException::COULD_NOT_BE_MODIFIED_NOT_FOUND, - $sPath, $iLine); + throw new MFException( + $sPath." at line $iLine: could not be modified (not found)", + MFException::COULD_NOT_BE_MODIFIED_NOT_FOUND, + $sPath, + $iLine + ); } $sPrevFlag = $oExisting->GetAlteration(); $sOldId = $oExisting->getAttribute('_old_id'); if ($oExisting->IsRemoved()) { $sPath = MFDocument::GetItopNodePath($this)."/".$oNode->tagName.(empty($sSearchId) ? '' : "[$sSearchId]"); $iLine = ModelFactory::GetXMLLineNumber($oNode); - throw new MFException($sPath." at line $iLine: could not be modified (marked as deleted)", - MFException::COULD_NOT_BE_MODIFIED_ALREADY_DELETED, $sPath, $iLine); + throw new MFException( + $sPath." at line $iLine: could not be modified (marked as deleted)", + MFException::COULD_NOT_BE_MODIFIED_ALREADY_DELETED, + $sPath, + $iLine + ); } $oExisting->ReplaceWithSingleNode($oNode); if (!$this->IsInDefinition()) { @@ -2263,11 +2205,9 @@ EOF; $oNode->AddTrace(); $oExisting = $this->_FindChildNode($oNode, $sSearchId); - if ($oExisting) - { + if ($oExisting) { $sOldId = $oExisting->getAttribute('_old_id'); - if (!empty($sOldId)) - { + if (!empty($sOldId)) { $oNode->setAttribute('_old_id', $sOldId); } @@ -2278,24 +2218,18 @@ EOF; $sFlag = $sPrevFlag; // added, replaced or '' } $oExisting->ReplaceWithSingleNode($oNode); - } - else - { + } else { $this->appendChild($oNode); $sFlag = $bForce ? 'forced' : 'added'; } - if (!$this->IsInDefinition()) - { - if ($sFlag == '') - { + if (!$this->IsInDefinition()) { + if ($sFlag == '') { $sFlag = $bForce ? 'forced' : 'replaced'; } $oNode->SetAlteration($sFlag); } } - - /** * Replaces a node by another one, making sure that recursive nodes are preserved * @@ -2325,8 +2259,7 @@ EOF; */ public function Delete(bool $bIsConditional = false) { - switch ($this->GetAlteration()) - { + switch ($this->GetAlteration()) { case 'replaced': $sFlag = $bIsConditional ? 'remove_needed' : 'removed'; break; @@ -2339,14 +2272,12 @@ EOF; default: $sFlag = $bIsConditional ? 'remove_needed' : 'removed'; - if ($this->IsInDefinition()) - { + if ($this->IsInDefinition()) { $sFlag = null; break; } } - if ($sFlag) - { + if ($sFlag) { // If class move the node AFTER all the removed classes to keep the delete order // and remain compatible with GetDelta/LoadDelta class flattening if ($this->IsClassNode()) { @@ -2358,9 +2289,7 @@ EOF; // Add trace data $this->AddTrace(); - } - else - { + } else { // Remove the node entirely $this->parentNode->removeChild($this); } @@ -2374,26 +2303,18 @@ EOF; public function Rename($sId) { $sAlteration = $this->GetAlteration(); - if (($sAlteration == 'replaced') || ($sAlteration == 'forced') || !$this->IsInDefinition()) - { + if (($sAlteration == 'replaced') || ($sAlteration == 'forced') || !$this->IsInDefinition()) { $sOriginalId = $this->getAttribute('_old_id'); - if ($sOriginalId == '') - { + if ($sOriginalId == '') { $sRenameOrig = $this->getAttribute('_rename_from'); - if (empty($sRenameOrig)) - { + if (empty($sRenameOrig)) { $this->setAttribute('_old_id', $this->getAttribute('id')); - } - else - { + } else { $this->setAttribute('_old_id', $sRenameOrig); $this->removeAttribute('_rename_from'); } - } - else - { - if ($sOriginalId == $sId) - { + } else { + if ($sOriginalId == $sId) { $this->removeAttribute('_old_id'); } } @@ -2404,7 +2325,6 @@ EOF; $this->AddTrace(); } - /** * List changes below a given node (see also MFDocument::ListChanges) */ @@ -2438,8 +2358,8 @@ EOF; } $oNode->parentNode->removeChild($oNode); } else { - // marked as added or modified, just reset the flag - $oNode->RemoveAlteration(); + // marked as added or modified, just reset the flag + $oNode->RemoveAlteration(); } } } @@ -2502,8 +2422,7 @@ class MFDocument extends \Combodo\iTop\DesignDocument public function saveXML(DOMNode $node = null, $options = 0) { $oRootNode = $this->firstChild; - if (!$oRootNode) - { + if (!$oRootNode) { $oRootNode = $this->createElement('itop_design'); // make sure that the document is not empty $oRootNode->setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance"); $oRootNode->setAttribute('version', ITOP_DESIGN_LATEST_VERSION); @@ -2529,12 +2448,11 @@ class MFDocument extends \Combodo\iTop\DesignDocument * * @since 3.1.0 N°4517 $namespaceURI parameter must be empty string by default so */ - function createElement($sName, $value = null, $namespaceURI = '') + public function createElement($sName, $value = null, $namespaceURI = '') { /** @var \MFElement $oElement */ $oElement = $this->importNode(new MFElement($sName, null, $namespaceURI)); - if (($value !== '') && ($value !== null)) - { + if (($value !== '') && ($value !== null)) { $oElement->appendChild(new DOMText($value)); } @@ -2573,17 +2491,13 @@ class MFDocument extends \Combodo\iTop\DesignDocument $oXPath->registerNamespace('xsi', 'http://www.w3.org/2001/XMLSchema-instance'); $oXPath->registerPhpFunctions(); - if ($bSafe) - { + if ($bSafe) { $sXPath = "($sXPath)[not(@_alteration) or (@_alteration!='removed' and @_alteration!='remove_needed')]"; } - if (is_null($oContextNode)) - { + if (is_null($oContextNode)) { $oResult = $oXPath->query($sXPath); - } - else - { + } else { $oResult = $oXPath->query($sXPath, $oContextNode); } @@ -2607,12 +2521,9 @@ class MFDocument extends \Combodo\iTop\DesignDocument $sQuotedId = self::XPathQuote($sId); $sXPath = "($sXPath)[@id=$sQuotedId and (not(@_alteration) or @_alteration!='removed' or @_alteration!='remove_needed')]"; - if (is_null($oContextNode)) - { + if (is_null($oContextNode)) { return $oXPath->query($sXPath); - } - else - { + } else { return $oXPath->query($sXPath, $oContextNode); } } @@ -2636,7 +2547,7 @@ class MFParameters */ public function __construct(DOMNode $oNode) { - $this->aData = array(); + $this->aData = []; $this->LoadFromDOM($oNode); } @@ -2648,8 +2559,7 @@ class MFParameters */ public function Get($sCode, $default = '') { - if (array_key_exists($sCode, $this->aData)) - { + if (array_key_exists($sCode, $this->aData)) { return $this->aData[$sCode]; } @@ -2671,11 +2581,9 @@ class MFParameters */ public function LoadFromDOM(DOMNode $oNode) { - $this->aData = array(); - foreach ($oNode->childNodes as $oChildNode) - { - if ($oChildNode instanceof DOMElement) - { + $this->aData = []; + foreach ($oNode->childNodes as $oChildNode) { + if ($oChildNode instanceof DOMElement) { $this->aData[$oChildNode->nodeName] = $this->ReadElement($oChildNode); } } @@ -2690,33 +2598,24 @@ class MFParameters protected function ReadElement(DOMNode $oNode) { $value = null; - if ($oNode instanceof DOMElement) - { + if ($oNode instanceof DOMElement) { $sDefaultNodeType = ($this->HasChildNodes($oNode)) ? 'hash' : 'string'; $sNodeType = $oNode->getAttribute('type'); - if ($sNodeType == '') - { + if ($sNodeType == '') { $sNodeType = $sDefaultNodeType; } - switch ($sNodeType) - { + switch ($sNodeType) { case 'array': - $value = array(); + $value = []; // Treat the current element as zero based array, child tag names are NOT meaningful $sFirstTagName = null; - foreach ($oNode->childNodes as $oChildElement) - { - if ($oChildElement instanceof DOMElement) - { - if ($sFirstTagName == null) - { + foreach ($oNode->childNodes as $oChildElement) { + if ($oChildElement instanceof DOMElement) { + if ($sFirstTagName == null) { $sFirstTagName = $oChildElement->nodeName; - } - else - { - if ($sFirstTagName != $oChildElement->nodeName) - { + } else { + if ($sFirstTagName != $oChildElement->nodeName) { throw new Exception("Invalid Parameters: mixed tags ('$sFirstTagName' and '".$oChildElement->nodeName."') inside array '".$oNode->nodeName."'"); } } @@ -2729,14 +2628,11 @@ class MFParameters break; case 'hash': - $value = array(); + $value = []; // Treat the current element as a hash, child tag names are keys - foreach ($oNode->childNodes as $oChildElement) - { - if ($oChildElement instanceof DOMElement) - { - if (array_key_exists($oChildElement->nodeName, $value)) - { + foreach ($oNode->childNodes as $oChildElement) { + if ($oChildElement instanceof DOMElement) { + if (array_key_exists($oChildElement->nodeName, $value)) { throw new Exception("Invalid Parameters file: duplicate tags '".$oChildElement->nodeName."' inside hash '".$oNode->nodeName."'"); } $val = $this->ReadElement($oChildElement); @@ -2752,12 +2648,9 @@ class MFParameters case 'bool': case 'boolean': - if (($this->GetText($oNode) == 'true') || ($this->GetText($oNode) == 1)) - { + if (($this->GetText($oNode) == 'true') || ($this->GetText($oNode) == 1)) { $value = true; - } - else - { + } else { $value = false; } break; @@ -2766,11 +2659,8 @@ class MFParameters default: $value = str_replace('\n', "\n", (string)$this->GetText($oNode)); } - } - else - { - if ($oNode instanceof DOMText) - { + } else { + if ($oNode instanceof DOMText) { $value = $oNode->wholeText; } } @@ -2789,10 +2679,8 @@ class MFParameters { $sRet = $sDefaultValue; - foreach ($oNode->attributes as $oAttribute) - { - if ($oAttribute->nodeName == $sAttName) - { + foreach ($oNode->attributes as $oAttribute) { + if ($oAttribute->nodeName == $sAttName) { $sRet = $oAttribute->nodeValue; break; } @@ -2812,23 +2700,17 @@ class MFParameters public function GetText($oNode, $sDefault = null) { $sText = null; - foreach ($oNode->childNodes as $oChildNode) - { - if ($oChildNode instanceof DOMText) - { - if (is_null($sText)) - { + foreach ($oNode->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; } } @@ -2842,12 +2724,9 @@ class MFParameters */ public function HasChildNodes($oNode) { - if ($oNode instanceof DOMElement) - { - foreach ($oNode->childNodes as $oChildNode) - { - if ($oChildNode instanceof DOMElement) - { + if ($oNode instanceof DOMElement) { + foreach ($oNode->childNodes as $oChildNode) { + if ($oChildNode instanceof DOMElement) { return true; } } @@ -2859,7 +2738,7 @@ class MFParameters /** * @param \XMLParameters $oTask */ - function Merge(XMLParameters $oTask) + public function Merge(XMLParameters $oTask) { //todo: clarify the usage of this function that CANNOT work $this->aData = $this->array_merge_recursive_distinct($this->aData, $oTask->aData); @@ -2895,14 +2774,10 @@ class MFParameters { $merged = $array1; - foreach ($array2 as $key => &$value) - { - if (is_array($value) && isset ($merged [$key]) && is_array($merged [$key])) - { + foreach ($array2 as $key => &$value) { + if (is_array($value) && isset($merged [$key]) && is_array($merged [$key])) { $merged [$key] = $this->array_merge_recursive_distinct($merged [$key], $value); - } - else - { + } else { $merged [$key] = $value; } } diff --git a/setup/modulediscovery.class.inc.php b/setup/modulediscovery.class.inc.php index 89cc86440..9fd0ababf 100644 --- a/setup/modulediscovery.class.inc.php +++ b/setup/modulediscovery.class.inc.php @@ -1,4 +1,5 @@ 'One line description shown during the interactive setup', 'dependencies' => 'array of module ids', 'mandatory' => 'boolean', @@ -83,17 +84,15 @@ class ModuleDiscovery 'data.sample' => 'array of sample data files', 'doc.manual_setup' => 'url', 'doc.more_information' => 'url', - ); - + ]; // Cache the results and the source directories protected static $m_aSearchDirs = null; - protected static $m_aModules = array(); - protected static $m_aModuleVersionByName = array(); + protected static $m_aModules = []; + protected static $m_aModuleVersionByName = []; // All the entries below are list of file paths relative to the module directory - protected static $m_aFilesList = array('datamodel', 'webservice', 'dictionary', 'data.struct', 'data.sample'); - + protected static $m_aFilesList = ['datamodel', 'webservice', 'dictionary', 'data.struct', 'data.sample']; // ModulePath is used by AddModule to get the path of the module being included (in ListModuleFiles) protected static $m_sModulePath = null; @@ -114,18 +113,15 @@ class ModuleDiscovery */ public static function AddModule($sFilePath, $sId, $aArgs) { - if (is_null($aArgs)||! is_array($aArgs)){ + if (is_null($aArgs) || ! is_array($aArgs)) { throw new ModuleFileReaderException("Error parsing module file args", 0, null, $sFilePath); } - if (!array_key_exists('itop_version', $aArgs)) - { + if (!array_key_exists('itop_version', $aArgs)) { // Assume 1.0.2 $aArgs['itop_version'] = '1.0.2'; } - foreach (array_keys(self::$m_aModuleArgs) as $sArgName) - { - if (!array_key_exists($sArgName, $aArgs)) - { + foreach (array_keys(self::$m_aModuleArgs) as $sArgName) { + if (!array_key_exists($sArgName, $aArgs)) { throw new Exception("Module '$sId': missing argument '$sArgName'"); } } @@ -134,30 +130,23 @@ class ModuleDiscovery $aArgs['module_file'] = $sFilePath; list($sModuleName, $sModuleVersion) = static::GetModuleName($sId); - if ($sModuleVersion == '') - { + if ($sModuleVersion == '') { $sModuleVersion = '1.0.0'; } - if (array_key_exists($sModuleName, self::$m_aModuleVersionByName)) - { - if (version_compare($sModuleVersion, self::$m_aModuleVersionByName[$sModuleName]['version'], '>')) - { + if (array_key_exists($sModuleName, self::$m_aModuleVersionByName)) { + if (version_compare($sModuleVersion, self::$m_aModuleVersionByName[$sModuleName]['version'], '>')) { // Newer version, let's upgrade $sIdToRemove = self::$m_aModuleVersionByName[$sModuleName]['id']; unset(self::$m_aModules[$sIdToRemove]); self::$m_aModuleVersionByName[$sModuleName]['version'] = $sModuleVersion; self::$m_aModuleVersionByName[$sModuleName]['id'] = $sId; - } - else - { + } else { // Older (or equal) version, let's ignore it return; } - } - else - { + } else { // First version to be loaded for this module, remember it self::$m_aModuleVersionByName[$sModuleName]['version'] = $sModuleVersion; self::$m_aModuleVersionByName[$sModuleName]['id'] = $sId; @@ -181,24 +170,19 @@ class ModuleDiscovery } */ // Populate automatically the list of dictionary files - $aMatches = array(); - if(preg_match('|^([^/]+)|', $sId, $aMatches)) // ModuleName = everything before the first forward slash - { + $aMatches = []; + if (preg_match('|^([^/]+)|', $sId, $aMatches)) { // ModuleName = everything before the first forward slash $sModuleName = $aMatches[1]; $sDir = dirname($sFilePath); $aDirs = [ $sDir => self::$m_sModulePath, - $sDir.'/dictionaries' => self::$m_sModulePath.'/dictionaries' + $sDir.'/dictionaries' => self::$m_sModulePath.'/dictionaries', ]; - foreach ($aDirs as $sRootDir => $sPath) - { - if ($hDir = @opendir($sRootDir)) - { - while (($sFile = readdir($hDir)) !== false) - { - $aMatches = array(); - if (preg_match("/^[^\\.]+.dict.$sModuleName.php$/i", $sFile, $aMatches)) // Dictionary files named like .dict..php are loaded automatically - { + foreach ($aDirs as $sRootDir => $sPath) { + if ($hDir = @opendir($sRootDir)) { + while (($sFile = readdir($hDir)) !== false) { + $aMatches = []; + if (preg_match("/^[^\\.]+.dict.$sModuleName.php$/i", $sFile, $aMatches)) { // Dictionary files named like .dict..php are loaded automatically self::$m_aModules[$sId]['dictionary'][] = $sPath.'/'.$sFile; } } @@ -236,11 +220,9 @@ class ModuleDiscovery // Order the modules to take into account their inter-dependencies $aDependencies = []; $aSelectedModules = []; - foreach($aModules as $sId => $aModule) - { + foreach ($aModules as $sId => $aModule) { list($sModuleName, ) = self::GetModuleName($sId); - if (is_null($aModulesToLoad) || in_array($sModuleName, $aModulesToLoad)) - { + if (is_null($aModulesToLoad) || in_array($sModuleName, $aModulesToLoad)) { $aDependencies[$sId] = $aModule['dependencies']; $aSelectedModules[$sModuleName] = true; } @@ -248,46 +230,36 @@ class ModuleDiscovery ksort($aDependencies); $aOrderedModules = []; $iLoopCount = 1; - while(($iLoopCount < count($aModules)) && (count($aDependencies) > 0) ) - { - foreach($aDependencies as $sId => $aRemainingDeps) - { + while (($iLoopCount < count($aModules)) && (count($aDependencies) > 0)) { + foreach ($aDependencies as $sId => $aRemainingDeps) { $bDependenciesSolved = true; - foreach($aRemainingDeps as $sDepId) - { - if (!self::DependencyIsResolved($sDepId, $aOrderedModules, $aSelectedModules)) - { + foreach ($aRemainingDeps as $sDepId) { + if (!self::DependencyIsResolved($sDepId, $aOrderedModules, $aSelectedModules)) { $bDependenciesSolved = false; } } - if ($bDependenciesSolved) - { + if ($bDependenciesSolved) { $aOrderedModules[] = $sId; unset($aDependencies[$sId]); } } $iLoopCount++; } - if ($bAbortOnMissingDependency && count($aDependencies) > 0) - { + if ($bAbortOnMissingDependency && count($aDependencies) > 0) { $aModulesInfo = []; $aModuleDeps = []; - foreach($aDependencies as $sId => $aDeps) - { + foreach ($aDependencies as $sId => $aDeps) { $aModule = $aModules[$sId]; $aDepsWithIcons = []; - foreach($aDeps as $sIndex => $sDepId) - { - if (self::DependencyIsResolved($sDepId, $aOrderedModules, $aSelectedModules)) - { - $aDepsWithIcons[$sIndex] = '✅ ' . $sDepId; - } else - { - $aDepsWithIcons[$sIndex] = '❌ ' . $sDepId; + foreach ($aDeps as $sIndex => $sDepId) { + if (self::DependencyIsResolved($sDepId, $aOrderedModules, $aSelectedModules)) { + $aDepsWithIcons[$sIndex] = '✅ '.$sDepId; + } else { + $aDepsWithIcons[$sIndex] = '❌ '.$sDepId; } } $aModuleDeps[] = "{$aModule['label']} (id: $sId) depends on: ".implode(' + ', $aDepsWithIcons); - $aModulesInfo[$sId] = array('module' => $aModule, 'dependencies' => $aDepsWithIcons); + $aModulesInfo[$sId] = ['module' => $aModule, 'dependencies' => $aDepsWithIcons]; } $sMessage = "The following modules have unmet dependencies:\n".implode(",\n", $aModuleDeps); $oException = new MissingDependencyException($sMessage); @@ -295,9 +267,8 @@ class ModuleDiscovery throw $oException; } // Return the ordered list, so that the dependencies are met... - $aResult = array(); - foreach($aOrderedModules as $sId) - { + $aResult = []; + foreach ($aOrderedModules as $sId) { $aResult[$sId] = $aModules[$sId]; } return $aResult; @@ -327,59 +298,44 @@ class ModuleDiscovery protected static function DependencyIsResolved($sDepString, $aOrderedModules, $aSelectedModules) { $bResult = false; - $aModuleVersions = array(); + $aModuleVersions = []; // Separate the module names from their version for an easier comparison later - foreach($aOrderedModules as $sModuleId) - { - $aMatches = array(); - if (preg_match('|^([^/]+)/(.*)$|', $sModuleId, $aMatches)) - { + foreach ($aOrderedModules as $sModuleId) { + $aMatches = []; + if (preg_match('|^([^/]+)/(.*)$|', $sModuleId, $aMatches)) { $aModuleVersions[$aMatches[1]] = $aMatches[2]; - } - else - { + } else { // No version number found, assume 1.0.0 $aModuleVersions[$sModuleId] = '1.0.0'; } } - if (preg_match_all('/([^\(\)&| ]+)/', $sDepString, $aMatches)) - { - $aReplacements = array(); - $aPotentialPrerequisites = array(); - foreach($aMatches as $aMatch) - { - foreach($aMatch as $sModuleId) - { + if (preg_match_all('/([^\(\)&| ]+)/', $sDepString, $aMatches)) { + $aReplacements = []; + $aPotentialPrerequisites = []; + foreach ($aMatches as $aMatch) { + foreach ($aMatch as $sModuleId) { // $sModuleId in the dependency string is made of a / // where the operator is < <= = > >= (by default >=) - $aModuleMatches = array(); - if(preg_match('|^([^/]+)/(?=?)([^><=]+)$|', $sModuleId, $aModuleMatches)) - { + $aModuleMatches = []; + if (preg_match('|^([^/]+)/(?=?)([^><=]+)$|', $sModuleId, $aModuleMatches)) { $sModuleName = $aModuleMatches[1]; $aPotentialPrerequisites[$sModuleName] = true; $sOperator = $aModuleMatches[2]; - if ($sOperator == '') - { + if ($sOperator == '') { $sOperator = '>='; } $sExpectedVersion = $aModuleMatches[3]; - if (array_key_exists($sModuleName, $aModuleVersions)) - { + if (array_key_exists($sModuleName, $aModuleVersions)) { // module is present, check the version $sCurrentVersion = $aModuleVersions[$sModuleName]; - if (version_compare($sCurrentVersion, $sExpectedVersion, $sOperator)) - { + if (version_compare($sCurrentVersion, $sExpectedVersion, $sOperator)) { $aReplacements[$sModuleId] = '(true)'; // Add parentheses to protect against invalid condition causing // a function call that results in a runtime fatal error - } - else - { + } else { $aReplacements[$sModuleId] = '(false)'; // Add parentheses to protect against invalid condition causing // a function call that results in a runtime fatal error } - } - else - { + } else { // module is not present $aReplacements[$sModuleId] = '(false)'; // Add parentheses to protect against invalid condition causing // a function call that results in a runtime fatal error @@ -388,27 +344,21 @@ class ModuleDiscovery } } $bMissingPrerequisite = false; - foreach (array_keys($aPotentialPrerequisites) as $sModuleName) - { - if (array_key_exists($sModuleName, $aSelectedModules)) - { + foreach (array_keys($aPotentialPrerequisites) as $sModuleName) { + if (array_key_exists($sModuleName, $aSelectedModules)) { // This module is actually a prerequisite - if (!array_key_exists($sModuleName, $aModuleVersions)) - { + if (!array_key_exists($sModuleName, $aModuleVersions)) { $bMissingPrerequisite = true; } } } - if ($bMissingPrerequisite) - { + if ($bMissingPrerequisite) { $bResult = false; - } - else - { + } else { $sBooleanExpr = str_replace(array_keys($aReplacements), array_values($aReplacements), $sDepString); - try{ + try { $bResult = self::GetPhpExpressionEvaluator()->ParseAndEvaluateBooleanExpression($sBooleanExpr); - } catch(ModuleFileReaderException $e){ + } catch (ModuleFileReaderException $e) { //logged already echo "Failed to parse the boolean Expression = '$sBooleanExpr'
"; } @@ -430,21 +380,17 @@ class ModuleDiscovery */ public static function GetAvailableModules($aSearchDirs, $bAbortOnMissingDependency = false, $aModulesToLoad = null) { - if (self::$m_aSearchDirs != $aSearchDirs) - { + if (self::$m_aSearchDirs != $aSearchDirs) { self::ResetCache(); } - if (is_null(self::$m_aSearchDirs)) - { + if (is_null(self::$m_aSearchDirs)) { self::$m_aSearchDirs = $aSearchDirs; // Not in cache, let's scan the disk - foreach($aSearchDirs as $sSearchDir) - { + foreach ($aSearchDirs as $sSearchDir) { $sLookupDir = realpath($sSearchDir); - if ($sLookupDir == '') - { + if ($sLookupDir == '') { throw new Exception("Invalid directory '$sSearchDir'"); } @@ -452,9 +398,7 @@ class ModuleDiscovery self::ListModuleFiles(basename($sSearchDir), dirname($sSearchDir)); } return self::GetModules($bAbortOnMissingDependency, $aModulesToLoad); - } - else - { + } else { // Reuse the previous results return self::GetModules($bAbortOnMissingDependency, $aModulesToLoad); } @@ -463,8 +407,8 @@ class ModuleDiscovery public static function ResetCache() { self::$m_aSearchDirs = null; - self::$m_aModules = array(); - self::$m_aModuleVersionByName = array(); + self::$m_aModules = []; + self::$m_aModuleVersionByName = []; } /** @@ -474,18 +418,15 @@ class ModuleDiscovery */ public static function GetModuleName($sModuleId) { - $aMatches = array(); - if (preg_match('!^(.*)/(.*)$!', $sModuleId, $aMatches)) - { + $aMatches = []; + if (preg_match('!^(.*)/(.*)$!', $sModuleId, $aMatches)) { $sName = $aMatches[1]; $sVersion = $aMatches[2]; - } - else - { + } else { $sName = $sModuleId; $sVersion = ""; } - return array($sName, $sVersion); + return [$sName, $sVersion]; } /** @@ -501,41 +442,32 @@ class ModuleDiscovery static $iDummyClassIndex = 0; $sDirectory = $sRootDir.'/'.$sRelDir; - if ($hDir = opendir($sDirectory)) - { + if ($hDir = opendir($sDirectory)) { // This is the correct way to loop over the directory. (according to the documentation) - while (($sFile = readdir($hDir)) !== false) - { - $aMatches = array(); - if (is_dir($sDirectory.'/'.$sFile)) - { - if (($sFile != '.') && ($sFile != '..') && ($sFile != '.svn') && ($sFile != 'vendor')) - { + while (($sFile = readdir($hDir)) !== false) { + $aMatches = []; + if (is_dir($sDirectory.'/'.$sFile)) { + if (($sFile != '.') && ($sFile != '..') && ($sFile != '.svn') && ($sFile != 'vendor')) { self::ListModuleFiles($sRelDir.'/'.$sFile, $sRootDir); } - } - else if (preg_match('/^module\.(.*).php$/i', $sFile, $aMatches)) - { + } elseif (preg_match('/^module\.(.*).php$/i', $sFile, $aMatches)) { self::SetModulePath($sRelDir); $sModuleFilePath = $sDirectory.'/'.$sFile; try { $aModuleInfo = ModuleFileReader::GetInstance()->ReadModuleFileInformation($sDirectory.'/'.$sFile); SetupWebPage::AddModule($sModuleFilePath, $aModuleInfo[ModuleFileReader::MODULE_INFO_ID], $aModuleInfo[ModuleFileReader::MODULE_INFO_CONFIG]); - } catch(ModuleFileReaderException $e){ + } catch (ModuleFileReaderException $e) { continue; } } } closedir($hDir); - } - else - { + } else { throw new Exception("Data directory (".$sDirectory.") not found or not readable."); } } } // End of class - /** Alias for backward compatibility with old module files in which * the declaration of a module invokes SetupWebPage::AddModule() * whereas the new form is ModuleDiscovery::AddModule() @@ -576,6 +508,6 @@ class SetupWebPage extends ModuleDiscovery * the class (in case some piece of code enumerate the classes derived from a well known class) * Note that this will not work if someone enumerates the classes that implement a given interface */ -class DummyHandler { +class DummyHandler +{ } - diff --git a/setup/modulediscovery/ModuleFileReader.php b/setup/modulediscovery/ModuleFileReader.php index b09d3ef3e..118f2249a 100644 --- a/setup/modulediscovery/ModuleFileReader.php +++ b/setup/modulediscovery/ModuleFileReader.php @@ -12,39 +12,42 @@ use PhpParser\Node\Stmt\Expression; use PhpParser\Node\Stmt\If_; use PhpParser\ParserFactory; use PhpParser\Node\Expr\Assign; -use \PhpParser\Node\Stmt\ElseIf_; +use PhpParser\Node\Stmt\ElseIf_; use PhpParser\Node\Expr\Array_; use PhpParser\Node\Scalar\String_; use PhpParser\Node\Arg; -require_once __DIR__ . '/ModuleFileReaderException.php'; -require_once APPROOT . 'sources/PhpParser/Evaluation/PhpExpressionEvaluator.php'; +require_once __DIR__.'/ModuleFileReaderException.php'; +require_once APPROOT.'sources/PhpParser/Evaluation/PhpExpressionEvaluator.php'; -class ModuleFileReader { +class ModuleFileReader +{ private static ModuleFileReader $oInstance; - private static int $iDummyClassIndex = 0; + private static int $iDummyClassIndex = 0; - private PhpExpressionEvaluator $oPhpExpressionEvaluator; + private PhpExpressionEvaluator $oPhpExpressionEvaluator; - const FUNC_CALL_WHITELIST=[ + public const FUNC_CALL_WHITELIST = [ "function_exists", "class_exists", - "method_exists" + "method_exists", ]; - const MODULE_INFO_PATH = 0; - const MODULE_INFO_ID = 1; - const MODULE_INFO_CONFIG = 2; + public const MODULE_INFO_PATH = 0; + public const MODULE_INFO_ID = 1; + public const MODULE_INFO_CONFIG = 2; - const STATIC_CALLWHITELIST=[ - "utils::GetItopVersionWikiSyntax" + public const STATIC_CALLWHITELIST = [ + "utils::GetItopVersionWikiSyntax", ]; - protected function __construct() { + protected function __construct() + { $this->oPhpExpressionEvaluator = new PhpExpressionEvaluator(static::FUNC_CALL_WHITELIST, static::STATIC_CALLWHITELIST); } - final public static function GetInstance(): ModuleFileReader { + final public static function GetInstance(): ModuleFileReader + { if (!isset(static::$oInstance)) { static::$oInstance = new static(); } @@ -52,7 +55,8 @@ class ModuleFileReader { return static::$oInstance; } - final public static function SetInstance(?ModuleFileReader $oInstance): void { + final public static function SetInstance(?ModuleFileReader $oInstance): void + { static::$oInstance = $oInstance; } @@ -62,14 +66,12 @@ class ModuleFileReader { * @return array * @throws ModuleFileReaderException */ - public function ReadModuleFileInformation(string $sModuleFilePath) : array + public function ReadModuleFileInformation(string $sModuleFilePath): array { - try - { + try { $oParser = (new ParserFactory())->createForNewestSupportedVersion(); $aNodes = $oParser->parse(file_get_contents($sModuleFilePath)); - } - catch (Error $e) { + } catch (Error $e) { throw new ModuleFileReaderException($e->getMessage(), 0, $e, $sModuleFilePath); } @@ -77,7 +79,7 @@ class ModuleFileReader { foreach ($aNodes as $sKey => $oNode) { if ($oNode instanceof Expression) { $aModuleInfo = $this->GetModuleInformationFromAddModuleCall($sModuleFilePath, $oNode); - if (! is_null($aModuleInfo)){ + if (! is_null($aModuleInfo)) { $this->CompleteModuleInfoWithFilePath($aModuleInfo); return $aModuleInfo; } @@ -85,16 +87,16 @@ class ModuleFileReader { if ($oNode instanceof If_) { $aModuleInfo = $this->GetModuleInformationFromIf($sModuleFilePath, $oNode); - if (! is_null($aModuleInfo)){ + if (! is_null($aModuleInfo)) { $this->CompleteModuleInfoWithFilePath($aModuleInfo); return $aModuleInfo; } } } - } catch(ModuleFileReaderException $e) { + } catch (ModuleFileReaderException $e) { // Continue... throw $e; - } catch(Exception $e) { + } catch (Exception $e) { // Continue... throw new ModuleFileReaderException("Eval of $sModuleFilePath caused an exception: ".$e->getMessage(), 0, $e, $sModuleFilePath); } @@ -110,11 +112,10 @@ class ModuleFileReader { * @return array * @throws ModuleFileReaderException */ - public function ReadModuleFileInformationUnsafe(string $sModuleFilePath) : array + public function ReadModuleFileInformationUnsafe(string $sModuleFilePath): array { $aModuleInfo = []; // will be filled by the "eval" line below... - try - { + try { $aMatches = []; $sModuleFileContents = file_get_contents($sModuleFilePath); $sModuleFileContents = str_replace([''], '', $sModuleFileContents); @@ -122,10 +123,8 @@ class ModuleFileReader { preg_match_all('/class ([A-Za-z0-9_]+) extends ([A-Za-z0-9_]+)/', $sModuleFileContents, $aMatches); //print_r($aMatches); $idx = 0; - foreach($aMatches[1] as $sClassName) - { - if (class_exists($sClassName)) - { + foreach ($aMatches[1] as $sClassName) { + if (class_exists($sClassName)) { // rename any class declaration inside the code to prevent a "duplicate class" declaration // and change its parent class as well so that nobody will find it and try to execute it // Note: don't use the same naming scheme as ModuleDiscovery otherwise you 'll have the duplicate class error again !! @@ -137,25 +136,18 @@ class ModuleFileReader { $sModuleFileContents = str_replace(['SetupWebPage::AddModule', 'ModuleDiscovery::AddModule'], '$aModuleInfo = array', $sModuleFileContents); eval($sModuleFileContents); // Assigns $aModuleInfo - if (count($aModuleInfo) === 0) - { + if (count($aModuleInfo) === 0) { throw new ModuleFileReaderException("Eval of $sModuleFilePath did not return the expected information..."); } $this->CompleteModuleInfoWithFilePath($aModuleInfo); - } - catch(ModuleFileReaderException $e) - { + } catch (ModuleFileReaderException $e) { // Continue... throw $e; - } - catch(ParseError $e) - { + } catch (ParseError $e) { // Continue... throw new ModuleFileReaderException("Eval of $sModuleFilePath caused a parse error: ".$e->getMessage()." at line ".$e->getLine()); - } - catch(Exception $e) - { + } catch (Exception $e) { // Continue... throw new ModuleFileReaderException("Eval of $sModuleFilePath caused an exception: ".$e->getMessage(), 0, $e); } @@ -171,14 +163,14 @@ class ModuleFileReader { */ private function CompleteModuleInfoWithFilePath(array &$aModuleInfo) { - if (count($aModuleInfo)==3) { + if (count($aModuleInfo) == 3) { $aModuleInfo[static::MODULE_INFO_CONFIG]['module_file_path'] = $aModuleInfo[static::MODULE_INFO_PATH]; } } - public function GetAndCheckModuleInstallerClass($aModuleInfo) : ?string + public function GetAndCheckModuleInstallerClass($aModuleInfo): ?string { - if (! isset($aModuleInfo['installer'])){ + if (! isset($aModuleInfo['installer'])) { return null; } @@ -188,12 +180,10 @@ class ModuleFileReader { $this->ReadModuleFileInformationUnsafe($sModuleFilePath); } - if (!class_exists($sModuleInstallerClass)) - { + if (!class_exists($sModuleInstallerClass)) { throw new CoreException("Wrong installer class: '$sModuleInstallerClass' is not a PHP class - Module: ".$aModuleInfo['label']); } - if (!is_subclass_of($sModuleInstallerClass, 'ModuleInstallerAPI')) - { + if (!is_subclass_of($sModuleInstallerClass, 'ModuleInstallerAPI')) { throw new CoreException("Wrong installer class: '$sModuleInstallerClass' is not derived from 'ModuleInstallerAPI' - Module: ".$aModuleInfo['label']); } @@ -207,7 +197,7 @@ class ModuleFileReader { * @return array|null * @throws ModuleFileReaderException */ - private function GetModuleInformationFromAddModuleCall(string $sModuleFilePath, \PhpParser\Node\Stmt\Expression $oExpression) : ?array + private function GetModuleInformationFromAddModuleCall(string $sModuleFilePath, \PhpParser\Node\Stmt\Expression $oExpression): ?array { /** @var Assign $oAssignation */ $oAssignation = $oExpression->expr; @@ -232,30 +222,30 @@ class ModuleFileReader { $oModuleId = $aArgs[1]; if (false === ($oModuleId instanceof Arg)) { - throw new ModuleFileReaderException("2nd parameter to SetupWebPage::AddModule call issue: " . get_class($oModuleId), 0, null, $sModuleFilePath); + throw new ModuleFileReaderException("2nd parameter to SetupWebPage::AddModule call issue: ".get_class($oModuleId), 0, null, $sModuleFilePath); } /** @var Arg $oModuleId */ if (false === ($oModuleId->value instanceof String_)) { - throw new ModuleFileReaderException("2nd parameter to SetupWebPage::AddModule not a string: " . get_class($oModuleId->value), 0, null, $sModuleFilePath); + throw new ModuleFileReaderException("2nd parameter to SetupWebPage::AddModule not a string: ".get_class($oModuleId->value), 0, null, $sModuleFilePath); } $sModuleId = $this->oPhpExpressionEvaluator->EvaluateExpression($oModuleId->value); $oModuleConfigInfo = $aArgs[2]; if (false === ($oModuleConfigInfo instanceof Arg)) { - throw new ModuleFileReaderException("3rd parameter to SetupWebPage::AddModule call issue: " . get_class($oModuleConfigInfo), 0, null, $sModuleFilePath); + throw new ModuleFileReaderException("3rd parameter to SetupWebPage::AddModule call issue: ".get_class($oModuleConfigInfo), 0, null, $sModuleFilePath); } /** @var Arg $oModuleConfigInfo */ if (false === ($oModuleConfigInfo->value instanceof Array_)) { - throw new ModuleFileReaderException("3rd parameter to SetupWebPage::AddModule not an array: " . get_class($oModuleConfigInfo->value), 0, null, $sModuleFilePath); + throw new ModuleFileReaderException("3rd parameter to SetupWebPage::AddModule not an array: ".get_class($oModuleConfigInfo->value), 0, null, $sModuleFilePath); } $aModuleConfig = $this->oPhpExpressionEvaluator->EvaluateExpression($oModuleConfigInfo->value); - if (! is_array($aModuleConfig)){ - throw new ModuleFileReaderException("3rd parameter to SetupWebPage::AddModule not an array: " . get_class($oModuleConfigInfo->value), 0, null, $sModuleFilePath); + if (! is_array($aModuleConfig)) { + throw new ModuleFileReaderException("3rd parameter to SetupWebPage::AddModule not an array: ".get_class($oModuleConfigInfo->value), 0, null, $sModuleFilePath); } return [ @@ -272,7 +262,7 @@ class ModuleFileReader { * @return array|null * @throws ModuleFileReaderException */ - private function GetModuleInformationFromIf(string $sModuleFilePath, \PhpParser\Node\Stmt\If_ $oNode) : ?array + private function GetModuleInformationFromIf(string $sModuleFilePath, \PhpParser\Node\Stmt\If_ $oNode): ?array { $bCondition = $this->oPhpExpressionEvaluator->EvaluateExpression($oNode->cond); if ($bCondition) { @@ -305,7 +295,7 @@ class ModuleFileReader { return null; } - private function GetModuleConfigurationFromStatement(string $sModuleFilePath, array $aStmts) : ?array + private function GetModuleConfigurationFromStatement(string $sModuleFilePath, array $aStmts): ?array { foreach ($aStmts as $oSubNode) { if ($oSubNode instanceof Expression) { diff --git a/setup/modulediscovery/ModuleFileReaderException.php b/setup/modulediscovery/ModuleFileReaderException.php index 44a94279d..64fef5e7f 100644 --- a/setup/modulediscovery/ModuleFileReaderException.php +++ b/setup/modulediscovery/ModuleFileReaderException.php @@ -1,6 +1,7 @@ - /** * Persistent class ModuleInstallation to record the installed modules * Log of module installations @@ -29,33 +29,33 @@ class ModuleInstallation extends DBObject { public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "core,view_in_gui", "key_type" => "autoincrement", - 'name_attcode' => array('name', 'version'), + 'name_attcode' => ['name', 'version'], "state_attcode" => "", - "reconc_keys" => array(), + "reconc_keys" => [], "db_table" => "priv_module_install", "db_key_field" => "id", "db_finalclass_field" => "", - 'order_by_default' => array('installed' => false), - ); + 'order_by_default' => ['installed' => false], + ]; 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("version", array("allowed_values" => null, "sql" => "version", "default_value" => null, "is_null_allowed" => true, "depends_on" => array()))); - MetaModel::Init_AddAttribute(new AttributeDateTime("installed", array("allowed_values" => null, "sql" => "installed", "default_value" => null, "is_null_allowed" => true, "depends_on" => array()))); - MetaModel::Init_AddAttribute(new AttributeText("comment", array("allowed_values" => null, "sql" => "comment", "default_value" => null, "is_null_allowed" => true, "depends_on" => array()))); - MetaModel::Init_AddAttribute(new AttributeExternalKey("parent_id", array("targetclass" => "ModuleInstallation", "jointype" => "", "allowed_values" => null, "sql" => "parent_id", "is_null_allowed" => true, "on_target_delete" => DEL_MANUAL, "depends_on" => array()))); - MetaModel::Init_AddAttribute(new AttributeEnum("uninstallable", array("allowed_values"=>new ValueSetEnum('yes,no,maybe'), "sql"=>"uninstallable", "default_value"=>'yes', "is_null_allowed"=>false, "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("version", ["allowed_values" => null, "sql" => "version", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeDateTime("installed", ["allowed_values" => null, "sql" => "installed", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeText("comment", ["allowed_values" => null, "sql" => "comment", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeExternalKey("parent_id", ["targetclass" => "ModuleInstallation", "jointype" => "", "allowed_values" => null, "sql" => "parent_id", "is_null_allowed" => true, "on_target_delete" => DEL_MANUAL, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeEnum("uninstallable", ["allowed_values" => new ValueSetEnum('yes,no,maybe'), "sql" => "uninstallable", "default_value" => 'yes', "is_null_allowed" => false, "depends_on" => []])); // Display lists - MetaModel::Init_SetZListItems('details', array('name', 'version', 'installed', 'comment', 'parent_id')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('installed', 'comment')); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('details', ['name', 'version', 'installed', 'comment', 'parent_id']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['installed', 'comment']); // 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 } } @@ -70,32 +70,29 @@ class ExtensionInstallation extends cmdbAbstractObject { public static function Init() { - $aParams = array - ( + $aParams = + [ "category" => "core,view_in_gui", "key_type" => "autoincrement", "name_attcode" => "", "state_attcode" => "", - "reconc_keys" => array(), + "reconc_keys" => [], "db_table" => "priv_extension_install", "db_key_field" => "id", "db_finalclass_field" => "", - ); + ]; MetaModel::Init_Params($aParams); //MetaModel::Init_InheritAttributes(); - MetaModel::Init_AddAttribute(new AttributeString("code", array("allowed_values"=>null, "sql"=>"code", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeString("label", array("allowed_values"=>null, "sql"=>"label", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeString("version", array("allowed_values"=>null, "sql"=>"version", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeString("source", array("allowed_values"=>null, "sql"=>"source", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeEnum("uninstallable", array("allowed_values"=>new ValueSetEnum('yes,no,maybe'), "sql"=>"uninstallable", "default_value"=>'yes', "is_null_allowed"=>false, "depends_on"=>array()))); - MetaModel::Init_AddAttribute(new AttributeDateTime("installed", array("allowed_values"=>null, "sql"=>"installed", "default_value"=>'NOW()', "is_null_allowed"=>false, "depends_on"=>array()))); - - + MetaModel::Init_AddAttribute(new AttributeString("code", ["allowed_values" => null, "sql" => "code", "default_value" => null, "is_null_allowed" => false, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeString("label", ["allowed_values" => null, "sql" => "label", "default_value" => null, "is_null_allowed" => false, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeString("version", ["allowed_values" => null, "sql" => "version", "default_value" => null, "is_null_allowed" => false, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeString("source", ["allowed_values" => null, "sql" => "source", "default_value" => null, "is_null_allowed" => false, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeEnum("uninstallable", ["allowed_values" => new ValueSetEnum('yes,no,maybe'), "sql" => "uninstallable", "default_value" => 'yes', "is_null_allowed" => false, "depends_on" => []])); + MetaModel::Init_AddAttribute(new AttributeDateTime("installed", ["allowed_values" => null, "sql" => "installed", "default_value" => 'NOW()', "is_null_allowed" => false, "depends_on" => []])); + // Display lists - MetaModel::Init_SetZListItems('details', array('code', 'label', 'version', 'installed', 'source')); // Attributes to be displayed for the complete details - MetaModel::Init_SetZListItems('list', array('code', 'label', 'version', 'installed', 'source')); // Attributes to be displayed for a list - MetaModel::Init_SetZListItems('standard_search', array('code', 'label', 'version', 'installed', 'source')); // Attributes to be displayed in the search form + MetaModel::Init_SetZListItems('details', ['code', 'label', 'version', 'installed', 'source']); // Attributes to be displayed for the complete details + MetaModel::Init_SetZListItems('list', ['code', 'label', 'version', 'installed', 'source']); // Attributes to be displayed for a list + MetaModel::Init_SetZListItems('standard_search', ['code', 'label', 'version', 'installed', 'source']); // Attributes to be displayed in the search form } } - - diff --git a/setup/moduleinstaller.class.inc.php b/setup/moduleinstaller.class.inc.php index 6266960d5..0815fd4ba 100644 --- a/setup/moduleinstaller.class.inc.php +++ b/setup/moduleinstaller.class.inc.php @@ -242,8 +242,7 @@ abstract class ModuleInstallerAPI } // Simple rename - if ($sOrigTable === $sDstTable && !$bDstTableFieldExists) - { + if ($sOrigTable === $sDstTable && !$bDstTableFieldExists) { $sFieldSpec = CMDBSource::GetFieldSpec($sOrigTable, $sOrigColumn); $sQueryRename = /** @lang MariaDB */ "ALTER TABLE `{$sOrigTable}` CHANGE `{$sOrigColumn}` `{$sDstColumn}` {$sFieldSpec};"; CMDBSource::Query($sQueryRename); diff --git a/setup/setuputils.class.inc.php b/setup/setuputils.class.inc.php index 5fe6c345d..bbcadf553 100644 --- a/setup/setuputils.class.inc.php +++ b/setup/setuputils.class.inc.php @@ -1,9 +1,10 @@ iSeverity = $iSeverity; $this->sLabel = $sLabel; $this->sDescription = $sDescription; @@ -46,7 +49,8 @@ class CheckResult { * @return string * @since 3.0.0 N°2214 */ - public function __toString(): string { + public function __toString(): string + { $sPrintDesc = (empty($this->sDescription)) ? '' : " ({$this->sDescription})"; return "{$this->sLabel}$sPrintDesc"; @@ -60,8 +64,10 @@ class CheckResult { * * @since 3.0.0 N°2214 */ - public static function FilterCheckResultArray(array $aResults, array $aCheckResultSeverities): array { - return array_filter($aResults, + public static function FilterCheckResultArray(array $aResults, array $aCheckResultSeverities): array + { + return array_filter( + $aResults, static function ($v) use ($aCheckResultSeverities) { if (in_array($v->iSeverity, $aCheckResultSeverities, true)) { return $v; @@ -69,7 +75,8 @@ class CheckResult { return false; }, - ARRAY_FILTER_USE_BOTH); + ARRAY_FILTER_USE_BOTH + ); } /** @@ -80,7 +87,8 @@ class CheckResult { * * @since 3.0.0 N°2214 */ - public static function FromObjectsToStrings(array $aResults): array { + public static function FromObjectsToStrings(array $aResults): array + { return array_map(static function ($value) { return $value->__toString(); }, $aResults); @@ -96,18 +104,18 @@ class CheckResult { class SetupUtils { // -- Minimum versions (requirements : forbids installation if not met) - const PHP_MIN_VERSION = '8.1.0'; - const MYSQL_MIN_VERSION = '5.7.0'; // 5.6 is no longer supported - const MYSQL_NOT_VALIDATED_VERSION = ''; // MySQL 8 is now OK (N°2010 in 2.7.0) but has no query cache so mind the perf on large volumes ! + public const PHP_MIN_VERSION = '8.1.0'; + public const MYSQL_MIN_VERSION = '5.7.0'; // 5.6 is no longer supported + public const MYSQL_NOT_VALIDATED_VERSION = ''; // MySQL 8 is now OK (N°2010 in 2.7.0) but has no query cache so mind the perf on large volumes ! // -- versions that will be the minimum in next iTop major release (warning if not met) - const PHP_NEXT_MIN_VERSION = ''; // No new PHP requirement for next iTop version yet - const MYSQL_NEXT_MIN_VERSION = ''; // No new MySQL requirement for next iTop version yet + public const PHP_NEXT_MIN_VERSION = ''; // No new PHP requirement for next iTop version yet + public const MYSQL_NEXT_MIN_VERSION = ''; // No new MySQL requirement for next iTop version yet // -- First recent version that is not yet validated by Combodo (warning) - const PHP_NOT_VALIDATED_VERSION = '8.4.0'; + public const PHP_NOT_VALIDATED_VERSION = '8.4.0'; - const MIN_MEMORY_LIMIT = '32M'; - const SUHOSIN_GET_MAX_VALUE_LENGTH = 2048; + public const MIN_MEMORY_LIMIT = '32M'; + public const SUHOSIN_GET_MAX_VALUE_LENGTH = 2048; /** * Check configuration parameters, for example : @@ -135,8 +143,9 @@ class SetupUtils * @since 3.0.0 N°2214 disable some checks when in CLI mode * @since 3.0.0 N°2214 replace SetupLog::Ok calls by CheckResult::TRACE */ - public static function CheckPhpAndExtensions() { - $aResult = array(); + public static function CheckPhpAndExtensions() + { + $aResult = []; // For log file(s) if (!is_dir(APPROOT.'log')) { @@ -167,83 +176,61 @@ class SetupUtils asort($aMandatoryExtensions); // Sort the list to look clean ! ksort($aOptionalExtensions); // Sort the list to look clean ! - $aExtensionsOk = array(); - $aMissingExtensions = array(); - $aMissingExtensionsLinks = array(); + $aExtensionsOk = []; + $aMissingExtensions = []; + $aMissingExtensionsLinks = []; // First check the mandatory extensions - foreach($aMandatoryExtensions as $sExtension) - { - if (extension_loaded($sExtension)) - { + foreach ($aMandatoryExtensions as $sExtension) { + if (extension_loaded($sExtension)) { $aExtensionsOk[] = $sExtension; - } - else - { + } else { $aMissingExtensions[] = $sExtension; $aMissingExtensionsLinks[] = "$sExtension"; } } - if (count($aExtensionsOk) > 0) - { + if (count($aExtensionsOk) > 0) { $aResult[] = new CheckResult(CheckResult::INFO, "Required PHP extension(s): ".implode(', ', $aExtensionsOk)."."); } - if (count($aMissingExtensions) > 0) - { + if (count($aMissingExtensions) > 0) { $aResult[] = new CheckResult(CheckResult::ERROR, "Missing PHP extension(s): ".implode(', ', $aMissingExtensionsLinks)."."); } // Next check the optional extensions - $aExtensionsOk = array(); - $aMissingExtensions = array(); - foreach($aOptionalExtensions as $sExtension => $sMessage) - { + $aExtensionsOk = []; + $aMissingExtensions = []; + foreach ($aOptionalExtensions as $sExtension => $sMessage) { //if sMessage is an array, extensions in it are conditional between them - if (is_array($sMessage)) - { + if (is_array($sMessage)) { $bIsAtLeastOneLoaded = false; $sConditionalMissingMessage = ''; - foreach($sMessage as $sConditionalExtension => $sConditionalMessage) - { - if (extension_loaded($sConditionalExtension)) - { + foreach ($sMessage as $sConditionalExtension => $sConditionalMessage) { + if (extension_loaded($sConditionalExtension)) { $bIsAtLeastOneLoaded = true; $aExtensionsOk[] = $sConditionalExtension; - } - else - { + } else { $sConditionalMissingMessage = $sConditionalMessage; } } - if(!$bIsAtLeastOneLoaded) - { + if (!$bIsAtLeastOneLoaded) { $aMissingExtensions[$sExtension] = $sConditionalMissingMessage; } - } - else - { - if (extension_loaded($sExtension)) - { + } else { + if (extension_loaded($sExtension)) { $aExtensionsOk[] = $sExtension; - } - else - { + } else { $aMissingExtensions[$sExtension] = $sMessage; } } } - if (count($aExtensionsOk) > 0) - { + if (count($aExtensionsOk) > 0) { $aResult[] = new CheckResult(CheckResult::INFO, "Optional PHP extension(s): ".implode(', ', $aExtensionsOk)."."); } - if (count($aMissingExtensions) > 0) - { - foreach($aMissingExtensions as $sExtension => $sMessage) - { + if (count($aMissingExtensions) > 0) { + foreach ($aMissingExtensions as $sExtension => $sMessage) { $aResult[] = new CheckResult(CheckResult::WARNING, "Missing optional PHP extension: $sExtension. ".$sMessage); } } // Check some ini settings here - if (function_exists('php_ini_loaded_file')) // PHP >= 5.2.4 - { + if (function_exists('php_ini_loaded_file')) { // PHP >= 5.2.4 $sPhpIniFile = php_ini_loaded_file(); // Other included/scanned files if ($sFileList = php_ini_scanned_files()) { @@ -259,45 +246,57 @@ class SetupUtils } if (!utils::IsModeCLI() && !ini_get('file_uploads')) { - $aResult[] = new CheckResult(CheckResult::ERROR, - "Files upload is not allowed on this server (file_uploads = ".ini_get('file_uploads').")."); + $aResult[] = new CheckResult( + CheckResult::ERROR, + "Files upload is not allowed on this server (file_uploads = ".ini_get('file_uploads').")." + ); } if (!utils::IsModeCLI()) { $sUploadTmpDir = self::GetUploadTmpDir(); if (empty($sUploadTmpDir)) { $sUploadTmpDir = '/tmp'; - $aResult[] = new CheckResult(CheckResult::WARNING, - "Temporary directory for files upload is not defined (upload_tmp_dir), assuming that $sUploadTmpDir is used."); + $aResult[] = new CheckResult( + CheckResult::WARNING, + "Temporary directory for files upload is not defined (upload_tmp_dir), assuming that $sUploadTmpDir is used." + ); } // check that the upload directory is indeed writable from PHP if (!empty($sUploadTmpDir)) { if (!file_exists($sUploadTmpDir)) { - $aResult[] = new CheckResult(CheckResult::ERROR, - "Temporary directory for files upload ($sUploadTmpDir) does not exist or cannot be read by PHP."); - } - else { + $aResult[] = new CheckResult( + CheckResult::ERROR, + "Temporary directory for files upload ($sUploadTmpDir) does not exist or cannot be read by PHP." + ); + } else { if (!is_writable($sUploadTmpDir)) { - $aResult[] = new CheckResult(CheckResult::ERROR, - "Temporary directory for files upload ($sUploadTmpDir) is not writable."); - } - else { - $aResult[] = new CheckResult(CheckResult::TRACE, - "Info - Temporary directory for files upload ($sUploadTmpDir) is writable."); + $aResult[] = new CheckResult( + CheckResult::ERROR, + "Temporary directory for files upload ($sUploadTmpDir) is not writable." + ); + } else { + $aResult[] = new CheckResult( + CheckResult::TRACE, + "Info - Temporary directory for files upload ($sUploadTmpDir) is writable." + ); } } } } if (!utils::IsModeCLI() && !ini_get('upload_max_filesize')) { - $aResult[] = new CheckResult(CheckResult::ERROR, - "File upload is not allowed on this server (upload_max_filesize = ".ini_get('upload_max_filesize').")."); + $aResult[] = new CheckResult( + CheckResult::ERROR, + "File upload is not allowed on this server (upload_max_filesize = ".ini_get('upload_max_filesize').")." + ); } $iMaxFileUploads = ini_get('max_file_uploads'); if (!utils::IsModeCLI() && !empty($iMaxFileUploads) && ($iMaxFileUploads < 1)) { - $aResult[] = new CheckResult(CheckResult::ERROR, - "File upload is not allowed on this server (max_file_uploads = ".ini_get('max_file_uploads').")."); + $aResult[] = new CheckResult( + CheckResult::ERROR, + "File upload is not allowed on this server (max_file_uploads = ".ini_get('max_file_uploads').")." + ); } if (!utils::IsModeCLI()) { @@ -305,8 +304,10 @@ class SetupUtils $iMaxPostSize = utils::ConvertToBytes(ini_get('post_max_size')); if ($iMaxPostSize <= $iMaxUploadSize) { - $aResult[] = new CheckResult(CheckResult::WARNING, - "post_max_size (".ini_get('post_max_size').") in php.ini should be strictly greater than upload_max_filesize (".ini_get('upload_max_filesize').") otherwise you cannot upload files of the maximum size."); + $aResult[] = new CheckResult( + CheckResult::WARNING, + "post_max_size (".ini_get('post_max_size').") in php.ini should be strictly greater than upload_max_filesize (".ini_get('upload_max_filesize').") otherwise you cannot upload files of the maximum size." + ); } $aResult[] = new CheckResult(CheckResult::TRACE, "Info - upload_max_filesize: ".ini_get('upload_max_filesize')); @@ -334,30 +335,28 @@ class SetupUtils } // Special case for APC - if (extension_loaded('apc')) - { + if (extension_loaded('apc')) { $sAPCVersion = phpversion('apc'); $aResult[] = new CheckResult(CheckResult::INFO, "APC detected (version $sAPCVersion). The APC cache will be used to speed-up ".ITOP_APPLICATION."."); } // Special case Suhosin extension - if (extension_loaded('suhosin')) - { + if (extension_loaded('suhosin')) { $sSuhosinVersion = phpversion('suhosin'); $aOk[] = "Suhosin extension detected (version $sSuhosinVersion)."; $iGetMaxValueLength = ini_get('suhosin.get.max_value_length'); if ($iGetMaxValueLength < self::SUHOSIN_GET_MAX_VALUE_LENGTH) { - $aResult[] = new CheckResult(CheckResult::WARNING, - "suhosin.get.max_value_length ($iGetMaxValueLength) is too small, the minimum value recommended to run the application is ".self::SUHOSIN_GET_MAX_VALUE_LENGTH."."); - } - else { + $aResult[] = new CheckResult( + CheckResult::WARNING, + "suhosin.get.max_value_length ($iGetMaxValueLength) is too small, the minimum value recommended to run the application is ".self::SUHOSIN_GET_MAX_VALUE_LENGTH."." + ); + } else { $aResult[] = new CheckResult(CheckResult::TRACE, "Info - suhosin.get.max_value_length = $iGetMaxValueLength, ok."); } } - if (function_exists('php_ini_loaded_file')) // PHP >= 5.2.4 - { + if (function_exists('php_ini_loaded_file')) { // PHP >= 5.2.4 $sPhpIniFile = php_ini_loaded_file(); // Other included/scanned files if ($sFileList = php_ini_scanned_files()) { @@ -387,22 +386,27 @@ class SetupUtils $sSavePath = substr($sSavePath, $iPos + 1); } if (!is_writable($sSavePath)) { - $aResult[] = new CheckResult(CheckResult::ERROR, - "The value for session.save_path ($sSavePath) is not writable for the web server. Make sure that PHP can actually save session variables. (Refer to the PHP documentation: http://php.net/manual/en/session.configuration.php#ini.session.save-path)"); - } - else { - $aResult[] = new CheckResult(CheckResult::INFO, - "The value for session.save_path ($sSavePath) is writable for the web server."); + $aResult[] = new CheckResult( + CheckResult::ERROR, + "The value for session.save_path ($sSavePath) is not writable for the web server. Make sure that PHP can actually save session variables. (Refer to the PHP documentation: http://php.net/manual/en/session.configuration.php#ini.session.save-path)" + ); + } else { + $aResult[] = new CheckResult( + CheckResult::INFO, + "The value for session.save_path ($sSavePath) is writable for the web server." + ); } + } else { + $aResult[] = new CheckResult( + CheckResult::WARNING, + "Empty path for session.save_path. Make sure that PHP can actually save session variables. (Refer to the PHP documentation: http://php.net/manual/en/session.configuration.php#ini.session.save-path)" + ); } - else { - $aResult[] = new CheckResult(CheckResult::WARNING, - "Empty path for session.save_path. Make sure that PHP can actually save session variables. (Refer to the PHP documentation: http://php.net/manual/en/session.configuration.php#ini.session.save-path)"); - } - } - else { - $aResult[] = new CheckResult(CheckResult::INFO, - "session.save_handler is: '".ini_get('session.save_handler')."' (different from 'files')."); + } else { + $aResult[] = new CheckResult( + CheckResult::INFO, + "session.save_handler is: '".ini_get('session.save_handler')."' (different from 'files')." + ); } } @@ -451,38 +455,43 @@ class SetupUtils * * @since 3.0.0 N°2214 replace SetupLog::Log calls by CheckResult::TRACE */ - private static function CheckPhpVersion(array &$aResult) { + private static function CheckPhpVersion(array &$aResult) + { $aResult[] = new CheckResult(CheckResult::TRACE, 'Info - CheckPHPVersion'); $sPhpVersion = phpversion(); if (version_compare($sPhpVersion, self::PHP_MIN_VERSION, '>=')) { - $aResult[] = new CheckResult(CheckResult::INFO, - "The current PHP Version (".$sPhpVersion.") is greater than the minimum version required to run ".ITOP_APPLICATION.", which is (".self::PHP_MIN_VERSION.")"); - + $aResult[] = new CheckResult( + CheckResult::INFO, + "The current PHP Version (".$sPhpVersion.") is greater than the minimum version required to run ".ITOP_APPLICATION.", which is (".self::PHP_MIN_VERSION.")" + ); $sPhpNextMinVersion = self::PHP_NEXT_MIN_VERSION; // mandatory before PHP 5.5 (arbitrary expressions), keeping compat because we're in the setup ! if (!empty($sPhpNextMinVersion)) { if (version_compare($sPhpVersion, self::PHP_NEXT_MIN_VERSION, '>=')) { - $aResult[] = new CheckResult(CheckResult::INFO, - "The current PHP Version (".$sPhpVersion.") is greater than the minimum version required to run next ".ITOP_APPLICATION." major release, which is (".self::PHP_NEXT_MIN_VERSION.")"); - } - else - { - $aResult[] = new CheckResult(CheckResult::WARNING, - "The current PHP Version (".$sPhpVersion.") is lower than the minimum version required to run next ".ITOP_APPLICATION." major release, which is (".self::PHP_NEXT_MIN_VERSION.")"); + $aResult[] = new CheckResult( + CheckResult::INFO, + "The current PHP Version (".$sPhpVersion.") is greater than the minimum version required to run next ".ITOP_APPLICATION." major release, which is (".self::PHP_NEXT_MIN_VERSION.")" + ); + } else { + $aResult[] = new CheckResult( + CheckResult::WARNING, + "The current PHP Version (".$sPhpVersion.") is lower than the minimum version required to run next ".ITOP_APPLICATION." major release, which is (".self::PHP_NEXT_MIN_VERSION.")" + ); } } - if (version_compare($sPhpVersion, self::PHP_NOT_VALIDATED_VERSION, '>=')) - { - $aResult[] = new CheckResult(CheckResult::WARNING, - "The current PHP Version (".$sPhpVersion.") is not yet validated by Combodo. You may experience some incompatibility issues."); + if (version_compare($sPhpVersion, self::PHP_NOT_VALIDATED_VERSION, '>=')) { + $aResult[] = new CheckResult( + CheckResult::WARNING, + "The current PHP Version (".$sPhpVersion.") is not yet validated by Combodo. You may experience some incompatibility issues." + ); } - } - else - { - $aResult[] = new CheckResult(CheckResult::ERROR, - "Error: The current PHP Version (".$sPhpVersion.") is lower than the minimum version required to run ".ITOP_APPLICATION.", which is (".self::PHP_MIN_VERSION.")"); + } else { + $aResult[] = new CheckResult( + CheckResult::ERROR, + "Error: The current PHP Version (".$sPhpVersion.") is lower than the minimum version required to run ".ITOP_APPLICATION.", which is (".self::PHP_MIN_VERSION.")" + ); } } @@ -497,10 +506,11 @@ class SetupUtils * * @since 3.0.0 N°2214 replace SetupLog::Log calls by CheckResult::TRACE */ - public static function CheckSelectedModules($sSourceDir, $sExtensionDir, $aSelectedModules) { - $aResult = array(); + public static function CheckSelectedModules($sSourceDir, $sExtensionDir, $aSelectedModules) + { + $aResult = []; - $aDirsToScan = array(APPROOT.$sSourceDir); + $aDirsToScan = [APPROOT.$sSourceDir]; $sExtensionsPath = APPROOT.$sExtensionDir; if (is_dir($sExtensionsPath)) { // if the extensions dir exists, scan it for additional modules as well @@ -525,8 +535,9 @@ class SetupUtils * * @since 3.0.0 N°2214 replace SetupLog::Log calls by CheckResult::TRACE */ - public static function CheckBackupPrerequisites($sDBBackupPath, $sMySQLBinDir = null) { - $aResult = array(); + public static function CheckBackupPrerequisites($sDBBackupPath, $sMySQLBinDir = null) + { + $aResult = []; $aResult[] = new CheckResult(CheckResult::TRACE, 'Info - CheckBackupPrerequisites'); // zip extension @@ -558,27 +569,28 @@ class SetupUtils $aResult[] = new CheckResult(CheckResult::ERROR, $e->getMessage()); return $aResult; } - if (!empty($sMySQLBinDir)) { - $aResult[] = new CheckResult(CheckResult::TRACE, 'Info - Found mysql_bindir: '.$sMySQLBinDir); - } + if (!empty($sMySQLBinDir)) { + $aResult[] = new CheckResult(CheckResult::TRACE, 'Info - Found mysql_bindir: '.$sMySQLBinDir); + } $sCommand = "$sMySQLDump -V 2>&1"; - $aOutput = array(); + $aOutput = []; $iRetCode = 0; exec($sCommand, $aOutput, $iRetCode); - if ($iRetCode == 0) - { + if ($iRetCode == 0) { $aResult[] = new CheckResult(CheckResult::INFO, "mysqldump is present: Ok."); - } - elseif ($iRetCode == 1) { + } elseif ($iRetCode == 1) { // Unfortunately $aOutput is not really usable since we don't know its encoding (character set) - $aResult[] = new CheckResult(CheckResult::ERROR, - "mysqldump could not be found. Please make sure it is installed and in the path."); - } - else { + $aResult[] = new CheckResult( + CheckResult::ERROR, + "mysqldump could not be found. Please make sure it is installed and in the path." + ); + } else { // Unfortunately $aOutput is not really usable since we don't know its encoding (character set) - $aResult[] = new CheckResult(CheckResult::ERROR, - "mysqldump could not be executed (retcode=$iRetCode): Please make sure it is installed and ".(empty($sMySQLBinDir) ? "in the path" : "located at : $sMySQLDump")); + $aResult[] = new CheckResult( + CheckResult::ERROR, + "mysqldump could not be executed (retcode=$iRetCode): Please make sure it is installed and ".(empty($sMySQLBinDir) ? "in the path" : "located at : $sMySQLDump") + ); } foreach ($aOutput as $sLine) { $aResult[] = new CheckResult(CheckResult::TRACE, 'Info - mysqldump -V said: '.$sLine); @@ -611,7 +623,8 @@ class SetupUtils * * @since 3.0.0 N°2214 replace SetupLog::Log calls by CheckResult::TRACE */ - public static function CheckGraphviz($sGraphvizPath) { + public static function CheckGraphviz($sGraphvizPath) + { $aResult = []; $aResult[] = new CheckResult(CheckResult::TRACE, 'Info - CheckGraphviz'); @@ -620,8 +633,10 @@ class SetupUtils $aDisabled = explode(', ', ini_get('disable_functions')); $aResult[] = new CheckResult(CheckResult::TRACE, 'Info - PHP functions disabled: '.implode(', ', $aDisabled)); if (in_array('exec', $aDisabled)) { - $aResult[] = new CheckResult(CheckResult::ERROR, - self::GetStringForJsonEncode('The PHP exec() function has been disabled on this server', 'Could not find Graphviz\' dot')); + $aResult[] = new CheckResult( + CheckResult::ERROR, + self::GetStringForJsonEncode('The PHP exec() function has been disabled on this server', 'Could not find Graphviz\' dot') + ); } // availability of dot / dot.exe @@ -632,34 +647,39 @@ class SetupUtils if (!is_file($sGraphvizPath) || !is_executable($sGraphvizPath)) { //N°3412 avoid shell injection $aResult = []; - $aResult[] = new CheckResult(CheckResult::WARNING, + $aResult[] = new CheckResult( + CheckResult::WARNING, self::GetStringForJsonEncode("$sGraphvizPath could not be executed: Please make sure it is installed and in the path", 'Graphviz could not be executed') ); return $aResult; } - if (!utils::IsWindowsEnvironment()){ + if (!utils::IsWindowsEnvironment()) { $sGraphvizPath = escapeshellcmd($sGraphvizPath); } } $sCommand = "\"$sGraphvizPath\" -V 2>&1"; - $aOutput = array(); + $aOutput = []; $iRetCode = 0; exec($sCommand, $aOutput, $iRetCode); if ($iRetCode == 0) { - $aResult[] = new CheckResult(CheckResult::INFO, - self::GetStringForJsonEncode("dot is present: ".$aOutput[0], 'Graphviz\' dot found')); + $aResult[] = new CheckResult( + CheckResult::INFO, + self::GetStringForJsonEncode("dot is present: ".$aOutput[0], 'Graphviz\' dot found') + ); } elseif ($iRetCode == 1) { - $aResult[] = new CheckResult(CheckResult::WARNING, + $aResult[] = new CheckResult( + CheckResult::WARNING, self::GetStringForJsonEncode( "dot could not be found: ".implode(' ', $aOutput)." - Please make sure it is installed and in the path.", 'Could not find Graphviz\' dot' ) ); } else { - $aResult[] = new CheckResult(CheckResult::WARNING, + $aResult[] = new CheckResult( + CheckResult::WARNING, self::GetStringForJsonEncode( "dot could not be executed (retcode=$iRetCode): Please make sure it is installed and in the path", 'Could not find Graphviz\' dot' @@ -684,7 +704,8 @@ class SetupUtils * * @since 3.0.0 */ - private static function GetStringForJsonEncode(string $sValue, string $sFallbackValue): string { + private static function GetStringForJsonEncode(string $sValue, string $sFallbackValue): string + { return (json_encode($sValue) !== false) ? $sValue : $sFallbackValue; @@ -697,7 +718,8 @@ class SetupUtils * @return string Path to the system's temp directory * @uses \sys_get_temp_dir() */ - public static function GetTmpDir() { + public static function GetTmpDir() + { return realpath(sys_get_temp_dir()); } @@ -706,7 +728,8 @@ class SetupUtils * * @return string Path to the temp directory used for uploading files */ - public static function GetUploadTmpDir() { + public static function GetUploadTmpDir() + { $sPath = ini_get('upload_tmp_dir'); if (empty($sPath)) { $sPath = self::GetTmpDir(); @@ -722,8 +745,7 @@ class SetupUtils */ public static function rrmdir($dir) { - if ((strlen(trim($dir)) == 0) || ($dir == '/') || ($dir == '\\')) - { + if ((strlen(trim($dir)) == 0) || ($dir == '/') || ($dir == '\\')) { throw new Exception("Attempting to delete directory: '$dir'"); } self::tidydir($dir); @@ -737,7 +759,8 @@ class SetupUtils * * @throws Exception */ - public static function tidydir(string $dir): void { + public static function tidydir(string $dir): void + { if ((strlen(trim($dir)) == 0) || ($dir == '/') || ($dir == '\\')) { throw new Exception("Attempting to delete directory: '$dir'"); } @@ -753,7 +776,7 @@ class SetupUtils } else { if (!unlink($dir.'/'.$file)) { SetupLog::Ok("Warning - FAILED to remove file '$dir/$file'"); - } else if (file_exists($dir.'/'.$file)) { + } elseif (file_exists($dir.'/'.$file)) { SetupLog::Ok("Warning - FAILED to remove file '$dir/.$file'"); } } @@ -769,13 +792,11 @@ class SetupUtils */ public static function builddir($dir) { - if (empty($dir)) - { + if (empty($dir)) { // avoid infinite loops :/ return; } - if (!is_dir($dir)) - { + if (!is_dir($dir)) { $parent = dirname($dir); self::builddir($parent); if (!mkdir($dir) && !is_dir($dir)) { @@ -816,49 +837,33 @@ class SetupUtils */ public static function copydir($sSource, $sDest, $bUseSymbolicLinks = false) { - if (is_dir($sSource)) - { - if (!is_dir($sDest)) - { + if (is_dir($sSource)) { + if (!is_dir($sDest)) { mkdir($sDest, 0777 /* Default */, true); } $aFiles = scandir($sSource); - if(sizeof($aFiles) > 0 ) - { - foreach($aFiles as $sFile) - { - if ($sFile == '.' || $sFile == '..' || $sFile == '.svn' || $sFile == '.git') - { + if (sizeof($aFiles) > 0) { + foreach ($aFiles as $sFile) { + if ($sFile == '.' || $sFile == '..' || $sFile == '.svn' || $sFile == '.git') { // Skip continue; } - if (is_dir($sSource.'/'.$sFile)) - { + if (is_dir($sSource.'/'.$sFile)) { // Recurse self::copydir($sSource.'/'.$sFile, $sDest.'/'.$sFile, $bUseSymbolicLinks); - } - else - { - if ($bUseSymbolicLinks) - { - if (function_exists('symlink')) - { - if (file_exists($sDest.'/'.$sFile)) - { + } else { + if ($bUseSymbolicLinks) { + if (function_exists('symlink')) { + if (file_exists($sDest.'/'.$sFile)) { unlink($sDest.'/'.$sFile); } symlink($sSource.'/'.$sFile, $sDest.'/'.$sFile); - } - else - { + } else { throw(new Exception("Error, cannot *copy* '$sSource/$sFile' to '$sDest/$sFile' using symbolic links, 'symlink' is not supported on this system.")); } - } - else - { - if (is_link($sDest.'/'.$sFile)) - { + } else { + if (is_link($sDest.'/'.$sFile)) { unlink($sDest.'/'.$sFile); } copy($sSource.'/'.$sFile, $sDest.'/'.$sFile); @@ -867,27 +872,17 @@ class SetupUtils } } return true; - } - elseif (is_file($sSource)) - { - if ($bUseSymbolicLinks) - { - if (function_exists('symlink')) - { + } elseif (is_file($sSource)) { + if ($bUseSymbolicLinks) { + if (function_exists('symlink')) { return symlink($sSource, $sDest); - } - else - { + } else { throw(new Exception("Error, cannot *copy* '$sSource' to '$sDest' using symbolic links, 'symlink' is not supported on this system.")); } - } - else - { + } else { return copy($sSource, $sDest); } - } - else - { + } else { return false; } } @@ -905,23 +900,18 @@ class SetupUtils */ public static function movedir($sSource, $sDest, $bRemoveSource = true) { - if (!is_dir($sSource)) - { + if (!is_dir($sSource)) { throw new Exception("movedir: the source directory '$sSource' is not a valid directory or cannot be read"); } - if (!is_dir($sDest)) - { + if (!is_dir($sDest)) { self::builddir($sDest); - } - else - { + } else { self::tidydir($sDest); } self::copydir($sSource, $sDest); self::tidydir($sSource); - if($bRemoveSource === true) - { + if ($bRemoveSource === true) { self::rmdir_safe($sSource); } } @@ -931,30 +921,26 @@ class SetupUtils $sSourceDir = ''; $sSourceEnvironment = ''; $sConfigFile = ''; - $aResult = array( + $aResult = [ 'found' => false, - ); + ]; - if (file_exists($sDir.'/config-itop.php')) - { + if (file_exists($sDir.'/config-itop.php')) { $sSourceDir = $sDir; $sSourceEnvironment = ''; $sConfigFile = $sDir.'/config-itop.php'; $aResult['found'] = true; - } - else if (file_exists($sDir.'/conf/production/config-itop.php')) - { + } elseif (file_exists($sDir.'/conf/production/config-itop.php')) { $sSourceDir = $sDir; $sSourceEnvironment = 'production'; $sConfigFile = $sDir.'/conf/production/config-itop.php'; $aResult['found'] = true; } - if ($aResult['found']) - { + if ($aResult['found']) { $oPrevConf = new Config($sConfigFile); - $aResult = array( + $aResult = [ 'found' => true, 'source_dir' => $sSourceDir, 'source_environment' => $sSourceEnvironment, @@ -968,7 +954,7 @@ class SetupUtils 'db_tls_ca' => $oPrevConf->Get('db_tls.ca'), 'graphviz_path' => $oPrevConf->Get('graphviz_path'), 'mysql_bindir' => $oPrevConf->GetModuleSetting('itop-backup', 'mysql_bindir', ''), - ); + ]; } return $aResult; @@ -982,28 +968,31 @@ class SetupUtils */ public static function CheckDiskSpace($sDir) { - while(($f = @disk_free_space($sDir)) == false) - { - if ($sDir == dirname($sDir)) break; - if ($sDir == '.') break; + while (($f = @disk_free_space($sDir)) == false) { + if ($sDir == dirname($sDir)) { + break; + } + if ($sDir == '.') { + break; + } $sDir = dirname($sDir); } return $f; } - /** - * @param float $fBytes size in raw bytes, for example 162594750464.0 - * @return string formatted string, for example "161.62 GB" - * - * @link https://en.wiktionary.org/wiki/byte byte and not Byte - * @link https://en.wikipedia.org/wiki/Kilobyte kB and not KB (IEC 80000-13) - * @link https://en.wiktionary.org/wiki/petabyte petabyte PB - * @link https://en.wiktionary.org/wiki/exabyte exabyte EB - */ + /** + * @param float $fBytes size in raw bytes, for example 162594750464.0 + * @return string formatted string, for example "161.62 GB" + * + * @link https://en.wiktionary.org/wiki/byte byte and not Byte + * @link https://en.wikipedia.org/wiki/Kilobyte kB and not KB (IEC 80000-13) + * @link https://en.wiktionary.org/wiki/petabyte petabyte PB + * @link https://en.wiktionary.org/wiki/exabyte exabyte EB + */ public static function HumanReadableSize($fBytes) { - $aSizes = array('bytes', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB'); + $aSizes = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB']; $index = 0; while (($fBytes > 1000) && ($index < count($aSizes))) { $index++; @@ -1031,7 +1020,15 @@ class SetupUtils * @param string $sNewDBName */ public static function DisplayDBParameters( - $oPage, $bIsItopInstall, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $bTlsEnabled, $sTlsCA, + $oPage, + $bIsItopInstall, + $sDBServer, + $sDBUser, + $sDBPwd, + $sDBName, + $sDBPrefix, + $bTlsEnabled, + $sTlsCA, $sNewDBName = '' ) { $sWikiVersion = utils::GetItopVersionWikiSyntax(); //eg : '2_7_0'; @@ -1084,7 +1081,8 @@ class SetupUtils $oPage->add(''); // Sub options toggle (TLS, prefix) - $oPage->add_script(<<<'JS' + $oPage->add_script( + <<<'JS' function toggleCollapsableOptions($tbody) { $tbody.children().not(":first-child").toggle(); updateCollapsableImage($tbody); @@ -1094,8 +1092,7 @@ function updateCollapsableImage($tbody) { } JS ); - if ($bTlsEnabled) - { + if ($bTlsEnabled) { $oPage->add_ready_script('toggleCollapsableOptions($("tbody#tls_options"));'); } $oPage->add_ready_script( @@ -1250,22 +1247,22 @@ EOF * Array of database names (as strings) or null if not allowed) */ public static function CheckDbServer( - $sDBServer, $sDBUser, $sDBPwd, $bTlsEnabled = false, $sTlsCA = null - ) - { - $aResult = array('checks' => array(), 'databases' => null); + $sDBServer, + $sDBUser, + $sDBPwd, + $bTlsEnabled = false, + $sTlsCA = null + ) { + $aResult = ['checks' => [], 'databases' => null]; - if ($bTlsEnabled) - { - if (!empty($sTlsCA) && !self::CheckFileExists($sTlsCA, $aResult, 'Can\'t open SSL CA file')) - { + if ($bTlsEnabled) { + if (!empty($sTlsCA) && !self::CheckFileExists($sTlsCA, $aResult, 'Can\'t open SSL CA file')) { return $aResult; } } - try - { - $oDBSource = new CMDBSource; + try { + $oDBSource = new CMDBSource(); $oDBSource->Init($sDBServer, $sDBUser, $sDBPwd, '', $bTlsEnabled, $sTlsCA); $aResult['checks'][] = new CheckResult(CheckResult::INFO, "Connection to '$sDBServer' as '$sDBUser' successful."); $aResult['checks'][] = new CheckResult(CheckResult::INFO, "Info - User privileges: ".($oDBSource->GetRawPrivileges())); @@ -1280,16 +1277,17 @@ EOF $sMaxAllowedPacketFriendly = utils::BytesToFriendlyFormat($iMaxAllowedPacket); $iMaxUploadSize = utils::ConvertToBytes(ini_get('upload_max_filesize')); $sMaxUploadSizeFriendly = utils::BytesToFriendlyFormat($iMaxUploadSize); - if ($iMaxAllowedPacket >= (500 + $iMaxUploadSize)) // Allow some space for the query + the file to upload - { + if ($iMaxAllowedPacket >= (500 + $iMaxUploadSize)) { // Allow some space for the query + the file to upload $aResult['checks'][] = new CheckResult(CheckResult::INFO, "MySQL server's max_allowed_packet ($sMaxAllowedPacketFriendly) is big enough compared to upload_max_filesize ($sMaxUploadSizeFriendly)."); - } else if ($iMaxAllowedPacket < $iMaxUploadSize) { + } elseif ($iMaxAllowedPacket < $iMaxUploadSize) { $sWikiVersion = utils::GetItopVersionWikiSyntax(); //eg : '2_7_0'; $sAttachmentsVarsWikiPageUrl = 'https://www.itophub.io/wiki/page?id='.$sWikiVersion .':install:php_and_mysql_configuration#attachments_upload'; - $aResult['checks'][] = new CheckResult(CheckResult::WARNING, - "MySQL server's max_allowed_packet ($sMaxAllowedPacketFriendly) is not big enough compared to upload_max_filesize ($sMaxUploadSizeFriendly), whereas it should has a greater value. Consider increasing its value of at least 500KB. See the documentation for details."); + $aResult['checks'][] = new CheckResult( + CheckResult::WARNING, + "MySQL server's max_allowed_packet ($sMaxAllowedPacketFriendly) is not big enough compared to upload_max_filesize ($sMaxUploadSizeFriendly), whereas it should has a greater value. Consider increasing its value of at least 500KB. See the documentation for details." + ); } $iMaxConnections = $oDBSource->GetServerVariable('max_connections'); @@ -1299,21 +1297,18 @@ EOF $aResult['checks'][] = new CheckResult(CheckResult::INFO, "MySQL server's max_connections is set to $iMaxConnections."); } - $iClusters = $oDBSource->GetClusterNb(); - if ($iClusters > 0) { - SetupLog::Warning('Warning - Using Galera will cause malfunctions and data corruptions. Combodo does not support this type of infrastructure.'); - $aResult['checks'][] = new CheckResult(CheckResult::WARNING, 'Using Galera will cause malfunctions and data corruptions. Combodo does not support this type of infrastructure.'); - } + $iClusters = $oDBSource->GetClusterNb(); + if ($iClusters > 0) { + SetupLog::Warning('Warning - Using Galera will cause malfunctions and data corruptions. Combodo does not support this type of infrastructure.'); + $aResult['checks'][] = new CheckResult(CheckResult::WARNING, 'Using Galera will cause malfunctions and data corruptions. Combodo does not support this type of infrastructure.'); + } try { $aResult['databases'] = $oDBSource->ListDB(); - } - catch (Exception $e) { + } catch (Exception $e) { $aResult['databases'] = null; } - } - catch(Exception $e) - { + } catch (Exception $e) { return false; } @@ -1332,8 +1327,7 @@ EOF */ private static function CheckFileExists($sPath, &$aResult, $sErrorMessage) { - if (!is_readable($sPath)) - { + if (!is_readable($sPath)) { $aResult['checks'][] = new CheckResult(CheckResult::ERROR, $sErrorMessage); return false; @@ -1358,39 +1352,42 @@ EOF && ($sDBVendor === CMDBSource::ENUM_DB_VENDOR_MYSQL) && version_compare($sDBVersion, self::MYSQL_NOT_VALIDATED_VERSION, '>=') ) { - $aResult['checks'][] = new CheckResult(CheckResult::ERROR, - "Error: Current MySQL version is $sDBVersion. iTop doesn't yet support MySQL ".self::MYSQL_NOT_VALIDATED_VERSION." and above."); + $aResult['checks'][] = new CheckResult( + CheckResult::ERROR, + "Error: Current MySQL version is $sDBVersion. iTop doesn't yet support MySQL ".self::MYSQL_NOT_VALIDATED_VERSION." and above." + ); return false; } $bRet = false; - if (version_compare($sDBVersion, self::MYSQL_MIN_VERSION, '>=')) - { - $aResult['checks'][] = new CheckResult(CheckResult::INFO, - "Current MySQL version ($sDBVersion), greater than minimum required version (".self::MYSQL_MIN_VERSION.")"); + if (version_compare($sDBVersion, self::MYSQL_MIN_VERSION, '>=')) { + $aResult['checks'][] = new CheckResult( + CheckResult::INFO, + "Current MySQL version ($sDBVersion), greater than minimum required version (".self::MYSQL_MIN_VERSION.")" + ); $sMySqlNextMinVersion = self::MYSQL_NEXT_MIN_VERSION; // mandatory before PHP 5.5 (arbitrary expressions), keeping compat because we're in the setup ! - if (!empty($sMySqlNextMinVersion)) - { - if (version_compare($sDBVersion, self::MYSQL_NEXT_MIN_VERSION, '>=')) - { - $aResult['checks'][] = new CheckResult(CheckResult::INFO, - "Current MySQL version ($sDBVersion), greater than minimum required version for next ".ITOP_APPLICATION." release (".self::MYSQL_NEXT_MIN_VERSION.")"); - } - else - { - $aResult['checks'][] = new CheckResult(CheckResult::WARNING, - "Warning : Current MySQL version is $sDBVersion, minimum required version for next ".ITOP_APPLICATION." release will be ".self::MYSQL_NEXT_MIN_VERSION); + if (!empty($sMySqlNextMinVersion)) { + if (version_compare($sDBVersion, self::MYSQL_NEXT_MIN_VERSION, '>=')) { + $aResult['checks'][] = new CheckResult( + CheckResult::INFO, + "Current MySQL version ($sDBVersion), greater than minimum required version for next ".ITOP_APPLICATION." release (".self::MYSQL_NEXT_MIN_VERSION.")" + ); + } else { + $aResult['checks'][] = new CheckResult( + CheckResult::WARNING, + "Warning : Current MySQL version is $sDBVersion, minimum required version for next ".ITOP_APPLICATION." release will be ".self::MYSQL_NEXT_MIN_VERSION + ); } } $bRet = true; - } - else - { - $aResult['checks'][] = new CheckResult(CheckResult::ERROR, - "Error: Current MySQL version is $sDBVersion, minimum required version is ".self::MYSQL_MIN_VERSION); + } else { + $aResult['checks'][] = new CheckResult( + CheckResult::ERROR, + "Error: Current MySQL version is $sDBVersion, minimum required version is ".self::MYSQL_MIN_VERSION + ); $bRet = false; } @@ -1408,10 +1405,13 @@ EOF * @throws \MySQLException */ public static function GetMySQLVersion( - $sDBServer, $sDBUser, $sDBPwd, $bTlsEnabled = false, $sTlsCa = null - ) - { - $oDBSource = new CMDBSource; + $sDBServer, + $sDBUser, + $sDBPwd, + $bTlsEnabled = false, + $sTlsCa = null + ) { + $oDBSource = new CMDBSource(); $oDBSource->Init($sDBServer, $sDBUser, $sDBPwd, '', $bTlsEnabled, $sTlsCa); $sDBVersion = $oDBSource->GetDBVersion(); @@ -1429,13 +1429,11 @@ EOF if ($bIsWindows && (preg_match('@([%!"])@', $sDBPwd) > 0)) { // Unsupported Password, warn the user $oPage->add_ready_script( -<<Error:On Windows, the backup won\'t work because database password contains %, ! or " character
'); JS ); - } - else - { + } else { $sTlsEnabled = (isset($aParameters['db_tls_enabled'])) ? $aParameters['db_tls_enabled'] : null; $sTlsCA = (isset($aParameters['db_tls_ca'])) ? $aParameters['db_tls_ca'] : null; @@ -1443,30 +1441,22 @@ JS $checks = SetupUtils::CheckDbServer($sDBServer, $sDBUser, $sDBPwd, $sTlsEnabled, $sTlsCA); - if ($checks === false) - { + if ($checks === false) { // Connection failed, disable the "Next" button $oPage->add_ready_script('$("#wiz_form").data("db_connection", "error");'); $oPage->add_ready_script( <<Error:No connection to the database
'); JS - ); - } - else - { - $aErrors = array(); - $aWarnings = array(); - foreach ($checks['checks'] as $oCheck) - { - if ($oCheck->iSeverity == CheckResult::ERROR) - { + ); + } else { + $aErrors = []; + $aWarnings = []; + foreach ($checks['checks'] as $oCheck) { + if ($oCheck->iSeverity == CheckResult::ERROR) { $aErrors[] = $oCheck->sLabel; - } - else - { - if ($oCheck->iSeverity == CheckResult::WARNING) - { + } else { + if ($oCheck->iSeverity == CheckResult::WARNING) { $aWarnings[] = $oCheck->sLabel; } } @@ -1581,7 +1571,7 @@ JS if (strpos($sSourceDir, APPROOT) !== false) { $sRelativeSourceDir = str_replace(APPROOT, '', $sSourceDir); - } else if (strpos($sSourceDir, $oWizard->GetParameter('previous_version_dir')) !== false) { + } elseif (strpos($sSourceDir, $oWizard->GetParameter('previous_version_dir')) !== false) { $sRelativeSourceDir = str_replace($oWizard->GetParameter('previous_version_dir'), '', $sSourceDir); } else { throw(new Exception('Internal error: AnalyzeInstallation: source_dir is neither under APPROOT nor under previous_installation_dir ???')); @@ -1590,7 +1580,7 @@ JS $aParamValues = $oWizard->GetParamForConfigArray(); $aParamValues['source_dir'] = $sRelativeSourceDir; $oConfig->UpdateFromParams($aParamValues, null); - $aDirsToScan = array($sSourceDir); + $aDirsToScan = [$sSourceDir]; if (is_dir(APPROOT.'extensions')) { $aDirsToScan[] = APPROOT.'extensions'; @@ -1599,18 +1589,15 @@ JS $aDirsToScan[] = $oWizard->GetParameter('copy_extensions_from'); } $sExtraDir = utils::GetDataPath().'production-modules/'; - if (is_dir($sExtraDir)) - { + if (is_dir($sExtraDir)) { $aDirsToScan[] = $sExtraDir; } $oProductionEnv = new RunTimeEnvironment(); $aAvailableModules = $oProductionEnv->AnalyzeInstallation($oConfig, $aDirsToScan, $bAbortOnMissingDependency, $aModulesToLoad); - foreach($aAvailableModules as $key => $aModule) - { + foreach ($aAvailableModules as $key => $aModule) { $bIsExtra = (array_key_exists('root_dir', $aModule) && (strpos($aModule['root_dir'], $sExtraDir) !== false)); // Some modules (root, datamodel) have no 'root_dir' - if ($bIsExtra) - { + if ($bIsExtra) { // Modules in data/production-modules/ are considered as mandatory and always installed $aAvailableModules[$key]['visible'] = false; } @@ -1671,18 +1658,15 @@ JS */ public static function CheckManualInstallDirEmpty($aModules, $sExtensionsDir = 'extensions') { - if (!static::IsProductVersion($aModules)) - { + if (!static::IsProductVersion($aModules)) { return ''; } $sManualInstallModulesFullPath = APPROOT.$sExtensionsDir.DIRECTORY_SEPARATOR; //simple test in order to prevent install iTop pro with module in extension folder $aFileInfo = scandir($sManualInstallModulesFullPath); - foreach ($aFileInfo as $sFolder) - { - if ($sFolder != "." && $sFolder != ".." && is_dir($sManualInstallModulesFullPath.$sFolder) === true) - { + foreach ($aFileInfo as $sFolder) { + if ($sFolder != "." && $sFolder != ".." && is_dir($sManualInstallModulesFullPath.$sFolder) === true) { return "Some modules are present in the '$sExtensionsDir' directory, this is not allowed when using ".ITOP_APPLICATION; } } @@ -1699,86 +1683,71 @@ JS * @return hash Hash array ('added' => array(), 'removed' => array(), 'modified' => array()) * @internal param array $aDOMManifest Array of array('path' => relative_path 'size'=> iSize, 'md5' => sHexMD5) */ - public static function CheckDirAgainstManifest($sBaseDir, $sSourceDir, $aManifest, $aExcludeNames = array('.svn', '.git'), $aResult = null) + public static function CheckDirAgainstManifest($sBaseDir, $sSourceDir, $aManifest, $aExcludeNames = ['.svn', '.git'], $aResult = null) { -//echo "CheckDirAgainstManifest($sBaseDir, $sSourceDir ...)\n"; - if ($aResult === null) - { - $aResult = array('added' => array(), 'removed' => array(), 'modified' => array()); + //echo "CheckDirAgainstManifest($sBaseDir, $sSourceDir ...)\n"; + if ($aResult === null) { + $aResult = ['added' => [], 'removed' => [], 'modified' => []]; } - if (substr($sSourceDir, 0, 1) == '/') - { + if (substr($sSourceDir, 0, 1) == '/') { $sSourceDir = substr($sSourceDir, 1); } // Manifest limited to all the files supposed to be located in this directory - $aDirManifest = array(); - foreach($aManifest as $aFileInfo) - { + $aDirManifest = []; + foreach ($aManifest as $aFileInfo) { $sDir = dirname($aFileInfo['path']); - if ($sDir == '.') - { + if ($sDir == '.') { // Hmm... the file seems located at the root of iTop $sDir = ''; } - if ($sDir == $sSourceDir) - { + if ($sDir == $sSourceDir) { $aDirManifest[basename($aFileInfo['path'])] = $aFileInfo; } } -//echo "The manifest contains ".count($aDirManifest)." files for the directory '$sSourceDir' (and below)\n"; + //echo "The manifest contains ".count($aDirManifest)." files for the directory '$sSourceDir' (and below)\n"; // Read the content of the directory - foreach(glob($sBaseDir.'/'.$sSourceDir .'/*') as $sFilePath) - { + foreach (glob($sBaseDir.'/'.$sSourceDir.'/*') as $sFilePath) { $sFile = basename($sFilePath); -//echo "Checking $sFile ($sFilePath)\n"; + //echo "Checking $sFile ($sFilePath)\n"; - if (in_array(basename($sFile), $aExcludeNames)) continue; - - if(is_dir($sFilePath)) - { - $aResult = self::CheckDirAgainstManifest($sBaseDir, $sSourceDir.'/'.$sFile, $aManifest, $aExcludeNames, $aResult); + if (in_array(basename($sFile), $aExcludeNames)) { + continue; } - else - { - if (!array_key_exists($sFile, $aDirManifest)) - { -//echo "New file ".$sFile." in $sSourceDir\n"; + + if (is_dir($sFilePath)) { + $aResult = self::CheckDirAgainstManifest($sBaseDir, $sSourceDir.'/'.$sFile, $aManifest, $aExcludeNames, $aResult); + } else { + if (!array_key_exists($sFile, $aDirManifest)) { + //echo "New file ".$sFile." in $sSourceDir\n"; $aResult['added'][$sSourceDir.'/'.$sFile] = true; - } - else - { + } else { $aStats = stat($sFilePath); - if ($aStats['size'] != $aDirManifest[$sFile]['size']) - { + if ($aStats['size'] != $aDirManifest[$sFile]['size']) { // Different sizes $aResult['modified'][$sSourceDir.'/'.$sFile] = 'Different sizes. Original size: '.$aDirManifest[$sFile]['size'].' bytes, actual file size on disk: '.$aStats['size'].' bytes.'; - } - else - { + } else { // Same size, compare the md5 signature $sMD5 = md5_file($sFilePath); - if ($sMD5 != $aDirManifest[$sFile]['md5']) - { + if ($sMD5 != $aDirManifest[$sFile]['md5']) { $aResult['modified'][$sSourceDir.'/'.$sFile] = 'Content modified (MD5 checksums differ).'; -//echo $sSourceDir.'/'.$sFile." modified ($sMD5 == {$aDirManifest[$sFile]['md5']})\n"; + //echo $sSourceDir.'/'.$sFile." modified ($sMD5 == {$aDirManifest[$sFile]['md5']})\n"; } -//else -//{ -// echo $sSourceDir.'/'.$sFile." unmodified ($sMD5 == {$aDirManifest[$sFile]['md5']})\n"; -//} + //else + //{ + // echo $sSourceDir.'/'.$sFile." unmodified ($sMD5 == {$aDirManifest[$sFile]['md5']})\n"; + //} } -//echo "Removing ".$sFile." from aDirManifest\n"; + //echo "Removing ".$sFile." from aDirManifest\n"; unset($aDirManifest[$sFile]); } } } // What remains in the array are files that were deleted - foreach($aDirManifest as $sDeletedFile => $void) - { + foreach ($aDirManifest as $sDeletedFile => $void) { $aResult['removed'][$sSourceDir.'/'.$sDeletedFile] = true; } return $aResult; @@ -1787,53 +1756,49 @@ JS public static function CheckDataModelFiles($sManifestFile, $sBaseDir) { $oXML = simplexml_load_file($sManifestFile); - $aManifest = array(); - foreach($oXML as $oFileInfo) - { - $aManifest[] = array('path' => (string)$oFileInfo->path, 'size' => (int)$oFileInfo->size, 'md5' => (string)$oFileInfo->md5); + $aManifest = []; + foreach ($oXML as $oFileInfo) { + $aManifest[] = ['path' => (string)$oFileInfo->path, 'size' => (int)$oFileInfo->size, 'md5' => (string)$oFileInfo->md5]; } $sBaseDir = preg_replace('|modules/?$|', '', $sBaseDir); $aResults = self::CheckDirAgainstManifest($sBaseDir, 'modules', $aManifest); -// echo "
Comparison of ".dirname($sBaseDir)."/modules against $sManifestFile:\n".print_r($aResults, true)."
"; + // echo "
Comparison of ".dirname($sBaseDir)."/modules against $sManifestFile:\n".print_r($aResults, true)."
"; return $aResults; } public static function CheckPortalFiles($sManifestFile, $sBaseDir) { $oXML = simplexml_load_file($sManifestFile); - $aManifest = array(); - foreach($oXML as $oFileInfo) - { - $aManifest[] = array('path' => (string)$oFileInfo->path, 'size' => (int)$oFileInfo->size, 'md5' => (string)$oFileInfo->md5); + $aManifest = []; + foreach ($oXML as $oFileInfo) { + $aManifest[] = ['path' => (string)$oFileInfo->path, 'size' => (int)$oFileInfo->size, 'md5' => (string)$oFileInfo->md5]; } $aResults = self::CheckDirAgainstManifest($sBaseDir, 'portal', $aManifest); -// echo "
Comparison of ".dirname($sBaseDir)."/portal:\n".print_r($aResults, true)."
"; + // echo "
Comparison of ".dirname($sBaseDir)."/portal:\n".print_r($aResults, true)."
"; return $aResults; } public static function CheckApplicationFiles($sManifestFile, $sBaseDir) { $oXML = simplexml_load_file($sManifestFile); - $aManifest = array(); - foreach($oXML as $oFileInfo) - { - $aManifest[] = array('path' => (string)$oFileInfo->path, 'size' => (int)$oFileInfo->size, 'md5' => (string)$oFileInfo->md5); + $aManifest = []; + foreach ($oXML as $oFileInfo) { + $aManifest[] = ['path' => (string)$oFileInfo->path, 'size' => (int)$oFileInfo->size, 'md5' => (string)$oFileInfo->md5]; } - $aResults = array('added' => array(), 'removed' => array(), 'modified' => array()); - foreach(array('addons', 'core', 'dictionaries', 'js', 'application', 'css', 'pages', 'synchro', 'webservices') as $sDir) - { + $aResults = ['added' => [], 'removed' => [], 'modified' => []]; + foreach (['addons', 'core', 'dictionaries', 'js', 'application', 'css', 'pages', 'synchro', 'webservices'] as $sDir) { $aTmp = self::CheckDirAgainstManifest($sBaseDir, $sDir, $aManifest); $aResults['added'] = array_merge($aResults['added'], $aTmp['added']); $aResults['modified'] = array_merge($aResults['modified'], $aTmp['modified']); $aResults['removed'] = array_merge($aResults['removed'], $aTmp['removed']); } -// echo "
Comparison of ".dirname($sBaseDir)."/portal:\n".print_r($aResults, true)."
"; + // echo "
Comparison of ".dirname($sBaseDir)."/portal:\n".print_r($aResults, true)."
"; return $aResults; } @@ -1846,10 +1811,8 @@ JS public static function CheckVersion($sInstalledVersion, $sSourceDir) { $sManifestFilePath = self::GetVersionManifest($sInstalledVersion); - if ($sSourceDir != '') - { - if (file_exists($sManifestFilePath)) - { + if ($sSourceDir != '') { + if (file_exists($sManifestFilePath)) { $aDMchanges = self::CheckDataModelFiles($sManifestFilePath, $sSourceDir); //$aPortalChanges = self::CheckPortalFiles($sManifestFilePath, $sSourceDir); //$aCodeChanges = self::CheckApplicationFiles($sManifestFilePath, $sSourceDir); @@ -1857,14 +1820,10 @@ JS //echo("Changes detected compared to $sInstalledVersion:
DataModel:
".print_r($aDMchanges, true)."
"); //echo("Changes detected compared to $sInstalledVersion:
DataModel:
".print_r($aDMchanges, true)."

Portal:
".print_r($aPortalChanges, true)."

Code:
".print_r($aCodeChanges, true)."
"); return $aDMchanges; - } - else - { + } else { return false; } - } - else - { + } else { throw(new Exception("Cannot check version '$sInstalledVersion', no source directory provided to check the files.")); } } @@ -1891,18 +1850,14 @@ JS */ public static function CheckWritableDirs($aWritableDirs) { - $aNonWritableDirs = array(); + $aNonWritableDirs = []; foreach ($aWritableDirs as $sDir) { $sFullPath = APPROOT.$sDir; if (is_dir($sFullPath) && !is_writable($sFullPath)) { $aNonWritableDirs[APPROOT.$sDir] = new CheckResult(CheckResult::ERROR, "The directory '".APPROOT.$sDir."' exists but is not writable for the application."); - } - else if (file_exists($sFullPath) && !is_dir($sFullPath)) - { + } elseif (file_exists($sFullPath) && !is_dir($sFullPath)) { $aNonWritableDirs[APPROOT.$sDir] = new CheckResult(CheckResult::ERROR, ITOP_APPLICATION." needs the directory '".APPROOT.$sDir."' to be writable. However file named '".APPROOT.$sDir."' already exists."); - } - else if (!is_dir($sFullPath) && !is_writable(APPROOT)) - { + } elseif (!is_dir($sFullPath) && !is_writable(APPROOT)) { $aNonWritableDirs[APPROOT.$sDir] = new CheckResult(CheckResult::ERROR, ITOP_APPLICATION." needs the directory '".APPROOT.$sDir."' to be writable. The directory '".APPROOT.$sDir."' does not exist and '".APPROOT."' is not writable, the application cannot create the directory '$sDir' inside it."); } } @@ -1914,8 +1869,7 @@ JS $sBaseDir = APPROOT.'datamodels'; $aDirs = glob($sBaseDir.'/*', GLOB_MARK | GLOB_ONLYDIR); - if ($aDirs !== false) - { + if ($aDirs !== false) { sort($aDirs); // Windows: there is a backslash at the end (though the path is made of slashes!!!) $sDir = basename(array_pop($aDirs)); @@ -1947,22 +1901,18 @@ JS */ public static function GetLicenses($sEnv = null) { - $aLicenses = array(); + $aLicenses = []; $aLicenceFiles = glob(APPROOT.'setup/licenses/*.xml'); if (empty($sEnv)) { $aLicenceFiles = array_merge($aLicenceFiles, glob(APPROOT.'datamodels/*/*/license.*.xml')); $aLicenceFiles = array_merge($aLicenceFiles, glob(APPROOT.'extensions/{*,*/*}/license.*.xml', GLOB_BRACE)); $aLicenceFiles = array_merge($aLicenceFiles, glob(utils::GetDataPath().'*-modules/{*,*/*}/license.*.xml', GLOB_BRACE)); - } - else - { + } else { $aLicenceFiles = array_merge($aLicenceFiles, glob(APPROOT.'env-'.$sEnv.'/*/license.*.xml')); } - foreach ($aLicenceFiles as $sFile) - { + foreach ($aLicenceFiles as $sFile) { $oXml = simplexml_load_file($sFile); - if (!empty($oXml->license)) - { + if (!empty($oXml->license)) { foreach ($oXml->license as $oLicense) { $aLicenses[(string)$oLicense->product] = $oLicense; } @@ -1998,8 +1948,7 @@ JS public static function ExitMaintenanceMode($bLog = true) { @unlink(MAINTENANCE_MODE_FILE); - if ($bLog) - { + if ($bLog) { SetupLog::Info("<---- Exiting maintenance mode"); } } @@ -2022,8 +1971,7 @@ JS public static function ExitReadOnlyMode($bLog = true) { @unlink(READONLY_MODE_FILE); - if ($bLog) - { + if ($bLog) { SetupLog::Info("<---- Exiting read only mode"); } } @@ -2039,8 +1987,7 @@ JS */ private static function WaitCronTermination($oConfig, $sMode) { - try - { + try { // Wait for cron to stop if (is_null($oConfig) || ContextTag::Check(ContextTag::TAG_CRON)) { return; @@ -2058,13 +2005,11 @@ JS $iStarted = time(); $iMaxDuration = $oConfig->Get('cron_max_execution_time'); $iTimeLimit = $iStarted + $iMaxDuration; - while ($oMutex->IsLocked()) - { + while ($oMutex->IsLocked()) { SetupLog::Info("Waiting for cron to stop ($iCount)"); $iCount++; sleep(1); - if (time() > $iTimeLimit) - { + if (time() > $iTimeLimit) { throw new Exception("Cannot enter $sMode mode, consider stopping the cron temporarily"); } } @@ -2147,7 +2092,8 @@ JS /** * @return string[] */ - public static function GetPHPMandatoryExtensions() { + public static function GetPHPMandatoryExtensions() + { return [ 'mysqli', 'iconv', @@ -2170,7 +2116,8 @@ JS /** * @return array */ - public static function GetPHPOptionalExtensions() { + public static function GetPHPOptionalExtensions() + { $aOptionalExtensions = [ 'mcrypt, sodium or openssl' => [ 'mcrypt' => 'Strong encryption will not be used.', @@ -2194,7 +2141,7 @@ JS */ class SetupInfo { - public static $aSelectedModules = array(); + public static $aSelectedModules = []; /** * Called by the setup process to initializes the list of selected modules. Do not call this method diff --git a/setup/unattended-install/InstallationFileService.php b/setup/unattended-install/InstallationFileService.php index 39ce907dc..5845d663b 100644 --- a/setup/unattended-install/InstallationFileService.php +++ b/setup/unattended-install/InstallationFileService.php @@ -8,7 +8,8 @@ require_once(APPROOT.'/setup/setuppage.class.inc.php'); require_once(APPROOT.'/setup/wizardcontroller.class.inc.php'); require_once(APPROOT.'/setup/wizardsteps.class.inc.php'); -class InstallationFileService { +class InstallationFileService +{ /** @var \RunTimeEnvironment $oProductionEnv */ private $oProductionEnv; @@ -31,17 +32,19 @@ class InstallationFileService { * @param bool $bInstallationOptionalChoicesChecked : this option is used only when no extensions are selected (ie empty * $aSelectedExtensions) */ - public function __construct(string $sInstallationPath, string $sTargetEnvironment='production', array $aSelectedExtensions = [], bool $bInstallationOptionalChoicesChecked=true) { + public function __construct(string $sInstallationPath, string $sTargetEnvironment = 'production', array $aSelectedExtensions = [], bool $bInstallationOptionalChoicesChecked = true) + { $this->sInstallationPath = $sInstallationPath; $this->aSelectedModules = []; $this->aUnSelectedModules = []; $this->sTargetEnvironment = $sTargetEnvironment; $this->aSelectedExtensions = $aSelectedExtensions; - $this->aAfterComputationSelectedExtensions = (count($aSelectedExtensions)==0) ? [] : $aSelectedExtensions; + $this->aAfterComputationSelectedExtensions = (count($aSelectedExtensions) == 0) ? [] : $aSelectedExtensions; $this->bInstallationOptionalChoicesChecked = $bInstallationOptionalChoicesChecked; } - public function Init(): void { + public function Init(): void + { clearstatcache(); $this->ProcessDefaultModules(); @@ -50,45 +53,54 @@ class InstallationFileService { $this->ProcessAutoSelectModules(); } - public function GetProductionEnv(): RunTimeEnvironment { - if (is_null($this->oProductionEnv)){ + public function GetProductionEnv(): RunTimeEnvironment + { + if (is_null($this->oProductionEnv)) { $this->oProductionEnv = new RunTimeEnvironment(); } return $this->oProductionEnv; } - public function SetProductionEnv(RunTimeEnvironment $oProductionEnv): void { + public function SetProductionEnv(RunTimeEnvironment $oProductionEnv): void + { $this->oProductionEnv = $oProductionEnv; } - public function GetAfterComputationSelectedExtensions(): array { + public function GetAfterComputationSelectedExtensions(): array + { return $this->aAfterComputationSelectedExtensions; } - public function SetItopExtensionsMap(ItopExtensionsMap $oItopExtensionsMap): void { + public function SetItopExtensionsMap(ItopExtensionsMap $oItopExtensionsMap): void + { $this->oItopExtensionsMap = $oItopExtensionsMap; } - public function GetItopExtensionsMap(): ItopExtensionsMap { - if (is_null($this->oItopExtensionsMap)){ + public function GetItopExtensionsMap(): ItopExtensionsMap + { + if (is_null($this->oItopExtensionsMap)) { $this->oItopExtensionsMap = new iTopExtensionsMap($this->sTargetEnvironment, true); } return $this->oItopExtensionsMap; } - public function GetAutoSelectModules(): array { + public function GetAutoSelectModules(): array + { return $this->aAutoSelectModules; } - public function GetSelectedModules(): array { + public function GetSelectedModules(): array + { return $this->aSelectedModules; } - public function GetUnSelectedModules(): array { + public function GetUnSelectedModules(): array + { return $this->aUnSelectedModules; } - public function ProcessInstallationChoices(): void { + public function ProcessInstallationChoices(): void + { $oXMLParameters = new XMLParameters($this->sInstallationPath); $aSteps = $oXMLParameters->Get('steps', []); if (! is_array($aSteps)) { @@ -110,20 +122,21 @@ class InstallationFileService { } } - foreach ($this->aSelectedModules as $sModuleId => $sVal){ - if (array_key_exists($sModuleId, $this->aUnSelectedModules)){ + foreach ($this->aSelectedModules as $sModuleId => $sVal) { + if (array_key_exists($sModuleId, $this->aUnSelectedModules)) { unset($this->aUnSelectedModules[$sModuleId]); } } } - private function ProcessUnSelectedChoice($aChoiceInfo) { + private function ProcessUnSelectedChoice($aChoiceInfo) + { if (!is_array($aChoiceInfo)) { return; } $aCurrentModules = $aChoiceInfo["modules"] ?? []; - foreach ($aCurrentModules as $sModuleId){ + foreach ($aCurrentModules as $sModuleId) { $this->aUnSelectedModules[$sModuleId] = true; } @@ -154,7 +167,8 @@ class InstallationFileService { } } - private function ProcessSelectedChoice($aChoiceInfo, bool $bAllChecked) { + private function ProcessSelectedChoice($aChoiceInfo, bool $bAllChecked) + { if (!is_array($aChoiceInfo)) { return; } @@ -164,17 +178,17 @@ class InstallationFileService { $aCurrentModules = $aChoiceInfo["modules"] ?? []; $sExtensionCode = $aChoiceInfo["extension_code"] ?? null; - if (0 === count($this->aSelectedExtensions)){ + if (0 === count($this->aSelectedExtensions)) { $bSelected = $bAllChecked || $sDefault === "true" || $sMandatory === "true"; - if ($bSelected){ - $this->aAfterComputationSelectedExtensions[]= $sExtensionCode; + if ($bSelected) { + $this->aAfterComputationSelectedExtensions[] = $sExtensionCode; } } else { $bSelected = $sMandatory === "true" || (null !== $sExtensionCode && in_array($sExtensionCode, $this->aSelectedExtensions)); } - foreach ($aCurrentModules as $sModuleId){ + foreach ($aCurrentModules as $sModuleId) { if ($bSelected) { $this->aSelectedModules[$sModuleId] = true; } else { @@ -221,19 +235,19 @@ class InstallationFileService { } } - private function GetExtraDirs() : array { + private function GetExtraDirs(): array + { $aSearchDirs = []; $aDirs = [ '/datamodels/1.x', '/datamodels/2.x', - 'data/' . $this->sTargetEnvironment . '-modules', + 'data/'.$this->sTargetEnvironment.'-modules', 'extensions', ]; - foreach ($aDirs as $sRelativeDir){ + foreach ($aDirs as $sRelativeDir) { $sDirPath = APPROOT.$sRelativeDir; - if (is_dir($sDirPath)) - { + if (is_dir($sDirPath)) { $aSearchDirs[] = $sDirPath; } } @@ -241,8 +255,9 @@ class InstallationFileService { return $aSearchDirs; } - public function ProcessDefaultModules() : void { - $sProductionModuleDir = APPROOT.'data/' . $this->sTargetEnvironment . '-modules/'; + public function ProcessDefaultModules(): void + { + $sProductionModuleDir = APPROOT.'data/'.$this->sTargetEnvironment.'-modules/'; $aAvailableModules = $this->GetProductionEnv()->AnalyzeInstallation(MetaModel::GetConfig(), $this->GetExtraDirs(), false, null); @@ -258,8 +273,10 @@ class InstallationFileService { $this->aSelectedModules[$sModuleId] = true; continue; } - $bIsExtra = (array_key_exists('root_dir', $aModule) && (strpos($aModule['root_dir'], - $sProductionModuleDir) !== false)); // Some modules (root, datamodel) have no 'root_dir' + $bIsExtra = (array_key_exists('root_dir', $aModule) && (strpos( + $aModule['root_dir'], + $sProductionModuleDir + ) !== false)); // Some modules (root, datamodel) have no 'root_dir' if ($bIsExtra) { // Modules in data/production-modules/ are considered as mandatory and always installed $this->aSelectedModules[$sModuleId] = true; @@ -268,35 +285,34 @@ class InstallationFileService { } } - public function ProcessAutoSelectModules() : void { + public function ProcessAutoSelectModules(): void + { $oPhpExpressionEvaluator = new PhpExpressionEvaluator([], RunTimeEnvironment::STATIC_CALL_AUTOSELECT_WHITELIST); - foreach($this->GetAutoSelectModules() as $sModuleId => $aModule) - { + foreach ($this->GetAutoSelectModules() as $sModuleId => $aModule) { try { SetupInfo::SetSelectedModules($this->aSelectedModules); $bSelected = $oPhpExpressionEvaluator->ParseAndEvaluateBooleanExpression($aModule['auto_select']); - if ($bSelected) - { + if ($bSelected) { // Modules in data/production-modules/ are considered as mandatory and always installed $this->aSelectedModules[$sModuleId] = true; } - } - catch (ModuleFileReaderException $e) { + } catch (ModuleFileReaderException $e) { //logged already } } } - public function CanChooseUnpackageExtension(iTopExtension $oExtension) : bool { - if ($oExtension->sSource === iTopExtension::SOURCE_REMOTE){ + public function CanChooseUnpackageExtension(iTopExtension $oExtension): bool + { + if ($oExtension->sSource === iTopExtension::SOURCE_REMOTE) { SetupLog::Info("Data Extension can be selected", null, ['extension' => $oExtension->sCode]); return true; } $bSelectable = $this->bInstallationOptionalChoicesChecked && ($oExtension->sSource === iTopExtension::SOURCE_MANUAL); - if ($bSelectable){ + if ($bSelectable) { SetupLog::Info("Manual Extension can be selected", null, ['extension' => $oExtension->sCode]); } else { SetupLog::Debug("Manual Extension can NOT be selected", null, ['extension' => $oExtension->sCode]); @@ -305,18 +321,22 @@ class InstallationFileService { return $bSelectable; } - public function ProcessExtensionModulesNotSpecifiedInChoices() { + public function ProcessExtensionModulesNotSpecifiedInChoices() + { /** @var \iTopExtension $oExtension */ - foreach($this->GetItopExtensionsMap()->GetAllExtensions() as $oExtension) { - if (in_array($oExtension->sCode, $this->aAfterComputationSelectedExtensions)){ + foreach ($this->GetItopExtensionsMap()->GetAllExtensions() as $oExtension) { + if (in_array($oExtension->sCode, $this->aAfterComputationSelectedExtensions)) { //extension already processed in installation.xml - SetupLog::Info("Extension already processed via installation choices", null, + SetupLog::Info( + "Extension already processed via installation choices", + null, [ 'extension' => $oExtension->sCode, - ]) ; + ] + ) ; continue; } - if ($this->CanChooseUnpackageExtension($oExtension)){ + if ($this->CanChooseUnpackageExtension($oExtension)) { if (($oExtension->bVisible) && (count($oExtension->aMissingDependencies) === 0)) { $aCurrentModules = []; $aUnselectableModules = []; @@ -338,23 +358,28 @@ class InstallationFileService { } if ($bIsExtensionSelectable) { - SetupLog::Debug("Add modules from unpackaged extension", null, + SetupLog::Debug( + "Add modules from unpackaged extension", + null, [ 'extension' => $oExtension->sCode, 'source' => $oExtension->sSource, 'modules to add' => array_keys($aCurrentModules), - ]); + ] + ); $this->aSelectedModules = array_merge($this->aSelectedModules, $aCurrentModules); $this->aAfterComputationSelectedExtensions[] = $oExtension->sCode; } else { - SetupLog::Warning("Unpackaged extension can not be selected due to modules incompatible with installation choices", + SetupLog::Warning( + "Unpackaged extension can not be selected due to modules incompatible with installation choices", null, [ 'extension' => $oExtension->sCode, 'source' => $oExtension->sSource, 'modules' => array_keys($aCurrentModules), 'unselectable modules' => $aUnselectableModules, - ]); + ] + ); } } } diff --git a/setup/wizardsteps.class.inc.php b/setup/wizardsteps.class.inc.php index 88c290c11..0e55e993b 100644 --- a/setup/wizardsteps.class.inc.php +++ b/setup/wizardsteps.class.inc.php @@ -1,4 +1,5 @@ oWizard->SetParameter('authent', $sUID); - return array('class' => 'WizStepInstallOrUpgrade', 'state' => ''); + return ['class' => 'WizStepInstallOrUpgrade', 'state' => '']; } public function Display(WebPage $oPage) { // Store the misc_options for the future... - $aMiscOptions = utils::ReadParam('option', array(), false, 'raw_data'); + $aMiscOptions = utils::ReadParam('option', [], false, 'raw_data'); $sMiscOptions = $this->oWizard->GetParameter('misc_options', json_encode($aMiscOptions)); $this->oWizard->SetParameter('misc_options', $sMiscOptions); @@ -102,13 +103,11 @@ EOF $oPage->add('

'.ITOP_APPLICATION.' Installation Wizard

'); $aResults = SetupUtils::CheckPhpAndExtensions(); $this->bCanMoveForward = true; - $aInfo = array(); - $aWarnings = array(); - $aErrors = array(); - foreach($aResults as $oCheckResult) - { - switch($oCheckResult->iSeverity) - { + $aInfo = []; + $aWarnings = []; + $aErrors = []; + foreach ($aResults as $oCheckResult) { + switch ($oCheckResult->iSeverity) { case CheckResult::ERROR: $aErrors[] = $oCheckResult->sLabel; $this->bCanMoveForward = false; @@ -129,19 +128,14 @@ EOF } $sStyle = 'style="display:none;overflow:auto;"'; $sToggleButtons = ''; - if (count($aErrors)> 0) - { + if (count($aErrors) > 0) { $sStyle = 'overflow:auto;"'; $sTitle = count($aErrors).' Error(s), '.count($aWarnings).' Warning(s).'; $sH2Class = 'text-error'; - } - else if (count($aWarnings)> 0) - { + } elseif (count($aWarnings) > 0) { $sTitle = count($aWarnings).' Warning(s) '.$sToggleButtons; $sH2Class = 'text-warning'; - } - else - { + } else { $sTitle = 'Ok. '.$sToggleButtons; $sH2Class = 'text-valid'; } @@ -151,21 +145,17 @@ EOF
HTML ); - foreach($aErrors as $sText) - { + foreach ($aErrors as $sText) { $oPage->error($sText); } - foreach($aWarnings as $sText) - { + foreach ($aWarnings as $sText) { $oPage->warning($sText); } - foreach($aInfo as $sText) - { + foreach ($aInfo as $sText) { $oPage->ok($sText); } $oPage->add('
'); - if (!$this->bCanMoveForward) - { + if (!$this->bCanMoveForward) { $oPage->p('Sorry, the installation cannot continue. Please fix the errors and reload this page to launch the installation again.'); $oPage->p(''); } @@ -190,7 +180,7 @@ class WizStepInstallOrUpgrade extends WizardStep public function GetPossibleSteps() { - return array('WizStepDetectedInfo', 'WizStepLicense'); + return ['WizStepDetectedInfo', 'WizStepLicense']; } public function ProcessParams($bMoveForward = true) @@ -209,21 +199,18 @@ class WizStepInstallOrUpgrade extends WizardStep $this->oWizard->SaveParameter('db_tls_enabled', false); $this->oWizard->SaveParameter('db_tls_ca', ''); - if ($sInstallMode == 'install') - { + if ($sInstallMode == 'install') { $this->oWizard->SetParameter('install_mode', 'install'); $sFullSourceDir = SetupUtils::GetLatestDataModelDir(); $this->oWizard->SetParameter('source_dir', $sFullSourceDir); $this->oWizard->SetParameter('datamodel_version', SetupUtils::GetDataModelVersion($sFullSourceDir)); $sNextStep = 'WizStepLicense'; - } - else - { + } else { $this->oWizard->SetParameter('install_mode', 'upgrade'); $sNextStep = 'WizStepDetectedInfo'; } - return array('class' => $sNextStep, 'state' => ''); + return ['class' => $sNextStep, 'state' => '']; } public function Display(WebPage $oPage) @@ -240,8 +227,7 @@ class WizStepInstallOrUpgrade extends WizardStep $sTlsCA = $this->oWizard->GetParameter('db_tls_ca', ''); $sMySQLBinDir = $this->oWizard->GetParameter('mysql_bindir', null); $sPreviousVersionDir = ''; - if ($sInstallMode == '') - { + if ($sInstallMode == '') { $sDBBackupPath = utils::GetDataPath().'backups/manual/setup-'.date('Y-m-d_H_i'); $bDBBackup = true; $aPreviousInstance = SetupUtils::GetPreviousInstance(APPROOT); @@ -258,17 +244,14 @@ class WizStepInstallOrUpgrade extends WizardStep $sMySQLBinDir = $aPreviousInstance['mysql_bindir']; $this->oWizard->SaveParameter('mysql_bindir', $aPreviousInstance['mysql_bindir']); $sPreviousVersionDir = APPROOT; - } - else - { + } else { $sInstallMode = 'install'; } } $sPreviousVersionDir = $this->oWizard->GetParameter('previous_version_dir', $sPreviousVersionDir); $sUpgradeInfoStyle = ''; - if ($sInstallMode == 'install') - { + if ($sInstallMode == 'install') { $sUpgradeInfoStyle = ' style="display: none;" '; } $oPage->add('
What do you want to do?
'); @@ -279,15 +262,26 @@ class WizStepInstallOrUpgrade extends WizardStep $oPage->p(''); $sUpgradeDir = utils::HtmlEntities($sPreviousVersionDir); - $oPage->add(<<add( + <<
Location on the disk:
HTML ); - SetupUtils::DisplayDBParameters($oPage, false, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, - $sTlsEnabled, $sTlsCA, null); + SetupUtils::DisplayDBParameters( + $oPage, + false, + $sDBServer, + $sDBUser, + $sDBPwd, + $sDBName, + $sDBPrefix, + $sTlsEnabled, + $sTlsCA, + null + ); $aBackupChecks = SetupUtils::CheckBackupPrerequisites($sDBBackupPath, $sMySQLBinDir); $bCanBackup = true; @@ -331,8 +325,7 @@ JS public function AsyncAction(WebPage $oPage, $sCode, $aParameters) { - switch($sCode) - { + switch ($sCode) { case 'check_path': $sPreviousVersionDir = $aParameters['previous_version_dir']; $aPreviousInstance = SetupUtils::GetPreviousInstance($sPreviousVersionDir); @@ -356,7 +349,7 @@ EOF break; case 'check_db': - SetupUtils:: AsyncCheckDB($oPage, $aParameters); + SetupUtils::AsyncCheckDB($oPage, $aParameters); break; case 'check_backup': @@ -405,7 +398,7 @@ EOF return bRet; } EOF - ; + ; } } @@ -424,7 +417,7 @@ class WizStepDetectedInfo extends WizardStep public function GetPossibleSteps() { - return array('WizStepUpgradeMiscParams', 'WizStepLicense2'); + return ['WizStepUpgradeMiscParams', 'WizStepLicense2']; } public function ProcessParams($bMoveForward = true) @@ -435,8 +428,7 @@ class WizStepDetectedInfo extends WizardStep $this->oWizard->SetParameter('upgrade_type', $sUpgradeType); $bDisplayLicense = $this->oWizard->GetParameter('display_license'); - switch ($sUpgradeType) - { + switch ($sUpgradeType) { case 'keep-previous': $sSourceDir = utils::ReadParam('relative_source_dir', '', false, 'raw_data'); $this->oWizard->SetParameter('source_dir', $this->oWizard->GetParameter('previous_version_dir').'/'.$sSourceDir); @@ -452,13 +444,10 @@ class WizStepDetectedInfo extends WizardStep default: // Do nothing, maybe the user pressed the Back button } - if ($bDisplayLicense) - { - $aRet = array('class' => 'WizStepLicense2', 'state' => ''); - } - else - { - $aRet = array('class' => 'WizStepUpgradeMiscParams', 'state' => ''); + if ($bDisplayLicense) { + $aRet = ['class' => 'WizStepLicense2', 'state' => '']; + } else { + $aRet = ['class' => 'WizStepUpgradeMiscParams', 'state' => '']; } return $aRet; } @@ -511,12 +500,9 @@ EOF $sPreviousVersionDir = $this->oWizard->GetParameter('previous_version_dir', ''); $aInstalledInfo = SetupUtils::GetApplicationVersion($this->oWizard); - if ($aInstalledInfo === false) - { + if ($aInstalledInfo === false) { throw(new Exception('No previous version of '.ITOP_APPLICATION.' found in the supplied database. The upgrade cannot continue.')); - } - else if (strcasecmp($aInstalledInfo['product_name'], ITOP_APPLICATION) != 0) - { + } elseif (strcasecmp($aInstalledInfo['product_name'], ITOP_APPLICATION) != 0) { $oPage->p("Warning: The installed products seem different. Are you sure that you want to upgrade {$aInstalledInfo['product_name']} with ".ITOP_APPLICATION."?"); } @@ -540,17 +526,16 @@ EOF $sUpgradeDMVersion = SetupUtils::GetDataModelVersion($sCompatibleDMDir); $sPreviousSourceDir = isset($aInstalledInfo['source_dir']) ? $aInstalledInfo['source_dir'] : 'modules'; $aChanges = false; - if (is_dir($sPreviousVersionDir)) - { + if (is_dir($sPreviousVersionDir)) { // Check if the previous version is a "genuine" one or not... $aChanges = SetupUtils::CheckVersion($sInstalledDataModelVersion, $sPreviousVersionDir.'/'.$sPreviousSourceDir); } - if (($aChanges !== false) && ( (count($aChanges['added']) > 0) || (count($aChanges['removed']) > 0) || (count($aChanges['modified']) > 0)) ) { + if (($aChanges !== false) && ((count($aChanges['added']) > 0) || (count($aChanges['removed']) > 0) || (count($aChanges['modified']) > 0))) { // Some changes were detected, prompt the user to keep or discard them $oPage->p(" Some modifications were detected between the ".ITOP_APPLICATION." version in '$sPreviousVersionDir' and a genuine $sInstalledVersion version."); $oPage->p("What do you want to do?"); - $aWritableDirs = array('modules', 'portal'); + $aWritableDirs = ['modules', 'portal']; $aErrors = SetupUtils::CheckWritableDirs($aWritableDirs); $sChecked = ($this->oWizard->GetParameter('upgrade_type') == 'keep-previous') ? ' checked ' : ''; $sDisabled = (count($aErrors) > 0) ? ' disabled ' : ''; @@ -584,25 +569,20 @@ EOF } if (count($aChanges['removed']) > 0) { $oPage->add(''); } - if (count($aChanges['modified']) > 0) - { + if (count($aChanges['modified']) > 0) { $oPage->add(''); } $oPage->add(''); - } - else - { + } else { // No changes detected... or no way to tell because of the lack of a manifest or previous source dir // Use the "compatible" datamodel as-is. $sCompatibleDMDirToDisplay = utils::HtmlEntities($sCompatibleDMDir); @@ -633,8 +613,7 @@ EOF $this->oWizard->GetParameter('db_tls_enabled', ''), $this->oWizard->GetParameter('db_tls_ca', '') ); - if ($oMutex->IsLocked()) - { + if ($oMutex->IsLocked()) { $oPage->add('
'.ITOP_APPLICATION.' cron process is being executed on the target database. '.ITOP_APPLICATION.' cron process will be stopped during the setup execution.
'); } } @@ -658,7 +637,7 @@ EOF bRet = ($('input[name=upgrade_type]:checked').length > 0); return bRet; EOF - ; + ; } } @@ -674,13 +653,13 @@ class WizStepLicense extends WizardStep public function GetPossibleSteps() { - return array('WizStepDBParams'); + return ['WizStepDBParams']; } public function ProcessParams($bMoveForward = true) { $this->oWizard->SaveParameter('accept_license', 'no'); - return array('class' => 'WizStepDBParams', 'state' => ''); + return ['class' => 'WizStepDBParams', 'state' => '']; } /** @@ -768,7 +747,6 @@ JS return 'return ($("#accept").prop("checked") && isRgpdConsentOk());'; } - } /** @@ -778,12 +756,12 @@ class WizStepLicense2 extends WizStepLicense { public function GetPossibleSteps() { - return array('WizStepUpgradeMiscParams'); + return ['WizStepUpgradeMiscParams']; } public function ProcessParams($bMoveForward = true) { - return array('class' => 'WizStepUpgradeMiscParams', 'state' => ''); + return ['class' => 'WizStepUpgradeMiscParams', 'state' => '']; } } @@ -799,7 +777,7 @@ class WizStepDBParams extends WizardStep public function GetPossibleSteps() { - return array('WizStepAdminAccount'); + return ['WizStepAdminAccount']; } public function ProcessParams($bMoveForward = true) @@ -815,7 +793,7 @@ class WizStepDBParams extends WizardStep $this->oWizard->SaveParameter('db_tls_enabled', false); $this->oWizard->SaveParameter('db_tls_ca', ''); - return array('class' => 'WizStepAdminAccount', 'state' => ''); + return ['class' => 'WizStepAdminAccount', 'state' => '']; } public function Display(WebPage $oPage) @@ -831,28 +809,34 @@ class WizStepDBParams extends WizardStep $sNewDBName = $this->oWizard->GetParameter('db_new_name', false); $oPage->add(''); - SetupUtils::DisplayDBParameters($oPage, true, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sTlsEnabled, - $sTlsCA, $sNewDBName); + SetupUtils::DisplayDBParameters( + $oPage, + true, + $sDBServer, + $sDBUser, + $sDBPwd, + $sDBName, + $sDBPrefix, + $sTlsEnabled, + $sTlsCA, + $sNewDBName + ); $sAuthentToken = $this->oWizard->GetParameter('authent', ''); $oPage->add(''); $oPage->add('
'); $sCreateDB = $this->oWizard->GetParameter('create_db', 'yes'); - if ($sCreateDB == 'no') - { + if ($sCreateDB == 'no') { $oPage->add_ready_script('$("#existing_db").prop("checked", true);'); - } - else - { + } else { $oPage->add_ready_script('$("#create_db").prop("checked", true);'); } } public function AsyncAction(WebPage $oPage, $sCode, $aParameters) { - switch($sCode) - { + switch ($sCode) { case 'check_db': - SetupUtils:: AsyncCheckDB($oPage, $aParameters); + SetupUtils::AsyncCheckDB($oPage, $aParameters); break; } } @@ -874,7 +858,7 @@ class WizStepDBParams extends WizardStep return bRet; EOF - ; + ; } } @@ -890,7 +874,7 @@ class WizStepAdminAccount extends WizardStep public function GetPossibleSteps() { - return array(WizStepInstallMiscParams::class); + return [WizStepInstallMiscParams::class]; } public function ProcessParams($bMoveForward = true) @@ -900,7 +884,7 @@ class WizStepAdminAccount extends WizardStep $this->oWizard->SaveParameter('confirm_pwd', ''); $this->oWizard->SaveParameter('admin_language', 'EN US'); - return array('class' => WizStepInstallMiscParams::class, 'state' => ''); + return ['class' => WizStepInstallMiscParams::class, 'state' => '']; } public function Display(WebPage $oPage) @@ -963,11 +947,10 @@ EOF return bRet; EOF - ; + ; } } - /** * @since 3.0.0 N°4092 */ @@ -985,7 +968,8 @@ abstract class AbstractWizStepMiscParams extends WizardStep $oPage->add('Dev parameters'); $oPage->p('