Compare commits

..

4 Commits

Author SHA1 Message Date
Eric Espie
4ada74e63f Debug data within the form 2025-10-22 17:37:38 +02:00
Eric Espie
0ccb452ab7 merge 2025-10-22 16:55:09 +02:00
Benjamin Dalsass
0dae7346d1 N°8772 - Form dependencies manager implementation
- turbo implementation
2025-10-20 15:16:44 +02:00
Benjamin Dalsass
cdfded766f N°8772 - Form dependencies manager implementation 2025-10-17 09:03:45 +02:00
3151 changed files with 66295 additions and 181426 deletions

View File

@@ -9,7 +9,7 @@ Any PRs not following the guidelines or with missing information will not be con
## Base information ## Base information
| Question | Answer | Question | Answer
|---------------------------------------------------------------|-------- |---------------------------------------------------------------|--------
| Related to a SourceForge thread / Another PR / Combodo ticket? | <!-- Put the URL --> | Related to a SourceForge thead / Another PR / Combodo ticket? | <!-- Put the URL -->
| Type of change? | Bug fix / Enhancement / Translations | Type of change? | Bug fix / Enhancement / Translations

View File

@@ -26,23 +26,13 @@ jobs:
fi fi
- name: Add internal tag if member of the organization - name: Add internal tag if member
if: env.is_member == 'true' if: env.is_member == 'true'
run: | run: |
curl -X POST -H "Authorization: token ${{ secrets.PR_AUTOMATICALLY_ADD_TO_PROJECT }}" \ curl -X POST -H "Authorization: token ${{ secrets.PR_AUTOMATICALLY_ADD_TO_PROJECT }}" \
-H "Accept: application/vnd.github.v3+json" \ -H "Accept: application/vnd.github.v3+json" \
https://api.github.com/repos/Combodo/iTop/issues/${{ github.event.pull_request.number }}/labels \ https://api.github.com/repos/Combodo/iTop/issues/${{ github.event.pull_request.number }}/labels \
-d '{"labels":["internal"]}' -d '{"labels":["internal"]}'
- name: Set PR author as assignee if member of the organization
if: env.is_member == 'true'
run: |
curl -L \
-X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer ${{ secrets.PR_AUTOMATICALLY_ADD_TO_PROJECT }}" \
https://api.github.com/repos/Combodo/iTop/issues/${{ github.event.pull_request.number }}/assignees \
-d '{"assignees":["${{ github.event.pull_request.user.login }}"]}'
env: env:
is_member: ${{ env.is_member }} is_member: ${{ env.is_member }}
@@ -50,4 +40,4 @@ jobs:
uses: actions/add-to-project@v1.0.2 uses: actions/add-to-project@v1.0.2
with: with:
project-url: ${{ env.project_url }} project-url: ${{ env.project_url }}
github-token: ${{ secrets.PR_AUTOMATICALLY_ADD_TO_PROJECT }} github-token: ${{ secrets.PR_AUTOMATICALLY_ADD_TO_PROJECT }}

View File

@@ -199,7 +199,7 @@ class DatamodelsXmlFiles extends AbstractGlobFileVersionUpdater
libxml_clear_errors(); libxml_clear_errors();
$oFileXml->formatOutput = true; $oFileXml->formatOutput = true;
$oFileXml->preserveWhiteSpace = false; $oFileXml->preserveWhiteSpace = false;
$oFileXml->loadXML($sFileContent, LIBXML_BIGLINES); $oFileXml->loadXML($sFileContent);
$oFileItopFormat = new iTopDesignFormat($oFileXml); $oFileItopFormat = new iTopDesignFormat($oFileXml);

View File

@@ -1,16 +0,0 @@
<?php
/*
* @copyright Copyright (C) 2010-2025 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
*/
namespace PHPSTORM_META
{
override(\MetaModel::NewObject(0), map([
'' => '@',
]));
override(\MetaModel::GetObject(0), map([
'' => '@',
]));
}

View File

@@ -5,6 +5,17 @@ You want to contribute to iTop? Many thanks to you! 🎉 👍
Here are some guidelines that will help us integrate your work! Here are some guidelines that will help us integrate your work!
## Contributions
```
_ _ _ _ _ __ _
| | | | __ _ ___| | _| |_ ___ | |__ ___ _ __ / _| ___ ___| |_
| |_| |/ _` |/ __| |/ / __/ _ \| '_ \ / _ \ '__| |_ / _ \/ __| __|
| _ | (_| | (__| <| || (_) | |_) | __/ | | _| __/\__ \ |_
|_| |_|\__,_|\___|_|\_\\__\___/|_.__/ \___|_| |_| \___||___/\__|
```
This repository is part of Hacktoberfest. Contributions are welcome! Feel free to suggest improvements, add translation, fix bugs, or propose new features. Thank you for contributing !
### Subjects ### Subjects

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -30,52 +29,56 @@ class UserRightsBaseClassGUI extends cmdbAbstractObject
} }
} }
class URP_Profiles extends UserRightsBaseClassGUI class URP_Profiles extends UserRightsBaseClassGUI
{ {
public static function Init() public static function Init()
{ {
$aParams = $aParams = array
[ (
"category" => "addon/userrights,grant_by_profile,filter", "category" => "addon/userrights,grant_by_profile,filter",
"key_type" => "autoincrement", "key_type" => "autoincrement",
"name_attcode" => "name", "name_attcode" => "name",
"complementary_name_attcode" => ['description'], "complementary_name_attcode" => array('description'),
"state_attcode" => "", "state_attcode" => "",
"reconc_keys" => [], "reconc_keys" => array(),
"db_table" => "priv_urp_profiles", "db_table" => "priv_urp_profiles",
"db_key_field" => "id", "db_key_field" => "id",
"db_finalclass_field" => "", "db_finalclass_field" => "",
]; );
MetaModel::Init_Params($aParams); MetaModel::Init_Params($aParams);
//MetaModel::Init_InheritAttributes(); //MetaModel::Init_InheritAttributes();
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("name", array("allowed_values"=>null, "sql"=>"name", "default_value"=>null, "is_null_allowed"=>false, "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 AttributeString("description", array("allowed_values"=>null, "sql"=>"description", "default_value"=>null, "is_null_allowed"=>false, "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" => []])); 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())));
// Display lists // Display lists
MetaModel::Init_SetZListItems('details', ['name', 'description', 'user_list']); // Attributes to be displayed for the complete details MetaModel::Init_SetZListItems('details', array('name', 'description', 'user_list')); // Attributes to be displayed for the complete details
MetaModel::Init_SetZListItems('list', ['description']); // Attributes to be displayed for a list MetaModel::Init_SetZListItems('list', array('description')); // Attributes to be displayed for a list
// Search criteria // Search criteria
MetaModel::Init_SetZListItems('standard_search', ['name','description']); // Criteria of the std search form MetaModel::Init_SetZListItems('standard_search', array('name','description')); // Criteria of the std search form
MetaModel::Init_SetZListItems('default_search', ['name','description']); MetaModel::Init_SetZListItems('default_search', array ('name','description'));
} }
protected static $m_aCacheProfiles = null; protected static $m_aCacheProfiles = null;
public static function DoCreateProfile($sName, $sDescription) public static function DoCreateProfile($sName, $sDescription)
{ {
if (is_null(self::$m_aCacheProfiles)) { if (is_null(self::$m_aCacheProfiles))
self::$m_aCacheProfiles = []; {
self::$m_aCacheProfiles = array();
$oFilterAll = new DBObjectSearch('URP_Profiles'); $oFilterAll = new DBObjectSearch('URP_Profiles');
$oSet = new DBObjectSet($oFilterAll); $oSet = new DBObjectSet($oFilterAll);
while ($oProfile = $oSet->Fetch()) { while ($oProfile = $oSet->Fetch())
{
self::$m_aCacheProfiles[$oProfile->Get('name')] = $oProfile->GetKey(); self::$m_aCacheProfiles[$oProfile->Get('name')] = $oProfile->GetKey();
} }
} }
$sCacheKey = $sName; $sCacheKey = $sName;
if (isset(self::$m_aCacheProfiles[$sCacheKey])) { if (isset(self::$m_aCacheProfiles[$sCacheKey]))
{
return self::$m_aCacheProfiles[$sCacheKey]; return self::$m_aCacheProfiles[$sCacheKey];
} }
$oNewObj = MetaModel::NewObject("URP_Profiles"); $oNewObj = MetaModel::NewObject("URP_Profiles");
@@ -86,21 +89,27 @@ class URP_Profiles extends UserRightsBaseClassGUI
return $iId; return $iId;
} }
public function GetGrantAsHtml($oUserRights, $sClass, $sAction) function GetGrantAsHtml($oUserRights, $sClass, $sAction)
{ {
$bGrant = $oUserRights->GetProfileActionGrant($this->GetKey(), $sClass, $sAction); $bGrant = $oUserRights->GetProfileActionGrant($this->GetKey(), $sClass, $sAction);
if (is_null($bGrant)) { if (is_null($bGrant))
return '<span class="ibo-user-rights ibo-is-failure">'.Dict::S('UI:UserManagement:ActionAllowed:No').'</span>'; {
} elseif ($bGrant) { return '<span style="background-color: #ffdddd;">'.Dict::S('UI:UserManagement:ActionAllowed:No').'</span>';
return '<span class="ibo-user-rights ibo-is-success">'.Dict::S('UI:UserManagement:ActionAllowed:Yes').'</span>'; }
} else { elseif ($bGrant)
return '<span class="ibo-user-rights ibo-is-failure">'.Dict::S('UI:UserManagement:ActionAllowed:No').'</span>'; {
return '<span style="background-color: #ddffdd;">'.Dict::S('UI:UserManagement:ActionAllowed:Yes').'</span>';
}
else
{
return '<span style="background-color: #ffdddd;">'.Dict::S('UI:UserManagement:ActionAllowed:No').'</span>';
} }
} }
public function DoShowGrantSumary($oPage) function DoShowGrantSumary($oPage)
{ {
if ($this->GetRawName() == "Administrator") { if ($this->GetRawName() == "Administrator")
{
// Looks dirty, but ok that's THE ONE // Looks dirty, but ok that's THE ONE
$oPage->p(Dict::S('UI:UserManagement:AdminProfile+')); $oPage->p(Dict::S('UI:UserManagement:AdminProfile+'));
return; return;
@@ -109,18 +118,21 @@ class URP_Profiles extends UserRightsBaseClassGUI
// Note: for sure, we assume that the instance is derived from UserRightsProfile // Note: for sure, we assume that the instance is derived from UserRightsProfile
$oUserRights = UserRights::GetModuleInstance(); $oUserRights = UserRights::GetModuleInstance();
$aDisplayData = []; $aDisplayData = array();
foreach (MetaModel::GetClasses('bizmodel,grant_by_profile') as $sClass) { foreach (MetaModel::GetClasses('bizmodel,grant_by_profile') as $sClass)
$aStimuli = []; {
foreach (MetaModel::EnumStimuli($sClass) as $sStimulusCode => $oStimulus) { $aStimuli = array();
foreach (MetaModel::EnumStimuli($sClass) as $sStimulusCode => $oStimulus)
{
$bGrant = $oUserRights->GetClassStimulusGrant($this->GetKey(), $sClass, $sStimulusCode); $bGrant = $oUserRights->GetClassStimulusGrant($this->GetKey(), $sClass, $sStimulusCode);
if ($bGrant === true) { if ($bGrant === true)
{
$aStimuli[] = '<span title="'.$sStimulusCode.': '.utils::EscapeHtml($oStimulus->GetDescription()).'">'.utils::EscapeHtml($oStimulus->GetLabel()).'</span>'; $aStimuli[] = '<span title="'.$sStimulusCode.': '.utils::EscapeHtml($oStimulus->GetDescription()).'">'.utils::EscapeHtml($oStimulus->GetLabel()).'</span>';
} }
} }
$sStimuli = implode(', ', $aStimuli); $sStimuli = implode(', ', $aStimuli);
$aDisplayData[] = [ $aDisplayData[] = array(
'class' => MetaModel::GetName($sClass), 'class' => MetaModel::GetName($sClass),
'read' => $this->GetGrantAsHtml($oUserRights, $sClass, 'r'), 'read' => $this->GetGrantAsHtml($oUserRights, $sClass, 'r'),
'bulkread' => $this->GetGrantAsHtml($oUserRights, $sClass, 'br'), 'bulkread' => $this->GetGrantAsHtml($oUserRights, $sClass, 'br'),
@@ -129,22 +141,22 @@ class URP_Profiles extends UserRightsBaseClassGUI
'delete' => $this->GetGrantAsHtml($oUserRights, $sClass, 'd'), 'delete' => $this->GetGrantAsHtml($oUserRights, $sClass, 'd'),
'bulkdelete' => $this->GetGrantAsHtml($oUserRights, $sClass, 'bd'), 'bulkdelete' => $this->GetGrantAsHtml($oUserRights, $sClass, 'bd'),
'stimuli' => $sStimuli, 'stimuli' => $sStimuli,
]; );
} }
$aDisplayConfig = []; $aDisplayConfig = array();
$aDisplayConfig['class'] = ['label' => Dict::S('UI:UserManagement:Class'), 'description' => Dict::S('UI:UserManagement:Class+')]; $aDisplayConfig['class'] = array('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['read'] = array('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['bulkread'] = array('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['write'] = array('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['bulkwrite'] = array('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['delete'] = array('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['bulkdelete'] = array('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+')]; $aDisplayConfig['stimuli'] = array('label' => Dict::S('UI:UserManagement:Action:Stimuli'), 'description' => Dict::S('UI:UserManagement:Action:Stimuli+'));
$oPage->table($aDisplayConfig, $aDisplayData); $oPage->table($aDisplayConfig, $aDisplayData);
} }
public function DisplayBareRelations(WebPage $oPage, $bEditMode = false) function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
{ {
parent::DisplayBareRelations($oPage, $bEditMode); parent::DisplayBareRelations($oPage, $bEditMode);
@@ -154,9 +166,10 @@ class URP_Profiles extends UserRightsBaseClassGUI
public static function GetReadOnlyAttributes() public static function GetReadOnlyAttributes()
{ {
return ['name', 'description']; return array('name', 'description');
} }
// returns an array of id => array of column => php value(so-called "real value") // returns an array of id => array of column => php value(so-called "real value")
public static function GetPredefinedObjects() public static function GetPredefinedObjects()
{ {
@@ -168,13 +181,15 @@ class URP_Profiles extends UserRightsBaseClassGUI
protected function OnDelete() protected function OnDelete()
{ {
// Don't remove admin profile // 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')); 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" ! // Note: this may break the rule that says: "a user must have at least ONE profile" !
$oLnkSet = $this->Get('user_list'); $oLnkSet = $this->Get('user_list');
while ($oLnk = $oLnkSet->Fetch()) { while($oLnk = $oLnkSet->Fetch())
{
$oLnk->DBDelete(); $oLnk->DBDelete();
} }
} }
@@ -187,10 +202,11 @@ 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 * @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 * @return integer Flags: the binary combination of the flags applicable to this attribute
*/ */
public function GetAttributeFlags($sAttCode, &$aReasons = [], $sTargetState = '') public function GetAttributeFlags($sAttCode, &$aReasons = array(), $sTargetState = '')
{ {
$iFlags = parent::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!'; $aReasons[] = 'Sorry, profiles are read-only in the demonstration mode!';
$iFlags |= OPT_ATT_READONLY; $iFlags |= OPT_ATT_READONLY;
} }
@@ -198,52 +214,52 @@ class URP_Profiles extends UserRightsBaseClassGUI
} }
} }
class URP_UserProfile extends UserRightsBaseClassGUI class URP_UserProfile extends UserRightsBaseClassGUI
{ {
public static function Init() public static function Init()
{ {
$aParams = $aParams = array
[ (
"category" => "addon/userrights,grant_by_profile,filter", "category" => "addon/userrights,grant_by_profile,filter",
"key_type" => "autoincrement", "key_type" => "autoincrement",
"name_attcode" => ["userlogin", "profile"], "name_attcode" => array("userlogin", "profile"),
"state_attcode" => "", "state_attcode" => "",
"reconc_keys" => [], "reconc_keys" => array(),
"db_table" => "priv_urp_userprofile", "db_table" => "priv_urp_userprofile",
"db_key_field" => "id", "db_key_field" => "id",
"db_finalclass_field" => "", "db_finalclass_field" => "",
"is_link" => true, /** @since 3.1.0 N°6482 */ "is_link" => true, /** @since 3.1.0 N°6482 */
'uniqueness_rules' => [ 'uniqueness_rules' => array(
'no_duplicate' => [ 'no_duplicate' => array(
'attributes' => [ 'attributes' => array(
0 => 'userid', 0 => 'userid',
1 => 'profileid', 1 => 'profileid',
], ),
'filter' => '', 'filter' => '',
'disabled' => false, 'disabled' => false,
'is_blocking' => true, 'is_blocking' => true,
], ),
], ),
]; );
MetaModel::Init_Params($aParams); MetaModel::Init_Params($aParams);
//MetaModel::Init_InheritAttributes(); //MetaModel::Init_InheritAttributes();
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 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", ["allowed_values" => null, "extkey_attcode" => 'userid', "target_attcode" => "login"])); MetaModel::Init_AddAttribute(new AttributeExternalField("userlogin", array("allowed_values" => null, "extkey_attcode" => 'userid', "target_attcode" => "login")));
MetaModel::Init_AddAttribute(new AttributeExternalKey( MetaModel::Init_AddAttribute(new AttributeExternalKey("profileid",
"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)));
["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", array("allowed_values" => null, "extkey_attcode" => 'profileid', "target_attcode" => "name")));
));
MetaModel::Init_AddAttribute(new AttributeExternalField("profile", ["allowed_values" => null, "extkey_attcode" => 'profileid', "target_attcode" => "name"]));
MetaModel::Init_AddAttribute(new AttributeString("reason", ["allowed_values" => null, "sql" => "description", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); MetaModel::Init_AddAttribute(new AttributeString("reason", array("allowed_values" => null, "sql" => "description", "default_value" => null, "is_null_allowed" => true, "depends_on" => array())));
// Display lists // Display lists
MetaModel::Init_SetZListItems('details', ['userid', 'profileid', 'reason']); // Attributes to be displayed for the complete details MetaModel::Init_SetZListItems('details', array('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 MetaModel::Init_SetZListItems('list', array('userid', 'profileid', 'reason')); // Attributes to be displayed for a list
// Search criteria // Search criteria
MetaModel::Init_SetZListItems('standard_search', ['userid', 'profileid']); // Criteria of the std search form MetaModel::Init_SetZListItems('standard_search', array('userid', 'profileid')); // Criteria of the std search form
MetaModel::Init_SetZListItems('advanced_search', ['userid', 'profileid']); // Criteria of the advanced search form MetaModel::Init_SetZListItems('advanced_search', array('userid', 'profileid')); // Criteria of the advanced search form
} }
public function CheckToDelete(&$oDeletionPlan) public function CheckToDelete(&$oDeletionPlan)
@@ -251,14 +267,15 @@ class URP_UserProfile extends UserRightsBaseClassGUI
if (MetaModel::GetConfig()->Get('demo_mode')) { if (MetaModel::GetConfig()->Get('demo_mode')) {
// Users deletion is NOT allowed in demo mode // Users deletion is NOT allowed in demo mode
$oDeletionPlan->AddToDelete($this, null); $oDeletionPlan->AddToDelete($this, null);
$oDeletionPlan->SetDeletionIssues($this, ['deletion not allowed in demo mode.'], true); $oDeletionPlan->SetDeletionIssues($this, array('deletion not allowed in demo mode.'), true);
$oDeletionPlan->ComputeResults(); $oDeletionPlan->ComputeResults();
return false; return false;
} }
try { try {
$this->CheckIfProfileIsAllowed(UR_ACTION_DELETE); $this->CheckIfProfileIsAllowed(UR_ACTION_DELETE);
} catch (SecurityException $e) { }
catch (SecurityException $e) {
// Users deletion is NOT allowed // Users deletion is NOT allowed
$oDeletionPlan->AddToDelete($this, null); $oDeletionPlan->AddToDelete($this, null);
$oDeletionPlan->SetDeletionIssues($this, [$e->getMessage()], true); $oDeletionPlan->SetDeletionIssues($this, [$e->getMessage()], true);
@@ -275,14 +292,15 @@ class URP_UserProfile extends UserRightsBaseClassGUI
if (MetaModel::GetConfig()->Get('demo_mode')) { if (MetaModel::GetConfig()->Get('demo_mode')) {
// Users deletion is NOT allowed in demo mode // Users deletion is NOT allowed in demo mode
$oDeletionPlan->AddToDelete($this, null); $oDeletionPlan->AddToDelete($this, null);
$oDeletionPlan->SetDeletionIssues($this, ['deletion not allowed in demo mode.'], true); $oDeletionPlan->SetDeletionIssues($this, array('deletion not allowed in demo mode.'), true);
$oDeletionPlan->ComputeResults(); $oDeletionPlan->ComputeResults();
return false; return false;
} }
try { try {
$this->CheckIfProfileIsAllowed(UR_ACTION_DELETE); $this->CheckIfProfileIsAllowed(UR_ACTION_DELETE);
} catch (SecurityException $e) { }
catch (SecurityException $e) {
// Users deletion is NOT allowed // Users deletion is NOT allowed
$oDeletionPlan->AddToDelete($this, null); $oDeletionPlan->AddToDelete($this, null);
$oDeletionPlan->SetDeletionIssues($this, [$e->getMessage()], true); $oDeletionPlan->SetDeletionIssues($this, [$e->getMessage()], true);
@@ -318,30 +336,29 @@ class URP_UserProfile extends UserRightsBaseClassGUI
protected function CheckIfProfileIsAllowed($iActionCode) protected function CheckIfProfileIsAllowed($iActionCode)
{ {
// When initializing or admin, we need to let everything pass trough // When initializing or admin, we need to let everything pass trough
if (!UserRights::IsLoggedIn() || UserRights::IsAdministrator()) { if (!UserRights::IsLoggedIn() || UserRights::IsAdministrator()) { return; }
return;
}
// Only administrators can manage administrators // Only administrators can manage administrators
$iOrigUserId = $this->GetOriginal('userid'); $iOrigUserId = $this->GetOriginal('userid');
if (!empty($iOrigUserId)) { if (!empty($iOrigUserId))
{
$oUser = MetaModel::GetObject('User', $iOrigUserId, true, true); $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')); throw new SecurityException(Dict::Format('UI:Login:Error:AccessRestricted'));
} }
} }
$oUser = MetaModel::GetObject('User', $this->Get('userid'), true, true); $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')); throw new SecurityException(Dict::Format('UI:Login:Error:AccessRestricted'));
} }
if (!UserRights::IsActionAllowed(get_class($this), $iActionCode, DBObjectSet::FromObject($this)))
$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)) {
throw new SecurityException(Dict::Format('UI:Error:ObjectCannotBeUpdated')); 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')); throw new SecurityException(Dict::Format('UI:Login:Error:AccessAdmin'));
} }
} }
@@ -352,33 +369,33 @@ class URP_UserOrg extends UserRightsBaseClassGUI
{ {
public static function Init() public static function Init()
{ {
$aParams = $aParams = array
[ (
"category" => "addon/userrights,grant_by_profile", "category" => "addon/userrights,grant_by_profile",
"key_type" => "autoincrement", "key_type" => "autoincrement",
"name_attcode" => ["userlogin", "allowed_org_name"], "name_attcode" => array("userlogin", "allowed_org_name"),
"state_attcode" => "", "state_attcode" => "",
"reconc_keys" => [], "reconc_keys" => array(),
"db_table" => "priv_urp_userorg", "db_table" => "priv_urp_userorg",
"db_key_field" => "id", "db_key_field" => "id",
"db_finalclass_field" => "", "db_finalclass_field" => "",
]; );
MetaModel::Init_Params($aParams); MetaModel::Init_Params($aParams);
//MetaModel::Init_InheritAttributes(); //MetaModel::Init_InheritAttributes();
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 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", ["allowed_values" => null, "extkey_attcode" => 'userid', "target_attcode" => "login"])); MetaModel::Init_AddAttribute(new AttributeExternalField("userlogin", array("allowed_values"=>null, "extkey_attcode"=> 'userid', "target_attcode"=>"login")));
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 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", ["allowed_values" => null, "extkey_attcode" => 'allowed_org_id', "target_attcode" => "name"])); MetaModel::Init_AddAttribute(new AttributeExternalField("allowed_org_name", array("allowed_values"=>null, "extkey_attcode"=> 'allowed_org_id', "target_attcode"=>"name")));
MetaModel::Init_AddAttribute(new AttributeString("reason", ["allowed_values" => null, "sql" => "reason", "default_value" => null, "is_null_allowed" => true, "depends_on" => []])); MetaModel::Init_AddAttribute(new AttributeString("reason", array("allowed_values"=>null, "sql"=>"reason", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
// Display lists // Display lists
MetaModel::Init_SetZListItems('details', ['userid', 'allowed_org_id', 'reason']); // Attributes to be displayed for the complete details MetaModel::Init_SetZListItems('details', array('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 MetaModel::Init_SetZListItems('list', array('allowed_org_id', 'reason')); // Attributes to be displayed for a list
// Search criteria // Search criteria
MetaModel::Init_SetZListItems('standard_search', ['userid', 'allowed_org_id']); // Criteria of the std search form MetaModel::Init_SetZListItems('standard_search', array('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 MetaModel::Init_SetZListItems('advanced_search', array('userid', 'allowed_org_id')); // Criteria of the advanced search form
} }
protected function OnInsert() protected function OnInsert()
@@ -401,37 +418,40 @@ class URP_UserOrg extends UserRightsBaseClassGUI
*/ */
protected function CheckIfOrgIsAllowed() protected function CheckIfOrgIsAllowed()
{ {
if (!UserRights::IsLoggedIn() || UserRights::IsAdministrator()) { if (!UserRights::IsLoggedIn() || UserRights::IsAdministrator()) { return; }
return;
}
$oUser = UserRights::GetUserObject(); $oUser = UserRights::GetUserObject();
$oAddon = UserRights::GetModuleInstance(); $oAddon = UserRights::GetModuleInstance();
$aOrgs = $oAddon->GetUserOrgs($oUser, ''); $aOrgs = $oAddon->GetUserOrgs($oUser, '');
if (count($aOrgs) > 0) { if (count($aOrgs) > 0)
{
$iOrigOrgId = $this->GetOriginal('allowed_org_id'); $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')); throw new SecurityException(Dict::Format('Class:User/Error:OrganizationNotAllowed'));
} }
} }
} }
} }
class UserRightsProfile extends UserRightsAddOnAPI class UserRightsProfile extends UserRightsAddOnAPI
{ {
public static $m_aActionCodes = [ static public $m_aActionCodes = array(
UR_ACTION_READ => 'r', UR_ACTION_READ => 'r',
UR_ACTION_MODIFY => 'w', UR_ACTION_MODIFY => 'w',
UR_ACTION_DELETE => 'd', UR_ACTION_DELETE => 'd',
UR_ACTION_BULK_READ => 'br', UR_ACTION_BULK_READ => 'br',
UR_ACTION_BULK_MODIFY => 'bw', UR_ACTION_BULK_MODIFY => 'bw',
UR_ACTION_BULK_DELETE => 'bd', 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, ...] * @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 * @since 2.7.10 3.0.4 3.1.1 3.2.0 N°6887
*/ */
private $aUsersProfilesList = []; private $aUsersProfilesList = [];
// Installation: create the very first user // Installation: create the very first user
@@ -452,7 +472,8 @@ class UserRightsProfile extends UserRightsAddOnAPI
$oContact = MetaModel::NewObject('Person'); $oContact = MetaModel::NewObject('Person');
$oContact->Set('name', 'My last name'); $oContact->Set('name', 'My last name');
$oContact->Set('first_name', 'My first 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('org_id', $iOrgId);
} }
$oContact->Set('email', 'my.email@foo.org'); $oContact->Set('email', 'my.email@foo.org');
@@ -460,19 +481,24 @@ class UserRightsProfile extends UserRightsAddOnAPI
} }
} }
$oUser = new UserLocal(); $oUser = new UserLocal();
$oUser->Set('login', $sAdminUser); $oUser->Set('login', $sAdminUser);
$oUser->Set('password', $sAdminPwd); $oUser->Set('password', $sAdminPwd);
if (MetaModel::IsValidAttCode('UserLocal', 'contactid') && ($iContactId != 0)) { if (MetaModel::IsValidAttCode('UserLocal', 'contactid') && ($iContactId != 0))
{
$oUser->Set('contactid', $iContactId); $oUser->Set('contactid', $iContactId);
} }
$oUser->Set('language', $sLanguage); // Language was chosen during the installation $oUser->Set('language', $sLanguage); // Language was chosen during the installation
// Add this user to the very specific 'admin' profile // Add this user to the very specific 'admin' profile
$oAdminProfile = MetaModel::GetObjectFromOQL("SELECT URP_Profiles WHERE name = :name", ['name' => ADMIN_PROFILE_NAME], true /*all data*/); $oAdminProfile = MetaModel::GetObjectFromOQL("SELECT URP_Profiles WHERE name = :name", array('name' => ADMIN_PROFILE_NAME), true /*all data*/);
if (is_object($oAdminProfile)) { 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'])); $oUserProfile = new URP_UserProfile();
$oUserProfile->Set('profileid', $oAdminProfile->GetKey());
$oUserProfile->Set('reason', 'By definition, the administrator must have the administrator profile');
$oSet = DBObjectSet::FromObject($oUserProfile);
$oUser->Set('profile_list', $oSet); $oUser->Set('profile_list', $oSet);
} }
$iUserId = $oUser->DBInsertNoReload(); $iUserId = $oUser->DBInsertNoReload();
@@ -483,11 +509,11 @@ class UserRightsProfile extends UserRightsAddOnAPI
{ {
} }
protected $m_aUserOrgs = []; // userid -> array of orgid protected $m_aUserOrgs = array(); // userid -> array of orgid
protected $m_aAdministrators = null; // [user id] 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) // Built on demand, could be optimized if necessary (doing a query for each attribute that needs to be read)
protected $m_aObjectActionGrants = []; protected $m_aObjectActionGrants = array();
/** /**
* Read and cache organizations allowed to the given user * Read and cache organizations allowed to the given user
@@ -502,25 +528,31 @@ class UserRightsProfile extends UserRightsAddOnAPI
public function GetUserOrgs($oUser, $sClass) public function GetUserOrgs($oUser, $sClass)
{ {
$iUser = $oUser->GetKey(); $iUser = $oUser->GetKey();
if (!array_key_exists($iUser, $this->m_aUserOrgs)) { if (!array_key_exists($iUser, $this->m_aUserOrgs))
$this->m_aUserOrgs[$iUser] = []; {
$this->m_aUserOrgs[$iUser] = array();
$sHierarchicalKeyCode = MetaModel::IsHierarchicalClass('Organization'); $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'; $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), [], ['userid' => $iUser]); $oUserOrgSet = new DBObjectSet(DBObjectSearch::FromOQL_AllData($sUserOrgQuery), array(), array('userid' => $iUser));
while ($aRow = $oUserOrgSet->FetchAssoc()) { while ($aRow = $oUserOrgSet->FetchAssoc())
{
$oOrg = $aRow['Org']; $oOrg = $aRow['Org'];
$this->m_aUserOrgs[$iUser][] = $oOrg->GetKey(); $this->m_aUserOrgs[$iUser][] = $oOrg->GetKey();
} }
} else { }
else
{
$oSearch = new DBObjectSearch('URP_UserOrg'); $oSearch = new DBObjectSearch('URP_UserOrg');
$oSearch->AllowAllData(); $oSearch->AllowAllData();
$oCondition = new BinaryExpression(new FieldExpression('userid'), '=', new VariableExpression('userid')); $oCondition = new BinaryExpression(new FieldExpression('userid'), '=', new VariableExpression('userid'));
$oSearch->AddConditionExpression($oCondition); $oSearch->AddConditionExpression($oCondition);
$oUserOrgSet = new DBObjectSet($oSearch, [], ['userid' => $iUser]); $oUserOrgSet = new DBObjectSet($oSearch, array(), array('userid' => $iUser));
while ($oUserOrg = $oUserOrgSet->Fetch()) { while ($oUserOrg = $oUserOrgSet->Fetch())
{
$this->m_aUserOrgs[$iUser][] = $oUserOrg->Get('allowed_org_id'); $this->m_aUserOrgs[$iUser][] = $oUserOrg->Get('allowed_org_id');
} }
} }
@@ -531,20 +563,21 @@ class UserRightsProfile extends UserRightsAddOnAPI
public function ResetCache() public function ResetCache()
{ {
// Loaded by Load cache // Loaded by Load cache
$this->m_aUserOrgs = []; $this->m_aUserOrgs = array();
// Cache // Cache
$this->m_aObjectActionGrants = []; $this->m_aObjectActionGrants = array();
$this->m_aAdministrators = null; $this->m_aAdministrators = null;
$this->aUsersProfilesList = [];
} }
public function LoadCache() public function LoadCache()
{ {
static $bSharedObjectInitialized = false; static $bSharedObjectInitialized = false;
if (!$bSharedObjectInitialized) { if (!$bSharedObjectInitialized)
{
$bSharedObjectInitialized = true; $bSharedObjectInitialized = true;
if (self::HasSharing()) { if (self::HasSharing())
{
SharedObject::InitSharedClassProperties(); SharedObject::InitSharedClassProperties();
} }
} }
@@ -582,40 +615,45 @@ class UserRightsProfile extends UserRightsAddOnAPI
*/ */
public function ListProfiles($oUser) public function ListProfiles($oUser)
{ {
$aRet = []; $aRet = array();
$oSearch = new DBObjectSearch('URP_UserProfile'); $oSearch = new DBObjectSearch('URP_UserProfile');
$oSearch->AllowAllData(); $oSearch->AllowAllData();
$oSearch->NoContextParameters(); $oSearch->NoContextParameters();
$oSearch->Addcondition('userid', $oUser->GetKey(), '='); $oSearch->Addcondition('userid', $oUser->GetKey(), '=');
$oProfiles = new DBObjectSet($oSearch); $oProfiles = new DBObjectSet($oSearch);
while ($oUserProfile = $oProfiles->Fetch()) { while ($oUserProfile = $oProfiles->Fetch())
{
$aRet[$oUserProfile->Get('profileid')] = $oUserProfile->Get('profileid_friendlyname'); $aRet[$oUserProfile->Get('profileid')] = $oUserProfile->Get('profileid_friendlyname');
} }
return $aRet; return $aRet;
} }
public function GetSelectFilter($oUser, $sClass, $aSettings = []) public function GetSelectFilter($oUser, $sClass, $aSettings = array())
{ {
$this->LoadCache(); $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 // 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) // 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) // 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); $aObjectPermissions = $this->GetUserActionGrant($oUser, $sClass, UR_ACTION_READ);
if ($aObjectPermissions['permission'] == UR_ALLOWED_NO) { if ($aObjectPermissions['permission'] == UR_ALLOWED_NO)
{
return false; return false;
} }
} }
$oFilter = true; $oFilter = true;
$aConditions = []; $aConditions = array();
// Determine if this class is part of a silo and build the filter for it // Determine if this class is part of a silo and build the filter for it
$sAttCode = self::GetOwnerOrganizationAttCode($sClass); $sAttCode = self::GetOwnerOrganizationAttCode($sClass);
if (!is_null($sAttCode)) { if (!is_null($sAttCode))
{
$aUserOrgs = $this->GetUserOrgs($oUser, $sClass); $aUserOrgs = $this->GetUserOrgs($oUser, $sClass);
if (count($aUserOrgs) > 0) { if (count($aUserOrgs) > 0)
{
$oFilter = $this->MakeSelectFilter($sClass, $aUserOrgs, $aSettings, $sAttCode); $oFilter = $this->MakeSelectFilter($sClass, $aUserOrgs, $aSettings, $sAttCode);
} }
// else: No org means 'any org' // else: No org means 'any org'
@@ -624,15 +662,20 @@ class UserRightsProfile extends UserRightsAddOnAPI
// Specific conditions to hide, for non-administrators, the Administrator Users, the Administrator Profile and related links // 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. // Note: when logged as an administrator, GetSelectFilter is completely bypassed.
if ($this->AdministratorsAreHidden()) { if ($this->AdministratorsAreHidden())
if ($sClass == 'URP_Profiles') { {
if ($sClass == 'URP_Profiles')
{
$oExpression = new FieldExpression('id', $sClass); $oExpression = new FieldExpression('id', $sClass);
$oScalarExpr = new ScalarExpression(1); $oScalarExpr = new ScalarExpression(1);
$aConditions[] = new BinaryExpression($oExpression, '!=', $oScalarExpr); $aConditions[] = new BinaryExpression($oExpression, '!=', $oScalarExpr);
} elseif (($sClass == 'URP_UserProfile') || ($sClass == 'User') || (is_subclass_of($sClass, 'User'))) { }
else if (($sClass == 'URP_UserProfile') || ($sClass == 'User') || (is_subclass_of($sClass, 'User')))
{
$aAdministrators = $this->GetAdministrators(); $aAdministrators = $this->GetAdministrators();
if (count($aAdministrators) > 0) { if (count($aAdministrators) > 0)
{
$sAttCode = ($sClass == 'URP_UserProfile') ? 'userid' : 'id'; $sAttCode = ($sClass == 'URP_UserProfile') ? 'userid' : 'id';
$oExpression = new FieldExpression($sAttCode, $sClass); $oExpression = new FieldExpression($sAttCode, $sClass);
$oListExpr = ListExpression::FromScalars($aAdministrators); $oListExpr = ListExpression::FromScalars($aAdministrators);
@@ -642,14 +685,17 @@ class UserRightsProfile extends UserRightsAddOnAPI
} }
// Handling of the added conditions // Handling of the added conditions
if (count($aConditions) > 0) { if (count($aConditions) > 0)
if ($oFilter === true) { {
if($oFilter === true)
{
// No 'silo' filter, let's build a clean one // No 'silo' filter, let's build a clean one
$oFilter = new DBObjectSearch($sClass); $oFilter = new DBObjectSearch($sClass);
} }
// Add the conditions to the filter // Add the conditions to the filter
foreach ($aConditions as $oCondition) { foreach($aConditions as $oCondition)
{
$oFilter->AddConditionExpression($oCondition); $oFilter->AddConditionExpression($oCondition);
} }
} }
@@ -664,9 +710,10 @@ class UserRightsProfile extends UserRightsAddOnAPI
*/ */
private function GetAdministrators() private function GetAdministrators()
{ {
if ($this->m_aAdministrators === null) { if ($this->m_aAdministrators === null)
{
// Find all administrators // Find all administrators
$this->m_aAdministrators = []; $this->m_aAdministrators = array();
$oAdministratorsFilter = new DBObjectSearch('User'); $oAdministratorsFilter = new DBObjectSearch('User');
$oLnkFilter = new DBObjectSearch('URP_UserProfile'); $oLnkFilter = new DBObjectSearch('URP_UserProfile');
$oExpression = new FieldExpression('profileid', 'URP_UserProfile'); $oExpression = new FieldExpression('profileid', 'URP_UserProfile');
@@ -676,8 +723,9 @@ class UserRightsProfile extends UserRightsAddOnAPI
$oAdministratorsFilter->AddCondition_ReferencedBy($oLnkFilter, 'userid'); $oAdministratorsFilter->AddCondition_ReferencedBy($oLnkFilter, 'userid');
$oAdministratorsFilter->AllowAllData(true); // Mandatory to prevent infinite recursion !! $oAdministratorsFilter->AllowAllData(true); // Mandatory to prevent infinite recursion !!
$oSet = new DBObjectSet($oAdministratorsFilter); $oSet = new DBObjectSet($oAdministratorsFilter);
$oSet->OptimizeColumnLoad(['User' => ['login']]); $oSet->OptimizeColumnLoad(array('User' => array('login')));
while ($oUser = $oSet->Fetch()) { while($oUser = $oSet->Fetch())
{
$this->m_aAdministrators[] = $oUser->GetKey(); $this->m_aAdministrators[] = $oUser->GetKey();
} }
} }
@@ -693,6 +741,7 @@ class UserRightsProfile extends UserRightsAddOnAPI
return ((bool)MetaModel::GetConfig()->Get('security.hide_administrators')); 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 // This verb has been made public to allow the development of an accurate feedback for the current configuration
public function GetProfileActionGrant($iProfile, $sClass, $sAction) public function GetProfileActionGrant($iProfile, $sClass, $sAction)
{ {
@@ -709,29 +758,33 @@ class UserRightsProfile extends UserRightsAddOnAPI
// load and cache permissions for the current user on the given class // load and cache permissions for the current user on the given class
// //
$iUser = $oUser->GetKey(); $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]; $aTest = $this->m_aObjectActionGrants[$iUser][$sClass][$iActionCode];
if (is_array($aTest)) { if (is_array($aTest)) return $aTest;
return $aTest;
}
} }
$sAction = self::$m_aActionCodes[$iActionCode]; $sAction = self::$m_aActionCodes[$iActionCode];
$bStatus = null; $bStatus = null;
// Cache user's profiles // Cache user's profiles
if (false === array_key_exists($iUser, $this->aUsersProfilesList)) { if(false === array_key_exists($iUser, $this->aUsersProfilesList)){
$this->aUsersProfilesList[$iUser] = UserRights::ListProfiles($oUser); $this->aUsersProfilesList[$iUser] = UserRights::ListProfiles($oUser);
} }
// Call the API of UserRights because it caches the list for us // 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); $bGrant = $this->GetProfileActionGrant($iProfile, $sClass, $sAction);
if (!is_null($bGrant)) { if (!is_null($bGrant))
if ($bGrant) { {
if (is_null($bStatus)) { if ($bGrant)
{
if (is_null($bStatus))
{
$bStatus = true; $bStatus = true;
} }
} else { }
else
{
$bStatus = false; $bStatus = false;
} }
} }
@@ -739,9 +792,9 @@ class UserRightsProfile extends UserRightsAddOnAPI
$iPermission = $bStatus ? UR_ALLOWED_YES : UR_ALLOWED_NO; $iPermission = $bStatus ? UR_ALLOWED_YES : UR_ALLOWED_NO;
$aRes = [ $aRes = array(
'permission' => $iPermission, 'permission' => $iPermission,
]; );
$this->m_aObjectActionGrants[$iUser][$sClass][$iActionCode] = $aRes; $this->m_aObjectActionGrants[$iUser][$sClass][$iActionCode] = $aRes;
return $aRes; return $aRes;
} }
@@ -756,13 +809,20 @@ class UserRightsProfile extends UserRightsAddOnAPI
// Note: In most cases the object set is ignored because it was interesting to optimize for huge data sets // 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 // 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! // 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 // 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 // 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 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 // We have to answer NO for objects shared for reading purposes
if (self::HasSharing() && SharedObject::GetSharedClassProperties($sClass)) { if (self::HasSharing() && SharedObject::GetSharedClassProperties($sClass)) {
@@ -826,8 +886,8 @@ class UserRightsProfile extends UserRightsAddOnAPI
// Note: this code is VERY close to the code of IsActionAllowed() // Note: this code is VERY close to the code of IsActionAllowed()
$iUser = $oUser->GetKey(); $iUser = $oUser->GetKey();
// Cache user's profiles // Cache user's profiles
if (false === array_key_exists($iUser, $this->aUsersProfilesList)) { if(false === array_key_exists($iUser, $this->aUsersProfilesList)){
$this->aUsersProfilesList[$iUser] = UserRights::ListProfiles($oUser); $this->aUsersProfilesList[$iUser] = UserRights::ListProfiles($oUser);
} }
@@ -835,14 +895,20 @@ class UserRightsProfile extends UserRightsAddOnAPI
// and acceptable to consider only the root class of the object set // and acceptable to consider only the root class of the object set
$bStatus = null; $bStatus = null;
// Call the API of UserRights because it caches the list for us // 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); $bGrant = $this->GetClassStimulusGrant($iProfile, $sClass, $sStimulusCode);
if (!is_null($bGrant)) { if (!is_null($bGrant))
if ($bGrant) { {
if (is_null($bStatus)) { if ($bGrant)
{
if (is_null($bStatus))
{
$bStatus = true; $bStatus = true;
} }
} else { }
else
{
$bStatus = false; $bStatus = false;
} }
} }
@@ -866,16 +932,22 @@ class UserRightsProfile extends UserRightsAddOnAPI
{ {
$sAttCode = null; $sAttCode = null;
$aCallSpec = [$sClass, 'MapContextParam']; $aCallSpec = array($sClass, 'MapContextParam');
if (($sClass == 'Organization') || is_subclass_of($sClass, 'Organization')) { if (($sClass == 'Organization') || is_subclass_of($sClass, 'Organization'))
{
$sAttCode = 'id'; $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 $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... // Skip silently. The data model checker will tell you something about this...
$sAttCode = null; $sAttCode = null;
} }
} elseif (MetaModel::IsValidAttCode($sClass, 'org_id')) { }
elseif(MetaModel::IsValidAttCode($sClass, 'org_id'))
{
$sAttCode = 'org_id'; $sAttCode = 'org_id';
} }
@@ -888,11 +960,14 @@ class UserRightsProfile extends UserRightsAddOnAPI
protected static function HasSharing() protected static function HasSharing()
{ {
static $bHasSharing; static $bHasSharing;
if (!isset($bHasSharing)) { if (!isset($bHasSharing))
{
$bHasSharing = class_exists('SharedObject'); $bHasSharing = class_exists('SharedObject');
} }
return $bHasSharing; return $bHasSharing;
} }
} }
UserRights::SelectModule('UserRightsProfile'); UserRights::SelectModule('UserRightsProfile');

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -49,7 +48,8 @@ class DBSearchHelper
$oHKFilter->AddCondition_PointingTo($oFilter, $sHierarchicalKeyCode, TREE_OPERATOR_BELOW); $oHKFilter->AddCondition_PointingTo($oFilter, $sHierarchicalKeyCode, TREE_OPERATOR_BELOW);
$oSearch->AddCondition_PointingTo($oHKFilter, $sAttCode); $oSearch->AddCondition_PointingTo($oHKFilter, $sAttCode);
} }
} catch (Exception $e) { }
catch (Exception $e) {
// If filtering fails just ignore it // If filtering fails just ignore it
} }
} }
@@ -57,4 +57,4 @@ class DBSearchHelper
} }
} }
} }
} }

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0

View File

@@ -1,10 +1,9 @@
<?php <?php
// Copyright (C) 2010-2024 Combodo SAS // Copyright (C) 2010-2024 Combodo SAS
// //
// This file is part of iTop. // This file is part of iTop.
// //
// iTop is free software; you can redistribute it and/or modify // iTop is free software; you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by // it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
@@ -17,6 +16,7 @@
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with iTop. If not, see <http://www.gnu.org/licenses/> // along with iTop. If not, see <http://www.gnu.org/licenses/>
/** /**
* Class ApplicationContext * Class ApplicationContext
* *
@@ -47,16 +47,16 @@ interface iDBObjectURLMaker
/** /**
* Direct end-users to the standard iTop application: UI.php * Direct end-users to the standard iTop application: UI.php
*/ */
class iTopStandardURLMaker implements iDBObjectURLMaker class iTopStandardURLMaker implements iDBObjectURLMaker
{ {
/** /**
* @param string $sClass * @param string $sClass
* @param string $iId * @param string $iId
* *
* @return string * @return string
* @throws \Exception * @throws \Exception
*/ */
public static function MakeObjectURL($sClass, $iId) public static function MakeObjectURL($sClass, $iId)
{ {
$sPage = DBObject::ComputeStandardUIPage($sClass); $sPage = DBObject::ComputeStandardUIPage($sClass);
@@ -68,16 +68,16 @@ class iTopStandardURLMaker implements iDBObjectURLMaker
/** /**
* Direct end-users to the standard Portal application * Direct end-users to the standard Portal application
*/ */
class PortalURLMaker implements iDBObjectURLMaker class PortalURLMaker implements iDBObjectURLMaker
{ {
/** /**
* @param string $sClass * @param string $sClass
* @param string $iId * @param string $iId
* *
* @return string * @return string
* @throws \Exception * @throws \Exception
*/ */
public static function MakeObjectURL($sClass, $iId) public static function MakeObjectURL($sClass, $iId)
{ {
$sAbsoluteUrl = utils::GetAbsoluteUrlAppRoot(); $sAbsoluteUrl = utils::GetAbsoluteUrlAppRoot();
@@ -86,6 +86,7 @@ class PortalURLMaker implements iDBObjectURLMaker
} }
} }
/** /**
* Helper class to store and manipulate the parameters that make the application's context * Helper class to store and manipulate the parameters that make the application's context
* *
@@ -98,90 +99,99 @@ class PortalURLMaker implements iDBObjectURLMaker
*/ */
class ApplicationContext class ApplicationContext
{ {
public static $m_sUrlMakerClass = null; public static $m_sUrlMakerClass = null;
protected static $m_aPluginProperties = null; protected static $m_aPluginProperties = null;
protected static $aDefaultValues; // Cache shared among all instances protected static $aDefaultValues; // Cache shared among all instances
protected $aNames; protected $aNames;
protected $aValues; protected $aValues;
/** /**
* ApplicationContext constructor. * ApplicationContext constructor.
* *
* @param bool $bReadContext * @param bool $bReadContext
* *
* @throws \Exception * @throws \Exception
*/ */
public function __construct($bReadContext = true) public function __construct($bReadContext = true)
{ {
$this->aNames = [ $this->aNames = array(
'org_id', 'menu', 'org_id', 'menu'
]; );
if ($bReadContext) { if ($bReadContext)
$this->ReadContext(); {
$this->ReadContext();
} }
} }
/** /**
* Read the context directly in the PHP parameters (either POST or GET) * Read the context directly in the PHP parameters (either POST or GET)
* return nothing * return nothing
* *
* @throws \Exception * @throws \Exception
*/ */
protected function ReadContext() protected function ReadContext()
{ {
if (!isset(self::$aDefaultValues)) { if (!isset(self::$aDefaultValues))
self::$aDefaultValues = []; {
$aContext = utils::ReadParam('c', [], false, 'context_param'); self::$aDefaultValues = array();
foreach ($this->aNames as $sName) { $aContext = utils::ReadParam('c', array(), false, 'context_param');
foreach($this->aNames as $sName)
{
$sValue = isset($aContext[$sName]) ? $aContext[$sName] : ''; $sValue = isset($aContext[$sName]) ? $aContext[$sName] : '';
// TO DO: check if some of the context parameters are mandatory (or have default values) // TO DO: check if some of the context parameters are mandatory (or have default values)
if (!empty($sValue)) { if (!empty($sValue))
{
self::$aDefaultValues[$sName] = $sValue; self::$aDefaultValues[$sName] = $sValue;
} }
// Hmm, there must be a better (more generic) way to handle the case below: // Hmm, there must be a better (more generic) way to handle the case below:
// When there is only one possible (allowed) organization, the context must be // When there is only one possible (allowed) organization, the context must be
// fixed to this org unless there is only one organization in the system then // fixed to this org unless there is only one organization in the system then
// no filter is applied // no filter is applied
if ($sName == 'org_id') { if ($sName == 'org_id')
if (MetaModel::IsValidClass('Organization')) { {
if (MetaModel::IsValidClass('Organization'))
{
$oSearchFilter = new DBObjectSearch('Organization'); $oSearchFilter = new DBObjectSearch('Organization');
$oSet = new CMDBObjectSet($oSearchFilter); $oSet = new CMDBObjectSet($oSearchFilter);
$iCount = $oSet->CountWithLimit(2); $iCount = $oSet->CountWithLimit(2);
if ($iCount > 1) { if ($iCount > 1)
{
$oSearchFilter->SetModifierProperty('UserRightsGetSelectFilter', 'bSearchMode', true); $oSearchFilter->SetModifierProperty('UserRightsGetSelectFilter', 'bSearchMode', true);
$oSet = new CMDBObjectSet($oSearchFilter); $oSet = new CMDBObjectSet($oSearchFilter);
$iCount = $oSet->CountWithLimit(2); $iCount = $oSet->CountWithLimit(2);
if ($iCount == 1) { if ($iCount == 1)
{
// Only one possible value for org_id, set it in the context // Only one possible value for org_id, set it in the context
$oOrg = $oSet->Fetch(); $oOrg = $oSet->Fetch();
self::$aDefaultValues[$sName] = $oOrg->GetKey(); self::$aDefaultValues[$sName] = $oOrg->GetKey();
} }
} }
} }
} }
} }
} }
$this->aValues = self::$aDefaultValues; $this->aValues = self::$aDefaultValues;
} }
/** /**
* Returns the current value for the given parameter * Returns the current value for the given parameter
* *
* @param string $sParamName Name of the parameter to read * @param string $sParamName Name of the parameter to read
* @param string $defaultValue * @param string $defaultValue
* *
* @return mixed The value for this parameter * @return mixed The value for this parameter
*/ */
public function GetCurrentValue($sParamName, $defaultValue = '') public function GetCurrentValue($sParamName, $defaultValue = '')
{ {
if (isset($this->aValues[$sParamName])) { if (isset($this->aValues[$sParamName]))
{
return $this->aValues[$sParamName]; return $this->aValues[$sParamName];
} }
return $defaultValue; return $defaultValue;
} }
/** /**
* Returns the context as string with the format name1=value1&name2=value2.... * Returns the context as string with the format name1=value1&name2=value2....
* @return string The context as a string to be appended to an href property * @return string The context as a string to be appended to an href property
@@ -190,20 +200,21 @@ class ApplicationContext
public function GetForLink(bool $bWithLeadingAmpersand = false) public function GetForLink(bool $bWithLeadingAmpersand = false)
{ {
// If there are no parameters, return an empty string // If there are no parameters, return an empty string
if (empty($this->aValues)) { if(empty($this->aValues)){
return ''; return '';
} }
// Build the query string with ampersand separated parameters // Build the query string with ampersand separated parameters
$aParams = []; $aParams = array();
foreach ($this->aValues as $sName => $sValue) { foreach($this->aValues as $sName => $sValue)
{
$aParams[] = "c[$sName]".'='.urlencode($sValue); $aParams[] = "c[$sName]".'='.urlencode($sValue);
} }
$sReturnValue = implode('&', $aParams); $sReturnValue = implode('&', $aParams);
// add the leading ampersand if requested // add the leading ampersand if requested
if ($bWithLeadingAmpersand) { if($bWithLeadingAmpersand){
$sReturnValue = '&'.$sReturnValue; $sReturnValue = '&' . $sReturnValue;
} }
return $sReturnValue; return $sReturnValue;
@@ -267,13 +278,14 @@ class ApplicationContext
*/ */
public function GetAsHash() public function GetAsHash()
{ {
$aReturn = []; $aReturn = array();
foreach ($this->aValues as $sName => $sValue) { foreach($this->aValues as $sName => $sValue)
{
$aReturn["c[$sName]"] = $sValue; $aReturn["c[$sName]"] = $sValue;
} }
return $aReturn; return $aReturn;
} }
/** /**
* Returns an array of the context parameters NAMEs * Returns an array of the context parameters NAMEs
* @return array The list of context parameters * @return array The list of context parameters
@@ -286,10 +298,11 @@ class ApplicationContext
* Removes the specified parameter from the context, for example when the same parameter * Removes the specified parameter from the context, for example when the same parameter
* is already a search parameter * is already a search parameter
* @param string $sParamName Name of the parameter to remove * @param string $sParamName Name of the parameter to remove
*/ */
public function Reset($sParamName) public function Reset($sParamName)
{ {
if (isset($this->aValues[$sParamName])) { if (isset($this->aValues[$sParamName]))
{
unset($this->aValues[$sParamName]); unset($this->aValues[$sParamName]);
} }
} }
@@ -305,22 +318,27 @@ class ApplicationContext
public function InitObjectFromContext(DBObject &$oObj) public function InitObjectFromContext(DBObject &$oObj)
{ {
$sClass = get_class($oObj); $sClass = get_class($oObj);
foreach ($this->GetNames() as $key) { foreach($this->GetNames() as $key)
$aCallSpec = [$sClass, 'MapContextParam']; {
if (is_callable($aCallSpec)) { $aCallSpec = array($sClass, 'MapContextParam');
$sAttCode = call_user_func($aCallSpec, $key); // Returns null when there is no mapping for this parameter if (is_callable($aCallSpec))
{
$sAttCode = call_user_func($aCallSpec, $key); // Returns null when there is no mapping for this parameter
if (MetaModel::IsValidAttCode($sClass, $sAttCode)) { if (MetaModel::IsValidAttCode($sClass, $sAttCode))
{
$oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode); $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
if ($oAttDef->IsWritable()) { if ($oAttDef->IsWritable())
{
$value = $this->GetCurrentValue($key, null); $value = $this->GetCurrentValue($key, null);
if (!is_null($value)) { if (!is_null($value))
{
$oObj->Set($sAttCode, $value); $oObj->Set($sAttCode, $value);
} }
} }
} }
} }
} }
} }
/** /**
@@ -344,10 +362,14 @@ class ApplicationContext
*/ */
public static function GetUrlMakerClass() public static function GetUrlMakerClass()
{ {
if (is_null(self::$m_sUrlMakerClass)) { if (is_null(self::$m_sUrlMakerClass))
if (Session::IsSet('UrlMakerClass')) { {
if (Session::IsSet('UrlMakerClass'))
{
self::$m_sUrlMakerClass = Session::Get('UrlMakerClass'); self::$m_sUrlMakerClass = Session::Get('UrlMakerClass');
} else { }
else
{
self::$m_sUrlMakerClass = 'iTopStandardURLMaker'; self::$m_sUrlMakerClass = 'iTopStandardURLMaker';
} }
} }
@@ -365,23 +387,23 @@ class ApplicationContext
* @return string the name of the class * @return string the name of the class
* @throws \Exception * @throws \Exception
*/ */
public static function MakeObjectUrl($sObjClass, $sObjKey, $sUrlMakerClass = null, $bWithNavigationContext = true) public static function MakeObjectUrl($sObjClass, $sObjKey, $sUrlMakerClass = null, $bWithNavigationContext = true)
{ {
$oAppContext = new ApplicationContext(); $oAppContext = new ApplicationContext();
if (is_null($sUrlMakerClass)) { if (is_null($sUrlMakerClass)) {
$sUrlMakerClass = self::GetUrlMakerClass(); $sUrlMakerClass = self::GetUrlMakerClass();
} }
$sUrl = call_user_func([$sUrlMakerClass, 'MakeObjectUrl'], $sObjClass, $sObjKey); $sUrl = call_user_func(array($sUrlMakerClass, 'MakeObjectUrl'), $sObjClass, $sObjKey);
if (utils::StrLen($sUrl) > 0) { if (utils::StrLen($sUrl) > 0) {
if ($bWithNavigationContext) { if ($bWithNavigationContext) {
return $sUrl.$oAppContext->GetForLink(true); return $sUrl.$oAppContext->GetForLink(true);
} else { } else {
return $sUrl; return $sUrl;
} }
} else { } else {
return ''; return '';
} }
} }
/** /**
@@ -390,10 +412,13 @@ class ApplicationContext
*/ */
protected static function LoadPluginProperties() protected static function LoadPluginProperties()
{ {
if (Session::IsSet('PluginProperties')) { if (Session::IsSet('PluginProperties'))
{
self::$m_aPluginProperties = Session::Get('PluginProperties'); self::$m_aPluginProperties = Session::Get('PluginProperties');
} else { }
self::$m_aPluginProperties = []; else
{
self::$m_aPluginProperties = array();
} }
} }
@@ -406,9 +431,7 @@ class ApplicationContext
*/ */
public static function SetPluginProperty($sPluginClass, $sProperty, $value) public static function SetPluginProperty($sPluginClass, $sProperty, $value)
{ {
if (is_null(self::$m_aPluginProperties)) { if (is_null(self::$m_aPluginProperties)) self::LoadPluginProperties();
self::LoadPluginProperties();
}
self::$m_aPluginProperties[$sPluginClass][$sProperty] = $value; self::$m_aPluginProperties[$sPluginClass][$sProperty] = $value;
Session::Set(['PluginProperties', $sPluginClass, $sProperty], $value); Session::Set(['PluginProperties', $sPluginClass, $sProperty], $value);
@@ -421,14 +444,15 @@ class ApplicationContext
*/ */
public static function GetPluginProperties($sPluginClass) public static function GetPluginProperties($sPluginClass)
{ {
if (is_null(self::$m_aPluginProperties)) { if (is_null(self::$m_aPluginProperties)) self::LoadPluginProperties();
self::LoadPluginProperties();
}
if (array_key_exists($sPluginClass, self::$m_aPluginProperties)) { if (array_key_exists($sPluginClass, self::$m_aPluginProperties))
{
return self::$m_aPluginProperties[$sPluginClass]; return self::$m_aPluginProperties[$sPluginClass];
} else { }
return []; else
{
return array();
} }
} }

View File

@@ -74,3 +74,7 @@ require_once(APPROOT.'application/applicationextension/rest/iRestInputSanitizer.
require_once(APPROOT.'application/applicationextension/rest/iRestServiceProvider.php'); require_once(APPROOT.'application/applicationextension/rest/iRestServiceProvider.php');
require_once(APPROOT.'application/applicationextension/rest/RestResult.php'); require_once(APPROOT.'application/applicationextension/rest/RestResult.php');
require_once(APPROOT.'application/applicationextension/rest/RestUtils.php'); require_once(APPROOT.'application/applicationextension/rest/RestUtils.php');

View File

@@ -9,64 +9,64 @@
*/ */
abstract class AbstractApplicationUIExtension implements iApplicationUIExtension abstract class AbstractApplicationUIExtension implements iApplicationUIExtension
{ {
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function OnDisplayProperties($oObject, \Combodo\iTop\Application\WebPage\WebPage $oPage, $bEditMode = false) public function OnDisplayProperties($oObject, \Combodo\iTop\Application\WebPage\WebPage $oPage, $bEditMode = false)
{ {
} }
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function OnDisplayRelations($oObject, \Combodo\iTop\Application\WebPage\WebPage $oPage, $bEditMode = false) public function OnDisplayRelations($oObject, \Combodo\iTop\Application\WebPage\WebPage $oPage, $bEditMode = false)
{ {
} }
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function OnFormSubmit($oObject, $sFormPrefix = '') public function OnFormSubmit($oObject, $sFormPrefix = '')
{ {
} }
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function OnFormCancel($sTempId) public function OnFormCancel($sTempId)
{ {
} }
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function EnumUsedAttributes($oObject) public function EnumUsedAttributes($oObject)
{ {
return []; return array();
} }
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function GetIcon($oObject) public function GetIcon($oObject)
{ {
return ''; return '';
} }
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function GetHilightClass($oObject) public function GetHilightClass($oObject)
{ {
return HILIGHT_CLASS_NONE; return HILIGHT_CLASS_NONE;
} }
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function EnumAllowedActions(DBObjectSet $oSet) public function EnumAllowedActions(DBObjectSet $oSet)
{ {
return []; return array();
} }
} }

View File

@@ -9,27 +9,27 @@
*/ */
abstract class AbstractPageUIBlockExtension implements iPageUIBlockExtension abstract class AbstractPageUIBlockExtension implements iPageUIBlockExtension
{ {
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function GetBannerBlock() public function GetBannerBlock()
{ {
return null; return null;
} }
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function GetHeaderBlock() public function GetHeaderBlock()
{ {
return null; return null;
} }
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function GetFooterBlock() public function GetFooterBlock()
{ {
return null; return null;
} }
} }

View File

@@ -9,20 +9,20 @@
*/ */
abstract class AbstractPreferencesExtension implements iPreferencesExtension abstract class AbstractPreferencesExtension implements iPreferencesExtension
{ {
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function DisplayPreferences(\Combodo\iTop\Application\WebPage\WebPage $oPage) public function DisplayPreferences(\Combodo\iTop\Application\WebPage\WebPage $oPage)
{ {
// Do nothing // Do nothing
} }
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function ApplyPreferences(\Combodo\iTop\Application\WebPage\WebPage $oPage, $sOperation) public function ApplyPreferences(\Combodo\iTop\Application\WebPage\WebPage $oPage, $sOperation)
{ {
// Do nothing // Do nothing
} }
} }

View File

@@ -8,28 +8,28 @@
*/ */
abstract class AbstractWelcomePopupExtension implements iWelcomePopupExtension abstract class AbstractWelcomePopupExtension implements iWelcomePopupExtension
{ {
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function GetIconRelPath(): string public function GetIconRelPath(): string
{ {
return \Combodo\iTop\Application\Branding::$aLogoPaths[\Combodo\iTop\Application\Branding::ENUM_LOGO_TYPE_MAIN_LOGO_COMPACT]['default']; return \Combodo\iTop\Application\Branding::$aLogoPaths[\Combodo\iTop\Application\Branding::ENUM_LOGO_TYPE_MAIN_LOGO_COMPACT]['default'];
} }
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function GetMessages(): array public function GetMessages(): array
{ {
return []; return [];
} }
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function AcknowledgeMessage(string $sMessageId): void public function AcknowledgeMessage(string $sMessageId): void
{ {
// No need to process the acknowledgment notice by default // No need to process the acknowledgment notice by default
return; return;
} }
} }

View File

@@ -9,141 +9,142 @@
*/ */
abstract class ApplicationPopupMenuItem abstract class ApplicationPopupMenuItem
{ {
/** @ignore */ /** @ignore */
protected $sUID; protected $sUID;
/** @ignore */ /** @ignore */
protected $sLabel; protected $sLabel;
/** @ignore */ /** @ignore */
protected $sTooltip; protected $sTooltip;
/** @ignore */ /** @ignore */
protected $sIconClass; protected $sIconClass;
/** @ignore */ /** @ignore */
protected $aCssClasses; protected $aCssClasses;
/** /**
* Constructor * Constructor
* *
* @param string $sUID The unique identifier of this menu in iTop... make sure you pass something unique enough * @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 $sLabel The display label of the menu (must be localized)
* @api * @api
*/ */
public function __construct($sUID, $sLabel) public function __construct($sUID, $sLabel)
{ {
$this->sUID = $sUID; $this->sUID = $sUID;
$this->sLabel = $sLabel; $this->sLabel = $sLabel;
$this->sTooltip = ''; $this->sTooltip = '';
$this->sIconClass = ''; $this->sIconClass = '';
$this->aCssClasses = []; $this->aCssClasses = array();
} }
/** /**
* Get the UID * Get the UID
* *
* @return string The unique identifier * @return string The unique identifier
* @ignore * @ignore
*/ */
public function GetUID() public function GetUID()
{ {
return $this->sUID; return $this->sUID;
} }
/** /**
* Get the label * Get the label
* *
* @return string The label * @return string The label
* @ignore * @ignore
*/ */
public function GetLabel() public function GetLabel()
{ {
return $this->sLabel; return $this->sLabel;
} }
/** /**
* Get the CSS classes * Get the CSS classes
* *
* @return array * @return array
* @ignore * @ignore
*/ */
public function GetCssClasses() public function GetCssClasses()
{ {
return $this->aCssClasses; return $this->aCssClasses;
} }
/** /**
* @param $aCssClasses * @param $aCssClasses
* @api * @api
*/ */
public function SetCssClasses($aCssClasses) public function SetCssClasses($aCssClasses)
{ {
$this->aCssClasses = $aCssClasses; $this->aCssClasses = $aCssClasses;
} }
/** /**
* Adds a CSS class to the CSS classes that will be put on the menu item * Adds a CSS class to the CSS classes that will be put on the menu item
* *
* @param $sCssClass * @param $sCssClass
* @api * @api
*/ */
public function AddCssClass($sCssClass) public function AddCssClass($sCssClass)
{ {
$this->aCssClasses[] = $sCssClass; $this->aCssClasses[] = $sCssClass;
} }
/**
* @param $sTooltip
*
* @api
* @since 3.0.0
*/
public function SetTooltip($sTooltip)
{
$this->sTooltip = $sTooltip;
}
/** /**
* @return string * @param $sTooltip
* *
* @api * @api
* @since 3.0.0 * @since 3.0.0
*/ */
public function GetTooltip() public function SetTooltip($sTooltip)
{ {
return $this->sTooltip; $this->sTooltip = $sTooltip;
} }
/** /**
* @param $sIconClass * @return string
* *
* @api * @api
* @since 3.0.0 * @since 3.0.0
*/ */
public function SetIconClass($sIconClass) public function GetTooltip()
{ {
$this->sIconClass = $sIconClass; return $this->sTooltip;
} }
/** /**
* @return string * @param $sIconClass
* *
* @api * @api
* @since 3.0.0 * @since 3.0.0
*/ */
public function GetIconClass() public function SetIconClass($sIconClass)
{ {
return $this->sIconClass; $this->sIconClass = $sIconClass;
} }
/** /**
* Returns the components to create a popup menu item in HTML * @return string
* *
* @return array A hash array: array('label' => , 'url' => , 'target' => , 'onclick' => ) * @api
* @ignore * @since 3.0.0
*/ */
abstract public function GetMenuItem(); public function GetIconClass()
{
return $this->sIconClass;
}
/** @ignore */ /**
public function GetLinkedScripts() * Returns the components to create a popup menu item in HTML
{ *
return []; * @return array A hash array: array('label' => , 'url' => , 'target' => , 'onclick' => )
} * @ignore
} */
abstract public function GetMenuItem();
/** @ignore */
public function GetLinkedScripts()
{
return array();
}
}

View File

@@ -9,4 +9,5 @@
*/ */
class JSButtonItem extends JSPopupMenuItem class JSButtonItem extends JSPopupMenuItem
{ {
}
}

View File

@@ -11,60 +11,60 @@
*/ */
class JSPopupMenuItem extends ApplicationPopupMenuItem class JSPopupMenuItem extends ApplicationPopupMenuItem
{ {
/** @ignore */ /** @ignore */
protected $sJsCode; protected $sJsCode;
/** @ignore */ /** @ignore */
protected $sUrl; protected $sUrl;
/** @ignore */ /** @ignore */
protected $aIncludeJSFiles; protected $aIncludeJSFiles;
/** /**
* Class for adding an item that triggers some Javascript code * 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 $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 $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 * @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 * 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. * @param array $aIncludeJSFiles An array of file URLs to be included (once) to provide some JS libraries for the page.
* @api * @api
*/ */
public function __construct($sUID, $sLabel, $sJSCode, $aIncludeJSFiles = []) public function __construct($sUID, $sLabel, $sJSCode, $aIncludeJSFiles = array())
{ {
parent::__construct($sUID, $sLabel); parent::__construct($sUID, $sLabel);
$this->sJsCode = $sJSCode; $this->sJsCode = $sJSCode;
$this->sUrl = '#'; $this->sUrl = '#';
$this->aIncludeJSFiles = $aIncludeJSFiles; $this->aIncludeJSFiles = $aIncludeJSFiles;
} }
/** @ignore */ /** @ignore */
public function GetMenuItem() public function GetMenuItem()
{ {
// Note: the semicolumn is a must here! // Note: the semicolumn is a must here!
return [ return array(
'label' => $this->GetLabel(), 'label' => $this->GetLabel(),
'onclick' => $this->GetJsCode().'; return false;', 'onclick' => $this->GetJsCode() . '; return false;',
'url' => $this->GetUrl(), 'url' => $this->GetUrl(),
'css_classes' => $this->GetCssClasses(), 'css_classes' => $this->GetCssClasses(),
'icon_class' => $this->sIconClass, 'icon_class' => $this->sIconClass,
'tooltip' => $this->sTooltip, 'tooltip' => $this->sTooltip
]; );
} }
/** @ignore */ /** @ignore */
public function GetLinkedScripts() public function GetLinkedScripts()
{ {
return $this->aIncludeJSFiles; return $this->aIncludeJSFiles;
} }
/** @ignore */ /** @ignore */
public function GetJsCode() public function GetJsCode()
{ {
return $this->sJsCode; return $this->sJsCode;
} }
/** @ignore */ /** @ignore */
public function GetUrl() public function GetUrl()
{ {
return $this->sUrl; return $this->sUrl;
} }
} }

View File

@@ -10,20 +10,20 @@
*/ */
class SeparatorPopupMenuItem extends ApplicationPopupMenuItem class SeparatorPopupMenuItem extends ApplicationPopupMenuItem
{ {
public static $idx = 0; static $idx = 0;
/** /**
* Constructor * Constructor
* @api * @api
*/ */
public function __construct() public function __construct()
{ {
parent::__construct('_separator_'.(self::$idx++), ''); parent::__construct('_separator_' . (self::$idx++), '');
} }
/** @ignore */ /** @ignore */
public function GetMenuItem() public function GetMenuItem()
{ {
return ['label' => '<hr class="menu-separator">', 'url' => '', 'css_classes' => $this->aCssClasses]; return array('label' => '<hr class="menu-separator">', 'url' => '', 'css_classes' => $this->aCssClasses);
} }
} }

View File

@@ -9,4 +9,5 @@
*/ */
class URLButtonItem extends URLPopupMenuItem class URLButtonItem extends URLPopupMenuItem
{ {
}
}

View File

@@ -11,48 +11,48 @@
*/ */
class URLPopupMenuItem extends ApplicationPopupMenuItem class URLPopupMenuItem extends ApplicationPopupMenuItem
{ {
/** @ignore */ /** @ignore */
protected $sUrl; protected $sUrl;
/** @ignore */ /** @ignore */
protected $sTarget; protected $sTarget;
/** /**
* Constructor * Constructor
* *
* @param string $sUID The unique identifier of this menu in iTop... make sure you pass something unique enough * @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 $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 $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 * @param string $sTarget In case the menu is an hyperlink and a specific target is needed (_blank for example), pass it here
* @api * @api
*/ */
public function __construct($sUID, $sLabel, $sUrl, $sTarget = '_top') public function __construct($sUID, $sLabel, $sUrl, $sTarget = '_top')
{ {
parent::__construct($sUID, $sLabel); parent::__construct($sUID, $sLabel);
$this->sUrl = $sUrl; $this->sUrl = $sUrl;
$this->sTarget = $sTarget; $this->sTarget = $sTarget;
} }
/** @ignore */ /** @ignore */
public function GetMenuItem() public function GetMenuItem()
{ {
return ['label' => $this->GetLabel(), return array('label' => $this->GetLabel(),
'url' => $this->GetUrl(), 'url' => $this->GetUrl(),
'target' => $this->GetTarget(), 'target' => $this->GetTarget(),
'css_classes' => $this->aCssClasses, 'css_classes' => $this->aCssClasses,
'icon_class' => $this->sIconClass, 'icon_class' => $this->sIconClass,
'tooltip' => $this->sTooltip, 'tooltip' => $this->sTooltip
]; );
} }
/** @ignore */ /** @ignore */
public function GetUrl() public function GetUrl()
{ {
return $this->sUrl; return $this->sUrl;
} }
/** @ignore */ /** @ignore */
public function GetTarget() public function GetTarget()
{ {
return $this->sTarget; return $this->sTarget;
} }
} }

View File

@@ -27,147 +27,147 @@
*/ */
interface iApplicationUIExtension interface iApplicationUIExtension
{ {
/** /**
* Invoked when an object is being displayed (wiew or edit) * Invoked when an object is being displayed (wiew or edit)
* *
* The method is called right after the main tab has been displayed. * 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 * You can add output to the page, either to change the display, or to add a form input
* *
* Example: * Example:
* <code> * <code>
* if ($bEditMode) * if ($bEditMode)
* { * {
* $oPage->p('Age of the captain: &lt;input type="text" name="captain_age"/&gt;'); * $oPage->p('Age of the captain: &lt;input type="text" name="captain_age"/&gt;');
* } * }
* else * else
* { * {
* $oPage->p('Age of the captain: '.$iCaptainAge); * $oPage->p('Age of the captain: '.$iCaptainAge);
* } * }
* </code> * </code>
* *
* @api * @api
* *
*@param \Combodo\iTop\Application\WebPage\WebPage $oPage The output context *@param \Combodo\iTop\Application\WebPage\WebPage $oPage The output context
* @param boolean $bEditMode True if the edition form is being displayed * @param boolean $bEditMode True if the edition form is being displayed
* *
* @param DBObject $oObject The object being displayed * @param DBObject $oObject The object being displayed
* *
* @return void * @return void
*/ */
public function OnDisplayProperties($oObject, \Combodo\iTop\Application\WebPage\WebPage $oPage, $bEditMode = false); public function OnDisplayProperties($oObject, \Combodo\iTop\Application\WebPage\WebPage $oPage, $bEditMode = false);
/** /**
* Invoked when an object is being displayed (wiew or edit) * Invoked when an object is being displayed (wiew or edit)
* *
* The method is called rigth after all the tabs have been displayed * The method is called rigth after all the tabs have been displayed
* *
* @api * @api
* *
*@param \Combodo\iTop\Application\WebPage\WebPage $oPage The output context *@param \Combodo\iTop\Application\WebPage\WebPage $oPage The output context
* @param boolean $bEditMode True if the edition form is being displayed * @param boolean $bEditMode True if the edition form is being displayed
* *
* @param DBObject $oObject The object being displayed * @param DBObject $oObject The object being displayed
* *
* @return void * @return void
*/ */
public function OnDisplayRelations($oObject, \Combodo\iTop\Application\WebPage\WebPage $oPage, $bEditMode = false); 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 * 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 * The method is called after the changes from the standard form have been
* taken into account, and before saving the changes into the database. * taken into account, and before saving the changes into the database.
* *
* @param DBObject $oObject The object being edited * @param DBObject $oObject The object being edited
* @param string $sFormPrefix Prefix given to the HTML form inputs * @param string $sFormPrefix Prefix given to the HTML form inputs
* *
* @return void * @return void
* @api * @api
*/ */
public function OnFormSubmit($oObject, $sFormPrefix = ''); public function OnFormSubmit($oObject, $sFormPrefix = '');
/** /**
* Invoked when the end-user clicks on Cancel from the object edition form * 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 * 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 * javascript into the edition form, and if that code requires to store temporary data
* (this is the case when a file must be uploaded). * (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. * @param string $sTempId Unique temporary identifier made of session_id and transaction_id. It identifies the object in a unique way.
* *
* @return void * @return void
* @api * @api
*/ */
public function OnFormCancel($sTempId); public function OnFormCancel($sTempId);
/** /**
* Not yet called by the framework! * Not yet called by the framework!
* *
* Sorry, the verb has been reserved. You must implement it, but it is not called as of now. * 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 * @param DBObject $oObject The object being displayed
* *
* @return string[] desc * @return string[] desc
* @api * @api
*/ */
public function EnumUsedAttributes($oObject); // Not yet implemented public function EnumUsedAttributes($oObject); // Not yet implemented
/** /**
* Not yet called by the framework! * Not yet called by the framework!
* *
* Sorry, the verb has been reserved. You must implement it, but it is not called as of now. * 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 * @param DBObject $oObject The object being displayed
* *
* @return string Path of the icon, relative to the modules directory. * @return string Path of the icon, relative to the modules directory.
* @api * @api
*/ */
public function GetIcon($oObject); // Not yet implemented public function GetIcon($oObject); // Not yet implemented
/** /**
* Invoked when the object is displayed alone or within a list * Invoked when the object is displayed alone or within a list
* *
* Returns a value influencing the appearance of the object depending on its * Returns a value influencing the appearance of the object depending on its
* state. * state.
* *
* Possible values are: * Possible values are:
* *
* * HILIGHT_CLASS_CRITICAL * * HILIGHT_CLASS_CRITICAL
* * HILIGHT_CLASS_WARNING * * HILIGHT_CLASS_WARNING
* * HILIGHT_CLASS_OK * * HILIGHT_CLASS_OK
* * HILIGHT_CLASS_NONE * * HILIGHT_CLASS_NONE
* *
* @param DBObject $oObject The object being displayed * @param DBObject $oObject The object being displayed
* *
* @return integer The value representing the mood of the object * @return integer The value representing the mood of the object
* @api * @api
*/ */
public function GetHilightClass($oObject); public function GetHilightClass($oObject);
/** /**
* Called when building the Actions menu for a single object or a list of objects * 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. * Use this to add items to the Actions menu. You will have to specify a label and an URL.
* *
* Example: * Example:
* <code> * <code>
* $oObject = $oSet->fetch(); * $oObject = $oSet->fetch();
* if ($oObject instanceof Sheep) * if ($oObject instanceof Sheep)
* { * {
* return array('View in my app' => 'http://myserver/view_sheeps?id='.$oObject->Get('name')); * return array('View in my app' => 'http://myserver/view_sheeps?id='.$oObject->Get('name'));
* } * }
* else * else
* { * {
* return array(); * return array();
* } * }
* </code> * </code>
* *
* See also iPopupMenuExtension for greater flexibility * See also iPopupMenuExtension for greater flexibility
* *
* @param DBObjectSet $oSet A set of persistent objects (DBObject) * @param DBObjectSet $oSet A set of persistent objects (DBObject)
* *
* @return array * @return array
* @api * @api
*/ */
public function EnumAllowedActions(DBObjectSet $oSet); public function EnumAllowedActions(DBObjectSet $oSet);
} }

View File

@@ -10,10 +10,10 @@
*/ */
interface iBackofficeDictEntriesExtension interface iBackofficeDictEntriesExtension
{ {
/** /**
* @return array * @return array
* @see \iTopWebPage::a_dict_entries * @see \iTopWebPage::a_dict_entries
* @api * @api
*/ */
public function GetDictEntries(): array; public function GetDictEntries(): array;
} }

View File

@@ -10,10 +10,10 @@
*/ */
interface iBackofficeDictEntriesPrefixesExtension interface iBackofficeDictEntriesPrefixesExtension
{ {
/** /**
* @return array * @return array
* @see \iTopWebPage::a_dict_entries_prefixes * @see \iTopWebPage::a_dict_entries_prefixes
* @api * @api
*/ */
public function GetDictEntriesPrefixes(): array; public function GetDictEntriesPrefixes(): array;
} }

View File

@@ -11,10 +11,10 @@
*/ */
interface iBackofficeEarlyScriptExtension interface iBackofficeEarlyScriptExtension
{ {
/** /**
* @return string * @return string
* @see \iTopWebPage::$a_early_scripts * @see \iTopWebPage::$a_early_scripts
* @api * @api
*/ */
public function GetEarlyScript(): string; public function GetEarlyScript(): string;
} }

View File

@@ -10,10 +10,10 @@
*/ */
interface iBackofficeInitScriptExtension interface iBackofficeInitScriptExtension
{ {
/** /**
* @return string * @return string
* @see \iTopWebPage::$a_init_scripts * @see \iTopWebPage::$a_init_scripts
* @api * @api
*/ */
public function GetInitScript(): string; public function GetInitScript(): string;
} }

View File

@@ -10,11 +10,11 @@
*/ */
interface iBackofficeLinkedScriptsExtension interface iBackofficeLinkedScriptsExtension
{ {
/** /**
* Each script will be included using this property * Each script will be included using this property
* @return array An array of absolute URLs to the files to include * @return array An array of absolute URLs to the files to include
* @see \iTopWebPage::$a_linked_scripts * @see \iTopWebPage::$a_linked_scripts
* @api * @api
*/ */
public function GetLinkedScriptsAbsUrls(): array; public function GetLinkedScriptsAbsUrls(): array;
} }

View File

@@ -10,10 +10,10 @@
*/ */
interface iBackofficeLinkedStylesheetsExtension interface iBackofficeLinkedStylesheetsExtension
{ {
/** /**
* @return array An array of absolute URLs to the files to include * @return array An array of absolute URLs to the files to include
* @see \iTopWebPage::$a_linked_stylesheets * @see \iTopWebPage::$a_linked_stylesheets
* @api * @api
*/ */
public function GetLinkedStylesheetsAbsUrls(): array; public function GetLinkedStylesheetsAbsUrls(): array;
} }

View File

@@ -10,10 +10,10 @@
*/ */
interface iBackofficeReadyScriptExtension interface iBackofficeReadyScriptExtension
{ {
/** /**
* @return string * @return string
* @see \iTopWebPage::$a_ready_scripts * @see \iTopWebPage::$a_ready_scripts
* @api * @api
*/ */
public function GetReadyScript(): string; public function GetReadyScript(): string;
} }

View File

@@ -10,10 +10,10 @@
*/ */
interface iBackofficeSassExtension interface iBackofficeSassExtension
{ {
/** /**
* @return string * @return string
* @see \iTopWebPage::$a_styles * @see \iTopWebPage::$a_styles
* @api * @api
*/ */
public function GetSass(): string; public function GetSass(): string;
} }

View File

@@ -10,10 +10,10 @@
*/ */
interface iBackofficeScriptExtension interface iBackofficeScriptExtension
{ {
/** /**
* @return string * @return string
* @see \iTopWebPage::$a_scripts * @see \iTopWebPage::$a_scripts
* @api * @api
*/ */
public function GetScript(): string; public function GetScript(): string;
} }

View File

@@ -10,10 +10,10 @@
*/ */
interface iBackofficeStyleExtension interface iBackofficeStyleExtension
{ {
/** /**
* @return string * @return string
* @see \iTopWebPage::$a_styles * @see \iTopWebPage::$a_styles
* @api * @api
*/ */
public function GetStyle(): string; public function GetStyle(): string;
} }

View File

@@ -11,25 +11,25 @@
*/ */
interface iFieldRendererMappingsExtension interface iFieldRendererMappingsExtension
{ {
/** /**
* @return array { * @return array {
* array: { * array: {
* field: string, * field: string,
* form_renderer: string, * form_renderer: string,
* field_renderer: string * field_renderer: string
* } * }
* } List of field renderer mapping: FQCN field class, FQCN Form Renderer class, FQCN Field Renderer class * } List of field renderer mapping: FQCN field class, FQCN Form Renderer class, FQCN Field Renderer class
* *
* Example: * Example:
* *
* ```php * ```php
* [ * [
* ['field' => 'FQCN\FieldA', 'form_renderer' => 'Combodo\iTop\Renderer\Console\ConsoleFormRenderer', 'field_renderer' => 'FQCN\FieldRendererA'], * ['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\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\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'], * ['field' => 'FQCN\FieldB', 'form_renderer' => 'Combodo\iTop\Renderer\Bootstrap\BsFormRenderer', 'field_renderer' => 'FQCN\FieldRendererB'],
* ] * ]
* ``` * ```
*/ */
public static function RegisterSupportedFields(): array; public static function RegisterSupportedFields(): array;
} }

View File

@@ -21,27 +21,27 @@
*/ */
interface iPageUIBlockExtension interface iPageUIBlockExtension
{ {
/** /**
* Add content to the "admin banner" * Add content to the "admin banner"
* *
* @api * @api
* @return \Combodo\iTop\Application\UI\Base\iUIBlock|null The Block to add into the page * @return \Combodo\iTop\Application\UI\Base\iUIBlock|null The Block to add into the page
*/ */
public function GetBannerBlock(); public function GetBannerBlock();
/** /**
* Add content to the header of the page * Add content to the header of the page
* *
* @api * @api
* @return \Combodo\iTop\Application\UI\Base\iUIBlock|null The Block to add into the page * @return \Combodo\iTop\Application\UI\Base\iUIBlock|null The Block to add into the page
*/ */
public function GetHeaderBlock(); public function GetHeaderBlock();
/** /**
* Add content to the footer of the page * Add content to the footer of the page
* *
* @api * @api
* @return \Combodo\iTop\Application\UI\Base\iUIBlock|null The Block to add into the page * @return \Combodo\iTop\Application\UI\Base\iUIBlock|null The Block to add into the page
*/ */
public function GetFooterBlock(); public function GetFooterBlock();
} }

View File

@@ -13,100 +13,100 @@
*/ */
interface iPopupMenuExtension interface iPopupMenuExtension
{ {
/** /**
* Insert an item into the Actions menu of a list * Insert an item into the Actions menu of a list
* *
* $param is a DBObjectSet containing the list of objects * $param is a DBObjectSet containing the list of objects
* @api * @api
*/ */
public const MENU_OBJLIST_ACTIONS = 1; const MENU_OBJLIST_ACTIONS = 1;
/** /**
* Insert an item into the Toolkit menu of a list * Insert an item into the Toolkit menu of a list
* *
* $param is a DBObjectSet containing the list of objects * $param is a DBObjectSet containing the list of objects
* @api * @api
*/ */
public const MENU_OBJLIST_TOOLKIT = 2; const MENU_OBJLIST_TOOLKIT = 2;
/** /**
* Insert an item into the Actions menu on an object details page * Insert an item into the Actions menu on an object details page
* *
* $param is a DBObject instance: the object currently displayed * $param is a DBObject instance: the object currently displayed
* @api * @api
*/ */
public const MENU_OBJDETAILS_ACTIONS = 3; const MENU_OBJDETAILS_ACTIONS = 3;
/** /**
* Insert an item into the Dashboard menu * Insert an item into the Dashboard menu
* *
* The dashboad menu is shown on the top right corner when a dashboard * The dashboad menu is shown on the top right corner when a dashboard
* is being displayed. * is being displayed.
* *
* $param is a Dashboard instance: the dashboard currently displayed * $param is a Dashboard instance: the dashboard currently displayed
* @api * @api
*/ */
public const MENU_DASHBOARD_ACTIONS = 4; const MENU_DASHBOARD_ACTIONS = 4;
/** /**
* Insert an item into the User menu (upper right corner) * Insert an item into the User menu (upper right corner)
* *
* $param is null * $param is null
* @api * @api
*/ */
public const MENU_USER_ACTIONS = 5; const MENU_USER_ACTIONS = 5;
/** /**
* Insert an item into the Action menu on an object item in an objects list in the portal * 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 * $param is an array('portal_id' => $sPortalId, 'object' => $oObject) containing the portal id and a DBObject instance (the object on
* the current line) * the current line)
* @api * @api
*/ */
public const PORTAL_OBJLISTITEM_ACTIONS = 7; const PORTAL_OBJLISTITEM_ACTIONS = 7;
/** /**
* Insert an item into the Action menu on an object details page in the portal * 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 * $param is an array('portal_id' => $sPortalId, 'object' => $oObject) containing the portal id and a DBObject instance (the object
* currently displayed) * currently displayed)
* @api * @api
*/ */
public const PORTAL_OBJDETAILS_ACTIONS = 8; const PORTAL_OBJDETAILS_ACTIONS = 8;
/** /**
* Insert an item into the Actions menu of a list in the portal * Insert an item into the Actions menu of a list in the portal
* Note: This is not implemented yet ! * Note: This is not implemented yet !
* *
* $param is an array('portal_id' => $sPortalId, 'object_set' => $oSet) containing DBObjectSet containing the list of objects * $param is an array('portal_id' => $sPortalId, 'object_set' => $oSet) containing DBObjectSet containing the list of objects
* *
* @todo * @todo
*/ */
public const PORTAL_OBJLIST_ACTIONS = 6; const PORTAL_OBJLIST_ACTIONS = 6;
/** /**
* Insert an item into the user menu of the portal * Insert an item into the user menu of the portal
* Note: This is not implemented yet ! * Note: This is not implemented yet !
* *
* $param is the portal id * $param is the portal id
* *
* @todo * @todo
*/ */
public const PORTAL_USER_ACTIONS = 9; const PORTAL_USER_ACTIONS = 9;
/** /**
* Insert an item into the navigation menu of the portal * Insert an item into the navigation menu of the portal
* Note: This is not implemented yet ! * Note: This is not implemented yet !
* *
* $param is the portal id * $param is the portal id
* *
* @todo * @todo
*/ */
public const PORTAL_MENU_ACTIONS = 10; const PORTAL_MENU_ACTIONS = 10;
/** /**
* Get the list of items to be added to a menu. * Get the list of items to be added to a menu.
* *
* This method is called by the framework for each 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. * 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 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 * @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 * @return object[] An array of ApplicationPopupMenuItem or an empty array if no action is to be added to the menu
* @api * @api
*/ */
public static function EnumItems($iMenuId, $param); public static function EnumItems($iMenuId, $param);
} }

View File

@@ -7,22 +7,22 @@
*/ */
interface iPreferencesExtension interface iPreferencesExtension
{ {
/** /**
* @api * @api
* *
* @param \Combodo\iTop\Application\WebPage\WebPage $oPage * @param \Combodo\iTop\Application\WebPage\WebPage $oPage
* *
*/ */
public function DisplayPreferences(\Combodo\iTop\Application\WebPage\WebPage $oPage); public function DisplayPreferences(\Combodo\iTop\Application\WebPage\WebPage $oPage);
/** /**
* @api * @api
* *
* @param string $sOperation * @param string $sOperation
* *
* @param \Combodo\iTop\Application\WebPage\WebPage $oPage * @param \Combodo\iTop\Application\WebPage\WebPage $oPage
* *
* @return bool true if the operation has been used * @return bool true if the operation has been used
*/ */
public function ApplyPreferences(\Combodo\iTop\Application\WebPage\WebPage $oPage, $sOperation); public function ApplyPreferences(\Combodo\iTop\Application\WebPage\WebPage $oPage, $sOperation);
} }

View File

@@ -8,31 +8,31 @@
*/ */
interface iWelcomePopupExtension interface iWelcomePopupExtension
{ {
// Importance for ordering messages // Importance for ordering messages
// Just two levels since less important messages have nothing to do in the welcome popup // 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_CRITICAL = 0;
public const ENUM_IMPORTANCE_HIGH = 1; public const ENUM_IMPORTANCE_HIGH = 1;
public const DEFAULT_IMPORTANCE = self::ENUM_IMPORTANCE_HIGH; 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, ...) * 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 * @return string Relative path (from app. root) of the icon representing the provider
* @api * @api
*/ */
public function GetIconRelPath(): string; public function GetIconRelPath(): string;
/** /**
* @return \Combodo\iTop\Application\WelcomePopup\Message[] * @return \Combodo\iTop\Application\WelcomePopup\Message[]
* @api * @api
*/ */
public function GetMessages(): array; 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 * 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 * @param string $sMessageId
* @api * @api
*/ */
public function AcknowledgeMessage(string $sMessageId): void; public function AcknowledgeMessage(string $sMessageId): void;
} }

View File

@@ -8,9 +8,9 @@
*/ */
interface iBackupExtraFilesExtension interface iBackupExtraFilesExtension
{ {
/** /**
* @return string[] Array of relative paths (from app root) for files and directories to be included in the backup * @return string[] Array of relative paths (from app root) for files and directories to be included in the backup
* @api * @api
*/ */
public function GetExtraFilesRelPaths(): array; public function GetExtraFilesRelPaths(): array;
} }

View File

@@ -7,19 +7,19 @@
*/ */
interface iKPILoggerExtension interface iKPILoggerExtension
{ {
/** /**
* Init the statistics collected * Init the statistics collected
* *
* @return void * @return void
*/ */
public function InitStats(); public function InitStats();
/** /**
* Add a new KPI to the stats * Add a new KPI to the stats
* *
* @param \Combodo\iTop\Core\Kpi\KpiLogData $oKpiLogData * @param \Combodo\iTop\Core\Kpi\KpiLogData $oKpiLogData
* *
* @return mixed * @return mixed
*/ */
public function LogOperation($oKpiLogData); public function LogOperation($oKpiLogData);
} }

View File

@@ -9,8 +9,8 @@
*/ */
interface iModuleExtension interface iModuleExtension
{ {
/** /**
* @api * @api
*/ */
public function __construct(); public function __construct();
} }

View File

@@ -16,144 +16,144 @@
*/ */
abstract class AbstractLoginFSMExtension implements iLoginFSMExtension abstract class AbstractLoginFSMExtension implements iLoginFSMExtension
{ {
/** /**
* @inheritDoc * @inheritDoc
*/ */
abstract public function ListSupportedLoginModes(); abstract public function ListSupportedLoginModes();
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function LoginAction($sLoginState, &$iErrorCode) public function LoginAction($sLoginState, &$iErrorCode)
{ {
switch ($sLoginState) { switch ($sLoginState) {
case LoginWebPage::LOGIN_STATE_START: case LoginWebPage::LOGIN_STATE_START:
return $this->OnStart($iErrorCode); return $this->OnStart($iErrorCode);
case LoginWebPage::LOGIN_STATE_MODE_DETECTION: case LoginWebPage::LOGIN_STATE_MODE_DETECTION:
return $this->OnModeDetection($iErrorCode); return $this->OnModeDetection($iErrorCode);
case LoginWebPage::LOGIN_STATE_READ_CREDENTIALS: case LoginWebPage::LOGIN_STATE_READ_CREDENTIALS:
return $this->OnReadCredentials($iErrorCode); return $this->OnReadCredentials($iErrorCode);
case LoginWebPage::LOGIN_STATE_CHECK_CREDENTIALS: case LoginWebPage::LOGIN_STATE_CHECK_CREDENTIALS:
return $this->OnCheckCredentials($iErrorCode); return $this->OnCheckCredentials($iErrorCode);
case LoginWebPage::LOGIN_STATE_CREDENTIALS_OK: case LoginWebPage::LOGIN_STATE_CREDENTIALS_OK:
return $this->OnCredentialsOK($iErrorCode); return $this->OnCredentialsOK($iErrorCode);
case LoginWebPage::LOGIN_STATE_USER_OK: case LoginWebPage::LOGIN_STATE_USER_OK:
return $this->OnUsersOK($iErrorCode); return $this->OnUsersOK($iErrorCode);
case LoginWebPage::LOGIN_STATE_CONNECTED: case LoginWebPage::LOGIN_STATE_CONNECTED:
return $this->OnConnected($iErrorCode); return $this->OnConnected($iErrorCode);
case LoginWebPage::LOGIN_STATE_ERROR: case LoginWebPage::LOGIN_STATE_ERROR:
return $this->OnError($iErrorCode); return $this->OnError($iErrorCode);
} }
return LoginWebPage::LOGIN_FSM_CONTINUE; return LoginWebPage::LOGIN_FSM_CONTINUE;
} }
/** /**
* Initialization * Initialization
* *
* @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...)
* *
* @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE
* @api * @api
*/ */
protected function OnStart(&$iErrorCode) protected function OnStart(&$iErrorCode)
{ {
return LoginWebPage::LOGIN_FSM_CONTINUE; return LoginWebPage::LOGIN_FSM_CONTINUE;
} }
/** /**
* Detect login mode explicitly without respecting configured order (legacy mode) * Detect login mode explicitly without respecting configured order (legacy mode)
* In most case do nothing here * In most case do nothing here
* *
* @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...)
* *
* @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE
* @api * @api
*/ */
protected function OnModeDetection(&$iErrorCode) protected function OnModeDetection(&$iErrorCode)
{ {
return LoginWebPage::LOGIN_FSM_CONTINUE; return LoginWebPage::LOGIN_FSM_CONTINUE;
} }
/** /**
* Obtain the credentials either if login mode is empty or set to yours. * Obtain the credentials either if login mode is empty or set to yours.
* This step can be called multiple times by the FSM: * This step can be called multiple times by the FSM:
* for example: * for example:
* 1 - display login form * 1 - display login form
* 2 - read the values posted by the user (store that in session) * 2 - read the values posted by the user (store that in session)
* *
* @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...)
* *
* @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE
* @api * @api
*/ */
protected function OnReadCredentials(&$iErrorCode) protected function OnReadCredentials(&$iErrorCode)
{ {
return LoginWebPage::LOGIN_FSM_CONTINUE; return LoginWebPage::LOGIN_FSM_CONTINUE;
} }
/** /**
* Control the validity of the data from the session * Control the validity of the data from the session
* Automatic user provisioning can be done here * Automatic user provisioning can be done here
* *
* @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...)
* *
* @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE
* @api * @api
*/ */
protected function OnCheckCredentials(&$iErrorCode) protected function OnCheckCredentials(&$iErrorCode)
{ {
return LoginWebPage::LOGIN_FSM_CONTINUE; return LoginWebPage::LOGIN_FSM_CONTINUE;
} }
/** /**
* @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...)
* *
* @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE
* @api * @api
*/ */
protected function OnCredentialsOK(&$iErrorCode) protected function OnCredentialsOK(&$iErrorCode)
{ {
return LoginWebPage::LOGIN_FSM_CONTINUE; return LoginWebPage::LOGIN_FSM_CONTINUE;
} }
/** /**
* @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...)
* *
* @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE
* @api * @api
*/ */
protected function OnUsersOK(&$iErrorCode) protected function OnUsersOK(&$iErrorCode)
{ {
return LoginWebPage::LOGIN_FSM_CONTINUE; return LoginWebPage::LOGIN_FSM_CONTINUE;
} }
/** /**
* @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...)
* *
* @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE
* @api * @api
*/ */
protected function OnConnected(&$iErrorCode) protected function OnConnected(&$iErrorCode)
{ {
return LoginWebPage::LOGIN_FSM_CONTINUE; return LoginWebPage::LOGIN_FSM_CONTINUE;
} }
/** /**
* @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...)
* *
* @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE
* @api * @api
*/ */
protected function OnError(&$iErrorCode) protected function OnError(&$iErrorCode)
{ {
return LoginWebPage::LOGIN_FSM_CONTINUE; return LoginWebPage::LOGIN_FSM_CONTINUE;
} }
} }

View File

@@ -7,11 +7,11 @@
*/ */
interface iLoginExtension interface iLoginExtension
{ {
/** /**
* Return the list of supported login modes for this plugin * Return the list of supported login modes for this plugin
* *
* @return array of supported login modes * @return array of supported login modes
* @api * @api
*/ */
public function ListSupportedLoginModes(); public function ListSupportedLoginModes();
} }

View File

@@ -7,18 +7,18 @@
*/ */
interface iLoginFSMExtension extends iLoginExtension interface iLoginFSMExtension extends iLoginExtension
{ {
/** /**
* Execute action for this login state * Execute action for this login state
* If a page is displayed, the action must exit at this point * 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_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_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 * 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 string $sLoginState (see LoginWebPage::LOGIN_STATE_...)
* @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...) * @param int $iErrorCode (see LoginWebPage::EXIT_CODE_...)
* *
* @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE * @return int LoginWebPage::LOGIN_FSM_RETURN_ERROR, LoginWebPage::LOGIN_FSM_RETURN_OK or LoginWebPage::LOGIN_FSM_CONTINUE
* @api * @api
*/ */
public function LoginAction($sLoginState, &$iErrorCode); public function LoginAction($sLoginState, &$iErrorCode);
} }

View File

@@ -9,9 +9,9 @@
*/ */
interface iLoginUIExtension extends iLoginExtension interface iLoginUIExtension extends iLoginExtension
{ {
/** /**
* @return LoginTwigContext * @return LoginTwigContext
* @api * @api
*/ */
public function GetTwigContext(); public function GetTwigContext();
} }

View File

@@ -7,9 +7,9 @@
*/ */
interface iLogoutExtension extends iLoginExtension interface iLogoutExtension extends iLoginExtension
{ {
/** /**
* Execute all actions to log out properly * Execute all actions to log out properly
* @api * @api
*/ */
public function LogoutAction(); public function LogoutAction();
} }

View File

@@ -9,59 +9,59 @@
*/ */
abstract class AbstractPortalUIExtension implements iPortalUIExtension abstract class AbstractPortalUIExtension implements iPortalUIExtension
{ {
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function GetCSSFiles(\Symfony\Component\DependencyInjection\Container $oContainer) public function GetCSSFiles(\Symfony\Component\DependencyInjection\Container $oContainer)
{ {
return []; return array();
} }
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function GetCSSInline(\Symfony\Component\DependencyInjection\Container $oContainer) public function GetCSSInline(\Symfony\Component\DependencyInjection\Container $oContainer)
{ {
return null; return null;
} }
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function GetJSFiles(\Symfony\Component\DependencyInjection\Container $oContainer) public function GetJSFiles(\Symfony\Component\DependencyInjection\Container $oContainer)
{ {
return []; return array();
} }
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function GetJSInline(\Symfony\Component\DependencyInjection\Container $oContainer) public function GetJSInline(\Symfony\Component\DependencyInjection\Container $oContainer)
{ {
return null; return null;
} }
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function GetBodyHTML(\Symfony\Component\DependencyInjection\Container $oContainer) public function GetBodyHTML(\Symfony\Component\DependencyInjection\Container $oContainer)
{ {
return null; return null;
} }
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function GetMainContentHTML(\Symfony\Component\DependencyInjection\Container $oContainer) public function GetMainContentHTML(\Symfony\Component\DependencyInjection\Container $oContainer)
{ {
return null; return null;
} }
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function GetNavigationMenuHTML(\Symfony\Component\DependencyInjection\Container $oContainer) public function GetNavigationMenuHTML(\Symfony\Component\DependencyInjection\Container $oContainer)
{ {
return null; return null;
} }
} }

View File

@@ -11,77 +11,77 @@
*/ */
interface iPortalUIExtension interface iPortalUIExtension
{ {
public const ENUM_PORTAL_EXT_UI_BODY = 'Body'; const ENUM_PORTAL_EXT_UI_BODY = 'Body';
public const ENUM_PORTAL_EXT_UI_NAVIGATION_MENU = 'NavigationMenu'; const ENUM_PORTAL_EXT_UI_NAVIGATION_MENU = 'NavigationMenu';
public const ENUM_PORTAL_EXT_UI_MAIN_CONTENT = 'MainContent'; const ENUM_PORTAL_EXT_UI_MAIN_CONTENT = 'MainContent';
/** /**
* Returns an array of CSS file urls * Returns an array of CSS file urls
* *
* @param \Symfony\Component\DependencyInjection\Container $oContainer * @param \Symfony\Component\DependencyInjection\Container $oContainer
* *
* @return array * @return array
* @api * @api
*/ */
public function GetCSSFiles(\Symfony\Component\DependencyInjection\Container $oContainer); public function GetCSSFiles(\Symfony\Component\DependencyInjection\Container $oContainer);
/** /**
* Returns inline (raw) CSS * Returns inline (raw) CSS
* *
* @param \Symfony\Component\DependencyInjection\Container $oContainer * @param \Symfony\Component\DependencyInjection\Container $oContainer
* *
* @return string * @return string
* @api * @api
*/ */
public function GetCSSInline(\Symfony\Component\DependencyInjection\Container $oContainer); public function GetCSSInline(\Symfony\Component\DependencyInjection\Container $oContainer);
/** /**
* Returns an array of JS file urls * Returns an array of JS file urls
* *
* @param \Symfony\Component\DependencyInjection\Container $oContainer * @param \Symfony\Component\DependencyInjection\Container $oContainer
* *
* @return array * @return array
* @api * @api
*/ */
public function GetJSFiles(\Symfony\Component\DependencyInjection\Container $oContainer); public function GetJSFiles(\Symfony\Component\DependencyInjection\Container $oContainer);
/** /**
* Returns raw JS code * Returns raw JS code
* *
* @param \Symfony\Component\DependencyInjection\Container $oContainer * @param \Symfony\Component\DependencyInjection\Container $oContainer
* *
* @return string * @return string
* @api * @api
*/ */
public function GetJSInline(\Symfony\Component\DependencyInjection\Container $oContainer); public function GetJSInline(\Symfony\Component\DependencyInjection\Container $oContainer);
/** /**
* Returns raw HTML code to put at the end of the <body> tag * Returns raw HTML code to put at the end of the <body> tag
* *
* @param \Symfony\Component\DependencyInjection\Container $oContainer * @param \Symfony\Component\DependencyInjection\Container $oContainer
* *
* @return string * @return string
* @api * @api
*/ */
public function GetBodyHTML(\Symfony\Component\DependencyInjection\Container $oContainer); public function GetBodyHTML(\Symfony\Component\DependencyInjection\Container $oContainer);
/** /**
* Returns raw HTML code to put at the end of the #main-wrapper element * Returns raw HTML code to put at the end of the #main-wrapper element
* *
* @param \Symfony\Component\DependencyInjection\Container $oContainer * @param \Symfony\Component\DependencyInjection\Container $oContainer
* *
* @return string * @return string
* @api * @api
*/ */
public function GetMainContentHTML(\Symfony\Component\DependencyInjection\Container $oContainer); public function GetMainContentHTML(\Symfony\Component\DependencyInjection\Container $oContainer);
/** /**
* Returns raw HTML code to put at the end of the #topbar and #sidebar elements * Returns raw HTML code to put at the end of the #topbar and #sidebar elements
* *
* @param \Symfony\Component\DependencyInjection\Container $oContainer * @param \Symfony\Component\DependencyInjection\Container $oContainer
* *
* @return string * @return string
* @api * @api
*/ */
public function GetNavigationMenuHTML(\Symfony\Component\DependencyInjection\Container $oContainer); public function GetNavigationMenuHTML(\Symfony\Component\DependencyInjection\Container $oContainer);
} }

View File

@@ -9,94 +9,94 @@
*/ */
class RestResult class RestResult
{ {
/** /**
* Result: no issue has been encountered * Result: no issue has been encountered
* @api * @api
*/ */
public const OK = 0; const OK = 0;
/** /**
* Result: missing/wrong credentials or the user does not have enough rights to perform the requested operation * Result: missing/wrong credentials or the user does not have enough rights to perform the requested operation
* @api * @api
*/ */
public const UNAUTHORIZED = 1; const UNAUTHORIZED = 1;
/** /**
* Result: the parameter 'version' is missing * Result: the parameter 'version' is missing
* @api * @api
*/ */
public const MISSING_VERSION = 2; const MISSING_VERSION = 2;
/** /**
* Result: the parameter 'json_data' is missing * Result: the parameter 'json_data' is missing
* @api * @api
*/ */
public const MISSING_JSON = 3; const MISSING_JSON = 3;
/** /**
* Result: the input structure is not a valid JSON string * Result: the input structure is not a valid JSON string
* @api * @api
*/ */
public const INVALID_JSON = 4; const INVALID_JSON = 4;
/** /**
* Result: the parameter 'auth_user' is missing, authentication aborted * Result: the parameter 'auth_user' is missing, authentication aborted
* @api * @api
*/ */
public const MISSING_AUTH_USER = 5; const MISSING_AUTH_USER = 5;
/** /**
* Result: the parameter 'auth_pwd' is missing, authentication aborted * Result: the parameter 'auth_pwd' is missing, authentication aborted
* @api * @api
*/ */
public const MISSING_AUTH_PWD = 6; const MISSING_AUTH_PWD = 6;
/** /**
* Result: no operation is available for the specified version * Result: no operation is available for the specified version
* @api * @api
*/ */
public const UNSUPPORTED_VERSION = 10; const UNSUPPORTED_VERSION = 10;
/** /**
* Result: the requested operation is not valid for the specified version * Result: the requested operation is not valid for the specified version
* @api * @api
*/ */
public const UNKNOWN_OPERATION = 11; const UNKNOWN_OPERATION = 11;
/** /**
* Result: the requested operation cannot be performed because it can cause data (integrity) loss * Result: the requested operation cannot be performed because it can cause data (integrity) loss
* @api * @api
*/ */
public const UNSAFE = 12; const UNSAFE = 12;
/** /**
* Result: the request page number is not valid. It must be an integer greater than 0 * Result: the request page number is not valid. It must be an integer greater than 0
* @api * @api
*/ */
public const INVALID_PAGE = 13; const INVALID_PAGE = 13;
/** /**
* Result: the operation could not be performed, see the message for troubleshooting * Result: the operation could not be performed, see the message for troubleshooting
* @api * @api
*/ */
public const INTERNAL_ERROR = 100; const INTERNAL_ERROR = 100;
/** /**
* Default constructor - ok! * Default constructor - ok!
* @api * @api
*/ */
public function __construct() public function __construct()
{ {
$this->code = RestResult::OK; $this->code = RestResult::OK;
} }
/** /**
* Result code * Result code
* @var int * @var int
* @api * @api
*/ */
public $code; public $code;
/** /**
* Result message * Result message
* @var string * @var string
* @api * @api
*/ */
public $message; public $message;
/** /**
* Sanitize the content of this result to hide sensitive information * Sanitize the content of this result to hide sensitive information
*/ */
public function SanitizeContent() public function SanitizeContent()
{ {
// The default implementation does nothing // The default implementation does nothing
} }
} }

View File

@@ -8,357 +8,361 @@
*/ */
class RestUtils class RestUtils
{ {
/** /**
* Registering tracking information. Any further object modification be associated with the given comment, when the modification gets * Registering tracking information. Any further object modification be associated with the given comment, when the modification gets
* recorded into the DB * recorded into the DB
* *
* @param StdClass $oData Structured input data. Must contain 'comment'. * @param StdClass $oData Structured input data. Must contain 'comment'.
* *
* @return void * @return void
* @throws Exception * @throws Exception
* @api * @api
* *
*/ */
public static function InitTrackingComment($oData) public static function InitTrackingComment($oData)
{ {
$sComment = self::GetMandatoryParam($oData, 'comment'); $sComment = self::GetMandatoryParam($oData, 'comment');
CMDBObject::SetTrackInfo($sComment); CMDBObject::SetTrackInfo($sComment);
} }
/** /**
* Read a mandatory parameter from from a Rest/Json structure. * Read a mandatory parameter from from a Rest/Json structure.
* *
* @param string $sParamName Name of the parameter to fetch from the input data * @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. * @param StdClass $oData Structured input data. Must contain the entry defined by sParamName.
* *
* @return mixed parameter value if present * @return mixed parameter value if present
* @throws Exception If the parameter is missing * @throws Exception If the parameter is missing
* @api * @api
*/ */
public static function GetMandatoryParam($oData, $sParamName) public static function GetMandatoryParam($oData, $sParamName)
{ {
if (isset($oData->$sParamName)) { if (isset($oData->$sParamName)) {
return $oData->$sParamName; return $oData->$sParamName;
} else { } else {
throw new Exception("Missing parameter '$sParamName'"); 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 a class from a Rest/Json structure. * Read an optional parameter from a Rest/Json structure.
* *
* @param string $sParamName Name of the parameter to fetch from the input data * @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. * @param mixed $default Default value if the parameter is not found in the input data
* *
* @return string * @param StdClass $oData Structured input data.
* @throws Exception If the parameter is missing or the class is unknown *
* @api * @return mixed
*/ * @throws Exception
public static function GetClass($oData, $sParamName) * @api
{ */
$sClass = self::GetMandatoryParam($oData, $sParamName); public static function GetOptionalParam($oData, $sParamName, $default)
if (!MetaModel::IsValidClass($sClass)) { {
throw new Exception("$sParamName: '$sClass' is not a valid class'"); if (isset($oData->$sParamName)) {
} return $oData->$sParamName;
} else {
return $default;
}
}
return $sClass;
}
/** /**
* Read a list of attribute codes from a Rest/Json structure. * Read a class 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 $sParamName Name of the parameter to fetch from the input data * @param StdClass $oData Structured input data. Must contain the entry defined by sParamName.
* *
* @param string $sClass Name of the class * @return string
* * @throws Exception If the parameter is missing or the class is unknown
* @return array of class => list of attributes (see RestResultWithObjects::AddObject that uses it) * @api
* @throws Exception */
* @api public static function GetClass($oData, $sParamName)
*/ {
public static function GetFieldList($sClass, $oData, $sParamName) $sClass = self::GetMandatoryParam($oData, $sParamName);
{ if (!MetaModel::IsValidClass($sClass)) {
$sFields = self::GetOptionalParam($oData, $sParamName, '*'); throw new Exception("$sParamName: '$sClass' is not a valid class'");
$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 $aShowFields; return $sClass;
} }
/**
* 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();
return $res; /**
} * 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 $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");
}
return $res; /**
} * 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;
* 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);
return $oObjectSet; /**
} * 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 $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());
}
return $value; /**
} * 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);
* Interpret a Rest/Json structure that defines attribute values, and build an object foreach ($key as $sAttCode => $value) {
* $realValue = static::MakeValue($sClass, $sAttCode, $value);
* @param array $aFields A hash of attribute code => value specification. $oSearch->AddCondition($sAttCode, $realValue, '=');
* @param string $sClass Name of the class }
* } elseif (is_numeric($key)) {
* @return DBObject The newly created object $oSearch = new DBObjectSearch($sClass);
* @throws Exception If the specification of the values is not valid $oSearch->AddCondition('id', $key);
* @api } elseif (is_string($key)) {
*/ // OQL
public static function MakeObjectFromFields($sClass, $aFields) try {
{ $oSearch = DBObjectSearch::FromOQL($key);
$oObject = MetaModel::NewObject($sClass); } catch (Exception $e) {
foreach ($aFields as $sAttCode => $value) { throw new CoreOqlException('Query failed to execute', [
$realValue = static::MakeValue($sClass, $sAttCode, $value); 'query' => $key,
try { 'exception_class' => get_class($e),
$oObject->Set($sAttCode, $realValue); 'exception_message' => $e->getMessage(),
} catch (Exception $e) { ]);
throw new Exception("$sAttCode: ".$e->getMessage(), $e->getCode()); }
} } else {
} throw new Exception("Wrong format for key");
}
$oObjectSet = new DBObjectSet($oSearch, array(), array(), null, $iLimit, $iOffset);
return $oObject; return $oObjectSet;
} }
/** /**
* Interpret a Rest/Json structure that defines attribute values, and update the given object * Interpret the Rest/Json value and get a valid attribute value
* *
* @param array $aFields A hash of attribute code => value specification. * @param string $sAttCode Attribute code
* @param DBObject $oObject The object being modified * @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 DBObject The object modified *
* @throws Exception If the specification of the values is not valid * @return mixed The value that can be used with DBObject::Set()
* @api * @throws Exception If the specification of the value is not valid.
*/ * @api
public static function UpdateObjectFromFields($oObject, $aFields) */
{ public static function MakeValue($sClass, $sAttCode, $value)
$sClass = get_class($oObject); {
foreach ($aFields as $sAttCode => $value) { try {
$realValue = static::MakeValue($sClass, $sAttCode, $value); if (!MetaModel::IsValidAttCode($sClass, $sAttCode)) {
try { throw new Exception("Unknown attribute");
$oObject->Set($sAttCode, $realValue); }
} catch (Exception $e) { $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
throw new Exception("$sAttCode: ".$e->getMessage(), $e->getCode()); 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());
}
return $oObject; 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;
}
}

View File

@@ -8,5 +8,5 @@
*/ */
interface iRestInputSanitizer interface iRestInputSanitizer
{ {
public function SanitizeJsonInput(string $sJsonInput): string; public function SanitizeJsonInput(string $sJsonInput): string;
} }

View File

@@ -9,25 +9,25 @@
*/ */
interface iRestServiceProvider interface iRestServiceProvider
{ {
/** /**
* Enumerate services delivered by this class * Enumerate services delivered by this class
* *
* @param string $sVersion The version (e.g. 1.0) supported by the services * @param string $sVersion The version (e.g. 1.0) supported by the services
* *
* @return array An array of hash 'verb' => verb, 'description' => description * @return array An array of hash 'verb' => verb, 'description' => description
* @api * @api
*/ */
public function ListOperations($sVersion); public function ListOperations($sVersion);
/** /**
* Enumerate services delivered by this class * Enumerate services delivered by this class
* *
* @param string $sVersion The version (e.g. 1.0) supported by the services * @param string $sVersion The version (e.g. 1.0) supported by the services
* @param string $sVerb * @param string $sVerb
* @param array $aParams * @param array $aParams
* *
* @return RestResult The standardized result structure (at least a message) * @return RestResult The standardized result structure (at least a message)
* @api * @api
*/ */
public function ExecOperation($sVersion, $sVerb, $aParams); public function ExecOperation($sVersion, $sVerb, $aParams);
} }

View File

@@ -1,10 +1,9 @@
<?php <?php
// Copyright (C) 2010-2024 Combodo SAS // Copyright (C) 2010-2024 Combodo SAS
// //
// This file is part of iTop. // This file is part of iTop.
// //
// iTop is free software; you can redistribute it and/or modify // iTop is free software; you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by // it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
@@ -17,6 +16,7 @@
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with iTop. If not, see <http://www.gnu.org/licenses/> // along with iTop. If not, see <http://www.gnu.org/licenses/>
/** /**
* This class manages the audit "categories". Each category defines a set of objects * This class manages the audit "categories". Each category defines a set of objects
* to check and is linked to a set of rules that determine the valid or invalid objects * to check and is linked to a set of rules that determine the valid or invalid objects
@@ -32,36 +32,34 @@ class AuditCategory extends cmdbAbstractObject
{ {
public static function Init() public static function Init()
{ {
$aParams = $aParams = array
[ (
"category" => "application,grant_by_profile", "category" => "application,grant_by_profile",
"key_type" => "autoincrement", "key_type" => "autoincrement",
"name_attcode" => "name", "name_attcode" => "name",
"state_attcode" => "", "state_attcode" => "",
"reconc_keys" => ['name'], "reconc_keys" => array('name'),
"db_table" => "priv_auditcategory", "db_table" => "priv_auditcategory",
"db_key_field" => "id", "db_key_field" => "id",
"db_finalclass_field" => "", "db_finalclass_field" => "",
'style' => new ormStyle(null, null, null, null, null, '../images/icons/icons8-audit-folder.svg'), 'style' => new ormStyle(null, null, null, null, null, '../images/icons/icons8-audit-folder.svg'),
]; );
MetaModel::Init_Params($aParams); MetaModel::Init_Params($aParams);
MetaModel::Init_AddAttribute(new AttributeString("name", ["description" => "Short name for this category", "allowed_values" => null, "sql" => "name", "default_value" => "", "is_null_allowed" => false, "depends_on" => []])); MetaModel::Init_AddAttribute(new AttributeString("name", array("description"=>"Short name for this category", "allowed_values"=>null, "sql"=>"name", "default_value"=>"", "is_null_allowed"=>false, "depends_on"=>array())));
MetaModel::Init_AddAttribute(new AttributeString("description", ["allowed_values" => null, "sql" => "description", "default_value" => "", "is_null_allowed" => true, "depends_on" => []])); 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 AttributeOQL("definition_set", ["allowed_values" => null, "sql" => "definition_set", "default_value" => "", "is_null_allowed" => false, "depends_on" => []])); MetaModel::Init_AddAttribute(new AttributeOQL("definition_set", array("allowed_values"=>null, "sql"=>"definition_set", "default_value"=>"", "is_null_allowed"=>false, "depends_on"=>array())));
MetaModel::Init_AddAttribute(new AttributeLinkedSet("rules_list", ["linked_class" => "AuditRule", "ext_key_to_me" => "category_id", "allowed_values" => null, "count_min" => 0, "count_max" => 0, "depends_on" => [], "edit_mode" => LINKSET_EDITMODE_INPLACE, "edit_when" => LINKSET_EDITWHEN_ALWAYS, "tracking_level" => LINKSET_TRACKING_ALL])); MetaModel::Init_AddAttribute(new AttributeLinkedSet("rules_list", array("linked_class"=>"AuditRule", "ext_key_to_me"=>"category_id", "allowed_values"=>null, "count_min"=>0, "count_max"=>0, "depends_on"=>array(), "edit_mode" => LINKSET_EDITMODE_INPLACE, "tracking_level" => LINKSET_TRACKING_ALL)));
MetaModel::Init_AddAttribute(new AttributeInteger("ok_error_tolerance", ["allowed_values" => null, "sql" => "ok_error_tolerance", "default_value" => 5, "is_null_allowed" => true, "depends_on" => []])); MetaModel::Init_AddAttribute(new AttributeInteger("ok_error_tolerance", array("allowed_values"=>null, "sql"=>"ok_error_tolerance", "default_value"=>5, "is_null_allowed"=>true, "depends_on"=>array())));
MetaModel::Init_AddAttribute(new AttributeInteger("warning_error_tolerance", ["allowed_values" => null, "sql" => "warning_error_tolerance", "default_value" => 25, "is_null_allowed" => true, "depends_on" => []])); MetaModel::Init_AddAttribute(new AttributeInteger("warning_error_tolerance", array("allowed_values" => null, "sql" => "warning_error_tolerance", "default_value" => 25, "is_null_allowed" => true, "depends_on" => array())));
MetaModel::Init_AddAttribute(new AttributeLinkedSetIndirect( MetaModel::Init_AddAttribute(new AttributeLinkedSetIndirect("domains_list",
"domains_list", array("linked_class" => "lnkAuditCategoryToAuditDomain", "ext_key_to_me" => "category_id", "ext_key_to_remote" => "domain_id", "allowed_values" => null, "count_min" => 0, "count_max" => 0, "depends_on" => array(), "display_style" => 'property')));
["linked_class" => "lnkAuditCategoryToAuditDomain", "ext_key_to_me" => "category_id", "ext_key_to_remote" => "domain_id", "allowed_values" => null, "count_min" => 0, "count_max" => 0, "depends_on" => [], "display_style" => 'property']
));
// Display lists // Display lists
MetaModel::Init_SetZListItems('details', ['name', 'description', 'definition_set', 'ok_error_tolerance', 'warning_error_tolerance', 'rules_list', 'domains_list']); // Attributes to be displayed for the complete details MetaModel::Init_SetZListItems('details', array('name', 'description', 'definition_set', 'ok_error_tolerance', 'warning_error_tolerance', 'rules_list', 'domains_list')); // Attributes to be displayed for the complete details
MetaModel::Init_SetZListItems('list', ['description', ]); // Attributes to be displayed for a list MetaModel::Init_SetZListItems('list', array('description', )); // Attributes to be displayed for a list
// Search criteria // Search criteria
MetaModel::Init_SetZListItems('standard_search', ['description', 'definition_set']); // Criteria of the std search form MetaModel::Init_SetZListItems('standard_search', array('description', 'definition_set')); // Criteria of the std search form
MetaModel::Init_SetZListItems('default_search', ['name', 'description']); // Criteria of the default search form MetaModel::Init_SetZListItems('default_search', array('name', 'description')); // Criteria of the default search form
} }
/** /**
@@ -76,9 +74,9 @@ class AuditCategory extends cmdbAbstractObject
public function GetReportColor($iTotal, $iErrors) public function GetReportColor($iTotal, $iErrors)
{ {
$sResult = 'red'; $sResult = 'red';
if (($iTotal == 0) || ($iErrors / $iTotal) <= ($this->Get('ok_error_tolerance') / 100)) { if ( ($iTotal == 0) || ($iErrors / $iTotal) <= ($this->Get('ok_error_tolerance') / 100) ) {
$sResult = 'green'; $sResult = 'green';
} elseif (($iErrors / $iTotal) <= ($this->Get('warning_error_tolerance') / 100)) { } else if (($iErrors / $iTotal) <= ($this->Get('warning_error_tolerance') / 100)) {
$sResult = 'orange'; $sResult = 'orange';
} }
@@ -95,3 +93,4 @@ class AuditCategory extends cmdbAbstractObject
return $aShortcutActions; return $aShortcutActions;
} }
} }
?>

View File

@@ -1,5 +1,4 @@
<?php <?php
// Copyright (C) 2010-2024 Combodo SAS // Copyright (C) 2010-2024 Combodo SAS
// //
// This file is part of iTop. // This file is part of iTop.
@@ -17,6 +16,7 @@
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with iTop. If not, see <http://www.gnu.org/licenses/> // along with iTop. If not, see <http://www.gnu.org/licenses/>
/** /**
* This class manages the audit "categories". Each category defines a set of objects * This class manages the audit "categories". Each category defines a set of objects
* to check and is linked to a set of rules that determine the valid or invalid objects * to check and is linked to a set of rules that determine the valid or invalid objects
@@ -33,34 +33,32 @@ class AuditDomain extends cmdbAbstractObject
{ {
public static function Init() public static function Init()
{ {
$aParams = $aParams = array
[ (
"category" => "application,grant_by_profile", "category" => "application,grant_by_profile",
"key_type" => "autoincrement", "key_type" => "autoincrement",
"name_attcode" => "name", "name_attcode" => "name",
"complementary_name_attcode" => ['description'], "complementary_name_attcode" => array('description'),
"state_attcode" => "", "state_attcode" => "",
"reconc_keys" => ['name'], "reconc_keys" => array('name'),
"db_table" => "priv_auditdomain", "db_table" => "priv_auditdomain",
"db_key_field" => "id", "db_key_field" => "id",
"db_finalclass_field" => "", "db_finalclass_field" => "",
'style' => new ormStyle(null, null, null, null, null, '../images/icons/icons8-audit-album.svg'), 'style' => new ormStyle(null, null, null, null, null, '../images/icons/icons8-audit-album.svg'),
]; );
MetaModel::Init_Params($aParams); MetaModel::Init_Params($aParams);
MetaModel::Init_AddAttribute(new AttributeString("name", ["description" => "Short name for this category", "allowed_values" => null, "sql" => "name", "default_value" => "", "is_null_allowed" => false, "depends_on" => []])); MetaModel::Init_AddAttribute(new AttributeString("name", array("description" => "Short name for this category", "allowed_values" => null, "sql" => "name", "default_value" => "", "is_null_allowed" => false, "depends_on" => array())));
MetaModel::Init_AddAttribute(new AttributeString("description", ["allowed_values" => null, "sql" => "description", "default_value" => "", "is_null_allowed" => true, "depends_on" => []])); 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 AttributeImage("icon", ["is_null_allowed" => true, "depends_on" => [], "display_max_width" => 96, "display_max_height" => 96, "storage_max_width" => 256, "storage_max_height" => 256, "default_image" => null, "always_load_in_tables" => false])); MetaModel::Init_AddAttribute(new AttributeImage("icon", array("is_null_allowed" => true, "depends_on" => array(), "display_max_width" => 96, "display_max_height" => 96, "storage_max_width" => 256, "storage_max_height" => 256, "default_image" => null, "always_load_in_tables" => false)));
MetaModel::Init_AddAttribute(new AttributeLinkedSetIndirect( MetaModel::Init_AddAttribute(new AttributeLinkedSetIndirect("categories_list",
"categories_list", array("linked_class" => "lnkAuditCategoryToAuditDomain", "ext_key_to_me" => "domain_id", "ext_key_to_remote" => "category_id", "allowed_values" => null, "count_min" => 0, "count_max" => 0, "depends_on" => array())));
["linked_class" => "lnkAuditCategoryToAuditDomain", "ext_key_to_me" => "domain_id", "ext_key_to_remote" => "category_id", "allowed_values" => null, "count_min" => 0, "count_max" => 0, "depends_on" => []]
));
// Display lists // Display lists
MetaModel::Init_SetZListItems('details', ['name', 'description', 'icon', 'categories_list']); // Attributes to be displayed for the complete details MetaModel::Init_SetZListItems('details', array('name', 'description', 'icon', 'categories_list')); // Attributes to be displayed for the complete details
MetaModel::Init_SetZListItems('list', ['description',]); // Attributes to be displayed for a list MetaModel::Init_SetZListItems('list', array('description',)); // Attributes to be displayed for a list
// Search criteria // Search criteria
MetaModel::Init_SetZListItems('standard_search', ['description']); // Criteria of the std search form MetaModel::Init_SetZListItems('standard_search', array('description')); // Criteria of the std search form
MetaModel::Init_SetZListItems('default_search', ['name', 'description']); // Criteria of the default search form MetaModel::Init_SetZListItems('default_search', array('name', 'description')); // Criteria of the default search form
} }
public static function GetShortcutActions($sFinalClass) public static function GetShortcutActions($sFinalClass)
@@ -86,39 +84,40 @@ class lnkAuditCategoryToAuditDomain extends cmdbAbstractObject
*/ */
public static function Init() public static function Init()
{ {
$aParams = $aParams = array
[ (
"category" => "application,grant_by_profile", "category" => "application,grant_by_profile",
"key_type" => "autoincrement", "key_type" => "autoincrement",
"name_attcode" => "", "name_attcode" => "",
"state_attcode" => "", "state_attcode" => "",
"reconc_keys" => ['category_id', 'domain_id'], "reconc_keys" => array('category_id', 'domain_id'),
"db_table" => "priv_link_audit_category_domain", "db_table" => "priv_link_audit_category_domain",
"db_key_field" => "id", "db_key_field" => "id",
"db_finalclass_field" => "", "db_finalclass_field" => "",
"is_link" => true, "is_link" => true,
'uniqueness_rules' => [ 'uniqueness_rules' => array(
'no_duplicate' => [ 'no_duplicate' => array(
'attributes' => [ 'attributes' => array(
0 => 'category_id', 0 => 'category_id',
1 => 'domain_id', 1 => 'domain_id',
], ),
'filter' => '', 'filter' => '',
'disabled' => false, 'disabled' => false,
'is_blocking' => true, 'is_blocking' => true,
], ),
], ),
]; );
MetaModel::Init_Params($aParams); MetaModel::Init_Params($aParams);
MetaModel::Init_AddAttribute(new AttributeExternalKey("category_id", ["targetclass" => "AuditCategory", "jointype" => '', "allowed_values" => null, "sql" => "category_id", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => []])); MetaModel::Init_AddAttribute(new AttributeExternalKey("category_id", array("targetclass" => "AuditCategory", "jointype" => '', "allowed_values" => null, "sql" => "category_id", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => array())));
MetaModel::Init_AddAttribute(new AttributeExternalField("category_name", ["allowed_values" => null, "extkey_attcode" => 'category_id', "target_attcode" => "name"])); MetaModel::Init_AddAttribute(new AttributeExternalField("category_name", array("allowed_values" => null, "extkey_attcode" => 'category_id', "target_attcode" => "name")));
MetaModel::Init_AddAttribute(new AttributeExternalKey("domain_id", ["targetclass" => "AuditDomain", "jointype" => '', "allowed_values" => null, "sql" => "domain_id", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => []])); MetaModel::Init_AddAttribute(new AttributeExternalKey("domain_id", array("targetclass" => "AuditDomain", "jointype" => '', "allowed_values" => null, "sql" => "domain_id", "is_null_allowed" => false, "on_target_delete" => DEL_AUTO, "depends_on" => array())));
MetaModel::Init_AddAttribute(new AttributeExternalField("domain_name", ["allowed_values" => null, "extkey_attcode" => 'domain_id', "target_attcode" => "name"])); MetaModel::Init_AddAttribute(new AttributeExternalField("domain_name", array("allowed_values" => null, "extkey_attcode" => 'domain_id', "target_attcode" => "name")));
// Display lists // Display lists
MetaModel::Init_SetZListItems('details', ['category_id', 'domain_id']); MetaModel::Init_SetZListItems('details', array('category_id', 'domain_id'));
MetaModel::Init_SetZListItems('list', ['category_id', 'domain_id']); MetaModel::Init_SetZListItems('list', array('category_id', 'domain_id'));
// Search criteria // Search criteria
MetaModel::Init_SetZListItems('standard_search', ['category_id', 'domain_id']); MetaModel::Init_SetZListItems('standard_search', array('category_id', 'domain_id'));
} }
} }

View File

@@ -1,10 +1,9 @@
<?php <?php
// Copyright (C) 2010-2024 Combodo SAS // Copyright (C) 2010-2024 Combodo SAS
// //
// This file is part of iTop. // This file is part of iTop.
// //
// iTop is free software; you can redistribute it and/or modify // iTop is free software; you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by // it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
@@ -17,6 +16,7 @@
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with iTop. If not, see <http://www.gnu.org/licenses/> // along with iTop. If not, see <http://www.gnu.org/licenses/>
/** /**
* This class manages the audit "rule" linked to a given audit category. * This class manages the audit "rule" linked to a given audit category.
* Each rule is based on an OQL expression that returns either the "good" objects * Each rule is based on an OQL expression that returns either the "good" objects
@@ -33,35 +33,35 @@ class AuditRule extends cmdbAbstractObject
{ {
public static function Init() public static function Init()
{ {
$aParams = $aParams = array
[ (
"category" => "application,grant_by_profile", "category" => "application,grant_by_profile",
"key_type" => "autoincrement", "key_type" => "autoincrement",
"name_attcode" => "name", "name_attcode" => "name",
"state_attcode" => "", "state_attcode" => "",
"reconc_keys" => ['name'], "reconc_keys" => array('name'),
"db_table" => "priv_auditrule", "db_table" => "priv_auditrule",
"db_key_field" => "id", "db_key_field" => "id",
"db_finalclass_field" => "", "db_finalclass_field" => "",
'style' => new ormStyle(null, null, null, null, null, '../images/icons/icons8-audit.svg'), 'style' => new ormStyle(null, null, null, null, null, '../images/icons/icons8-audit.svg'),
]; );
MetaModel::Init_Params($aParams); MetaModel::Init_Params($aParams);
MetaModel::Init_AddAttribute(new AttributeString("name", ["allowed_values" => null, "sql" => "name", "default_value" => "", "is_null_allowed" => false, "depends_on" => []])); 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", ["allowed_values" => null, "sql" => "description", "default_value" => "", "is_null_allowed" => true, "depends_on" => []])); 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 AttributeOQL("query", ["allowed_values" => null, "sql" => "query", "default_value" => "", "is_null_allowed" => false, "depends_on" => []])); MetaModel::Init_AddAttribute(new AttributeOQL("query", array("allowed_values" => null, "sql" => "query", "default_value" => "", "is_null_allowed" => false, "depends_on" => array())));
MetaModel::Init_AddAttribute(new AttributeEnum("valid_flag", ["allowed_values" => new ValueSetEnum('true,false'), "sql" => "valid_flag", "default_value" => "true", "is_null_allowed" => false, "depends_on" => []])); MetaModel::Init_AddAttribute(new AttributeEnum("valid_flag", array("allowed_values" => new ValueSetEnum('true,false'), "sql" => "valid_flag", "default_value" => "true", "is_null_allowed" => false, "depends_on" => array())));
MetaModel::Init_AddAttribute(new AttributeExternalKey("category_id", ["allowed_values" => null, "sql" => "category_id", "targetclass" => "AuditCategory", "is_null_allowed" => false, "on_target_delete" => DEL_MANUAL, "depends_on" => []])); MetaModel::Init_AddAttribute(new AttributeExternalKey("category_id", array("allowed_values" => null, "sql" => "category_id", "targetclass" => "AuditCategory", "is_null_allowed" => false, "on_target_delete" => DEL_MANUAL, "depends_on" => array())));
MetaModel::Init_AddAttribute(new AttributeExternalField("category_name", ["allowed_values" => null, "extkey_attcode" => 'category_id', "target_attcode" => "name"])); MetaModel::Init_AddAttribute(new AttributeExternalField("category_name", array("allowed_values" => null, "extkey_attcode" => 'category_id', "target_attcode" => "name")));
MetaModel::Init_AddAttribute(new AttributeExternalKey("contact_id", ["allowed_values" => null, "sql" => "contact_id", "targetclass" => "Contact", "is_null_allowed" => true, "on_target_delete" => DEL_MANUAL, "depends_on" => []]));
MetaModel::Init_AddAttribute(new AttributeHTML("process", ["allowed_values" => null, "sql" => "process", "default_value" => "", "is_null_allowed" => true, "depends_on" => []]));
// Display lists // Display lists
MetaModel::Init_SetZListItems('details', ['category_id', 'name', 'description', 'query', 'valid_flag', 'process', 'contact_id']); // Attributes to be displayed for the complete details MetaModel::Init_SetZListItems('details', array('category_id', 'name', 'description', 'query', 'valid_flag')); // Attributes to be displayed for the complete details
MetaModel::Init_SetZListItems('list', ['category_id', 'description', 'query']); // Attributes to be displayed for a list MetaModel::Init_SetZListItems('list', array('category_id', 'description', 'valid_flag')); // Attributes to be displayed for a list
// Search criteria // Search criteria
MetaModel::Init_SetZListItems('standard_search', ['category_id', 'name', 'description', 'valid_flag', 'query']); // Criteria of the std search form MetaModel::Init_SetZListItems('standard_search', array('category_id', 'name', 'description', 'valid_flag', 'query')); // Criteria of the std search form
MetaModel::Init_SetZListItems('default_search', ['name', 'description', 'category_id', 'contact_id', 'query']); // Criteria of the advanced search form MetaModel::Init_SetZListItems('default_search', array('name', 'description', 'category_id')); // Criteria of the advanced search form
} }
public static function GetShortcutActions($sFinalClass) public static function GetShortcutActions($sFinalClass)
{ {
$aShortcutActions = parent::GetShortcutActions($sFinalClass); $aShortcutActions = parent::GetShortcutActions($sFinalClass);
@@ -72,3 +72,4 @@ class AuditRule extends cmdbAbstractObject
return $aShortcutActions; return $aShortcutActions;
} }
} }
?>

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,4 @@
<?php <?php
/** /**
* Copyright (C) 2013-2024 Combodo SAS * Copyright (C) 2013-2024 Combodo SAS
* *
@@ -33,8 +32,7 @@ class CompileCSSService
{ {
} }
public function CompileCSSFromSASS($sSassContent, $aImportPaths = [], $aVariables = []) public function CompileCSSFromSASS($sSassContent, $aImportPaths = [], $aVariables = []){
{
return utils::CompileCSSFromSASS($sSassContent, $aImportPaths, $aVariables); return utils::CompileCSSFromSASS($sSassContent, $aImportPaths, $aVariables);
} }
} }

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -54,7 +53,7 @@ abstract class Dashboard
$this->sLayoutClass = 'DashboardLayoutOneCol'; $this->sLayoutClass = 'DashboardLayoutOneCol';
$this->bAutoReload = false; $this->bAutoReload = false;
$this->iAutoReloadSec = MetaModel::GetConfig()->GetStandardReloadInterval(); $this->iAutoReloadSec = MetaModel::GetConfig()->GetStandardReloadInterval();
$this->aCells = []; $this->aCells = array();
$this->oDOMNode = null; $this->oDOMNode = null;
$this->sId = $sId; $this->sId = $sId;
} }
@@ -66,8 +65,8 @@ abstract class Dashboard
*/ */
public function FromXml($sXml) public function FromXml($sXml)
{ {
$this->aCells = []; // reset the content of the dashboard $this->aCells = array(); // reset the content of the dashboard
set_error_handler(['Dashboard', 'ErrorHandler']); set_error_handler(array('Dashboard', 'ErrorHandler'));
$oDoc = new DOMDocument(); $oDoc = new DOMDocument();
$oDoc->loadXML($sXml); $oDoc->loadXML($sXml);
restore_error_handler(); restore_error_handler();
@@ -80,69 +79,87 @@ abstract class Dashboard
public function FromDOMDocument(DOMDocument $oDoc) public function FromDOMDocument(DOMDocument $oDoc)
{ {
$this->oDOMNode = $oDoc->getElementsByTagName('dashboard')->item(0); $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; $this->sLayoutClass = $oLayoutNode->textContent;
} else { }
else
{
$this->sLayoutClass = 'DashboardLayoutOneCol'; $this->sLayoutClass = 'DashboardLayoutOneCol';
} }
if ($oTitleNode = $this->oDOMNode->getElementsByTagName('title')->item(0)) { if ($oTitleNode = $this->oDOMNode->getElementsByTagName('title')->item(0))
{
$this->sTitle = $oTitleNode->textContent; $this->sTitle = $oTitleNode->textContent;
} else { }
else
{
$this->sTitle = ''; $this->sTitle = '';
} }
$this->bAutoReload = false; $this->bAutoReload = false;
$this->iAutoReloadSec = MetaModel::GetConfig()->GetStandardReloadInterval(); $this->iAutoReloadSec = MetaModel::GetConfig()->GetStandardReloadInterval();
if ($oAutoReloadNode = $this->oDOMNode->getElementsByTagName('auto_reload')->item(0)) { if ($oAutoReloadNode = $this->oDOMNode->getElementsByTagName('auto_reload')->item(0))
if ($oAutoReloadEnabled = $oAutoReloadNode->getElementsByTagName('enabled')->item(0)) { {
if ($oAutoReloadEnabled = $oAutoReloadNode->getElementsByTagName('enabled')->item(0))
{
$this->bAutoReload = ($oAutoReloadEnabled->textContent == 'true'); $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); $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'); $oCellsList = $oCellsNode->getElementsByTagName('cell');
$aCellOrder = []; $aCellOrder = array();
$iCellRank = 0; $iCellRank = 0;
/** @var \DOMElement $oCellNode */ /** @var \DOMElement $oCellNode */
foreach ($oCellsList as $oCellNode) { foreach($oCellsList as $oCellNode)
{
$oCellRank = $oCellNode->getElementsByTagName('rank')->item(0); $oCellRank = $oCellNode->getElementsByTagName('rank')->item(0);
if ($oCellRank) { if ($oCellRank)
{
$iCellRank = (float)$oCellRank->textContent; $iCellRank = (float)$oCellRank->textContent;
} }
$oDashletsNode = $oCellNode->getElementsByTagName('dashlets')->item(0); $oDashletsNode = $oCellNode->getElementsByTagName('dashlets')->item(0);
{ {
$oDashletList = $oDashletsNode->getElementsByTagName('dashlet'); $oDashletList = $oDashletsNode->getElementsByTagName('dashlet');
$iRank = 0; $iRank = 0;
$aDashletOrder = []; $aDashletOrder = array();
/** @var \DOMElement $oDomNode */ /** @var \DOMElement $oDomNode */
foreach ($oDashletList as $oDomNode) { foreach($oDashletList as $oDomNode)
{
$oRank = $oDomNode->getElementsByTagName('rank')->item(0); $oRank = $oDomNode->getElementsByTagName('rank')->item(0);
if ($oRank) { if ($oRank)
{
$iRank = (float)$oRank->textContent; $iRank = (float)$oRank->textContent;
} }
$oNewDashlet = $this->InitDashletFromDOMNode($oDomNode); $oNewDashlet = $this->InitDashletFromDOMNode($oDomNode);
$aDashletOrder[] = ['rank' => $iRank, 'dashlet' => $oNewDashlet]; $aDashletOrder[] = array('rank' => $iRank, 'dashlet' => $oNewDashlet);
} }
usort($aDashletOrder, [get_class($this), 'SortOnRank']); usort($aDashletOrder, array(get_class($this), 'SortOnRank'));
$aDashletList = []; $aDashletList = array();
foreach ($aDashletOrder as $aItem) { foreach($aDashletOrder as $aItem)
{
$aDashletList[] = $aItem['dashlet']; $aDashletList[] = $aItem['dashlet'];
} }
$aCellOrder[] = ['rank' => $iCellRank, 'dashlets' => $aDashletList]; $aCellOrder[] = array('rank' => $iCellRank, 'dashlets' => $aDashletList);
} }
} }
usort($aCellOrder, [get_class($this), 'SortOnRank']); usort($aCellOrder, array(get_class($this), 'SortOnRank'));
foreach ($aCellOrder as $aItem) { foreach($aCellOrder as $aItem)
{
$this->aCells[] = $aItem['dashlets']; $this->aCells[] = $aItem['dashlets'];
} }
} else { }
$this->aCells = []; else
{
$this->aCells = array();
} }
} }
@@ -152,20 +169,20 @@ abstract class Dashboard
* @return mixed * @return mixed
*/ */
protected function InitDashletFromDOMNode($oDomNode) 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 // Test if dashlet can be instantiated, otherwise (uninstalled, broken, ...) we display a placeholder
$sClass = static::GetDashletClassFromType($sDashletType); $sClass = static::GetDashletClassFromType($sDashletType);
/** @var \Dashlet $oNewDashlet */ /** @var \Dashlet $oNewDashlet */
$oNewDashlet = new $sClass($this->oMetaModel, $sId); $oNewDashlet = new $sClass($this->oMetaModel, $sId);
$oNewDashlet->SetDashletType($sDashletType); $oNewDashlet->SetDashletType($sDashletType);
$oNewDashlet->FromDOMNode($oDomNode); $oNewDashlet->FromDOMNode($oDomNode);
return $oNewDashlet; return $oNewDashlet;
} }
/** /**
* @param array $aItem1 * @param array $aItem1
@@ -191,9 +208,12 @@ abstract class Dashboard
*/ */
public static function ErrorHandler($errno, $errstr, $errfile, $errline) 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); throw new DOMException($errstr);
} else { }
else
{
return false; return false;
} }
} }
@@ -211,7 +231,7 @@ abstract class Dashboard
$oMainNode = $oDoc->createElement('dashboard'); $oMainNode = $oDoc->createElement('dashboard');
$oMainNode->setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance"); $oMainNode->setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance");
$oDoc->appendChild($oMainNode); $oDoc->appendChild($oMainNode);
$this->ToDOMNode($oMainNode); $this->ToDOMNode($oMainNode);
$sXml = $oDoc->saveXML(); $sXml = $oDoc->saveXML();
@@ -241,21 +261,23 @@ abstract class Dashboard
$oCellsNode = $oDoc->createElement('cells'); $oCellsNode = $oDoc->createElement('cells');
$oDefinition->appendChild($oCellsNode); $oDefinition->appendChild($oCellsNode);
$iCellRank = 0; $iCellRank = 0;
foreach ($this->aCells as $aCell) { foreach ($this->aCells as $aCell)
{
$oCellNode = $oDoc->createElement('cell'); $oCellNode = $oDoc->createElement('cell');
$oCellNode->setAttribute('id', $iCellRank); $oCellNode->setAttribute('id', $iCellRank);
$oCellsNode->appendChild($oCellNode); $oCellsNode->appendChild($oCellNode);
$oCellRank = $oDoc->createElement('rank', $iCellRank); $oCellRank = $oDoc->createElement('rank', $iCellRank);
$oCellNode->appendChild($oCellRank); $oCellNode->appendChild($oCellRank);
$iCellRank++; $iCellRank++;
$iDashletRank = 0; $iDashletRank = 0;
$oDashletsNode = $oDoc->createElement('dashlets'); $oDashletsNode = $oDoc->createElement('dashlets');
$oCellNode->appendChild($oDashletsNode); $oCellNode->appendChild($oDashletsNode);
/** @var \Dashlet $oDashlet */ /** @var \Dashlet $oDashlet */
foreach ($aCell as $oDashlet) { foreach ($aCell as $oDashlet)
{
$oNode = $oDoc->createElement('dashlet'); $oNode = $oDoc->createElement('dashlet');
$oDashletsNode->appendChild($oNode); $oDashletsNode->appendChild($oNode);
$oNode->setAttribute('id', $oDashlet->GetID()); $oNode->setAttribute('id', $oDashlet->GetID());
@@ -274,16 +296,16 @@ abstract class Dashboard
public function FromParams($aParams) public function FromParams($aParams)
{ {
$this->sLayoutClass = $aParams['layout_class']; $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'].'"'); throw new InvalidParameterException('Invalid parameter layout_class "'.$aParams['layout_class'].'"');
} }
$this->sTitle = $aParams['title']; $this->sTitle = $aParams['title'];
$this->bAutoReload = $aParams['auto_reload'] == 'true'; $this->bAutoReload = $aParams['auto_reload'] == 'true';
$this->iAutoReloadSec = max(MetaModel::GetConfig()->Get('min_reload_interval'), (int) $aParams['auto_reload_sec']); $this->iAutoReloadSec = max(MetaModel::GetConfig()->Get('min_reload_interval'), (int) $aParams['auto_reload_sec']);
foreach ($aParams['cells'] as $aCell) { foreach($aParams['cells'] as $aCell) {
$aCellDashlets = []; $aCellDashlets = array();
foreach ($aCell as $aDashletParams) { foreach($aCell as $aDashletParams) {
$sDashletClass = $aDashletParams['dashlet_class']; $sDashletClass = $aDashletParams['dashlet_class'];
$sId = $aDashletParams['dashlet_id']; $sId = $aDashletParams['dashlet_id'];
/** @var \Dashlet $oNewDashlet */ /** @var \Dashlet $oNewDashlet */
@@ -300,12 +322,12 @@ abstract class Dashboard
} }
$this->aCells[] = $aCellDashlets; $this->aCells[] = $aCellDashlets;
} }
} }
public function Save() public function Save()
{ {
} }
/** /**
@@ -398,7 +420,7 @@ abstract class Dashboard
{ {
$sId = $this->GetNewDashletId(); $sId = $this->GetNewDashletId();
$oDashlet->SetId($sId); $oDashlet->SetId($sId);
$this->aCells[] = [$oDashlet]; $this->aCells[] = array($oDashlet);
} }
/** /**
@@ -408,7 +430,7 @@ abstract class Dashboard
* @throws \ReflectionException * @throws \ReflectionException
* @throws \Exception * @throws \Exception
*/ */
public function RenderProperties($oPage, $aExtraParams = []) public function RenderProperties($oPage, $aExtraParams = array())
{ {
// menu to pick a layout and edit other properties of the dashboard // menu to pick a layout and edit other properties of the dashboard
$oPage->add('<div class="ui-widget-content ui-corner-all ibo-dashboard-editor--properties"><div class="ui-widget-header ui-corner-all ibo-dashboard-editor--properties-title">'.Dict::S('UI:DashboardEdit:Properties').'</div>'); $oPage->add('<div class="ui-widget-content ui-corner-all ibo-dashboard-editor--properties"><div class="ui-widget-header ui-corner-all ibo-dashboard-editor--properties-title">'.Dict::S('UI:DashboardEdit:Properties').'</div>');
@@ -420,7 +442,7 @@ abstract class Dashboard
if (is_subclass_of($sLayoutClass, 'DashboardLayout')) { if (is_subclass_of($sLayoutClass, 'DashboardLayout')) {
$oReflection = new ReflectionClass($sLayoutClass); $oReflection = new ReflectionClass($sLayoutClass);
if (!$oReflection->isAbstract()) { if (!$oReflection->isAbstract()) {
$aCallSpec = [$sLayoutClass, 'GetInfo']; $aCallSpec = array($sLayoutClass, 'GetInfo');
$aInfo = call_user_func($aCallSpec); $aInfo = call_user_func($aCallSpec);
$sChecked = ($this->sLayoutClass == $sLayoutClass) ? 'checked' : ''; $sChecked = ($this->sLayoutClass == $sLayoutClass) ? 'checked' : '';
$oPage->add('<input type="radio" name="layout_class" '.$sChecked.' value="'.$sLayoutClass.'" id="layout_'.$sLayoutClass.'"><label for="layout_'.$sLayoutClass.'"><img src="'.$sUrl.$aInfo['icon'].'" class="ibo-dashboard--properties--icon" data-role="ibo-dashboard--properties--icon"/></label>'); // title="" on either the img or the label does nothing ! $oPage->add('<input type="radio" name="layout_class" '.$sChecked.' value="'.$sLayoutClass.'" id="layout_'.$sLayoutClass.'"><label for="layout_'.$sLayoutClass.'"><img src="'.$sUrl.$aInfo['icon'].'" class="ibo-dashboard--properties--icon" data-role="ibo-dashboard--properties--icon"/></label>'); // title="" on either the img or the label does nothing !
@@ -444,6 +466,7 @@ abstract class Dashboard
$oField->SetBoundaries(MetaModel::GetConfig()->Get('min_reload_interval'), null); // no upper limit $oField->SetBoundaries(MetaModel::GetConfig()->Get('min_reload_interval'), null); // no upper limit
$oForm->AddField($oField); $oForm->AddField($oField);
$this->SetFormParams($oForm, $aExtraParams); $this->SetFormParams($oForm, $aExtraParams);
$oForm->RenderAsPropertySheet($oPage, false, '.itop-dashboard'); $oForm->RenderAsPropertySheet($oPage, false, '.itop-dashboard');
@@ -451,7 +474,7 @@ abstract class Dashboard
$sRateTitle = addslashes(Dict::Format('UI:DashboardEdit:AutoReloadSec+', MetaModel::GetConfig()->Get('min_reload_interval'))); $sRateTitle = addslashes(Dict::Format('UI:DashboardEdit:AutoReloadSec+', MetaModel::GetConfig()->Get('min_reload_interval')));
$oPage->add_ready_script( $oPage->add_ready_script(
<<<EOF <<<EOF
// Note: the title gets deleted by the validation mechanism // Note: the title gets deleted by the validation mechanism
$("#attr_auto_reload_sec").attr('data-tooltip-content', '$sRateTitle'); $("#attr_auto_reload_sec").attr('data-tooltip-content', '$sRateTitle');
CombodoTooltip.InitTooltipFromMarkup($("#attr_auto_reload_sec")); CombodoTooltip.InitTooltipFromMarkup($("#attr_auto_reload_sec"));
@@ -499,7 +522,7 @@ EOF
* *
* @return \Combodo\iTop\Application\UI\Base\Layout\Dashboard\DashboardLayout * @return \Combodo\iTop\Application\UI\Base\Layout\Dashboard\DashboardLayout
*/ */
public function Render($oPage, $bEditMode = false, $aExtraParams = [], $bCanEdit = true) public function Render($oPage, $bEditMode = false, $aExtraParams = array(), $bCanEdit = true)
{ {
$aExtraParams['dashboard_div_id'] = utils::Sanitize($aExtraParams['dashboard_div_id'] ?? null, $this->GetId(), utils::ENUM_SANITIZATION_FILTER_ELEMENT_IDENTIFIER); $aExtraParams['dashboard_div_id'] = utils::Sanitize($aExtraParams['dashboard_div_id'] ?? null, $this->GetId(), utils::ENUM_SANITIZATION_FILTER_ELEMENT_IDENTIFIER);
@@ -528,8 +551,7 @@ EOF
$oToolbar->AddHtml($sHtml); $oToolbar->AddHtml($sHtml);
} else { } else {
$oPage->add_script( $oPage->add_script(<<<JS
<<<JS
$(".ibo-top-bar--toolbar-dashboard-title").html("$sTitleForHTML").attr("title", $('<div>').html("$sTitleForHTML").text()); $(".ibo-top-bar--toolbar-dashboard-title").html("$sTitleForHTML").attr("title", $('<div>').html("$sTitleForHTML").text());
JS JS
); );
@@ -573,7 +595,7 @@ JS
* @param WebPage $oPage * @param WebPage $oPage
* @param array $aExtraParams * @param array $aExtraParams
*/ */
public function RenderDashletsProperties(WebPage $oPage, $aExtraParams = []) public function RenderDashletsProperties(WebPage $oPage, $aExtraParams = array())
{ {
// Toolbox/palette to edit the properties of each dashlet // Toolbox/palette to edit the properties of each dashlet
$oPage->add('<div class="ui-widget-content ui-corner-all ibo-dashlet--properties"><div class="ui-widget-header ui-corner-all ibo-dashlet--properties--title">'.Dict::S('UI:DashboardEdit:DashletProperties').'</div>'); $oPage->add('<div class="ui-widget-content ui-corner-all ibo-dashlet--properties"><div class="ui-widget-header ui-corner-all ibo-dashlet--properties--title">'.Dict::S('UI:DashboardEdit:DashletProperties').'</div>');
@@ -582,10 +604,13 @@ JS
$oLayout = new $this->sLayoutClass(); $oLayout = new $this->sLayoutClass();
$oPage->add('<div id="dashlet_properties">'); $oPage->add('<div id="dashlet_properties">');
foreach ($this->aCells as $iCellIdx => $aCell) { foreach($this->aCells as $iCellIdx => $aCell)
{
/** @var \Dashlet $oDashlet */ /** @var \Dashlet $oDashlet */
foreach ($aCell as $oDashlet) { foreach($aCell as $oDashlet)
if ($oDashlet->IsVisible()) { {
if ($oDashlet->IsVisible())
{
$oPage->add('<div class="dashlet_properties" id="dashlet_properties_'.$oDashlet->GetID().'" style="display:none">'); $oPage->add('<div class="dashlet_properties" id="dashlet_properties_'.$oDashlet->GetID().'" style="display:none">');
$oForm = $oDashlet->GetForm(); $oForm = $oDashlet->GetForm();
$this->SetFormParams($oForm, $aExtraParams); $this->SetFormParams($oForm, $aExtraParams);
@@ -607,17 +632,18 @@ JS
*/ */
protected function GetAvailableDashlets() protected function GetAvailableDashlets()
{ {
$aDashlets = []; $aDashlets = array();
foreach (get_declared_classes() as $sDashletClass) { foreach( get_declared_classes() as $sDashletClass)
{
// DashletUnknown is not among the selection as it is just a fallback for dashlets that can't instantiated. // DashletUnknown is not among the selection as it is just a fallback for dashlets that can't instantiated.
if (is_subclass_of($sDashletClass, 'Dashlet') && !in_array($sDashletClass, ['DashletUnknown', 'DashletProxy'])) { if (is_subclass_of($sDashletClass, 'Dashlet') && !in_array($sDashletClass, array('DashletUnknown', 'DashletProxy'))) {
$oReflection = new ReflectionClass($sDashletClass); $oReflection = new ReflectionClass($sDashletClass);
if (!$oReflection->isAbstract()) { if (!$oReflection->isAbstract()) {
$aCallSpec = [$sDashletClass, 'IsVisible']; $aCallSpec = array($sDashletClass, 'IsVisible');
$bVisible = call_user_func($aCallSpec); $bVisible = call_user_func($aCallSpec);
if ($bVisible) { if ($bVisible) {
$aCallSpec = [$sDashletClass, 'GetInfo']; $aCallSpec = array($sDashletClass, 'GetInfo');
$aInfo = call_user_func($aCallSpec); $aInfo = call_user_func($aCallSpec);
$aDashlets[$sDashletClass] = $aInfo; $aDashlets[$sDashletClass] = $aInfo;
} }
@@ -634,9 +660,11 @@ JS
protected function GetNewDashletId() protected function GetNewDashletId()
{ {
$iNewId = 0; $iNewId = 0;
foreach ($this->aCells as $aDashlets) { foreach($this->aCells as $aDashlets)
{
/** @var \Dashlet $oDashlet */ /** @var \Dashlet $oDashlet */
foreach ($aDashlets as $oDashlet) { foreach($aDashlets as $oDashlet)
{
$iNewId = max($iNewId, (int)$oDashlet->GetID()); $iNewId = max($iNewId, (int)$oDashlet->GetID());
} }
} }
@@ -653,15 +681,15 @@ JS
* *
* @return void * @return void
*/ */
abstract protected function PrepareDashletForRendering(Dashlet $oDashlet, $aCoordinates, $aExtraParams = []); abstract protected function PrepareDashletForRendering(Dashlet $oDashlet, $aCoordinates, $aExtraParams = array());
/** /**
* @param \DesignerForm $oForm * @param \DesignerForm $oForm
* @param array $aExtraParams * @param array $aExtraParams
* *
* @return mixed * @return mixed
*/ */
abstract protected function SetFormParams($oForm, $aExtraParams = []); abstract protected function SetFormParams($oForm, $aExtraParams = array());
/** /**
* @param string $sType * @param string $sType
@@ -671,7 +699,8 @@ JS
*/ */
public static function GetDashletClassFromType($sType, $oFactory = null) public static function GetDashletClassFromType($sType, $oFactory = null)
{ {
if (is_subclass_of($sType, 'Dashlet')) { if (is_subclass_of($sType, 'Dashlet'))
{
return $sType; return $sType;
} }
return 'DashletUnknown'; return 'DashletUnknown';
@@ -694,12 +723,14 @@ JS
*/ */
public static function GetDashletUniqueId($bIsCustomized, $sDashboardDivId, $iRow, $iCol, $sDashletOrigId) public static function GetDashletUniqueId($bIsCustomized, $sDashboardDivId, $iRow, $iCol, $sDashletOrigId)
{ {
if (strpos($sDashletOrigId, '_ID_row') !== false) { if(strpos($sDashletOrigId, '_ID_row') !== false)
{
return $sDashletOrigId; return $sDashletOrigId;
} }
$sDashletId = $sDashboardDivId."_ID_row".$iRow."_col".$iCol."_".$sDashletOrigId; $sDashletId = $sDashboardDivId."_ID_row".$iRow."_col".$iCol."_".$sDashletOrigId;
if ($bIsCustomized) { if ($bIsCustomized)
{
$sDashletId = 'CUSTOM_'.$sDashletId; $sDashletId = 'CUSTOM_'.$sDashletId;
} }
@@ -751,9 +782,9 @@ class RuntimeDashboard extends Dashboard
* @inheritDoc * @inheritDoc
* @throws \Exception * @throws \Exception
*/ */
protected function SetFormParams($oForm, $aExtraParams = []) protected function SetFormParams($oForm, $aExtraParams = array())
{ {
$oForm->SetSubmitParams(utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php', ['operation' => 'update_dashlet_property', 'extra_params' => $aExtraParams]); $oForm->SetSubmitParams(utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php', array('operation' => 'update_dashlet_property', 'extra_params' => $aExtraParams));
} }
/** /**
@@ -769,11 +800,14 @@ class RuntimeDashboard extends Dashboard
$oUDSearch->AddCondition('menu_code', $this->sId, '='); $oUDSearch->AddCondition('menu_code', $this->sId, '=');
$oUDSet = new DBObjectSet($oUDSearch); $oUDSet = new DBObjectSet($oUDSearch);
$bIsNew = false; $bIsNew = false;
if ($oUDSet->Count() > 0) { if ($oUDSet->Count() > 0)
{
// Assuming there is at most one couple {user, menu}! // Assuming there is at most one couple {user, menu}!
$oUserDashboard = $oUDSet->Fetch(); $oUserDashboard = $oUDSet->Fetch();
$oUserDashboard->Set('contents', $sXml); $oUserDashboard->Set('contents', $sXml);
} else { }
else
{
// No such customized dashboard for the current user, let's create a new record // No such customized dashboard for the current user, let's create a new record
$oUserDashboard = new UserDashboard(); $oUserDashboard = new UserDashboard();
$oUserDashboard->Set('user_id', UserRights::GetUserId()); $oUserDashboard->Set('user_id', UserRights::GetUserId());
@@ -804,7 +838,8 @@ class RuntimeDashboard extends Dashboard
$oUDSearch->AddCondition('user_id', UserRights::GetUserId(), '='); $oUDSearch->AddCondition('user_id', UserRights::GetUserId(), '=');
$oUDSearch->AddCondition('menu_code', $this->sId, '='); $oUDSearch->AddCondition('menu_code', $this->sId, '=');
$oUDSet = new DBObjectSet($oUDSearch); $oUDSet = new DBObjectSet($oUDSearch);
if ($oUDSet->Count() > 0) { if ($oUDSet->Count() > 0)
{
// Assuming there is at most one couple {user, menu}! // Assuming there is at most one couple {user, menu}!
$oUserDashboard = $oUDSet->Fetch(); $oUserDashboard = $oUDSet->Fetch();
utils::PushArchiveMode(false); utils::PushArchiveMode(false);
@@ -848,11 +883,14 @@ class RuntimeDashboard extends Dashboard
} else { } else {
$sDashboardDefinition = @file_get_contents($sDashboardFileSanitized); $sDashboardDefinition = @file_get_contents($sDashboardFileSanitized);
} }
} else { }
else
{
$sDashboardDefinition = @file_get_contents($sDashboardFileSanitized); $sDashboardDefinition = @file_get_contents($sDashboardFileSanitized);
} }
if ($sDashboardDefinition !== false) { if ($sDashboardDefinition !== false)
{
$oDashboard = new RuntimeDashboard($sDashBoardId); $oDashboard = new RuntimeDashboard($sDashBoardId);
$oDashboard->FromXml($sDashboardDefinition); $oDashboard->FromXml($sDashboardDefinition);
$oDashboard->SetCustomFlag($bCustomized); $oDashboard->SetCustomFlag($bCustomized);
@@ -899,6 +937,7 @@ class RuntimeDashboard extends Dashboard
$sDashboardDefinition = @file_get_contents($sDashboardFileSanitized); $sDashboardDefinition = @file_get_contents($sDashboardFileSanitized);
} }
if ($sDashboardDefinition !== false) { if ($sDashboardDefinition !== false) {
$oDashboard = new RuntimeDashboard($sDashBoardId); $oDashboard = new RuntimeDashboard($sDashBoardId);
$oDashboard->FromXml($sDashboardDefinition); $oDashboard->FromXml($sDashboardDefinition);
@@ -915,11 +954,11 @@ class RuntimeDashboard extends Dashboard
* @inheritDoc * @inheritDoc
* @throws \Exception * @throws \Exception
*/ */
public function Render($oPage, $bEditMode = false, $aExtraParams = [], $bCanEdit = true) public function Render($oPage, $bEditMode = false, $aExtraParams = array(), $bCanEdit = true)
{ {
if (!isset($aExtraParams['query_params']) && isset($aExtraParams['this->class'])) { if (!isset($aExtraParams['query_params']) && isset($aExtraParams['this->class'])) {
$oObj = MetaModel::GetObject($aExtraParams['this->class'], $aExtraParams['this->id']); $oObj = MetaModel::GetObject($aExtraParams['this->class'], $aExtraParams['this->id']);
$aRenderParams = ['query_params' => $oObj->ToArgsForQuery()]; $aRenderParams = array('query_params' => $oObj->ToArgsForQuery());
} else { } else {
$aRenderParams = $aExtraParams; $aRenderParams = $aExtraParams;
} }
@@ -929,7 +968,7 @@ class RuntimeDashboard extends Dashboard
if (isset($aExtraParams['query_params']['this->object()'])) { if (isset($aExtraParams['query_params']['this->object()'])) {
/** @var \DBObject $oObj */ /** @var \DBObject $oObj */
$oObj = $aExtraParams['query_params']['this->object()']; $oObj = $aExtraParams['query_params']['this->object()'];
$aAjaxParams = ['this->class' => get_class($oObj), 'this->id' => $oObj->GetKey()]; $aAjaxParams = array('this->class' => get_class($oObj), 'this->id' => $oObj->GetKey());
if (isset($aExtraParams['from_dashboard_page'])) { if (isset($aExtraParams['from_dashboard_page'])) {
$aAjaxParams['from_dashboard_page'] = $aExtraParams['from_dashboard_page']; $aAjaxParams['from_dashboard_page'] = $aExtraParams['from_dashboard_page'];
} }
@@ -962,7 +1001,9 @@ class RuntimeDashboard extends Dashboard
} }
JS JS
); );
} else { }
else
{
$oPage->add_script( $oPage->add_script(
<<<EOF <<<EOF
if (typeof(AutoReloadDashboardId$sDivId) !== 'undefined') if (typeof(AutoReloadDashboardId$sDivId) !== 'undefined')
@@ -991,7 +1032,7 @@ EOF
* @throws \CoreUnexpectedValue * @throws \CoreUnexpectedValue
* @throws \MySQLException * @throws \MySQLException
*/ */
protected function RenderSelector(WebPage $oPage, DashboardLayoutUIBlock $oDashboard, $aAjaxParams = []) protected function RenderSelector(WebPage $oPage, DashboardLayoutUIBlock $oDashboard, $aAjaxParams = array())
{ {
if (!$this->HasCustomDashboard()) { if (!$this->HasCustomDashboard()) {
return; return;
@@ -1051,7 +1092,8 @@ JS
*/ */
protected function HasCustomDashboard() protected function HasCustomDashboard()
{ {
try { try
{
// Search for an eventual user defined dashboard // Search for an eventual user defined dashboard
$oUDSearch = new DBObjectSearch('UserDashboard'); $oUDSearch = new DBObjectSearch('UserDashboard');
$oUDSearch->AddCondition('user_id', UserRights::GetUserId(), '='); $oUDSearch->AddCondition('user_id', UserRights::GetUserId(), '=');
@@ -1059,7 +1101,9 @@ JS
$oUDSet = new DBObjectSet($oUDSearch); $oUDSet = new DBObjectSet($oUDSearch);
return ($oUDSet->Count() > 0); return ($oUDSet->Count() > 0);
} catch (Exception $e) { }
catch (Exception $e)
{
return false; return false;
} }
} }
@@ -1095,23 +1139,21 @@ JS
->AddCSSClass('ibo-action-button'); ->AddCSSClass('ibo-action-button');
$oToolbar->AddSubBlock($oActionButton); $oToolbar->AddSubBlock($oActionButton);
$aActions = []; $aActions = array();
$sFile = addslashes(utils::LocalPath($this->sDefinitionFile)); $sFile = addslashes(utils::LocalPath($this->sDefinitionFile));
$sJSExtraParams = json_encode($aExtraParams); $sJSExtraParams = json_encode($aExtraParams);
if ($this->HasCustomDashboard()) { if ($this->HasCustomDashboard()) {
$oEdit = new JSPopupMenuItem('UI:Dashboard:Edit', Dict::S('UI:Dashboard:EditCustom'), "return EditDashboard('{$this->sId}', '$sFile', $sJSExtraParams)"); $oEdit = new JSPopupMenuItem('UI:Dashboard:Edit', Dict::S('UI:Dashboard:EditCustom'), "return EditDashboard('{$this->sId}', '$sFile', $sJSExtraParams)");
$aActions[$oEdit->GetUID()] = $oEdit->GetMenuItem(); $aActions[$oEdit->GetUID()] = $oEdit->GetMenuItem();
$oRevert = new JSPopupMenuItem( $oRevert = new JSPopupMenuItem('UI:Dashboard:RevertConfirm', Dict::S('UI:Dashboard:DeleteCustom'),
'UI:Dashboard:RevertConfirm', "if (confirm('".addslashes(Dict::S('UI:Dashboard:RevertConfirm'))."')) return RevertDashboard('{$this->sId}', $sJSExtraParams); else return false");
Dict::S('UI:Dashboard:DeleteCustom'),
"if (confirm('".addslashes(Dict::S('UI:Dashboard:RevertConfirm'))."')) return RevertDashboard('{$this->sId}', $sJSExtraParams); else return false"
);
$aActions[$oRevert->GetUID()] = $oRevert->GetMenuItem(); $aActions[$oRevert->GetUID()] = $oRevert->GetMenuItem();
} else { } else {
$oEdit = new JSPopupMenuItem('UI:Dashboard:Edit', Dict::S('UI:Dashboard:CreateCustom'), "return EditDashboard('{$this->sId}', '$sFile', $sJSExtraParams)"); $oEdit = new JSPopupMenuItem('UI:Dashboard:Edit', Dict::S('UI:Dashboard:CreateCustom'), "return EditDashboard('{$this->sId}', '$sFile', $sJSExtraParams)");
$aActions[$oEdit->GetUID()] = $oEdit->GetMenuItem(); $aActions[$oEdit->GetUID()] = $oEdit->GetMenuItem();
} }
utils::GetPopupMenuItems($oPage, iPopupMenuExtension::MENU_DASHBOARD_ACTIONS, $this, $aActions); utils::GetPopupMenuItems($oPage, iPopupMenuExtension::MENU_DASHBOARD_ACTIONS, $this, $aActions);
$oActionsMenu = $oPage->GetPopoverMenu($sPopoverMenuId, $aActions) $oActionsMenu = $oPage->GetPopoverMenu($sPopoverMenuId, $aActions)
@@ -1151,12 +1193,12 @@ EOF
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function RenderProperties($oPage, $aExtraParams = []) public function RenderProperties($oPage, $aExtraParams = array())
{ {
parent::RenderProperties($oPage, $aExtraParams); parent::RenderProperties($oPage, $aExtraParams);
$oPage->add_ready_script( $oPage->add_ready_script(
<<<EOF <<<EOF
$('#select_layout input').on('click', function() { $('#select_layout input').on('click', function() {
var sLayoutClass = $(this).val(); var sLayoutClass = $(this).val();
$('.itop-dashboard').runtimedashboard('option', {layout_class: sLayoutClass}); $('.itop-dashboard').runtimedashboard('option', {layout_class: sLayoutClass});
@@ -1183,6 +1225,7 @@ EOF
); );
} }
/** /**
* @param WebPage $oPage * @param WebPage $oPage
* *
@@ -1193,11 +1236,11 @@ EOF
* @throws \ReflectionException * @throws \ReflectionException
* @throws \Exception * @throws \Exception
*/ */
public function RenderEditor($oPage, $aExtraParams = []) public function RenderEditor($oPage, $aExtraParams = array())
{ {
if (isset($aExtraParams['this->class'])) { if (isset($aExtraParams['this->class'])) {
$oObj = MetaModel::GetObject($aExtraParams['this->class'], $aExtraParams['this->id']); $oObj = MetaModel::GetObject($aExtraParams['this->class'], $aExtraParams['this->id']);
$aRenderParams = ['query_params' => $oObj->ToArgsForQuery()]; $aRenderParams = array('query_params' => $oObj->ToArgsForQuery());
} else { } else {
$aRenderParams = $aExtraParams; $aRenderParams = $aExtraParams;
} }
@@ -1219,7 +1262,7 @@ EOF
$sDialogTitle = Dict::S('UI:DashboardEdit:Title'); $sDialogTitle = Dict::S('UI:DashboardEdit:Title');
$sOkButtonLabel = Dict::S('UI:Button:Save'); $sOkButtonLabel = Dict::S('UI:Button:Save');
$sCancelButtonLabel = Dict::S('UI:Button:Cancel'); $sCancelButtonLabel = Dict::S('UI:Button:Cancel');
$sId = json_encode($this->sId); $sId = json_encode($this->sId);
$sLayoutClass = json_encode($this->sLayoutClass); $sLayoutClass = json_encode($this->sLayoutClass);
$sAutoReload = $this->bAutoReload ? 'true' : 'false'; $sAutoReload = $this->bAutoReload ? 'true' : 'false';
@@ -1232,9 +1275,9 @@ EOF
$sExitConfirmationMessage = addslashes(Dict::S('UI:NavigateAwayConfirmationMessage')); $sExitConfirmationMessage = addslashes(Dict::S('UI:NavigateAwayConfirmationMessage'));
$sCancelConfirmationMessage = addslashes(Dict::S('UI:CancelConfirmationMessage')); $sCancelConfirmationMessage = addslashes(Dict::S('UI:CancelConfirmationMessage'));
$sAutoApplyConfirmationMessage = addslashes(Dict::S('UI:AutoApplyConfirmationMessage')); $sAutoApplyConfirmationMessage = addslashes(Dict::S('UI:AutoApplyConfirmationMessage'));
$oPage->add_ready_script( $oPage->add_ready_script(
<<<JS <<<JS
window.bLeavingOnUserAction = false; window.bLeavingOnUserAction = false;
$('#dashboard_editor').dialog({ $('#dashboard_editor').dialog({
@@ -1342,89 +1385,104 @@ JS
$sContextMenuId = $oAppContext->GetCurrentValue('menu', null); $sContextMenuId = $oAppContext->GetCurrentValue('menu', null);
$oForm = new DesignerForm(); $oForm = new DesignerForm();
// Get the list of all 'dashboard' menus in which we can insert a dashlet // Get the list of all 'dashboard' menus in which we can insert a dashlet
$aAllMenus = ApplicationMenu::ReflectionMenuNodes(); $aAllMenus = ApplicationMenu::ReflectionMenuNodes();
$sRootMenuId = ApplicationMenu::GetRootMenuId($sContextMenuId); $sRootMenuId = ApplicationMenu::GetRootMenuId($sContextMenuId);
$aAllowedDashboards = []; $aAllowedDashboards = array();
$sDefaultDashboard = null; $sDefaultDashboard = null;
// Store the parent menus for acces check // Store the parent menus for acces check
$aParentMenus = []; $aParentMenus = array();
foreach ($aAllMenus as $idx => $aMenu) { foreach($aAllMenus as $idx => $aMenu)
/** @var MenuNode $oMenu */ {
$oMenu = $aMenu['node']; /** @var MenuNode $oMenu */
if (count(ApplicationMenu::GetChildren($oMenu->GetIndex())) > 0) { $oMenu = $aMenu['node'];
$aParentMenus[$oMenu->GetMenuId()] = $aMenu; if (count(ApplicationMenu::GetChildren($oMenu->GetIndex())) > 0)
} {
} $aParentMenus[$oMenu->GetMenuId()] = $aMenu;
}
}
foreach ($aAllMenus as $idx => $aMenu) { foreach($aAllMenus as $idx => $aMenu)
{
$oMenu = $aMenu['node']; $oMenu = $aMenu['node'];
if ($oMenu instanceof DashboardMenuNode) { if ($oMenu instanceof DashboardMenuNode)
// Get the root parent for access check {
$sParentId = $aMenu['parent']; // Get the root parent for access check
$aParentMenu = $aParentMenus[$sParentId]; $sParentId = $aMenu['parent'];
while (isset($aParentMenus[$aParentMenu['parent']])) { $aParentMenu = $aParentMenus[$sParentId];
// grand parent exists while (isset($aParentMenus[$aParentMenu['parent']]))
$sParentId = $aParentMenu['parent']; {
$aParentMenu = $aParentMenus[$sParentId]; // grand parent exists
} $sParentId = $aParentMenu['parent'];
/** @var \MenuNode $oParentMenu */ $aParentMenu = $aParentMenus[$sParentId];
$oParentMenu = $aParentMenu['node']; }
if ($oMenu->IsEnabled() && $oParentMenu->IsEnabled()) { /** @var \MenuNode $oParentMenu */
$sMenuLabel = $oMenu->GetTitle(); $oParentMenu = $aParentMenu['node'];
$sParentLabel = Dict::S('Menu:'.$sParentId); if ($oMenu->IsEnabled() && $oParentMenu->IsEnabled())
if ($sParentLabel != $sMenuLabel) { {
$aAllowedDashboards[$oMenu->GetMenuId()] = $sParentLabel.' - '.$sMenuLabel; $sMenuLabel = $oMenu->GetTitle();
} else { $sParentLabel = Dict::S('Menu:'.$sParentId);
$aAllowedDashboards[$oMenu->GetMenuId()] = $sMenuLabel; if ($sParentLabel != $sMenuLabel)
} {
if (empty($sDefaultDashboard) && ($sRootMenuId == ApplicationMenu::GetRootMenuId($oMenu->GetMenuId()))) { $aAllowedDashboards[$oMenu->GetMenuId()] = $sParentLabel.' - '.$sMenuLabel;
$sDefaultDashboard = $oMenu->GetMenuId(); }
} else
} {
} $aAllowedDashboards[$oMenu->GetMenuId()] = $sMenuLabel;
}
if (empty($sDefaultDashboard) && ($sRootMenuId == ApplicationMenu::GetRootMenuId($oMenu->GetMenuId())))
{
$sDefaultDashboard = $oMenu->GetMenuId();
}
}
}
} }
asort($aAllowedDashboards); asort($aAllowedDashboards);
$oField = new DesignerComboField('menu_id', Dict::S('UI:DashletCreation:Dashboard'), $sDefaultDashboard); $oField = new DesignerComboField('menu_id', Dict::S('UI:DashletCreation:Dashboard'), $sDefaultDashboard);
$oField->SetAllowedValues($aAllowedDashboards); $oField->SetAllowedValues($aAllowedDashboards);
$oField->SetMandatory(true); $oField->SetMandatory(true);
$oForm->AddField($oField); $oForm->AddField($oField);
// Get the list of possible dashlets that support a creation from // Get the list of possible dashlets that support a creation from
// an OQL // an OQL
$aDashlets = []; $aDashlets = array();
foreach (get_declared_classes() as $sDashletClass) { foreach(get_declared_classes() as $sDashletClass)
if (is_subclass_of($sDashletClass, 'Dashlet')) { {
if (is_subclass_of($sDashletClass, 'Dashlet'))
{
$oReflection = new ReflectionClass($sDashletClass); $oReflection = new ReflectionClass($sDashletClass);
if (!$oReflection->isAbstract()) { if (!$oReflection->isAbstract())
$aCallSpec = [$sDashletClass, 'CanCreateFromOQL']; {
$aCallSpec = array($sDashletClass, 'CanCreateFromOQL');
$bShorcutMode = call_user_func($aCallSpec); $bShorcutMode = call_user_func($aCallSpec);
if ($bShorcutMode) { if ($bShorcutMode)
$aCallSpec = [$sDashletClass, 'GetInfo']; {
$aCallSpec = array($sDashletClass, 'GetInfo');
$aInfo = call_user_func($aCallSpec); $aInfo = call_user_func($aCallSpec);
$aDashlets[$sDashletClass] = ['label' => $aInfo['label'], 'class' => $sDashletClass, 'icon' => $aInfo['icon']]; $aDashlets[$sDashletClass] = array('label' => $aInfo['label'], 'class' => $sDashletClass, 'icon' => $aInfo['icon']);
} }
} }
} }
} }
$oSelectorField = new DesignerFormSelectorField('dashlet_class', Dict::S('UI:DashletCreation:DashletType'), ''); $oSelectorField = new DesignerFormSelectorField('dashlet_class', Dict::S('UI:DashletCreation:DashletType'), '');
$oForm->AddField($oSelectorField); $oForm->AddField($oSelectorField);
foreach ($aDashlets as $sDashletClass => $aDashletInfo) { foreach($aDashlets as $sDashletClass => $aDashletInfo)
{
$oSubForm = new DesignerForm(); $oSubForm = new DesignerForm();
$oMetaModel = new ModelReflectionRuntime(); $oMetaModel = new ModelReflectionRuntime();
/** @var \Dashlet $oDashlet */ /** @var \Dashlet $oDashlet */
$oDashlet = new $sDashletClass($oMetaModel, 0); $oDashlet = new $sDashletClass($oMetaModel, 0);
$oDashlet->GetPropertiesFieldsFromOQL($oSubForm, $sOQL); $oDashlet->GetPropertiesFieldsFromOQL($oSubForm, $sOQL);
$oSelectorField->AddSubForm($oSubForm, $aDashletInfo['label'], $aDashletInfo['class']); $oSelectorField->AddSubForm($oSubForm, $aDashletInfo['label'], $aDashletInfo['class']);
} }
$oField = new DesignerBooleanField('open_editor', Dict::S('UI:DashletCreation:EditNow'), true); $oField = new DesignerBooleanField('open_editor', Dict::S('UI:DashletCreation:EditNow'), true);
$oForm->AddField($oField); $oForm->AddField($oField);
return $oForm; return $oForm;
} }
@@ -1443,11 +1501,11 @@ JS
$oForm->Render($oPage); $oForm->Render($oPage);
$oPage->add('</div>'); $oPage->add('</div>');
$sDialogTitle = Dict::S('UI:DashletCreation:Title'); $sDialogTitle = Dict::S('UI:DashletCreation:Title');
$sOkButtonLabel = Dict::S('UI:Button:Ok'); $sOkButtonLabel = Dict::S('UI:Button:Ok');
$sCancelButtonLabel = Dict::S('UI:Button:Cancel'); $sCancelButtonLabel = Dict::S('UI:Button:Cancel');
$oPage->add_ready_script( $oPage->add_ready_script(
<<<JS <<<JS
$('#dashlet_creation_dlg').dialog({ $('#dashlet_creation_dlg').dialog({
@@ -1545,7 +1603,7 @@ JS
/** /**
* @inheritDoc * @inheritDoc
*/ */
protected function PrepareDashletForRendering(Dashlet $oDashlet, $aCoordinates, $aExtraParams = []) protected function PrepareDashletForRendering(Dashlet $oDashlet, $aCoordinates, $aExtraParams = array())
{ {
$sDashletIdOrig = $oDashlet->GetID(); $sDashletIdOrig = $oDashlet->GetID();
$sDashboardSanitizedId = $this->GetSanitizedId(); $sDashboardSanitizedId = $this->GetSanitizedId();
@@ -1572,27 +1630,31 @@ JS
private function UpdateDashletUserPrefs(Dashlet $oDashlet, $sDashletIdOrig, array $aExtraParams) private function UpdateDashletUserPrefs(Dashlet $oDashlet, $sDashletIdOrig, array $aExtraParams)
{ {
$bIsDashletWithListPref = ($oDashlet instanceof DashletObjectList); $bIsDashletWithListPref = ($oDashlet instanceof DashletObjectList);
if (!$bIsDashletWithListPref) { if (!$bIsDashletWithListPref)
{
return; return;
} }
/** @var \DashletObjectList $oDashlet */ /** @var \DashletObjectList $oDashlet */
$bDashletIdInNewFormat = ($sDashletIdOrig === $oDashlet->GetID()); $bDashletIdInNewFormat = ($sDashletIdOrig === $oDashlet->GetID());
if ($bDashletIdInNewFormat) { if ($bDashletIdInNewFormat)
{
return; return;
} }
$sNewPrefKey = $this->GetDashletObjectListAppUserPreferencesPrefix($oDashlet, $aExtraParams, $oDashlet->GetID()); $sNewPrefKey = $this->GetDashletObjectListAppUserPreferencesPrefix($oDashlet, $aExtraParams, $oDashlet->GetID());
$sPrefValueForNewKey = appUserPreferences::GetPref($sNewPrefKey, null); $sPrefValueForNewKey = appUserPreferences::GetPref($sNewPrefKey, null);
$bHasPrefInNewFormat = ($sPrefValueForNewKey !== null); $bHasPrefInNewFormat = ($sPrefValueForNewKey !== null);
if ($bHasPrefInNewFormat) { if ($bHasPrefInNewFormat)
{
return; return;
} }
$sOldPrefKey = $this->GetDashletObjectListAppUserPreferencesPrefix($oDashlet, $aExtraParams, $sDashletIdOrig); $sOldPrefKey = $this->GetDashletObjectListAppUserPreferencesPrefix($oDashlet, $aExtraParams, $sDashletIdOrig);
$sPrefValueForOldKey = appUserPreferences::GetPref($sOldPrefKey, null); $sPrefValueForOldKey = appUserPreferences::GetPref($sOldPrefKey, null);
$bHasPrefInOldFormat = ($sPrefValueForOldKey !== null); $bHasPrefInOldFormat = ($sPrefValueForOldKey !== null);
if (!$bHasPrefInOldFormat) { if (!$bHasPrefInOldFormat)
{
return; return;
} }
@@ -1611,7 +1673,7 @@ JS
private function GetDashletObjectListAppUserPreferencesPrefix(DashletObjectList $oDashlet, $aExtraParams, $sDashletId) private function GetDashletObjectListAppUserPreferencesPrefix(DashletObjectList $oDashlet, $aExtraParams, $sDashletId)
{ {
$sDataTableId = Dashlet::APPUSERPREFERENCES_PREFIX.$sDashletId; $sDataTableId = Dashlet::APPUSERPREFERENCES_PREFIX.$sDashletId;
$aClassAliases = []; $aClassAliases = array();
try { try {
$oFilter = $oDashlet->GetDBSearch($aExtraParams); $oFilter = $oDashlet->GetDBSearch($aExtraParams);
$aClassAliases = $oFilter->GetSelectedClasses(); $aClassAliases = $oFilter->GetSelectedClasses();

View File

@@ -1,10 +1,9 @@
<?php <?php
// Copyright (C) 2010-2024 Combodo SAS // Copyright (C) 2010-2024 Combodo SAS
// //
// This file is part of iTop. // This file is part of iTop.
// //
// iTop is free software; you can redistribute it and/or modify // iTop is free software; you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by // it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
@@ -39,21 +38,21 @@ abstract class DashboardLayout
* @since 2.7.0 * @since 2.7.0
*/ */
abstract public function GetDashletCoordinates($iCellIdx); abstract public function GetDashletCoordinates($iCellIdx);
public static function GetInfo() public static function GetInfo()
{ {
return [ return array(
'label' => '', 'label' => '',
'icon' => '', 'icon' => '',
'description' => '', 'description' => '',
]; );
} }
} }
abstract class DashboardLayoutMultiCol extends DashboardLayout abstract class DashboardLayoutMultiCol extends DashboardLayout
{ {
protected $iNbCols; protected $iNbCols;
public function __construct() public function __construct()
{ {
$this->iNbCols = 1; $this->iNbCols = 1;
@@ -64,38 +63,47 @@ abstract class DashboardLayoutMultiCol extends DashboardLayout
$aKeys = array_reverse(array_keys($aDashlets)); $aKeys = array_reverse(array_keys($aDashlets));
$idx = 0; $idx = 0;
$bNoVisibleFound = true; $bNoVisibleFound = true;
while ($idx < count($aKeys) && $bNoVisibleFound) { while($idx < count($aKeys) && $bNoVisibleFound)
{
/** @var \Dashlet $oDashlet */ /** @var \Dashlet $oDashlet */
$oDashlet = $aDashlets[$aKeys[$idx]]; $oDashlet = $aDashlets[$aKeys[$idx]];
if ($oDashlet::IsVisible()) { if ($oDashlet::IsVisible())
{
$bNoVisibleFound = false; $bNoVisibleFound = false;
} else { }
else
{
unset($aDashlets[$aKeys[$idx]]); unset($aDashlets[$aKeys[$idx]]);
} }
$idx++; $idx++;
} }
return $aDashlets; return $aDashlets;
} }
protected function TrimCellsArray($aCells) protected function TrimCellsArray($aCells)
{ {
foreach ($aCells as $key => $aDashlets) { foreach($aCells as $key => $aDashlets)
{
$aCells[$key] = $this->TrimCell($aDashlets); $aCells[$key] = $this->TrimCell($aDashlets);
} }
$aKeys = array_reverse(array_keys($aCells)); $aKeys = array_reverse(array_keys($aCells));
$idx = 0; $idx = 0;
$bNoVisibleFound = true; $bNoVisibleFound = true;
while ($idx < count($aKeys) && $bNoVisibleFound) { while($idx < count($aKeys) && $bNoVisibleFound)
{
$aDashlets = $aCells[$aKeys[$idx]]; $aDashlets = $aCells[$aKeys[$idx]];
if (count($aDashlets) > 0) { if (count($aDashlets) > 0)
{
$bNoVisibleFound = false; $bNoVisibleFound = false;
} else { }
else
{
unset($aCells[$aKeys[$idx]]); unset($aCells[$aKeys[$idx]]);
} }
$idx++; $idx++;
} }
return $aCells; return $aCells;
} }
/** /**
@@ -104,7 +112,7 @@ abstract class DashboardLayoutMultiCol extends DashboardLayout
* @param bool $bEditMode * @param bool $bEditMode
* @param array $aExtraParams * @param array $aExtraParams
*/ */
public function Render($oPage, $aCells, $bEditMode = false, $aExtraParams = []) public function Render($oPage, $aCells, $bEditMode = false, $aExtraParams = array())
{ {
// Trim the list of cells to remove the invisible/empty ones at the end of the array // Trim the list of cells to remove the invisible/empty ones at the end of the array
$aCells = $this->TrimCellsArray($aCells); $aCells = $this->TrimCellsArray($aCells);
@@ -149,7 +157,8 @@ abstract class DashboardLayoutMultiCol extends DashboardLayout
$oPage->add_script("function updateDashboard".$aExtraParams['dashboard_div_id']."(){".$sJSReload."}"); $oPage->add_script("function updateDashboard".$aExtraParams['dashboard_div_id']."(){".$sJSReload."}");
if ($bEditMode) { // Add one row for extensibility if ($bEditMode) // Add one row for extensibility
{
$oDashboardRow = new DashboardRow(); $oDashboardRow = new DashboardRow();
$oDashboardLayout->AddDashboardRow($oDashboardRow); $oDashboardLayout->AddDashboardRow($oDashboardRow);
@@ -171,7 +180,7 @@ abstract class DashboardLayoutMultiCol extends DashboardLayout
$iColNumber = (int) $iCellIdx % $this->iNbCols; $iColNumber = (int) $iCellIdx % $this->iNbCols;
$iRowNumber = (int) floor($iCellIdx / $this->iNbCols); $iRowNumber = (int) floor($iCellIdx / $this->iNbCols);
return [$iColNumber, $iRowNumber]; return array($iColNumber, $iRowNumber);
} }
} }
@@ -182,13 +191,13 @@ class DashboardLayoutOneCol extends DashboardLayoutMultiCol
parent::__construct(); parent::__construct();
$this->iNbCols = 1; $this->iNbCols = 1;
} }
public static function GetInfo() static public function GetInfo()
{ {
return [ return array(
'label' => 'One Column', 'label' => 'One Column',
'icon' => 'images/layout_1col.png', 'icon' => 'images/layout_1col.png',
'description' => '', 'description' => '',
]; );
} }
} }
@@ -199,13 +208,13 @@ class DashboardLayoutTwoCols extends DashboardLayoutMultiCol
parent::__construct(); parent::__construct();
$this->iNbCols = 2; $this->iNbCols = 2;
} }
public static function GetInfo() static public function GetInfo()
{ {
return [ return array(
'label' => 'Two Columns', 'label' => 'Two Columns',
'icon' => 'images/layout_2col.png', 'icon' => 'images/layout_2col.png',
'description' => '', 'description' => '',
]; );
} }
} }
@@ -216,12 +225,12 @@ class DashboardLayoutThreeCols extends DashboardLayoutMultiCol
parent::__construct(); parent::__construct();
$this->iNbCols = 3; $this->iNbCols = 3;
} }
public static function GetInfo() static public function GetInfo()
{ {
return [ return array(
'label' => 'Two Columns', 'label' => 'Two Columns',
'icon' => 'images/layout_3col.png', 'icon' => 'images/layout_3col.png',
'description' => '', 'description' => '',
]; );
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -1,12 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<itop_design xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <itop_design xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="3.3">
xsi:noNamespaceSchemaLocation="https://www.combodo.com/itop-schema/3.3"
version="3.3">
<classes> <classes>
<class id="AbstractResource" _delta="define"> <class id="AbstractResource" _delta="define">
<parent>cmdbAbstractObject</parent> <parent>cmdbAbstractObject</parent>
<properties> <properties>
<comment>/* Resource access control abstraction. Can be herited by abstract resource access control classes. Generally controlled using UR_ACTION_MODIFY access right. */</comment> <comment>/* Resource access control abstraction. Can be herited by abstract resource access control classes. Generaly controlled using UR_ACTION_MODIFY access right. */</comment>
<abstract>true</abstract> <abstract>true</abstract>
</properties> </properties>
<presentation/> <presentation/>
@@ -554,7 +552,7 @@ Call $this->AddInitialAttributeFlags($sAttCode, $iFlags) for all the initial att
<description><![CDATA[Inform the listeners about the connection states]]></description> <description><![CDATA[Inform the listeners about the connection states]]></description>
<event_data> <event_data>
<event_datum id="code"> <event_datum id="code">
<description>The login step result code (LoginWebPage::EXIT_CODE_...)</description> <description>The login step result code (LoginWebPage::EXIT_CODE_...) </description>
<type>integer</type> <type>integer</type>
</event_datum> </event_datum>
<event_datum id="state"> <event_datum id="state">
@@ -851,168 +849,5 @@ Call $this->AddInitialAttributeFlags($sAttCode, $iFlags) for all the initial att
</methods> </methods>
</class> </class>
</classes> </classes>
<property_types _delta="define">
<property_type id="Dashlet" xsi:type="Combodo-AbstractPropertyType"/>
<property_type id="DashletGroupBy" xsi:type="Combodo-PropertyType">
<extends>Dashlet</extends>
<definition xsi:type="Combodo-ValueType-PropertyTree">
<label>UI:DashletGroupBy:Title</label>
<nodes>
<node id="title" xsi:type="Combodo-ValueType-Label">
<label>UI:DashletGroupBy:Prop-Title</label>
</node>
<node id="query" xsi:type="Combodo-ValueType-OQL">
<label>UI:DashletGroupBy:Prop-Query</label>
</node>
<node id="group_by" xsi:type="Combodo-ValueType-ClassAttributeGroupBy">
<label>UI:DashletGroupBy:Prop-GroupBy</label>
<class>{{query.selected_class}}</class>
</node>
<node id="style" xsi:type="Combodo-ValueType-Choice"> <!-- Possible de le cacher, etc celui-ci nous met dedans -->
<label>UI:DashletGroupBy:Prop-Style</label>
<values>
<value id="bars">
<label>UI:DashletGroupByBars:Label</label>
</value>
<value id="pie">
<label>UI:DashletGroupByPie:Label</label>
</value>
<value id="table">
<label>UI:DashletGroupByTable:Label</label>
</value>
</values>
</node>
<node id="aggregation_function" xsi:type="Combodo-ValueType-AggregateFunction">
<label>UI:DashletGroupBy:Prop-Function</label>
<class>{{query.selected_class}}</class> <!-- pour savoir si il y a des attributs additionnables -->
</node>
<node id="aggregation_attribute" xsi:type="Combodo-ValueType-ClassAttribute">
<label>UI:DashletGroupBy:Prop-FunctionAttribute</label>
<relevance-condition>{{aggregation_function.value != 'count'}}</relevance-condition>
<class>{{query.selected_class}}</class>
<category>numeric</category>
</node>
<node id="order_by" xsi:type="Combodo-ValueType-ChoiceFromInput">
<label>UI:DashletGroupBy:Prop-OrderField</label>
<values>
<value id="attribute">
<label>{{aggregation_attribute.label}}</label>
</value>
<value id="function">
<label>{{aggregation_function.label}}</label>
</value>
</values>
</node>
<node id="limit" xsi:type="Combodo-ValueType-Integer">
<label>UI:DashletGroupBy:Prop-Limit</label>
<relevance-condition>{{order_by.value = 'function'}}</relevance-condition>
</node>
<node id="order_direction" xsi:type="Combodo-ValueType-Choice">
<label>UI:DashletGroupBy:Prop-OrderDirection</label>
<values>
<value id="asc">
<label>UI:DashletGroupBy:Order:asc</label>
</value>
<value id="desc">
<label>UI:DashletGroupBy:Order:desc</label>
</value>
</values>
</node>
</nodes>
</definition>
</property_type>
<property_type id="DashletBadge" xsi:type="Combodo-PropertyType">
<extends>Dashlet</extends>
<definition xsi:type="Combodo-ValueType-PropertyTree">
<nodes>
<node id="class" xsi:type="Combodo-ValueType-Class">
<label>UI:DashletBadge:Prop-Class</label>
<categories-csv>bizmodel</categories-csv>
</node>
</nodes>
</definition>
</property_type>
<property_type id="DashletHeaderDynamic" xsi:type="Combodo-PropertyType">
<extends>Dashlet</extends>
<definition xsi:type="Combodo-ValueType-PropertyTree">
<label>UI:DashletHeaderDynamic:Title</label>
<nodes>
<node id="title" xsi:type="Combodo-ValueType-Label">
<label>UI:DashletHeaderDynamic:Prop-Title</label>
</node>
<node id="icon" xsi:type="Combodo-ValueType-Icon">
<label>UI:DashletHeaderDynamic:Prop-Icon</label>
</node>
<node id="subtitle" xsi:type="Combodo-ValueType-Label">
<label>UI:DashletHeaderDynamic:Prop-Subtitle</label>
</node>
<node id="query" xsi:type="Combodo-ValueType-OQL">
<label>UI:DashletHeaderDynamic:Prop-Query</label>
</node>
<node id="group_by" xsi:type="Combodo-ValueType-ClassAttribute">
<label>UI:DashletHeaderDynamic:Prop-GroupBy</label>
<class>{{query.selected_class}}</class>
<category>enum</category>
</node>
<node id="values" xsi:type="Combodo-ValueType-CollectionOfValues">
<label>UI:DashletHeaderDynamic:Prop-Values</label>
<xml-format xsi:type="Combodo-XMLFormat-CSV"/>
<value-type xsi:type="Combodo-ValueType-ClassAttributeValue">
<class>{{query.selected_class}}</class>
<attribute>{{group_by.attribute}}</attribute>
</value-type>
</node>
</nodes>
</definition>
</property_type>
<property_type id="DashletHeaderStatic" xsi:type="Combodo-PropertyType">
<extends>Dashlet</extends>
<definition xsi:type="Combodo-ValueType-PropertyTree">
<nodes>
<node id="title" xsi:type="Combodo-ValueType-Label">
<label>UI:DashletHeaderStatic:Prop-Title</label>
</node>
<node id="icon" xsi:type="Combodo-ValueType-Icon">
<label>UI:DashletHeaderStatic:Prop-Icon</label>
</node>
</nodes>
</definition>
</property_type>
<property_type id="DashletObjectList" xsi:type="Combodo-PropertyType">
<extends>Dashlet</extends>
<definition xsi:type="Combodo-ValueType-PropertyTree">
<nodes>
<node id="title" xsi:type="Combodo-ValueType-Label">
<label>UI:DashletObjectList:Prop-Title</label>
</node>
<node id="query" xsi:type="Combodo-ValueType-OQL">
<label>UI:DashletObjectList:Prop-Query</label>
</node>
<node id="menu" xsi:type="Combodo-ValueType-Boolean">
<label>UI:DashletObjectList:Prop-Menu</label>
<on>
<!-- not so cute, but matches exactly 3.2 implementation of boolean fields -->
<label>UI:UserManagement:ActionAllowed:Yes</label>
<value>true</value>
</on>
<off>
<label>UI:UserManagement:ActionAllowed:No</label>
<value>false</value>
</off>
</node>
</nodes>
</definition>
</property_type>
<property_type id="DashletPlainText" xsi:type="Combodo-PropertyType">
<extends>Dashlet</extends>
<definition xsi:type="Combodo-ValueType-PropertyTree">
<nodes>
<node id="text" xsi:type="Combodo-ValueType-Text">
<label>UI:DashletPlainText:Prop-Text</label>
</node>
</nodes>
</definition>
</property_type>
</property_types>
</meta> </meta>
</itop_design> </itop_design>

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -105,7 +104,7 @@ class DisplayBlock
*/ */
public const ENUM_STYLE_CHART_AJAX = 'chart_ajax'; public const ENUM_STYLE_CHART_AJAX = 'chart_ajax';
public const TAG_BLOCK = 'itopblock'; const TAG_BLOCK = 'itopblock';
/** @var \DBSearch */ /** @var \DBSearch */
protected $m_oFilter; protected $m_oFilter;
protected $m_aConditions; // Conditions added to the filter -> avoid duplicate conditions protected $m_aConditions; // Conditions added to the filter -> avoid duplicate conditions
@@ -138,18 +137,20 @@ class DisplayBlock
* *
* @throws \ApplicationException * @throws \ApplicationException
*/ */
public function __construct(DBSearch $oFilter, $sStyle = self::ENUM_STYLE_LIST, $bAsynchronous = false, $aParams = [], $oSet = null) public function __construct(DBSearch $oFilter, $sStyle = self::ENUM_STYLE_LIST, $bAsynchronous = false, $aParams = array(), $oSet = null)
{ {
$this->m_oFilter = $oFilter->DeepClone(); $this->m_oFilter = $oFilter->DeepClone();
$this->m_aConditions = []; $this->m_aConditions = array();
$this->m_sStyle = $sStyle; $this->m_sStyle = $sStyle;
$this->m_bAsynchronous = $bAsynchronous; $this->m_bAsynchronous = $bAsynchronous;
$this->m_aParams = $aParams; $this->m_aParams = $aParams;
$this->m_oSet = $oSet; $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']; $this->m_bShowObsoleteData = $aParams['show_obsolete_data'];
} }
if ($this->m_bShowObsoleteData === null) { if ($this->m_bShowObsoleteData === null)
{
// User defined // User defined
$this->m_bShowObsoleteData = utils::ShowObsoleteData(); $this->m_bShowObsoleteData = utils::ShowObsoleteData();
} }
@@ -411,18 +412,22 @@ class DisplayBlock
* @throws \CoreException * @throws \CoreException
* @throws \Exception * @throws \Exception
*/ */
public static function FromObjectSet(DBObjectSet $oSet, $sStyle, $aParams = []) public static function FromObjectSet(DBObjectSet $oSet, $sStyle, $aParams = array())
{ {
$oDummyFilter = new DBObjectSearch($oSet->GetClass()); $oDummyFilter = new DBObjectSearch($oSet->GetClass());
$aKeys = []; $aKeys = array();
$oSet->OptimizeColumnLoad([$oSet->GetClassAlias() => []]); // No need to load all the columns just to get the id $oSet->OptimizeColumnLoad(array($oSet->GetClassAlias() => array())); // No need to load all the columns just to get the id
while ($oObject = $oSet->Fetch()) { while($oObject = $oSet->Fetch())
{
$aKeys[] = $oObject->GetKey(); $aKeys[] = $oObject->GetKey();
} }
$oSet->Rewind(); $oSet->Rewind();
if (count($aKeys) > 0) { if (count($aKeys) > 0)
{
$oDummyFilter->AddCondition('id', $aKeys, 'IN'); $oDummyFilter->AddCondition('id', $aKeys, 'IN');
} else { }
else
{
$oDummyFilter->AddCondition('id', 0, '='); $oDummyFilter->AddCondition('id', 0, '=');
} }
$oBlock = new DisplayBlock($oDummyFilter, $sStyle, false, $aParams); // DisplayBlocks built this way are synchronous $oBlock = new DisplayBlock($oDummyFilter, $sStyle, false, $aParams); // DisplayBlocks built this way are synchronous
@@ -443,7 +448,7 @@ class DisplayBlock
$iStartPos = stripos($sTemplate, '<'.self::TAG_BLOCK.' ', 0); $iStartPos = stripos($sTemplate, '<'.self::TAG_BLOCK.' ', 0);
$iEndPos = stripos($sTemplate, '</'.self::TAG_BLOCK.'>', $iStartPos); $iEndPos = stripos($sTemplate, '</'.self::TAG_BLOCK.'>', $iStartPos);
$iEndTag = stripos($sTemplate, '>', $iStartPos); $iEndTag = stripos($sTemplate, '>', $iStartPos);
$aParams = []; $aParams = array();
if (($iStartPos === false) || ($iEndPos === false)) { if (($iStartPos === false) || ($iEndPos === false)) {
return null; return null;
@@ -451,7 +456,7 @@ class DisplayBlock
$sITopData = substr($sTemplate, 1 + $iEndTag, $iEndPos - $iEndTag - 1); $sITopData = substr($sTemplate, 1 + $iEndTag, $iEndPos - $iEndTag - 1);
$sITopTag = substr($sTemplate, $iStartPos + strlen('<'.self::TAG_BLOCK), $iEndTag - $iStartPos - strlen('<'.self::TAG_BLOCK)); $sITopTag = substr($sTemplate, $iStartPos + strlen('<'.self::TAG_BLOCK), $iEndTag - $iStartPos - strlen('<'.self::TAG_BLOCK));
$aMatches = []; $aMatches = array();
$sBlockClass = "DisplayBlock"; $sBlockClass = "DisplayBlock";
$bAsynchronous = false; $bAsynchronous = false;
$sBlockType = 'list'; $sBlockType = 'list';
@@ -517,28 +522,25 @@ class DisplayBlock
return new $sBlockClass($oFilter, $sBlockType, $bAsynchronous, $aParams); return new $sBlockClass($oFilter, $sBlockType, $bAsynchronous, $aParams);
} }
public function DisplayIntoContentBlock(UIContentBlock $oContentBlock, WebPage $oPage, $sId, $aExtraParams = []) public function DisplayIntoContentBlock(UIContentBlock $oContentBlock, WebPage $oPage, $sId, $aExtraParams = array())
{ {
$oContentBlock->AddSubBlock($this->GetDisplay($oPage, $sId, $aExtraParams)); $oContentBlock->AddSubBlock($this->GetDisplay($oPage, $sId, $aExtraParams));
} }
public function Display(WebPage $oPage, $sId, $aExtraParams = []) public function Display(WebPage $oPage, $sId, $aExtraParams = array())
{ {
$oPage->AddUiBlock($this->GetDisplay($oPage, $sId, $aExtraParams)); $oPage->AddUiBlock($this->GetDisplay($oPage, $sId, $aExtraParams));
} }
public function GetDisplay(WebPage $oPage, $sId, $aExtraParams = []): UIContentBlock public function GetDisplay(WebPage $oPage, $sId, $aExtraParams = array()): UIContentBlock
{ {
$oHtml = new UIContentBlock($sId); $oHtml = new UIContentBlock($sId);
$oHtml->AddCSSClass("display_block"); $oHtml->AddCSSClass("display_block");
$aExtraParams = array_merge($aExtraParams, $this->m_aParams); $aExtraParams = array_merge($aExtraParams, $this->m_aParams);
$aExtraParams['currentId'] = $sId; $aExtraParams['currentId'] = $sId;
$sExtraParams = addslashes(str_replace( $sExtraParams = addslashes(str_replace('"', "'",
'"', json_encode($aExtraParams))); // JSON encode, change the style of the quotes and escape them
"'",
json_encode($aExtraParams)
)); // JSON encode, change the style of the quotes and escape them
if (isset($aExtraParams['query_params'])) { if (isset($aExtraParams['query_params'])) {
$aQueryParams = $aExtraParams['query_params']; $aQueryParams = $aExtraParams['query_params'];
@@ -547,9 +549,9 @@ class DisplayBlock
$sClass = $aExtraParams['this->class']; $sClass = $aExtraParams['this->class'];
$iKey = $aExtraParams['this->id']; $iKey = $aExtraParams['this->id'];
$oObj = MetaModel::GetObject($sClass, $iKey); $oObj = MetaModel::GetObject($sClass, $iKey);
$aQueryParams = ['this->object()' => $oObj]; $aQueryParams = array('this->object()' => $oObj);
} else { } else {
$aQueryParams = []; $aQueryParams = array();
} }
} }
@@ -585,7 +587,8 @@ 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)); $listJsonExtraParams = json_encode(json_encode($aExtraParams));
$oPage->add_ready_script(" $oPage->add_ready_script("
$('#$sId').data('sExtraParams', ".$listJsonExtraParams."); $('#$sId').data('sExtraParams', ".$listJsonExtraParams.");
@@ -605,7 +608,7 @@ class DisplayBlock
* @throws \DictExceptionMissingString * @throws \DictExceptionMissingString
* @throws \MySQLException * @throws \MySQLException
*/ */
public function RenderContent(WebPage $oPage, $aExtraParams = []) public function RenderContent(WebPage $oPage, $aExtraParams = array())
{ {
if (!isset($aExtraParams['currentId'])) { if (!isset($aExtraParams['currentId'])) {
$sId = utils::GetUniqueId(); // Works only if the page is not an Ajax one ! $sId = utils::GetUniqueId(); // Works only if the page is not an Ajax one !
@@ -637,7 +640,7 @@ class DisplayBlock
$this->CheckParams($this->m_sStyle, $aExtraParams); $this->CheckParams($this->m_sStyle, $aExtraParams);
// Add the extra params into the filter if they make sense for such a filter // Add the extra params into the filter if they make sense for such a filter
$bDoSearch = utils::ReadParam('dosearch', false); $bDoSearch = utils::ReadParam('dosearch', false);
$aQueryParams = []; $aQueryParams = array();
if (isset($aExtraParams['query_params'])) { if (isset($aExtraParams['query_params'])) {
$aQueryParams = $aExtraParams['query_params']; $aQueryParams = $aExtraParams['query_params'];
} else { } else {
@@ -645,7 +648,7 @@ class DisplayBlock
$sClass = $aExtraParams['this->class']; $sClass = $aExtraParams['this->class'];
$iKey = $aExtraParams['this->id']; $iKey = $aExtraParams['this->id'];
$oObj = MetaModel::GetObject($sClass, $iKey); $oObj = MetaModel::GetObject($sClass, $iKey);
$aQueryParams = ['this->object()' => $oObj]; $aQueryParams = array('this->object()' => $oObj);
} }
} }
if ($this->m_oSet == null) { if ($this->m_oSet == null) {
@@ -655,7 +658,7 @@ class DisplayBlock
$oAppContext = new ApplicationContext(); $oAppContext = new ApplicationContext();
$sClass = $this->m_oFilter->GetClass(); $sClass = $this->m_oFilter->GetClass();
$aFilterCodes = MetaModel::GetFiltersList($sClass); $aFilterCodes = MetaModel::GetFiltersList($sClass);
$aCallSpec = [$sClass, 'MapContextParam']; $aCallSpec = array($sClass, 'MapContextParam');
if (is_callable($aCallSpec)) { if (is_callable($aCallSpec)) {
foreach ($oAppContext->GetNames() as $sContextParam) { foreach ($oAppContext->GetNames() as $sContextParam) {
$sParamCode = call_user_func($aCallSpec, $sContextParam); //Map context parameter to the value/filter code depending on the class $sParamCode = call_user_func($aCallSpec, $sContextParam); //Map context parameter to the value/filter code depending on the class
@@ -690,9 +693,11 @@ class DisplayBlock
} }
} }
if (!is_null($condition)) { if (!is_null($condition))
{
$sOpCode = null; // default operator $sOpCode = null; // default operator
if (is_array($condition)) { if (is_array($condition))
{
// Multiple values, add them as AND X IN (v1, v2, v3...) // Multiple values, add them as AND X IN (v1, v2, v3...)
$sOpCode = 'IN'; $sOpCode = 'IN';
} }
@@ -700,22 +705,26 @@ class DisplayBlock
$this->AddCondition($sFilterCode, $condition, $sOpCode, $bParseSearchString); $this->AddCondition($sFilterCode, $condition, $sOpCode, $bParseSearchString);
} }
} }
if ($bDoSearch) { if ($bDoSearch)
{
// Keep the table_id identifying this table if we're performing a search // 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); $sTableId = utils::ReadParam('_table_id_', null, false, utils::ENUM_SANITIZATION_FILTER_ELEMENT_IDENTIFIER);
if ($sTableId != null) { if ($sTableId != null)
{
$aExtraParams['table_id'] = $sTableId; $aExtraParams['table_id'] = $sTableId;
} }
} }
} }
$aOrderBy = []; $aOrderBy = array();
if (isset($aExtraParams['order_by'])) { if (isset($aExtraParams['order_by']))
{
// Convert the string describing the order_by parameter into an array // Convert the string describing the order_by parameter into an array
// The syntax is +attCode1,-attCode2 // The syntax is +attCode1,-attCode2
// attCode1 => ascending, attCode2 => descending // attCode1 => ascending, attCode2 => descending
$aTemp = explode(',', $aExtraParams['order_by']); $aTemp = explode(',', $aExtraParams['order_by']);
foreach ($aTemp as $sTemp) { foreach($aTemp as $sTemp)
$aMatches = []; {
$aMatches = array();
if (preg_match('/^([+-])?(.+)$/', $sTemp, $aMatches)) { if (preg_match('/^([+-])?(.+)$/', $sTemp, $aMatches)) {
$bAscending = true; $bAscending = true;
if ($aMatches[1] == '-') { if ($aMatches[1] == '-') {
@@ -731,7 +740,7 @@ class DisplayBlock
} }
$this->m_oSet->SetShowObsoleteData($this->m_bShowObsoleteData); $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_SEARCH:
case static::ENUM_STYLE_LIST: case static::ENUM_STYLE_LIST:
break; break;
@@ -761,7 +770,7 @@ class DisplayBlock
case static::ENUM_STYLE_LIST: case static::ENUM_STYLE_LIST:
case static::ENUM_STYLE_LIST_IN_OBJECT: case static::ENUM_STYLE_LIST_IN_OBJECT:
$oBlock = $this->RenderList($aExtraParams, $oPage); $oBlock = $this->RenderList($aExtraParams, $oPage);
break; break;
case static::ENUM_STYLE_ACTIONS: case static::ENUM_STYLE_ACTIONS:
$oBlock = $this->RenderActions($aExtraParams); $oBlock = $this->RenderActions($aExtraParams);
@@ -788,39 +797,47 @@ class DisplayBlock
break; break;
default: default:
// Unsupported style, do nothing. // Unsupported style, do nothing.
$sHtml .= Dict::format('UI:Error:UnsupportedStyleOfBlock', $this->m_sStyle); $sHtml .= Dict::format('UI:Error:UnsupportedStyleOfBlock', $this->m_sStyle);
} }
$bAutoReload = false; $bAutoReload = false;
if (isset($aExtraParams['auto_reload'])) { if (isset($aExtraParams['auto_reload']))
if ($aExtraParams['auto_reload'] === true) { {
if ($aExtraParams['auto_reload'] === true)
{
// Note: does not work in the switch (case true) because a positive number evaluates to true!!! // Note: does not work in the switch (case true) because a positive number evaluates to true!!!
$aExtraParams['auto_reload'] = 'standard'; $aExtraParams['auto_reload'] = 'standard';
} }
switch ($aExtraParams['auto_reload']) { switch($aExtraParams['auto_reload'])
{
case 'fast': case 'fast':
$bAutoReload = true; $bAutoReload = true;
$iReloadInterval = MetaModel::GetConfig()->GetFastReloadInterval() * 1000; $iReloadInterval = MetaModel::GetConfig()->GetFastReloadInterval()*1000;
break; break;
case 'standard': case 'standard':
case 'true': case 'true':
$bAutoReload = true; $bAutoReload = true;
$iReloadInterval = MetaModel::GetConfig()->GetStandardReloadInterval() * 1000; $iReloadInterval = MetaModel::GetConfig()->GetStandardReloadInterval()*1000;
break; break;
default: default:
if (is_numeric($aExtraParams['auto_reload']) && ($aExtraParams['auto_reload'] > 0)) { if (is_numeric($aExtraParams['auto_reload']) && ($aExtraParams['auto_reload'] > 0))
{
$bAutoReload = true; $bAutoReload = true;
$iReloadInterval = max(MetaModel::GetConfig()->Get('min_reload_interval'), $aExtraParams['auto_reload']) * 1000; $iReloadInterval = max(MetaModel::GetConfig()->Get('min_reload_interval'), $aExtraParams['auto_reload'])*1000;
} else { }
else
{
// incorrect config, ignore it // incorrect config, ignore it
$bAutoReload = false; $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 // Used either for asynchronous or auto_reload
// does a json_encode twice to get a string usable as function parameter // does a json_encode twice to get a string usable as function parameter
$sFilterBefore = $this->m_oFilter->serialize(); $sFilterBefore = $this->m_oFilter->serialize();
@@ -867,7 +884,8 @@ JS
{ {
// Workaround to an issue revealed whenever a condition on org_id is applied twice (with a hierarchy of organizations) // 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 // 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 // Skip
return; return;
} }
@@ -877,42 +895,53 @@ JS
$bConditionAdded = false; $bConditionAdded = false;
// If the condition is an external key with a class having a hierarchy, use a "below" criteria // 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); $oAttDef = MetaModel::GetAttributeDef($sClass, $sFilterCode);
if ($oAttDef->IsExternalKey()) { if ($oAttDef->IsExternalKey())
{
$sHierarchicalKeyCode = MetaModel::IsHierarchicalClass($oAttDef->GetTargetClass()); $sHierarchicalKeyCode = MetaModel::IsHierarchicalClass($oAttDef->GetTargetClass());
if ($sHierarchicalKeyCode !== false) { if ($sHierarchicalKeyCode !== false)
{
$oFilter = new DBObjectSearch($oAttDef->GetTargetClass()); $oFilter = new DBObjectSearch($oAttDef->GetTargetClass());
if (($sOpCode == 'IN') && is_array($condition)) { if (($sOpCode == 'IN') && is_array($condition))
{
$oFilter->AddConditionExpression(self::GetConditionIN($oFilter, 'id', $condition)); $oFilter->AddConditionExpression(self::GetConditionIN($oFilter, 'id', $condition));
} else { }
else
{
$oFilter->AddCondition('id', $condition); $oFilter->AddCondition('id', $condition);
} }
$oHKFilter = new DBObjectSearch($oAttDef->GetTargetClass()); $oHKFilter = new DBObjectSearch($oAttDef->GetTargetClass());
$oHKFilter->AddCondition_PointingTo($oFilter, $sHierarchicalKeyCode, TREE_OPERATOR_BELOW); // Use the 'below' operator by default $oHKFilter->AddCondition_PointingTo($oFilter, $sHierarchicalKeyCode, TREE_OPERATOR_BELOW); // Use the 'below' operator by default
$this->m_oFilter->AddCondition_PointingTo($oHKFilter, $sFilterCode); $this->m_oFilter->AddCondition_PointingTo($oHKFilter, $sFilterCode);
$bConditionAdded = true; $bConditionAdded = true;
} elseif (($sOpCode == 'IN') && is_array($condition)) { }
else if (($sOpCode == 'IN') && is_array($condition))
{
$this->m_oFilter->AddConditionExpression(self::GetConditionIN($this->m_oFilter, $sFilterCode, $condition)); $this->m_oFilter->AddConditionExpression(self::GetConditionIN($this->m_oFilter, $sFilterCode, $condition));
$bConditionAdded = true; $bConditionAdded = true;
} }
} elseif (($sOpCode == 'IN') && is_array($condition)) { }
else if (($sOpCode == 'IN') && is_array($condition))
{
$this->m_oFilter->AddConditionExpression(self::GetConditionIN($this->m_oFilter, $sFilterCode, $condition)); $this->m_oFilter->AddConditionExpression(self::GetConditionIN($this->m_oFilter, $sFilterCode, $condition));
$bConditionAdded = true; $bConditionAdded = true;
} }
} }
// In all other cases, just add the condition directly // 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 $this->m_oFilter->AddCondition($sFilterCode, $condition, null); // Use the default 'loose' operator
} }
} }
protected static function GetConditionIN($oFilter, $sFilterCode, $condition) static protected function GetConditionIN($oFilter, $sFilterCode, $condition)
{ {
$oField = new FieldExpression($sFilterCode, $oFilter->GetClassAlias()); $oField = new FieldExpression($sFilterCode, $oFilter->GetClassAlias());
$sListExpr = '('.implode(', ', CMDBSource::Quote($condition)).')'; $sListExpr = '('.implode(', ', CMDBSource::Quote($condition)).')';
$sOQLCondition = $oField->RenderExpression()." IN $sListExpr"; $sOQLCondition = $oField->RenderExpression()." IN $sListExpr";
$oNewCondition = Expression::FromOQL($sOQLCondition); $oNewCondition = Expression::FromOQL($sOQLCondition);
@@ -943,10 +972,13 @@ JS
protected function MakeGroupByQuery(&$aExtraParams, &$oGroupByExp, &$sGroupByLabel, &$aGroupBy, &$sAggregationFunction, &$sFctVar, &$sAggregationAttr, &$sSql) protected function MakeGroupByQuery(&$aExtraParams, &$oGroupByExp, &$sGroupByLabel, &$aGroupBy, &$sAggregationFunction, &$sFctVar, &$sAggregationAttr, &$sSql)
{ {
$sAlias = $this->m_oFilter->GetClassAlias(); $sAlias = $this->m_oFilter->GetClassAlias();
if (isset($aExtraParams['group_by_label'])) { if (isset($aExtraParams['group_by_label']))
{
$oGroupByExp = Expression::FromOQL($aExtraParams['group_by']); $oGroupByExp = Expression::FromOQL($aExtraParams['group_by']);
$sGroupByLabel = $aExtraParams['group_by_label']; $sGroupByLabel = $aExtraParams['group_by_label'];
} else { }
else
{
// Backward compatibility: group_by is simply a field id // Backward compatibility: group_by is simply a field id
$oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias); $oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias);
$sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']); $sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']);
@@ -954,52 +986,61 @@ JS
// Security filtering // Security filtering
$aFields = $oGroupByExp->ListRequiredFields(); $aFields = $oGroupByExp->ListRequiredFields();
foreach ($aFields as $sFieldAlias) { foreach($aFields as $sFieldAlias)
$aMatches = []; {
if (preg_match('/^([^.]+)\\.([^.]+)$/', $sFieldAlias, $aMatches)) { $aMatches = array();
if (preg_match('/^([^.]+)\\.([^.]+)$/', $sFieldAlias, $aMatches))
{
$sFieldClass = $this->m_oFilter->GetClassName($aMatches[1]); $sFieldClass = $this->m_oFilter->GetClassName($aMatches[1]);
$oAttDef = MetaModel::GetAttributeDef($sFieldClass, $aMatches[2]); $oAttDef = MetaModel::GetAttributeDef($sFieldClass, $aMatches[2]);
if ($oAttDef instanceof AttributeOneWayPassword) { if ($oAttDef instanceof AttributeOneWayPassword)
{
throw new Exception('Grouping on password fields is not supported.'); throw new Exception('Grouping on password fields is not supported.');
} }
} }
} }
$aGroupBy = []; $aGroupBy = array();
$aGroupBy['grouped_by_1'] = $oGroupByExp; $aGroupBy['grouped_by_1'] = $oGroupByExp;
$aQueryParams = []; $aQueryParams = array();
if (isset($aExtraParams['query_params'])) { if (isset($aExtraParams['query_params']))
{
$aQueryParams = $aExtraParams['query_params']; $aQueryParams = $aExtraParams['query_params'];
} }
$aFunctions = []; $aFunctions = array();
$sAggregationFunction = 'count'; $sAggregationFunction = 'count';
$sFctVar = '_itop_count_'; $sFctVar = '_itop_count_';
$sAggregationAttr = ''; $sAggregationAttr = '';
if (isset($aExtraParams['aggregation_function']) && !empty($aExtraParams['aggregation_attribute'])) { if (isset($aExtraParams['aggregation_function']) && !empty($aExtraParams['aggregation_attribute']))
{
$sAggregationFunction = $aExtraParams['aggregation_function']; $sAggregationFunction = $aExtraParams['aggregation_function'];
$sAggregationAttr = $aExtraParams['aggregation_attribute']; $sAggregationAttr = $aExtraParams['aggregation_attribute'];
$oAttrExpr = Expression::FromOQL('`'.$sAlias.'`.`'.$sAggregationAttr.'`'); $oAttrExpr = Expression::FromOQL('`'.$sAlias.'`.`'.$sAggregationAttr.'`');
$oFctExpr = new FunctionExpression(strtoupper($sAggregationFunction), [$oAttrExpr]); $oFctExpr = new FunctionExpression(strtoupper($sAggregationFunction), array($oAttrExpr));
$sFctVar = '_itop_'.$sAggregationFunction.'_'; $sFctVar = '_itop_'.$sAggregationFunction.'_';
$aFunctions = [$sFctVar => $oFctExpr]; $aFunctions = array($sFctVar => $oFctExpr);
} }
if (!empty($sAggregationAttr)) { if (!empty($sAggregationAttr))
{
$sClass = $this->m_oFilter->GetClass(); $sClass = $this->m_oFilter->GetClass();
$sAggregationAttr = MetaModel::GetLabel($sClass, $sAggregationAttr); $sAggregationAttr = MetaModel::GetLabel($sClass, $sAggregationAttr);
} }
$iLimit = 0; $iLimit = 0;
if (isset($aExtraParams['limit'])) { if (isset($aExtraParams['limit']))
{
$iLimit = intval($aExtraParams['limit']); $iLimit = intval($aExtraParams['limit']);
} }
$aOrderBy = []; $aOrderBy = array();
if (isset($aExtraParams['order_direction']) && isset($aExtraParams['order_by'])) { if (isset($aExtraParams['order_direction']) && isset($aExtraParams['order_by']))
switch ($aExtraParams['order_by']) { {
switch ($aExtraParams['order_by'])
{
case 'attribute': case 'attribute':
$aOrderBy = ['grouped_by_1' => ($aExtraParams['order_direction'] === 'asc')]; $aOrderBy = array('grouped_by_1' => ($aExtraParams['order_direction'] === 'asc'));
break; break;
case 'function': case 'function':
$aOrderBy = [$sFctVar => ($aExtraParams['order_direction'] === 'asc')]; $aOrderBy = array($sFctVar => ($aExtraParams['order_direction'] === 'asc'));
break; break;
} }
} }
@@ -1035,31 +1076,31 @@ JS
$this->AddCondition($sFilterCode, $sContextParamValue); $this->AddCondition($sFilterCode, $sContextParamValue);
} }
} }
$aQueryParams = []; $aQueryParams = array();
if (isset($aExtraParams['query_params'])) { if (isset($aExtraParams['query_params'])) {
$aQueryParams = $aExtraParams['query_params']; $aQueryParams = $aExtraParams['query_params'];
} }
$this->m_oSet = new CMDBObjectSet($this->m_oFilter, [], $aQueryParams); $this->m_oSet = new CMDBObjectSet($this->m_oFilter, array(), $aQueryParams);
$this->m_oSet->SetShowObsoleteData($this->m_bShowObsoleteData); $this->m_oSet->SetShowObsoleteData($this->m_bShowObsoleteData);
} }
// Summary details // Summary details
$aCounts = []; $aCounts = array();
$aStateLabels = []; $aStateLabels = array();
if (!empty($sStateAttrCode) && !empty($sStatesList)) { if (!empty($sStateAttrCode) && !empty($sStatesList)) {
$aStates = explode(',', $sStatesList); $aStates = explode(',', $sStatesList);
// Generate one count + group by query [#1330] // Generate one count + group by query [#1330]
$sClassAlias = $this->m_oFilter->GetClassAlias(); $sClassAlias = $this->m_oFilter->GetClassAlias();
$oGroupByExpr = Expression::FromOQL($sClassAlias.'.'.$sStateAttrCode); $oGroupByExpr = Expression::FromOQL($sClassAlias.'.'.$sStateAttrCode);
$aGroupBy = ['group1' => $oGroupByExpr]; $aGroupBy = array('group1' => $oGroupByExpr);
$oGroupBySearch = $this->m_oFilter->DeepClone(); $oGroupBySearch = $this->m_oFilter->DeepClone();
if (isset($this->m_bShowObsoleteData)) { if (isset($this->m_bShowObsoleteData)) {
$oGroupBySearch->SetShowObsoleteData($this->m_bShowObsoleteData); $oGroupBySearch->SetShowObsoleteData($this->m_bShowObsoleteData);
} }
$sCountGroupByQuery = $oGroupBySearch->MakeGroupByQuery($aQueryParams, $aGroupBy, false); $sCountGroupByQuery = $oGroupBySearch->MakeGroupByQuery($aQueryParams, $aGroupBy, false);
$aCountGroupByResults = CMDBSource::QueryToArray($sCountGroupByQuery); $aCountGroupByResults = CMDBSource::QueryToArray($sCountGroupByQuery);
$aCountsQueryResults = []; $aCountsQueryResults = array();
foreach ($aCountGroupByResults as $aCountGroupBySingleResult) { foreach ($aCountGroupByResults as $aCountGroupBySingleResult) {
$aCountsQueryResults[$aCountGroupBySingleResult[0]] = $aCountGroupBySingleResult[1]; $aCountsQueryResults[$aCountGroupBySingleResult[0]] = $aCountGroupBySingleResult[1];
} }
@@ -1073,8 +1114,7 @@ JS
: 0; : 0;
if ($aCounts[$sStateValue] == 0) { if ($aCounts[$sStateValue] == 0) {
$aCounts[$sStateValue] = ['link' => '-', 'label' => $aCounts[$sStateValue]]; $aCounts[$sStateValue] = ['link' => '-', 'label' => $aCounts[$sStateValue]];;
;
} else { } else {
$oSingleGroupByValueFilter = $this->m_oFilter->DeepClone(); $oSingleGroupByValueFilter = $this->m_oFilter->DeepClone();
$oSingleGroupByValueFilter->AddCondition($sStateAttrCode, $sStateValue, '='); $oSingleGroupByValueFilter->AddCondition($sStateAttrCode, $sStateValue, '=');
@@ -1124,7 +1164,7 @@ JS
$oBlock->AddSubBlock($oPill); $oBlock->AddSubBlock($oPill);
} }
$aExtraParams['query_params'] = $this->m_oFilter->GetInternalParams(); $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->class'] = get_class($aExtraParams['query_params']['this->object()']);
$aExtraParams['query_params']['this->id'] = $aExtraParams['query_params']['this->object()']->GetKey(); $aExtraParams['query_params']['this->id'] = $aExtraParams['query_params']['this->object()']->GetKey();
unset($aExtraParams['query_params']['this->object()']); unset($aExtraParams['query_params']['this->object()']);
@@ -1138,8 +1178,7 @@ JS
$('#".$oBlock->GetId()."').html(data); $('#".$oBlock->GetId()."').html(data);
$('#".$oBlock->GetId()."').unblock(); $('#".$oBlock->GetId()."').unblock();
}); });
$('#".$oBlock->GetId()."').unblock();" $('#".$oBlock->GetId()."').unblock();");
);
return $oBlock; return $oBlock;
} }
@@ -1149,7 +1188,7 @@ JS
* *
* @return string[] * @return string[]
*/ */
protected function GetAllowedActionsParams(array $aExtraParams) protected function GetAllowedActionsParams(array $aExtraParams)
{ {
return [ return [
'context_filter', /** int if != 0 filter with user context */ 'context_filter', /** int if != 0 filter with user context */
@@ -1181,11 +1220,11 @@ JS
$this->AddCondition($sFilterCode, $sContextParamValue); $this->AddCondition($sFilterCode, $sContextParamValue);
} }
} }
$aQueryParams = []; $aQueryParams = array();
if (isset($aExtraParams['query_params'])) { if (isset($aExtraParams['query_params'])) {
$aQueryParams = $aExtraParams['query_params']; $aQueryParams = $aExtraParams['query_params'];
} }
$this->m_oSet = new CMDBObjectSet($this->m_oFilter, [], $aQueryParams); $this->m_oSet = new CMDBObjectSet($this->m_oFilter, array(), $aQueryParams);
$this->m_oSet->SetShowObsoleteData($this->m_bShowObsoleteData); $this->m_oSet->SetShowObsoleteData($this->m_bShowObsoleteData);
} }
$iCount = $this->m_oSet->Count(); $iCount = $this->m_oSet->Count();
@@ -1202,15 +1241,8 @@ JS
if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY)) { if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY)) {
$sCreateActionUrl = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=new&class='.$sClass.$oAppContext->GetForLink(true); $sCreateActionUrl = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=new&class='.$sClass.$oAppContext->GetForLink(true);
$sCreateActionLabel = Dict::Format('UI:Button:Create'); $sCreateActionLabel = Dict::Format('UI:Button:Create');
$oBlock = DashletFactory::MakeForDashletBadge( $oBlock = DashletFactory::MakeForDashletBadge($sClassIconUrl, $sHyperlink, $iCount, $sClassLabel, $sCreateActionUrl,
$sClassIconUrl, $sCreateActionLabel, $aRefreshParams);
$sHyperlink,
$iCount,
$sClassLabel,
$sCreateActionUrl,
$sCreateActionLabel,
$aRefreshParams
);
} else { } else {
$oBlock = DashletFactory::MakeForDashletBadge($sClassIconUrl, $sHyperlink, $iCount, $sClassLabel, null, null, $aRefreshParams); $oBlock = DashletFactory::MakeForDashletBadge($sClassIconUrl, $sHyperlink, $iCount, $sClassLabel, null, null, $aRefreshParams);
} }
@@ -1240,9 +1272,9 @@ JS
$aRes = CMDBSource::QueryToArray($sSql); $aRes = CMDBSource::QueryToArray($sSql);
$aGroupBy = []; $aGroupBy = array();
$aLabels = []; $aLabels = array();
$aValues = []; $aValues = array();
$iTotalCount = 0; $iTotalCount = 0;
foreach ($aRes as $iRow => $aRow) { foreach ($aRes as $iRow => $aRow) {
$sValue = $aRow['grouped_by_1']; $sValue = $aRow['grouped_by_1'];
@@ -1253,7 +1285,7 @@ JS
$iTotalCount += $aRow['_itop_count_']; $iTotalCount += $aRow['_itop_count_'];
} }
$aData = []; $aData = array();
$oAppContext = new ApplicationContext(); $oAppContext = new ApplicationContext();
$sParams = $oAppContext->GetForLink(true); $sParams = $oAppContext->GetForLink(true);
foreach ($aGroupBy as $iRow => $iCount) { foreach ($aGroupBy as $iRow => $iCount) {
@@ -1264,22 +1296,22 @@ JS
if (isset($aExtraParams['query_params'])) { if (isset($aExtraParams['query_params'])) {
$aQueryParams = $aExtraParams['query_params']; $aQueryParams = $aExtraParams['query_params'];
} else { } else {
$aQueryParams = []; $aQueryParams = array();
} }
$sFilter = rawurlencode($oSubsetSearch->serialize(false, $aQueryParams)); $sFilter = rawurlencode($oSubsetSearch->serialize(false, $aQueryParams));
$aData[] = [ $aData[] = array(
'group' => $aLabels[$iRow], 'group' => $aLabels[$iRow],
'value' => "<a href=\"".utils::GetAbsoluteUrlAppRoot()."pages/UI.php?operation=search&dosearch=1$sParams&filter=$sFilter\">$iCount</a>", 'value' => "<a href=\"".utils::GetAbsoluteUrlAppRoot()."pages/UI.php?operation=search&dosearch=1$sParams&filter=$sFilter\">$iCount</a>"
]; // TO DO: add the context information ); // TO DO: add the context information
} }
$aAttribs = [ $aAttribs = array(
'group' => ['label' => $sGroupByLabel, 'description' => ''], 'group' => array('label' => $sGroupByLabel, 'description' => ''),
'value' => [ 'value' => array(
'label' => Dict::S('UI:GroupBy:'.$sAggregationFunction), 'label' => Dict::S('UI:GroupBy:'.$sAggregationFunction),
'description' => Dict::Format('UI:GroupBy:'.$sAggregationFunction.'+', $sAggregationAttr), 'description' => Dict::Format('UI:GroupBy:'.$sAggregationFunction.'+', $sAggregationAttr),
], ),
]; );
$sFormat = isset($aExtraParams['format']) ? $aExtraParams['format'] : 'UI:Pagination:HeaderNoSelection'; $sFormat = isset($aExtraParams['format']) ? $aExtraParams['format'] : 'UI:Pagination:HeaderNoSelection';
$aExtraParams['query_params'] = $this->m_oFilter->GetInternalParams(); $aExtraParams['query_params'] = $this->m_oFilter->GetInternalParams();
@@ -1290,7 +1322,7 @@ JS
$oBlock = PanelUIBlockFactory::MakeForClass($aExtraParams["panel_class"], $aExtraParams["panel_title"]); $oBlock = PanelUIBlockFactory::MakeForClass($aExtraParams["panel_class"], $aExtraParams["panel_title"]);
$oBlock->AddSubTitleBlock(new Html($sTitle)); $oBlock->AddSubTitleBlock(new Html($sTitle));
$oBlock->AddCSSClass('ibo-datatable-panel'); $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"]); $oBlock->SetIcon($aExtraParams["panel_icon"]);
} }
$oDataTable = DataTableUIBlockFactory::MakeForStaticData("", $aAttribs, $aData, null, $aExtraParams, $this->m_oFilter->ToOQL(), $aOption); $oDataTable = DataTableUIBlockFactory::MakeForStaticData("", $aAttribs, $aData, null, $aExtraParams, $this->m_oFilter->ToOQL(), $aOption);
@@ -1309,7 +1341,7 @@ JS
} }
if (isset($aExtraParams["surround_with_panel"]) && $aExtraParams["surround_with_panel"]) { if (isset($aExtraParams["surround_with_panel"]) && $aExtraParams["surround_with_panel"]) {
$oBlock = PanelUIBlockFactory::MakeForClass($aExtraParams["panel_class"], $aExtraParams["panel_title"]); $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->SetIcon($aExtraParams["panel_icon"]);
} }
$oBlock->AddSubBlock(new Html('<p>'.Dict::Format($sFormat, $iCount).'</p>')); $oBlock->AddSubBlock(new Html('<p>'.Dict::Format($sFormat, $iCount).'</p>'));
@@ -1319,7 +1351,7 @@ JS
} }
return $oBlock; return $oBlock;
} }
/** /**
* @param WebPage $oPage * @param WebPage $oPage
@@ -1377,6 +1409,7 @@ JS
$oBlock->aExtraParams = $aExtraParams; $oBlock->aExtraParams = $aExtraParams;
$oBlock->sFilter = $this->m_oFilter->ToOQL(); $oBlock->sFilter = $this->m_oFilter->ToOQL();
// Check the classes that can be read (i.e authorized) by this user... // Check the classes that can be read (i.e authorized) by this user...
foreach ($aClasses as $sAlias => $sClassName) { foreach ($aClasses as $sAlias => $sClassName) {
if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $this->m_oSet) != UR_ALLOWED_NO) { if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $this->m_oSet) != UR_ALLOWED_NO) {
@@ -1398,7 +1431,7 @@ JS
$sSearchFilter = $this->m_oSet->GetFilter()->serialize(); $sSearchFilter = $this->m_oSet->GetFilter()->serialize();
// Limit the size of the URL (N°1585 - request uri too long) // Limit the size of the URL (N°1585 - request uri too long)
if (strlen($sSearchFilter) < SERVER_MAX_URL_LENGTH) { if (strlen($sSearchFilter) < SERVER_MAX_URL_LENGTH) {
$oBlock->sEventAttachedData = json_encode([ $oBlock->sEventAttachedData = json_encode(array(
'filter' => $sSearchFilter, 'filter' => $sSearchFilter,
'breadcrumb_id' => "ui-search-".$this->m_oSet->GetClass(), 'breadcrumb_id' => "ui-search-".$this->m_oSet->GetClass(),
'breadcrumb_label' => MetaModel::GetName($this->m_oSet->GetClass()), 'breadcrumb_label' => MetaModel::GetName($this->m_oSet->GetClass()),
@@ -1406,7 +1439,7 @@ JS
'breadcrumb_instance_id' => MetaModel::GetConfig()->GetItopInstanceid(), 'breadcrumb_instance_id' => MetaModel::GetConfig()->GetItopInstanceid(),
'breadcrumb_icon' => 'fas fa-search', 'breadcrumb_icon' => 'fas fa-search',
'breadcrumb_icon_type' => iTopWebPage::ENUM_BREADCRUMB_ENTRY_ICON_TYPE_CSS_CLASSES, 'breadcrumb_icon_type' => iTopWebPage::ENUM_BREADCRUMB_ENTRY_ICON_TYPE_CSS_CLASSES,
]); ));
} }
} }
@@ -1439,25 +1472,25 @@ JS
$oContentBlock = new UIContentBlock(); $oContentBlock = new UIContentBlock();
$oHtml = new Html(); $oHtml = new Html();
$oContentBlock->AddSubBlock($oHtml); $oContentBlock->AddSubBlock($oHtml);
$aDisplayAliases = isset($aExtraParams['display_aliases']) ? explode(',', $aExtraParams['display_aliases']) : []; $aDisplayAliases = isset($aExtraParams['display_aliases']) ? explode(',', $aExtraParams['display_aliases']) : array();
if (!isset($aExtraParams['group_by'])) { if (!isset($aExtraParams['group_by'])) {
$oHtml->AddHtml('<p>'.Dict::S('UI:Error:MandatoryTemplateParameter_group_by').'</p>'); $oHtml->AddHtml('<p>'.Dict::S('UI:Error:MandatoryTemplateParameter_group_by').'</p>');
} else { } else {
$aGroupByFields = []; $aGroupByFields = array();
$aGroupBy = explode(',', $aExtraParams['group_by']); $aGroupBy = explode(',', $aExtraParams['group_by']);
foreach ($aGroupBy as $sGroupBy) { foreach ($aGroupBy as $sGroupBy) {
$aMatches = []; $aMatches = array();
if (preg_match('/^(.+)\.(.+)$/', $sGroupBy, $aMatches) > 0) { if (preg_match('/^(.+)\.(.+)$/', $sGroupBy, $aMatches) > 0) {
$aGroupByFields[] = ['alias' => $aMatches[1], 'att_code' => $aMatches[2]]; $aGroupByFields[] = array('alias' => $aMatches[1], 'att_code' => $aMatches[2]);
} }
} }
if (count($aGroupByFields) == 0) { if (count($aGroupByFields) == 0) {
$oHtml->AddHtml('<p>'.Dict::Format('UI:Error:InvalidGroupByFields', $aExtraParams['group_by']).'</p>'); $oHtml->AddHtml('<p>'.Dict::Format('UI:Error:InvalidGroupByFields', $aExtraParams['group_by']).'</p>');
} else { } else {
$aResults = []; $aResults = array();
$aCriteria = []; $aCriteria = array();
while ($aObjects = $this->m_oSet->FetchAssoc()) { while ($aObjects = $this->m_oSet->FetchAssoc()) {
$aKeys = []; $aKeys = array();
foreach ($aGroupByFields as $aField) { foreach ($aGroupByFields as $aField) {
$sAlias = $aField['alias']; $sAlias = $aField['alias'];
if (is_null($aObjects[$sAlias])) { if (is_null($aObjects[$sAlias])) {
@@ -1474,7 +1507,7 @@ JS
$oHtml->AddHtml("<table>\n"); $oHtml->AddHtml("<table>\n");
// Construct a new (parametric) query that will return the content of this block // Construct a new (parametric) query that will return the content of this block
$oBlockFilter = $this->m_oFilter->DeepClone(); $oBlockFilter = $this->m_oFilter->DeepClone();
$aExpressions = []; $aExpressions = array();
$index = 0; $index = 0;
foreach ($aGroupByFields as $aField) { foreach ($aGroupByFields as $aField) {
$aExpressions[] = '`'.$aField['alias'].'`.`'.$aField['att_code'].'` = :param'.$index++; $aExpressions[] = '`'.$aField['alias'].'`.`'.$aField['att_code'].'` = :param'.$index++;
@@ -1486,7 +1519,7 @@ JS
foreach ($aResults as $sCategory => $aObjects) { foreach ($aResults as $sCategory => $aObjects) {
$oHtml->AddHtml("<tr><td><h1>$sCategory</h1></td></tr>\n"); $oHtml->AddHtml("<tr><td><h1>$sCategory</h1></td></tr>\n");
if (count($aDisplayAliases) == 1) { if (count($aDisplayAliases) == 1) {
$aSimpleArray = []; $aSimpleArray = array();
foreach ($aObjects as $aRow) { foreach ($aObjects as $aRow) {
$oObj = $aRow[$aDisplayAliases[0]]; $oObj = $aRow[$aDisplayAliases[0]];
if (!is_null($oObj)) { if (!is_null($oObj)) {
@@ -1502,12 +1535,12 @@ JS
$oHtml->AddHtml("</td></tr>\n"); $oHtml->AddHtml("</td></tr>\n");
} else { } else {
$index = 0; $index = 0;
$aArgs = []; $aArgs = array();
foreach ($aGroupByFields as $aField) { foreach ($aGroupByFields as $aField) {
$aArgs['param'.$index] = $aCriteria[$sCategory][$aField['alias'].'.'.$aField['att_code']]; $aArgs['param'.$index] = $aCriteria[$sCategory][$aField['alias'].'.'.$aField['att_code']];
$index++; $index++;
} }
$oSet = new CMDBObjectSet($oBlockFilter, [], $aArgs); $oSet = new CMDBObjectSet($oBlockFilter, array(), $aArgs);
if (empty($aExtraParams['currentId'])) { if (empty($aExtraParams['currentId'])) {
$iListId = utils::GetUniqueId(); // Works only if not in an Ajax page !! $iListId = utils::GetUniqueId(); // Works only if not in an Ajax page !!
} else { } else {
@@ -1570,7 +1603,7 @@ JS
if (isset($aExtraParams["surround_with_panel"]) && $aExtraParams["surround_with_panel"]) { if (isset($aExtraParams["surround_with_panel"]) && $aExtraParams["surround_with_panel"]) {
$oPanel = PanelUIBlockFactory::MakeForClass($aExtraParams["panel_class"], $aExtraParams["panel_title"]); $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->SetIcon($aExtraParams["panel_icon"]);
} }
$oPanel->AddSubBlock($oBlock); $oPanel->AddSubBlock($oBlock);
@@ -1594,7 +1627,7 @@ JS
{ {
$sChartType = isset($aExtraParams['chart_type']) ? $aExtraParams['chart_type'] : 'pie'; $sChartType = isset($aExtraParams['chart_type']) ? $aExtraParams['chart_type'] : 'pie';
$sId = utils::ReadParam('id', ''); $sId = utils::ReadParam('id', '');
$aValues = []; $aValues = array();
$oBlock = null; $oBlock = null;
$sJSURLs = ''; $sJSURLs = '';
@@ -1605,18 +1638,21 @@ JS
$this->MakeGroupByQuery($aExtraParams, $oGroupByExp, $sGroupByLabel, $aGroupBy, $sAggregationFunction, $sFctVar, $sAggregationAttr, $sSql); $this->MakeGroupByQuery($aExtraParams, $oGroupByExp, $sGroupByLabel, $aGroupBy, $sAggregationFunction, $sFctVar, $sAggregationAttr, $sSql);
$aRes = CMDBSource::QueryToArray($sSql); $aRes = CMDBSource::QueryToArray($sSql);
$iTotalCount = 0; $iTotalCount = 0;
$aURLs = []; $aURLs = array();
foreach ($aRes as $iRow => $aRow) { foreach ($aRes as $iRow => $aRow) {
$sValue = $aRow['grouped_by_1']; $sValue = $aRow['grouped_by_1'];
$sHtmlValue = $oGroupByExp->MakeValueLabel($this->m_oFilter, $sValue, $sValue); $sHtmlValue = $oGroupByExp->MakeValueLabel($this->m_oFilter, $sValue, $sValue);
$iTotalCount += $aRow['_itop_count_']; $iTotalCount += $aRow['_itop_count_'];
$aValues[] = [ $aValues[] = array(
'label' => html_entity_decode(strip_tags($sHtmlValue), ENT_QUOTES, 'UTF-8'), 'label' => html_entity_decode(strip_tags($sHtmlValue), ENT_QUOTES, 'UTF-8'),
'label_html' => $sHtmlValue, 'label_html' => $sHtmlValue,
'value' => (float)$aRow[$sFctVar], 'value' => (float)$aRow[$sFctVar],
]; );
// Build the search for this subset // Build the search for this subset
$oSubsetSearch = $this->m_oFilter->DeepClone(); $oSubsetSearch = $this->m_oFilter->DeepClone();
@@ -1655,7 +1691,7 @@ JS
$aColumns = []; $aColumns = [];
$aNames = []; $aNames = [];
foreach ($aValues as $idx => $aValue) { foreach ($aValues as $idx => $aValue) {
$aColumns[] = ['series_'.$idx, (float)$aValue['value']]; $aColumns[] = array('series_'.$idx, (float)$aValue['value']);
$aNames['series_'.$idx] = $aValue['label']; $aNames['series_'.$idx] = $aValue['label'];
} }
@@ -1677,7 +1713,7 @@ JS
} }
if (isset($aExtraParams["surround_with_panel"]) && $aExtraParams["surround_with_panel"]) { if (isset($aExtraParams["surround_with_panel"]) && $aExtraParams["surround_with_panel"]) {
$oPanel = PanelUIBlockFactory::MakeForClass($aExtraParams["panel_class"], $aExtraParams["panel_title"]); $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->SetIcon($aExtraParams["panel_icon"]);
} }
$oPanel->AddSubBlock($oBlock); $oPanel->AddSubBlock($oBlock);
@@ -1704,12 +1740,12 @@ JS
$oBlock->sDownloadLink = utils::GetAbsoluteUrlAppRoot().'webservices/export.php?expression='.urlencode($this->m_oFilter->ToOQL(true)).'&format=csv&filename='.urlencode($oBlock->sCsvFile); $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'; $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 // Pass the parameters via POST, since expression may be very long
$aParamsToPost = [ $aParamsToPost = array(
'expression' => $this->m_oFilter->ToOQL(true), 'expression' => $this->m_oFilter->ToOQL(true),
'format' => 'csv', 'format' => 'csv',
'filename' => $oBlock->sCsvFile, 'filename' => $oBlock->sCsvFile,
'charset' => 'UTF-8', 'charset' => 'UTF-8',
]; );
if ($oBlock->bAdvancedMode) { if ($oBlock->bAdvancedMode) {
$oBlock->sDownloadLink .= '&fields_advanced=1'; $oBlock->sDownloadLink .= '&fields_advanced=1';
$aParamsToPost['fields_advanced'] = 1; $aParamsToPost['fields_advanced'] = 1;
@@ -1768,7 +1804,8 @@ class MenuBlock extends DisplayBlock
$oRouter = Router::GetInstance(); $oRouter = Router::GetInstance();
$oRenderBlock = new UIContentBlock(); $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; $this->m_sStyle = static::ENUM_STYLE_LIST;
} }
@@ -1776,7 +1813,7 @@ class MenuBlock extends DisplayBlock
$aSelectedClasses = $this->GetFilter()->GetSelectedClasses(); $aSelectedClasses = $this->GetFilter()->GetSelectedClasses();
$bIsForLinkset = isset($aExtraParams['target_attr']); $bIsForLinkset = isset($aExtraParams['target_attr']);
$oSet = new CMDBObjectSet($this->GetFilter()); $oSet = new CMDBObjectSet($this->GetFilter());
if (isset($aExtraParams['object_count'])) { if(isset($aExtraParams['object_count'])){
$iSetCount = $aExtraParams['object_count']; $iSetCount = $aExtraParams['object_count'];
} else { } else {
$iSetCount = $oSet->Count(); $iSetCount = $oSet->Count();
@@ -1807,6 +1844,7 @@ class MenuBlock extends DisplayBlock
$oAppContext = new ApplicationContext(); $oAppContext = new ApplicationContext();
$sContext = $oAppContext->GetForLink(true); $sContext = $oAppContext->GetForLink(true);
$sFilter = $this->GetFilter()->serialize(); $sFilter = $this->GetFilter()->serialize();
$sUIPage = cmdbAbstractObject::ComputeStandardUIPage($sClass); $sUIPage = cmdbAbstractObject::ComputeStandardUIPage($sClass);
$sRootUrl = utils::GetAbsoluteUrlAppRoot(); $sRootUrl = utils::GetAbsoluteUrlAppRoot();
@@ -1864,7 +1902,7 @@ class MenuBlock extends DisplayBlock
$iLimit = MetaModel::GetConfig()->Get('complex_actions_limit'); $iLimit = MetaModel::GetConfig()->Get('complex_actions_limit');
if ( if (
($iSetCount > 0) && (false === $bLocked) && MetaModel::HasLifecycle($sClass) && ($iSetCount > 0) && (false === $bLocked) && MetaModel::HasLifecycle($sClass) &&
(($iLimit == 0) || ($iSetCount < $iLimit)) ( ($iLimit == 0) || ($iSetCount < $iLimit) )
) { ) {
$aTransitions = []; $aTransitions = [];
// Processing (optimizations) and endpoints are not exactly the same depending on if there is only 1 object or a set // Processing (optimizations) and endpoints are not exactly the same depending on if there is only 1 object or a set
@@ -1884,8 +1922,8 @@ class MenuBlock extends DisplayBlock
// Life cycle actions may be available... if all objects are in the same state // Life cycle actions may be available... if all objects are in the same state
// Group by <state> // Group by <state>
$oGroupByExp = new FieldExpression(MetaModel::GetStateAttributeCode($sClass), $this->m_oFilter->GetClassAlias()); $oGroupByExp = new FieldExpression(MetaModel::GetStateAttributeCode($sClass), $this->m_oFilter->GetClassAlias());
$aGroupBy = ['__state__' => $oGroupByExp]; $aGroupBy = array('__state__' => $oGroupByExp);
$aQueryParams = []; $aQueryParams = array();
if (isset($aExtraParams['query_params'])) { if (isset($aExtraParams['query_params'])) {
$aQueryParams = $aExtraParams['query_params']; $aQueryParams = $aExtraParams['query_params'];
} }
@@ -1917,10 +1955,10 @@ class MenuBlock extends DisplayBlock
switch ($iActionAllowed) { switch ($iActionAllowed) {
case UR_ALLOWED_YES: case UR_ALLOWED_YES:
case UR_ALLOWED_DEPENDS: case UR_ALLOWED_DEPENDS:
$aTransitionActions[$sStimulusCode] = [ $aTransitionActions[$sStimulusCode] = array(
'label' => $aStimuli[$sStimulusCode]->GetLabel(), 'label' => $aStimuli[$sStimulusCode]->GetLabel(),
'url' => "{$sRootUrl}pages/UI.php?stimulus=$sStimulusCode&class=$sLifecycleClass&{$sUrlQueryString}", 'url' => "{$sRootUrl}pages/UI.php?stimulus=$sStimulusCode&class=$sLifecycleClass&{$sUrlQueryString}",
] + $aActionParams; ) + $aActionParams;
break; break;
default: default:
@@ -1982,16 +2020,16 @@ class MenuBlock extends DisplayBlock
// Just one object in the set, possible actions are "new / clone / modify and delete" // Just one object in the set, possible actions are "new / clone / modify and delete"
if (!isset($aExtraParams['link_attr'])) { if (!isset($aExtraParams['link_attr'])) {
if ($bIsModifyAllowed) { if ($bIsModifyAllowed) {
$aRegularActions['UI:Menu:Modify'] = [ $aRegularActions['UI:Menu:Modify'] = array(
'label' => Dict::S('UI:Menu:Modify'), 'label' => Dict::S('UI:Menu:Modify'),
'url' => $oRouter->GenerateUrl('object.modify', ['class' => $sClass, 'id' => $id])."{$sContext}#", 'url' => $oRouter->GenerateUrl('object.modify', ['class' => $sClass, 'id' => $id]) . "{$sContext}#",
] + $aActionParams; ) + $aActionParams;
} }
if ($bIsDeleteAllowed) { if ($bIsDeleteAllowed) {
$aRegularActions['UI:Menu:Delete'] = [ $aRegularActions['UI:Menu:Delete'] = array(
'label' => Dict::S('UI:Menu:Delete'), 'label' => Dict::S('UI:Menu:Delete'),
'url' => "{$sRootUrl}pages/$sUIPage?operation=delete&class=$sClass&id=$id{$sContext}", 'url' => "{$sRootUrl}pages/$sUIPage?operation=delete&class=$sClass&id=$id{$sContext}",
] + $aActionParams; ) + $aActionParams;
} }
// Relations... // Relations...
@@ -2000,16 +2038,16 @@ class MenuBlock extends DisplayBlock
$this->AddMenuSeparator($aRegularActions); $this->AddMenuSeparator($aRegularActions);
foreach ($aRelations as $sRelationCode => $aRelationInfo) { foreach ($aRelations as $sRelationCode => $aRelationInfo) {
if (array_key_exists('down', $aRelationInfo)) { if (array_key_exists('down', $aRelationInfo)) {
$aRegularActions['UI:Menu:'.$sRelationCode.'_down'] = [ $aRegularActions[$sRelationCode.'_down'] = array(
'label' => $aRelationInfo['down'], 'label' => $aRelationInfo['down'],
'url' => "{$sRootUrl}pages/$sUIPage?operation=view_relations&relation=$sRelationCode&direction=down&class=$sClass&id=$id{$sContext}", 'url' => "{$sRootUrl}pages/$sUIPage?operation=view_relations&relation=$sRelationCode&direction=down&class=$sClass&id=$id{$sContext}",
] + $aActionParams; ) + $aActionParams;
} }
if (array_key_exists('up', $aRelationInfo)) { if (array_key_exists('up', $aRelationInfo)) {
$aRegularActions['UI:Menu:'.$sRelationCode.'_up'] = [ $aRegularActions[$sRelationCode.'_up'] = array(
'label' => $aRelationInfo['up'], 'label' => $aRelationInfo['up'],
'url' => "{$sRootUrl}pages/$sUIPage?operation=view_relations&relation=$sRelationCode&direction=up&class=$sClass&id=$id{$sContext}", 'url' => "{$sRootUrl}pages/$sUIPage?operation=view_relations&relation=$sRelationCode&direction=up&class=$sClass&id=$id{$sContext}",
] + $aActionParams; ) + $aActionParams;
} }
} }
} }
@@ -2021,7 +2059,7 @@ class MenuBlock extends DisplayBlock
$bCanKill = false; $bCanKill = false;
$oUser = UserRights::GetUserObject(); $oUser = UserRights::GetUserObject();
$aUserProfiles = []; $aUserProfiles = array();
if (!is_null($oUser)) { if (!is_null($oUser)) {
$oProfileSet = $oUser->Get('profile_list'); $oProfileSet = $oUser->Get('profile_list');
while ($oProfile = $oProfileSet->Fetch()) { while ($oProfile = $oProfileSet->Fetch()) {
@@ -2043,10 +2081,10 @@ class MenuBlock extends DisplayBlock
if ($bCanKill) { if ($bCanKill) {
$this->AddMenuSeparator($aRegularActions); $this->AddMenuSeparator($aRegularActions);
$aRegularActions['concurrent_lock_unlock'] = [ $aRegularActions['concurrent_lock_unlock'] = array(
'label' => Dict::S('UI:Menu:KillConcurrentLock'), 'label' => Dict::S('UI:Menu:KillConcurrentLock'),
'url' => "{$sRootUrl}pages/$sUIPage?operation=kill_lock&class=$sClass&id=$id{$sContext}", 'url' => "{$sRootUrl}pages/$sUIPage?operation=kill_lock&class=$sClass&id=$id{$sContext}",
]; );
} }
} }
} }
@@ -2054,7 +2092,7 @@ class MenuBlock extends DisplayBlock
$this->AddMenuSeparator($aRegularActions); $this->AddMenuSeparator($aRegularActions);
$this->GetEnumAllowedActions($oSet, function ($sLabel, $data) use (&$aRegularActions, $aActionParams) { $this->GetEnumAllowedActions($oSet, function ($sLabel, $data) use (&$aRegularActions, $aActionParams) {
$aRegularActions[$sLabel] = ['label' => $sLabel, 'url' => $data] + $aActionParams; $aRegularActions[$sLabel] = array('label' => $sLabel, 'url' => $data) + $aActionParams;
}); });
} }
break; break;
@@ -2251,16 +2289,6 @@ class MenuBlock extends DisplayBlock
$sIconClass = 'fas fa-file-pdf fa-lg'; $sIconClass = 'fas fa-file-pdf fa-lg';
$sLabel = ''; $sLabel = '';
break; break;
case 'UI:Menu:impacts_up':
$sIconClass = 'fas fa-sitemap fa-rotate-180';
$sLabel = '';
$aAction['tooltip'] = Dict::S('Relation:impacts/UpStream');
break;
case 'UI:Menu:impacts_down':
$sIconClass = 'fas fa-sitemap';
$sLabel = '';
$aAction['tooltip'] = Dict::S('Relation:impacts/DownStream');
break;
default: default:
if (isset($aAction['icon_class']) && (strlen($aAction['icon_class']) > 0)) { if (isset($aAction['icon_class']) && (strlen($aAction['icon_class']) > 0)) {
@@ -2271,7 +2299,7 @@ class MenuBlock extends DisplayBlock
$sTarget = isset($aAction['target']) ? $aAction['target'] : ''; $sTarget = isset($aAction['target']) ? $aAction['target'] : '';
if (!empty($aAction['onclick'])) { 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']); $oActionButton->SetOnClickJsCode($aAction['onclick']);
} else { } else {
$oActionButton = ButtonUIBlockFactory::MakeLinkNeutral($sUrl, $sLabel, $sIconClass, $sTarget, utils::Sanitize($sActionId, '', utils::ENUM_SANITIZATION_FILTER_ELEMENT_IDENTIFIER)); $oActionButton = ButtonUIBlockFactory::MakeLinkNeutral($sUrl, $sLabel, $sIconClass, $sTarget, utils::Sanitize($sActionId, '', utils::ENUM_SANITIZATION_FILTER_ELEMENT_IDENTIFIER));
@@ -2430,11 +2458,13 @@ class MenuBlock extends DisplayBlock
protected function AddMenuSeparator(&$aActions) protected function AddMenuSeparator(&$aActions)
{ {
$sSeparator = '<hr class="menu-separator"/>'; $sSeparator = '<hr class="menu-separator"/>';
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); $aKeys = array_keys($aActions);
$sLastKey = array_pop($aKeys); $sLastKey = array_pop($aKeys);
if ($aActions[$sLastKey]['label'] != $sSeparator) { // Make sure there are no 2 consecutive separators if ($aActions[$sLastKey]['label'] != $sSeparator) // Make sure there are no 2 consecutive separators
$aActions['sep_'.(count($aActions) - 1)] = ['label' => $sSeparator, 'url' => '']; {
$aActions['sep_'.(count($aActions)-1)] = array('label' => $sSeparator, 'url' => '');
} }
} }
} }
@@ -2494,10 +2524,10 @@ class MenuBlock extends DisplayBlock
*/ */
protected function AddBulkDeleteObjectsMenuAction(array &$aActions, string $sClass, string $sFilter, string $sActionIdentifier = 'UI:Menu:BulkDelete', $sActionLabel = 'UI:Menu:BulkDelete') protected function AddBulkDeleteObjectsMenuAction(array &$aActions, string $sClass, string $sFilter, string $sActionIdentifier = 'UI:Menu:BulkDelete', $sActionLabel = 'UI:Menu:BulkDelete')
{ {
$aActions[$sActionIdentifier] = [ $aActions[$sActionIdentifier] = array(
'label' => Dict::S($sActionLabel), 'label' => Dict::S($sActionLabel),
'url' => $this->PrepareUrlForStandardMenuAction($sClass, "operation=select_for_deletion&filter=".urlencode($sFilter)), 'url' => $this->PrepareUrlForStandardMenuAction($sClass, "operation=select_for_deletion&filter=".urlencode($sFilter)),
] + $this->GetDefaultParamsForMenuAction(); ) + $this->GetDefaultParamsForMenuAction();
} }
/** /**
@@ -2534,6 +2564,6 @@ class MenuBlock extends DisplayBlock
$oAppContext = new ApplicationContext(); $oAppContext = new ApplicationContext();
$sContext = $oAppContext->GetForLink(true); $sContext = $oAppContext->GetForLink(true);
return $sUrl.$sContext; return $sUrl . $sContext;
} }
} }

View File

@@ -19,67 +19,73 @@ class ExcelExporter
protected $iPosition; protected $iPosition;
protected $sOutputFilePath; protected $sOutputFilePath;
protected $bAdvancedMode; protected $bAdvancedMode;
public function __construct($sToken = null) public function __construct($sToken = null)
{ {
$this->aStatistics = [ $this->aStatistics = array(
'objects_count' => 0, 'objects_count' => 0,
'total_duration' => 0, 'total_duration' => 0,
'data_retrieval_duration' => 0, 'data_retrieval_duration' => 0,
'excel_build_duration' => 0, 'excel_build_duration' => 0,
'excel_write_duration' => 0, 'excel_write_duration' => 0,
'peak_memory_usage' => 0, 'peak_memory_usage' => 0,
]; );
$this->fStartTime = microtime(true); $this->fStartTime = microtime(true);
$this->oSearch = null; $this->oSearch = null;
$this->sState = 'new'; $this->sState = 'new';
$this->aObjectsIDs = []; $this->aObjectsIDs = array();
$this->iPosition = 0; $this->iPosition = 0;
$this->aAuthorizedClasses = null; $this->aAuthorizedClasses = null;
$this->aTableHeaders = null; $this->aTableHeaders = null;
$this->sOutputFilePath = null; $this->sOutputFilePath = null;
$this->bAdvancedMode = false; $this->bAdvancedMode = false;
$this->CheckDataDir(); $this->CheckDataDir();
if ($sToken == null) { if ($sToken == null)
{
$this->sToken = $this->GetNewToken(); $this->sToken = $this->GetNewToken();
} else { }
else
{
$this->sToken = $sToken; $this->sToken = $sToken;
$this->ReloadState(); $this->ReloadState();
} }
} }
public function __destruct() 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 // Operation in progress, save the state
$this->SaveState(); $this->SaveState();
} else { }
else
{
// Operation completed, cleanup the temp files // Operation completed, cleanup the temp files
@unlink($this->GetStateFile()); @unlink($this->GetStateFile());
@unlink($this->GetDataFile()); @unlink($this->GetDataFile());
} }
self::CleanupOldFiles(); self::CleanupOldFiles();
} }
public function SetChunkSize($iChunkSize) public function SetChunkSize($iChunkSize)
{ {
$this->iChunkSize = $iChunkSize; $this->iChunkSize = $iChunkSize;
} }
public function SetOutputFilePath($sDestFilePath) public function SetOutputFilePath($sDestFilePath)
{ {
$this->sOutputFilePath = $sDestFilePath; $this->sOutputFilePath = $sDestFilePath;
} }
public function SetAdvancedMode($bAdvanced) public function SetAdvancedMode($bAdvanced)
{ {
$this->bAdvancedMode = $bAdvanced; $this->bAdvancedMode = $bAdvanced;
} }
public function SaveState() public function SaveState()
{ {
$aState = [ $aState = array(
'state' => $this->sState, 'state' => $this->sState,
'statistics' => $this->aStatistics, 'statistics' => $this->aStatistics,
'filter' => $this->oSearch->serialize(), 'filter' => $this->oSearch->serialize(),
@@ -88,28 +94,31 @@ class ExcelExporter
'object_ids' => $this->aObjectsIDs, 'object_ids' => $this->aObjectsIDs,
'output_file_path' => $this->sOutputFilePath, 'output_file_path' => $this->sOutputFilePath,
'advanced_mode' => $this->bAdvancedMode, 'advanced_mode' => $this->bAdvancedMode,
]; );
file_put_contents($this->GetStateFile(), json_encode($aState)); file_put_contents($this->GetStateFile(), json_encode($aState));
return $this->sToken; return $this->sToken;
} }
public function ReloadState() public function ReloadState()
{ {
if ($this->sToken == null) { if ($this->sToken == null)
{
throw new Exception('ExcelExporter not initialized with a token, cannot reload state'); 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."); throw new Exception("ExcelExporter: missing status file '".$this->GetStateFile()."', cannot reload state.");
} }
$sJson = file_get_contents($this->GetStateFile()); $sJson = file_get_contents($this->GetStateFile());
$aState = json_decode($sJson, true); $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."); throw new Exception("ExcelExporter:corrupted status file '".$this->GetStateFile()."', not a JSON, cannot reload state.");
} }
$this->sState = $aState['state']; $this->sState = $aState['state'];
$this->aStatistics = $aState['statistics']; $this->aStatistics = $aState['statistics'];
$this->oSearch = DBObjectSearch::unserialize($aState['filter']); $this->oSearch = DBObjectSearch::unserialize($aState['filter']);
@@ -119,183 +128,206 @@ class ExcelExporter
$this->sOutputFilePath = $aState['output_file_path']; $this->sOutputFilePath = $aState['output_file_path'];
$this->bAdvancedMode = $aState['advanced_mode']; $this->bAdvancedMode = $aState['advanced_mode'];
} }
public function SetObjectList($oSearch) public function SetObjectList($oSearch)
{ {
$this->oSearch = $oSearch; $this->oSearch = $oSearch;
} }
public function Run() public function Run()
{ {
$sCode = 'error'; $sCode = 'error';
$iPercentage = 100; $iPercentage = 100;
$sMessage = Dict::Format('ExcelExporter:ErrorUnexpected_State', $this->sState); $sMessage = Dict::Format('ExcelExporter:ErrorUnexpected_State', $this->sState);
$fTime = microtime(true); $fTime = microtime(true);
try { try
switch ($this->sState) { {
switch($this->sState)
{
case 'new': case 'new':
$oIDSet = new DBObjectSet($this->oSearch); $oIDSet = new DBObjectSet($this->oSearch);
$oIDSet->OptimizeColumnLoad(['id']); $oIDSet->OptimizeColumnLoad(array('id'));
$this->aObjectsIDs = []; $this->aObjectsIDs = array();
while ($oObj = $oIDSet->Fetch()) { while($oObj = $oIDSet->Fetch())
$this->aObjectsIDs[] = $oObj->GetKey(); {
} $this->aObjectsIDs[] = $oObj->GetKey();
$sCode = 'retrieving-data'; }
$iPercentage = 5; $sCode = 'retrieving-data';
$sMessage = Dict::S('ExcelExporter:RetrievingData'); $iPercentage = 5;
$this->iPosition = 0; $sMessage = Dict::S('ExcelExporter:RetrievingData');
$this->aStatistics['objects_count'] = count($this->aObjectsIDs); $this->iPosition = 0;
$this->aStatistics['data_retrieval_duration'] += microtime(true) - $fTime; $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); // The first line of the file is the "headers" specifying the label and the type of each column
$sRow = json_encode($this->aTableHeaders); $this->GetFieldsList($oIDSet, $this->bAdvancedMode);
$hFile = @fopen($this->GetDataFile(), 'ab'); $sRow = json_encode($this->aTableHeaders);
if ($hFile === false) { $hFile = @fopen($this->GetDataFile(), 'ab');
throw new Exception('ExcelExporter: Failed to open temporary data file: "'.$this->GetDataFile().'" for writing.'); if ($hFile === false)
} {
fwrite($hFile, $sRow."\n"); throw new Exception('ExcelExporter: Failed to open temporary data file: "'.$this->GetDataFile().'" for writing.');
fclose($hFile); }
fwrite($hFile, $sRow."\n");
// Next state fclose($hFile);
$this->sState = 'retrieving-data';
break; // Next state
$this->sState = 'retrieving-data';
break;
case 'retrieving-data': case 'retrieving-data':
$oCurrentSearch = clone $this->oSearch; $oCurrentSearch = clone $this->oSearch;
$aIDs = array_slice($this->aObjectsIDs, $this->iPosition, $this->iChunkSize); $aIDs = array_slice($this->aObjectsIDs, $this->iPosition, $this->iChunkSize);
$oCurrentSearch->AddCondition('id', $aIDs, 'IN'); $oCurrentSearch->AddCondition('id', $aIDs, 'IN');
$hFile = @fopen($this->GetDataFile(), 'ab'); $hFile = @fopen($this->GetDataFile(), 'ab');
if ($hFile === false) { if ($hFile === false)
throw new Exception('ExcelExporter: Failed to open temporary data file: "'.$this->GetDataFile().'" for writing.'); {
} throw new Exception('ExcelExporter: Failed to open temporary data file: "'.$this->GetDataFile().'" for writing.');
$oSet = new DBObjectSet($oCurrentSearch); }
$this->GetFieldsList($oSet, $this->bAdvancedMode); $oSet = new DBObjectSet($oCurrentSearch);
while ($aObjects = $oSet->FetchAssoc()) { $this->GetFieldsList($oSet, $this->bAdvancedMode);
$aRow = []; while($aObjects = $oSet->FetchAssoc())
foreach ($this->aAuthorizedClasses as $sAlias => $sClassName) { {
$oObj = $aObjects[$sAlias]; $aRow = array();
if ($this->bAdvancedMode) { foreach($this->aAuthorizedClasses as $sAlias => $sClassName)
$aRow[] = $oObj->GetKey(); {
} $oObj = $aObjects[$sAlias];
foreach ($this->aFieldsList[$sAlias] as $sAttCodeEx => $oAttDef) { if ($this->bAdvancedMode)
$value = $oObj->Get($sAttCodeEx); {
if ($value instanceof ormCaseLog) { $aRow[] = $oObj->GetKey();
// 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())); foreach($this->aFieldsList[$sAlias] as $sAttCodeEx => $oAttDef)
} else { {
$sExcelVal = $oAttDef->GetEditValue($value, $oObj); $value = $oObj->Get($sAttCodeEx);
} if ($value instanceOf ormCaseLog)
$aRow[] = $sExcelVal; {
} // 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); $sRow = json_encode($aRow);
fwrite($hFile, $sRow."\n");
if (($this->iPosition + $this->iChunkSize) > count($this->aObjectsIDs)) { }
// Next state fclose($hFile);
$this->sState = 'building-excel';
$sCode = 'building-excel'; if (($this->iPosition + $this->iChunkSize) > count($this->aObjectsIDs))
$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 = [];
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 // Next state
$this->sState = 'done'; $this->sState = 'building-excel';
$sCode = 'done'; $sCode = 'building-excel';
$iPercentage = 100; $iPercentage = 80;
$sMessage = Dict::S('ExcelExporter:Done'); $sMessage = Dict::S('ExcelExporter:BuildingExcelFile');
break; }
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;
case 'done': case 'done':
$this->sState = 'done'; $this->sState = 'done';
$sCode = 'done'; $sCode = 'done';
$iPercentage = 100; $iPercentage = 100;
$sMessage = Dict::S('ExcelExporter:Done'); $sMessage = Dict::S('ExcelExporter:Done');
break; break;
} }
} catch (Exception $e) { }
catch(Exception $e)
{
$sCode = 'error'; $sCode = 'error';
$sMessage = $e->getMessage(); $sMessage = $e->getMessage();
} }
$this->aStatistics['total_duration'] += microtime(true) - $fTime; $this->aStatistics['total_duration'] += microtime(true) - $fTime;
$peak_memory = memory_get_peak_usage(true); $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; $this->aStatistics['peak_memory_usage'] = $peak_memory;
} }
return [ return array(
'code' => $sCode, 'code' => $sCode,
'message' => $sMessage, 'message' => $sMessage,
'percentage' => $iPercentage, 'percentage' => $iPercentage,
]; );
} }
public function GetExcelFilePath() public function GetExcelFilePath()
{ {
if ($this->sOutputFilePath == null) { if ($this->sOutputFilePath == null)
{
return utils::GetDataPath().'bulk_export/'.$this->sToken.'.xlsx'; return utils::GetDataPath().'bulk_export/'.$this->sToken.'.xlsx';
} else { }
else
{
return $this->sOutputFilePath; return $this->sOutputFilePath;
} }
} }
public static function GetExcelFileFromToken($sToken) public static function GetExcelFileFromToken($sToken)
{ {
return @file_get_contents(utils::GetDataPath().'bulk_export/'.$sToken.'.xlsx'); return @file_get_contents(utils::GetDataPath().'bulk_export/'.$sToken.'.xlsx');
} }
public static function CleanupFromToken($sToken) public static function CleanupFromToken($sToken)
{ {
@unlink(utils::GetDataPath().'bulk_export/'.$sToken.'.status'); @unlink(utils::GetDataPath().'bulk_export/'.$sToken.'.status');
@unlink(utils::GetDataPath().'bulk_export/'.$sToken.'.data'); @unlink(utils::GetDataPath().'bulk_export/'.$sToken.'.data');
@unlink(utils::GetDataPath().'bulk_export/'.$sToken.'.xlsx'); @unlink(utils::GetDataPath().'bulk_export/'.$sToken.'.xlsx');
} }
public function Cleanup() public function Cleanup()
{ {
self::CleanupFromToken($this->sToken); self::CleanupFromToken($this->sToken);
} }
/** /**
* Delete all files in the data/bulk_export directory which are older than 1 day * Delete all files in the data/bulk_export directory which are older than 1 day
* unless a different delay is configured. * unless a different delay is configured.
@@ -304,12 +336,15 @@ class ExcelExporter
{ {
$aFiles = glob(utils::GetDataPath().'bulk_export/*.*'); $aFiles = glob(utils::GetDataPath().'bulk_export/*.*');
$iDelay = MetaModel::GetConfig()->Get('xlsx_exporter_cleanup_old_files_delay'); $iDelay = MetaModel::GetConfig()->Get('xlsx_exporter_cleanup_old_files_delay');
if ($iDelay > 0) { if($iDelay > 0)
foreach ($aFiles as $sFile) { {
foreach($aFiles as $sFile)
{
$iModificationTime = filemtime($sFile); $iModificationTime = filemtime($sFile);
if ($iModificationTime < (time() - $iDelay)) { if($iModificationTime < (time() - $iDelay))
{
// Temporary files older than one day are deleted // Temporary files older than one day are deleted
//echo "Supposed to delete: '".$sFile." (Unix Modification Time: $iModificationTime)'\n"; //echo "Supposed to delete: '".$sFile." (Unix Modification Time: $iModificationTime)'\n";
@unlink($sFile); @unlink($sFile);
@@ -317,155 +352,189 @@ class ExcelExporter
} }
} }
} }
public function DisplayStatistics(Page $oPage) public function DisplayStatistics(Page $oPage)
{ {
$aStats = [ $aStats = array(
'Number of objects exported' => $this->aStatistics['objects_count'], 'Number of objects exported' => $this->aStatistics['objects_count'],
'Total export duration' => sprintf('%.3f s', $this->aStatistics['total_duration']), 'Total export duration' => sprintf('%.3f s', $this->aStatistics['total_duration']),
'Data retrieval duration' => sprintf('%.3f s', $this->aStatistics['data_retrieval_duration']), 'Data retrieval duration' => sprintf('%.3f s', $this->aStatistics['data_retrieval_duration']),
'Excel build duration' => sprintf('%.3f s', $this->aStatistics['excel_build_duration']), 'Excel build duration' => sprintf('%.3f s', $this->aStatistics['excel_build_duration']),
'Excel write duration' => sprintf('%.3f s', $this->aStatistics['excel_write_duration']), 'Excel write duration' => sprintf('%.3f s', $this->aStatistics['excel_write_duration']),
'Peak memory usage' => self::HumanDisplay($this->aStatistics['peak_memory_usage']), 'Peak memory usage' => self::HumanDisplay($this->aStatistics['peak_memory_usage']),
]; );
if ($oPage instanceof CLIPage) { if ($oPage instanceof CLIPage)
{
$oPage->add($this->GetStatistics('text')); $oPage->add($this->GetStatistics('text'));
} else { }
else
{
$oPage->add($this->GetStatistics('html')); $oPage->add($this->GetStatistics('html'));
} }
} }
public function GetStatistics($sFormat = 'html') public function GetStatistics($sFormat = 'html')
{ {
$sStats = ''; $sStats = '';
$aStats = [ $aStats = array(
'Number of objects exported' => $this->aStatistics['objects_count'], 'Number of objects exported' => $this->aStatistics['objects_count'],
'Total export duration' => sprintf('%.3f s', $this->aStatistics['total_duration']), 'Total export duration' => sprintf('%.3f s', $this->aStatistics['total_duration']),
'Data retrieval duration' => sprintf('%.3f s', $this->aStatistics['data_retrieval_duration']), 'Data retrieval duration' => sprintf('%.3f s', $this->aStatistics['data_retrieval_duration']),
'Excel build duration' => sprintf('%.3f s', $this->aStatistics['excel_build_duration']), 'Excel build duration' => sprintf('%.3f s', $this->aStatistics['excel_build_duration']),
'Excel write duration' => sprintf('%.3f s', $this->aStatistics['excel_write_duration']), 'Excel write duration' => sprintf('%.3f s', $this->aStatistics['excel_write_duration']),
'Peak memory usage' => self::HumanDisplay($this->aStatistics['peak_memory_usage']), 'Peak memory usage' => self::HumanDisplay($this->aStatistics['peak_memory_usage']),
]; );
if ($sFormat == 'text') { if ($sFormat == 'text')
foreach ($aStats as $sLabel => $sValue) { {
foreach($aStats as $sLabel => $sValue)
{
$sStats .= "+------------------------------+----------+\n"; $sStats .= "+------------------------------+----------+\n";
$sStats .= sprintf("|%-30s|%10s|\n", $sLabel, $sValue); $sStats .= sprintf("|%-30s|%10s|\n", $sLabel, $sValue);
} }
$sStats .= "+------------------------------+----------+"; $sStats .= "+------------------------------+----------+";
} else { }
else
{
$sStats .= '<table><tbody>'; $sStats .= '<table><tbody>';
foreach ($aStats as $sLabel => $sValue) { foreach($aStats as $sLabel => $sValue)
{
$sStats .= "<tr><td>$sLabel</td><td>$sValue</td></tr>"; $sStats .= "<tr><td>$sLabel</td><td>$sValue</td></tr>";
} }
$sStats .= '</tbody></table>'; $sStats .= '</tbody></table>';
} }
return $sStats; return $sStats;
} }
public static function HumanDisplay($iSize) public static function HumanDisplay($iSize)
{ {
$aUnits = ['B','KB','MB','GB','TB','PB']; $aUnits = array('B','KB','MB','GB','TB','PB');
return @round($iSize / pow(1024, ($i = floor(log($iSize, 1024)))), 2).' '.$aUnits[$i]; return @round($iSize/pow(1024,($i=floor(log($iSize,1024)))),2).' '.$aUnits[$i];
} }
protected function CheckDataDir() 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 */); @mkdir(utils::GetDataPath()."bulk_export", 0777, true /* recursive */);
clearstatcache(); 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.'); throw new Exception('Data directory "'.utils::GetDataPath().'bulk_export" could not be written.');
} }
} }
protected function GetStateFile($sToken = null) protected function GetStateFile($sToken = null)
{ {
if ($sToken == null) { if ($sToken == null)
{
$sToken = $this->sToken; $sToken = $this->sToken;
} }
return utils::GetDataPath()."bulk_export/$sToken.status"; return utils::GetDataPath()."bulk_export/$sToken.status";
} }
protected function GetDataFile() protected function GetDataFile()
{ {
return utils::GetDataPath().'bulk_export/'.$this->sToken.'.data'; return utils::GetDataPath().'bulk_export/'.$this->sToken.'.data';
} }
protected function GetNewToken() protected function GetNewToken()
{ {
$iNum = rand(); $iNum = rand();
do { do
{
$iNum++; $iNum++;
$sToken = sprintf("%08x", $iNum); $sToken = sprintf("%08x", $iNum);
$sFileName = $this->GetStateFile($sToken); $sFileName = $this->GetStateFile($sToken);
$hFile = @fopen($sFileName, 'x'); $hFile = @fopen($sFileName, 'x');
} while ($hFile === false); }
while($hFile === false);
fclose($hFile); fclose($hFile);
return $sToken; return $sToken;
} }
protected function GetFieldsList($oSet, $bFieldsAdvanced = false, $bLocalize = true, $aFields = null) protected function GetFieldsList($oSet, $bFieldsAdvanced = false, $bLocalize = true, $aFields = null)
{ {
$this->aFieldsList = []; $this->aFieldsList = array();
$oAppContext = new ApplicationContext(); $oAppContext = new ApplicationContext();
$aClasses = $oSet->GetFilter()->GetSelectedClasses(); $aClasses = $oSet->GetFilter()->GetSelectedClasses();
$this->aAuthorizedClasses = []; $this->aAuthorizedClasses = array();
foreach ($aClasses as $sAlias => $sClassName) { foreach($aClasses as $sAlias => $sClassName)
if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) != UR_ALLOWED_NO) { {
if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) != UR_ALLOWED_NO)
{
$this->aAuthorizedClasses[$sAlias] = $sClassName; $this->aAuthorizedClasses[$sAlias] = $sClassName;
} }
} }
$aAttribs = []; $aAttribs = array();
$this->aTableHeaders = []; $this->aTableHeaders = array();
foreach ($this->aAuthorizedClasses as $sAlias => $sClassName) { foreach($this->aAuthorizedClasses as $sAlias => $sClassName)
$aList[$sAlias] = []; {
$aList[$sAlias] = array();
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) // 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; $sAttCodeEx = $oAttDef->IsExternalField() ? $oAttDef->GetKeyAttCode().'->'.$oAttDef->GetExtAttCode() : $sAttCode;
if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) { if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
if ($bFieldsAdvanced) { {
if ($bFieldsAdvanced)
{
$aList[$sAlias][$sAttCodeEx] = $oAttDef; $aList[$sAlias][$sAttCodeEx] = $oAttDef;
if ($oAttDef->IsExternalKey(EXTKEY_RELATIVE)) { if ($oAttDef->IsExternalKey(EXTKEY_RELATIVE))
$sRemoteClass = $oAttDef->GetTargetClass(); {
foreach (MetaModel::GetReconcKeys($sRemoteClass) as $sRemoteAttCode) { $sRemoteClass = $oAttDef->GetTargetClass();
foreach(MetaModel::GetReconcKeys($sRemoteClass) as $sRemoteAttCode)
{
$this->aFieldsList[$sAlias][$sAttCode.'->'.$sRemoteAttCode] = MetaModel::GetAttributeDef($sRemoteClass, $sRemoteAttCode); $this->aFieldsList[$sAlias][$sAttCode.'->'.$sRemoteAttCode] = MetaModel::GetAttributeDef($sRemoteClass, $sRemoteAttCode);
} }
} }
} }
} else { }
else
{
// Any other attribute // Any other attribute
$this->aFieldsList[$sAlias][$sAttCodeEx] = $oAttDef; $this->aFieldsList[$sAlias][$sAttCodeEx] = $oAttDef;
} }
} }
} else { }
else
{
// User defined list of attributes // 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; $this->aFieldsList[$sAlias][$sAttCode] = $oAttDef;
} }
} }
} }
if ($bFieldsAdvanced) { if ($bFieldsAdvanced)
{
$this->aTableHeaders['id'] = '0'; $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; $sLabel = $bLocalize ? MetaModel::GetLabel($sClassName, $sAttCodeEx, isset($aParams['showMandatoryFields'])) : $sAttCodeEx;
if ($oAttDef instanceof AttributeDateTime) { if($oAttDef instanceof AttributeDateTime)
{
$this->aTableHeaders[$sLabel] = 'datetime'; $this->aTableHeaders[$sLabel] = 'datetime';
} else { }
else
{
$this->aTableHeaders[$sLabel] = 'string'; $this->aTableHeaders[$sLabel] = 'string';
} }
} }
} }
} }
} }

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -7,4 +6,4 @@
class BulkChangeException extends CoreException class BulkChangeException extends CoreException
{ {
} }

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -7,4 +6,4 @@
class CSVParserException extends CoreException class CSVParserException extends CoreException
{ {
} }

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -7,4 +6,4 @@
class ConfigException extends CoreException class ConfigException extends CoreException
{ {
} }

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -64,20 +63,21 @@ class CoreCannotSaveObjectException extends CoreException
public function getTextMessage() public function getTextMessage()
{ {
$sTitle = Dict::S('UI:Error:SaveFailed'); $sTitle = Dict::S('UI:Error:SaveFailed');
$sContent = $sTitle; $sContent = $sTitle;
if (count($this->aIssues) == 1) { if (count($this->aIssues) == 1) {
$sIssue = reset($this->aIssues); $sIssue = reset($this->aIssues);
$sContent .= $sIssue; $sContent .= $sIssue;
} else { } else {
foreach ($this->aIssues as $sError) { foreach ($this->aIssues as $sError) {
$sContent .= " ".$sError.", "; $sContent .= " " . $sError . ", ";
} }
} }
return $sContent; return $sContent;
} }
public function getIssues() public function getIssues()
{ {
return $this->aIssues; return $this->aIssues;

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -36,10 +35,10 @@ class CoreException extends Exception
} }
if (count($this->m_aContextData) > 0) { if (count($this->m_aContextData) > 0) {
$sMessage .= ": "; $sMessage .= ": ";
$aContextItems = []; $aContextItems = array();
foreach ($this->m_aContextData as $sKey => $value) { foreach ($this->m_aContextData as $sKey => $value) {
if (is_array($value)) { if (is_array($value)) {
$aPairs = []; $aPairs = array();
foreach ($value as $key => $val) { foreach ($value as $key => $val) {
if (is_array($val)) { if (is_array($val)) {
$aPairs[] = $key.'=>('.implode(', ', $val).')'; $aPairs[] = $key.'=>('.implode(', ', $val).')';
@@ -110,4 +109,4 @@ class CoreException extends Exception
{ {
return $this->m_aContextData; return $this->m_aContextData;
} }
} }

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -10,4 +9,5 @@
*/ */
class CorePortalInvalidActionRuleException extends CoreException class CorePortalInvalidActionRuleException extends CoreException
{ {
} }

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -15,4 +14,4 @@ class CoreTemplateException extends CoreException
$sMessage = "Twig Exception when rendering '$sTemplatePath' : ".$oTwigException->getMessage(); $sMessage = "Twig Exception when rendering '$sTemplatePath' : ".$oTwigException->getMessage();
parent::__construct($sMessage, null, '', $oTwigException); parent::__construct($sMessage, null, '', $oTwigException);
} }
} }

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -7,4 +6,4 @@
class DeleteException extends CoreException class DeleteException extends CoreException
{ {
} }

View File

@@ -1,10 +0,0 @@
<?php
/**
* @copyright Copyright (C) 2010-2026 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
*/
class ForgotPasswordApplicationException extends Exception
{
}

View File

@@ -1,10 +0,0 @@
<?php
/**
* @copyright Copyright (C) 2010-2026 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
*/
class ForgotPasswordUserInputException extends Exception
{
}

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0

View File

@@ -12,13 +12,13 @@ class InvalidExternalKeyValueException extends CoreUnexpectedValue
public function __construct($oObject, $sAttCode, $aContextData = null, $oPrevious = null) public function __construct($oObject, $sAttCode, $aContextData = null, $oPrevious = null)
{ {
$aContextData[self::ENUM_PARAMS_OBJECT] = get_class($oObject).'::'.$oObject->GetKey(); $aContextData[self::ENUM_PARAMS_OBJECT] = get_class($oObject) . '::' . $oObject->GetKey();
$aContextData[self::ENUM_PARAMS_ATTCODE] = $sAttCode; $aContextData[self::ENUM_PARAMS_ATTCODE] = $sAttCode;
$aContextData[self::ENUM_PARAMS_ATTVALUE] = $oObject->Get($sAttCode); $aContextData[self::ENUM_PARAMS_ATTVALUE] = $oObject->Get($sAttCode);
$oCurrentUser = UserRights::GetUserObject(); $oCurrentUser = UserRights::GetUserObject();
if (false === is_null($oCurrentUser)) { if (false === is_null($oCurrentUser)) {
$aContextData[self::ENUM_PARAMS_USER] = get_class($oCurrentUser).'::'.$oCurrentUser->GetKey(); $aContextData[self::ENUM_PARAMS_USER] = get_class($oCurrentUser) . '::' . $oCurrentUser->GetKey();
} }
parent::__construct('Attribute pointing to an object that is either non existing or not readable by the current user', $aContextData, '', $oPrevious); parent::__construct('Attribute pointing to an object that is either non existing or not readable by the current user', $aContextData, '', $oPrevious);

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -12,4 +11,4 @@
*/ */
class InvalidPasswordAttributeOneWayPassword extends CoreException class InvalidPasswordAttributeOneWayPassword extends CoreException
{ {
} }

View File

@@ -1,5 +1,4 @@
<?php <?php
/** /**
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -11,4 +10,4 @@ use Exception;
class PageNotFoundException extends Exception class PageNotFoundException extends Exception
{ {
} }

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -7,4 +6,4 @@
class SynchroExceptionNotStarted extends CoreException class SynchroExceptionNotStarted extends CoreException
{ {
} }

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -7,4 +6,4 @@
class UserRightException extends CoreException class UserRightException extends CoreException
{ {
} }

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -7,4 +6,4 @@
class DictException extends CoreException class DictException extends CoreException
{ {
} }

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -9,9 +8,9 @@ class DictExceptionMissingString extends DictException
{ {
public function __construct($sLanguageCode, $sStringCode) public function __construct($sLanguageCode, $sStringCode)
{ {
$aContext = []; $aContext = array();
$aContext['language_code'] = $sLanguageCode; $aContext['language_code'] = $sLanguageCode;
$aContext['string_code'] = $sStringCode; $aContext['string_code'] = $sStringCode;
parent::__construct('Missing localized string', $aContext); parent::__construct('Missing localized string', $aContext);
} }
} }

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -9,8 +8,8 @@ class DictExceptionUnknownLanguage extends DictException
{ {
public function __construct($sLanguageCode) public function __construct($sLanguageCode)
{ {
$aContext = []; $aContext = array();
$aContext['language_code'] = $sLanguageCode; $aContext['language_code'] = $sLanguageCode;
parent::__construct('Unknown localization language', $aContext); parent::__construct('Unknown localization language', $aContext);
} }
} }

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -7,4 +6,5 @@
class iTopXmlException extends CoreException class iTopXmlException extends CoreException
{ {
}
}

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -21,7 +20,7 @@ class MySQLException extends CoreException
$aContext['mysql_errno'] = $oException->getCode(); $aContext['mysql_errno'] = $oException->getCode();
$this->code = $oException->getCode(); $this->code = $oException->getCode();
$aContext['mysql_error'] = $oException->getMessage(); $aContext['mysql_error'] = $oException->getMessage();
} elseif ($oMysqli != null) { } else if ($oMysqli != null) {
$aContext['mysql_errno'] = $oMysqli->errno; $aContext['mysql_errno'] = $oMysqli->errno;
$this->code = $oMysqli->errno; $this->code = $oMysqli->errno;
$aContext['mysql_error'] = $oMysqli->error; $aContext['mysql_error'] = $oMysqli->error;
@@ -37,4 +36,4 @@ class MySQLException extends CoreException
error_reporting(0); error_reporting(0);
} }
} }
} }

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -20,14 +19,14 @@ class MySQLHasGoneAwayException extends MySQLException
*/ */
public static function getErrorCodes() public static function getErrorCodes()
{ {
return [ return array(
2006, 2006,
2013, 2013,
]; );
} }
public function __construct($sIssue, $aContext) public function __construct($sIssue, $aContext)
{ {
parent::__construct($sIssue, $aContext, null); parent::__construct($sIssue, $aContext, null);
} }
} }

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -10,4 +9,5 @@
*/ */
class MySQLNoTransactionException extends MySQLException class MySQLNoTransactionException extends MySQLException
{ {
}
}

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -12,4 +11,5 @@
*/ */
class MySQLQueryHasNoResultException extends MySQLException class MySQLQueryHasNoResultException extends MySQLException
{ {
}
}

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -10,4 +9,5 @@
*/ */
class MySQLTransactionNotClosedException extends MySQLException class MySQLTransactionNotClosedException extends MySQLException
{ {
}
}

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -10,4 +9,5 @@
*/ */
class CoreOqlException extends CoreException class CoreOqlException extends CoreException
{ {
} }

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -10,4 +9,5 @@
*/ */
class CoreOqlMultipleResultsForbiddenException extends CoreOqlException class CoreOqlMultipleResultsForbiddenException extends CoreOqlException
{ {
} }

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -13,4 +12,4 @@
*/ */
class ProcessException extends CoreException class ProcessException extends CoreException
{ {
} }

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -14,4 +13,4 @@
*/ */
class ProcessFatalException extends CoreException class ProcessFatalException extends CoreException
{ {
} }

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* @copyright Copyright (C) 2010-2024 Combodo SAS * @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0 * @license http://opensource.org/licenses/AGPL-3.0
@@ -10,4 +9,4 @@
*/ */
class ProcessInvalidConfigException extends ProcessException class ProcessInvalidConfigException extends ProcessException
{ {
} }

View File

@@ -1,5 +1,4 @@
<?php <?php
/** /**
* Copyright (C) 2013-2024 Combodo SAS * Copyright (C) 2013-2024 Combodo SAS
* *
@@ -23,8 +22,8 @@
* @author Olivier DAIN <olivier.dain@combodo.com> * @author Olivier DAIN <olivier.dain@combodo.com>
* @since 3.0.0 N°3588 * @since 3.0.0 N°3588
*/ */
class FindStylesheetObject class FindStylesheetObject{
{
//file URIs //file URIs
private $aStylesheetFileURIs; private $aStylesheetFileURIs;
@@ -65,7 +64,7 @@ class FindStylesheetObject
return $this->aStylesheetFileURIs; return $this->aStylesheetFileURIs;
} }
public function GetLastModified(): int public function GetLastModified() : int
{ {
return $this->iLastModified; return $this->iLastModified;
} }
@@ -93,8 +92,7 @@ class FindStylesheetObject
$this->sLastStyleSheetPath = $sStylesheetFilePath; $this->sLastStyleSheetPath = $sStylesheetFilePath;
} }
public function AlreadyFetched(string $sStylesheetFilePath): bool public function AlreadyFetched(string $sStylesheetFilePath) : bool {
{
return in_array($sStylesheetFilePath, $this->aAllStylesheetFilePaths); return in_array($sStylesheetFilePath, $this->aAllStylesheetFilePaths);
} }
@@ -113,4 +111,4 @@ class FindStylesheetObject
{ {
$this->sLastStyleSheetPath = ""; $this->sLastStyleSheetPath = "";
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -1,10 +1,9 @@
<?php <?php
// Copyright (C) 2010-2024 Combodo SAS // Copyright (C) 2010-2024 Combodo SAS
// //
// This file is part of iTop. // This file is part of iTop.
// //
// iTop is free software; you can redistribute it and/or modify // iTop is free software; you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by // it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
@@ -17,6 +16,7 @@
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with iTop. If not, see <http://www.gnu.org/licenses/> // along with iTop. If not, see <http://www.gnu.org/licenses/>
/** /**
* Persistent class InputOutputTask * Persistent class InputOutputTask
* *
@@ -28,43 +28,42 @@ require_once(APPROOT.'/application/cmdbabstract.class.inc.php');
/** /**
* This class manages the input/output tasks * 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 class InputOutputTask extends cmdbAbstractObject
{ {
public static function Init() public static function Init()
{ {
$aParams = $aParams = array
[ (
"category" => "application", "category" => "application",
"key_type" => "autoincrement", "key_type" => "autoincrement",
"name_attcode" => "name", "name_attcode" => "name",
"state_attcode" => "", "state_attcode" => "",
"reconc_keys" => [], "reconc_keys" => array(),
"db_table" => "priv_iotask", "db_table" => "priv_iotask",
"db_key_field" => "id", "db_key_field" => "id",
"db_finalclass_field" => "", "db_finalclass_field" => "",
]; );
MetaModel::Init_Params($aParams); MetaModel::Init_Params($aParams);
MetaModel::Init_AddAttribute(new AttributeString("name", ["allowed_values" => null, "sql" => "name", "default_value" => "", "is_null_allowed" => false, "depends_on" => []])); 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", ["allowed_values" => null, "sql" => "description", "default_value" => "", "is_null_allowed" => true, "depends_on" => []])); 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", ["allowed_values" => new ValueSetEnum('Input, Ouput'), "sql" => "category", "default_value" => "Input", "is_null_allowed" => false, "depends_on" => []])); 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", ["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_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( MetaModel::Init_AddAttribute(new AttributeEnum("source_subtype",
"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())));
["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", 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 AttributeString("source_path", ["allowed_values" => null, "sql" => "source_path", "default_value" => "", "is_null_allowed" => false, "depends_on" => []])); 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 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("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("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("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 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 // Display lists
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('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', ['description', 'category', 'objects_class', 'source_type', 'source_subtype', 'options']); // Attributes to be displayed for a list MetaModel::Init_SetZListItems('list', array('description', 'category', 'objects_class', 'source_type', 'source_subtype', 'options')); // Attributes to be displayed for a list
// Search criteria // Search criteria
MetaModel::Init_SetZListItems('standard_search', ['name', 'category', 'objects_class', 'source_type', 'source_subtype']); // Criteria of the std search form 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', ['name', 'description', 'category', 'objects_class', 'source_type', 'source_subtype']); // Criteria of the advanced search form MetaModel::Init_SetZListItems('advanced_search', array('name', 'description', 'category', 'objects_class', 'source_type', 'source_subtype')); // Criteria of the advanced search form
} }
} }
?>

View File

@@ -18,17 +18,23 @@ class LoginBasic extends AbstractLoginFSMExtension
*/ */
public function ListSupportedLoginModes() public function ListSupportedLoginModes()
{ {
return ['basic']; return array('basic');
} }
protected function OnModeDetection(&$iErrorCode) protected function OnModeDetection(&$iErrorCode)
{ {
if (!Session::IsSet('login_mode')) { if (!Session::IsSet('login_mode'))
if (isset($_SERVER['HTTP_AUTHORIZATION']) && !empty($_SERVER['HTTP_AUTHORIZATION'])) { {
if (isset($_SERVER['HTTP_AUTHORIZATION']) && !empty($_SERVER['HTTP_AUTHORIZATION']))
{
Session::Set('login_mode', 'basic'); Session::Set('login_mode', 'basic');
} elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']) && !empty($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) { }
elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']) && !empty($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
{
Session::Set('login_mode', 'basic'); Session::Set('login_mode', 'basic');
} elseif (isset($_SERVER['PHP_AUTH_USER'])) { }
elseif (isset($_SERVER['PHP_AUTH_USER']))
{
Session::Set('login_mode', 'basic'); Session::Set('login_mode', 'basic');
} }
} }
@@ -37,18 +43,22 @@ class LoginBasic extends AbstractLoginFSMExtension
protected function OnReadCredentials(&$iErrorCode) protected function OnReadCredentials(&$iErrorCode)
{ {
if (!Session::IsSet('login_mode') || Session::Get('login_mode') == 'basic') { if (!Session::IsSet('login_mode') || Session::Get('login_mode') == 'basic')
{
list($sAuthUser) = $this->GetAuthUserAndPassword(); list($sAuthUser) = $this->GetAuthUserAndPassword();
Session::Set('login_temp_auth_user', $sAuthUser); Session::Set('login_temp_auth_user', $sAuthUser);
} }
return LoginWebPage::LOGIN_FSM_CONTINUE; return LoginWebPage::LOGIN_FSM_CONTINUE;
} }
protected function OnCheckCredentials(&$iErrorCode) protected function OnCheckCredentials(&$iErrorCode)
{ {
if (Session::Get('login_mode') == 'basic') { if (Session::Get('login_mode') == 'basic')
{
list($sAuthUser, $sAuthPwd) = $this->GetAuthUserAndPassword(); list($sAuthUser, $sAuthPwd) = $this->GetAuthUserAndPassword();
if (!UserRights::CheckCredentials($sAuthUser, $sAuthPwd, Session::Get('login_mode'), 'internal')) { if (!UserRights::CheckCredentials($sAuthUser, $sAuthPwd, Session::Get('login_mode'), 'internal'))
{
$iErrorCode = LoginWebPage::EXIT_CODE_WRONGCREDENTIALS; $iErrorCode = LoginWebPage::EXIT_CODE_WRONGCREDENTIALS;
return LoginWebPage::LOGIN_FSM_ERROR; return LoginWebPage::LOGIN_FSM_ERROR;
} }
@@ -59,7 +69,8 @@ class LoginBasic extends AbstractLoginFSMExtension
protected function OnCredentialsOK(&$iErrorCode) protected function OnCredentialsOK(&$iErrorCode)
{ {
if (Session::Get('login_mode') == 'basic') { if (Session::Get('login_mode') == 'basic')
{
LoginWebPage::OnLoginSuccess(Session::Get('auth_user'), 'internal', Session::Get('login_mode')); LoginWebPage::OnLoginSuccess(Session::Get('auth_user'), 'internal', Session::Get('login_mode'));
} }
return LoginWebPage::LOGIN_FSM_CONTINUE; return LoginWebPage::LOGIN_FSM_CONTINUE;
@@ -67,11 +78,13 @@ class LoginBasic extends AbstractLoginFSMExtension
protected function OnError(&$iErrorCode) protected function OnError(&$iErrorCode)
{ {
if (Session::Get('login_mode') == 'basic') { if (Session::Get('login_mode') == 'basic')
$iOnExit = LoginWebPage::getIOnExit(); {
if ($iOnExit === LoginWebPage::EXIT_RETURN) { $iOnExit = LoginWebPage::getIOnExit();
return LoginWebPage::LOGIN_FSM_RETURN; // Error, exit FSM if ($iOnExit === LoginWebPage::EXIT_RETURN)
} {
return LoginWebPage::LOGIN_FSM_RETURN; // Error, exit FSM
}
LoginWebPage::HTTP401Error(); LoginWebPage::HTTP401Error();
} }
return LoginWebPage::LOGIN_FSM_CONTINUE; return LoginWebPage::LOGIN_FSM_CONTINUE;
@@ -79,7 +92,8 @@ class LoginBasic extends AbstractLoginFSMExtension
protected function OnConnected(&$iErrorCode) protected function OnConnected(&$iErrorCode)
{ {
if (Session::Get('login_mode') == 'basic') { if (Session::Get('login_mode') == 'basic')
{
Session::Set('can_logoff', true); Session::Set('can_logoff', true);
return LoginWebPage::CheckLoggedUser($iErrorCode); return LoginWebPage::CheckLoggedUser($iErrorCode);
} }
@@ -91,33 +105,42 @@ class LoginBasic extends AbstractLoginFSMExtension
$sAuthUser = ''; $sAuthUser = '';
$sAuthPwd = null; $sAuthPwd = null;
$sAuthorization = ''; $sAuthorization = '';
if (isset($_SERVER['HTTP_AUTHORIZATION']) && !empty($_SERVER['HTTP_AUTHORIZATION'])) { if (isset($_SERVER['HTTP_AUTHORIZATION']) && !empty($_SERVER['HTTP_AUTHORIZATION']))
{
$sAuthorization = $_SERVER['HTTP_AUTHORIZATION']; $sAuthorization = $_SERVER['HTTP_AUTHORIZATION'];
} elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']) && !empty($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) { }
elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']) && !empty($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
{
$sAuthorization = $_SERVER['REDIRECT_HTTP_AUTHORIZATION']; $sAuthorization = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
} }
if (!empty($sAuthorization)) { if (!empty($sAuthorization))
{
list($sAuthUser, $sAuthPwd) = explode(':', base64_decode(substr($sAuthorization, 6))); list($sAuthUser, $sAuthPwd) = explode(':', base64_decode(substr($sAuthorization, 6)));
} else { }
if (isset($_SERVER['PHP_AUTH_USER'])) { else
{
if (isset($_SERVER['PHP_AUTH_USER']))
{
$sAuthUser = $_SERVER['PHP_AUTH_USER']; $sAuthUser = $_SERVER['PHP_AUTH_USER'];
// Unfortunately, the RFC is not clear about the encoding... // Unfortunately, the RFC is not clear about the encoding...
// IE and FF supply the user and password encoded in ISO-8859-1 whereas Chrome provides them encoded in UTF-8 // IE and FF supply the user and password encoded in ISO-8859-1 whereas Chrome provides them encoded in UTF-8
// So let's try to guess if it's an UTF-8 string or not... fortunately all encodings share the same ASCII base // So let's try to guess if it's an UTF-8 string or not... fortunately all encodings share the same ASCII base
if (!LoginWebPage::LooksLikeUTF8($sAuthUser)) { if (!LoginWebPage::LooksLikeUTF8($sAuthUser))
{
// Does not look like and UTF-8 string, try to convert it from iso-8859-1 to UTF-8 // Does not look like and UTF-8 string, try to convert it from iso-8859-1 to UTF-8
// Supposed to be harmless in case of a plain ASCII string... // Supposed to be harmless in case of a plain ASCII string...
$sAuthUser = iconv('iso-8859-1', 'utf-8', $sAuthUser); $sAuthUser = iconv('iso-8859-1', 'utf-8', $sAuthUser);
} }
$sAuthPwd = $_SERVER['PHP_AUTH_PW']; $sAuthPwd = $_SERVER['PHP_AUTH_PW'];
if (!LoginWebPage::LooksLikeUTF8($sAuthPwd)) { if (!LoginWebPage::LooksLikeUTF8($sAuthPwd))
{
// Does not look like and UTF-8 string, try to convert it from iso-8859-1 to UTF-8 // Does not look like and UTF-8 string, try to convert it from iso-8859-1 to UTF-8
// Supposed to be harmless in case of a plain ASCII string... // Supposed to be harmless in case of a plain ASCII string...
$sAuthPwd = iconv('iso-8859-1', 'utf-8', $sAuthPwd); $sAuthPwd = iconv('iso-8859-1', 'utf-8', $sAuthPwd);
} }
} }
} }
return [$sAuthUser, $sAuthPwd]; return array($sAuthUser, $sAuthPwd);
} }
} }

Some files were not shown because too many files have changed in this diff Show More