N°8796 - Add PHP code style validation in iTop and extensions - format whole code base

This commit is contained in:
odain
2025-11-07 20:39:38 +01:00
parent 7681c157ec
commit b0a792afab
369 changed files with 22041 additions and 26866 deletions

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2025 Combodo SARL
* @license http://opensource.org/licenses/AGPL-3.0
@@ -6,20 +7,19 @@
namespace Combodo\iTop\Application\TwigBase\Controller;
abstract class AbstractProfilerExtension implements iProfilerExtension
{
public function Init()
{
}
public abstract function GetTemplatesPath(): null|string|array;
abstract public function GetTemplatesPath(): null|string|array;
public abstract function IsEnabled(): bool;
abstract public function IsEnabled(): bool;
public abstract function GetDebugTemplate(): string;
abstract public function GetDebugTemplate(): string;
public abstract function GetDebugParams(array $aParams): array;
abstract public function GetDebugParams(array $aParams): array;
public function GetLinkedScripts(): ?array
{
@@ -35,4 +35,4 @@ abstract class AbstractProfilerExtension implements iProfilerExtension
{
return null;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* Copyright (C) 2013-2024 Combodo SAS
*
@@ -55,10 +56,10 @@ use ZipArchive;
abstract class Controller extends AbstractController
{
const ENUM_PAGE_TYPE_HTML = 'html';
const ENUM_PAGE_TYPE_BASIC_HTML = 'basic_html';
const ENUM_PAGE_TYPE_AJAX = 'ajax';
const ENUM_PAGE_TYPE_SETUP = 'setup';
public const ENUM_PAGE_TYPE_HTML = 'html';
public const ENUM_PAGE_TYPE_BASIC_HTML = 'basic_html';
public const ENUM_PAGE_TYPE_AJAX = 'ajax';
public const ENUM_PAGE_TYPE_SETUP = 'setup';
/** @var \Twig\Environment */
private $oTwig;
@@ -147,7 +148,7 @@ abstract class Controller extends AbstractController
if (!in_array($path, $aAdditionalPaths)) {
$aAdditionalPaths[] = $path;
}
} else if (is_array($path)) {
} elseif (is_array($path)) {
foreach ($path as $sPath) {
if (!in_array($sPath, $aAdditionalPaths)) {
$aAdditionalPaths[] = $sPath;
@@ -160,8 +161,7 @@ abstract class Controller extends AbstractController
if ($sModuleName != 'core') {
try {
$this->aDefaultParams = ['sIndexURL' => utils::GetAbsoluteUrlModulePage($this->m_sModule, 'index.php')];
}
catch (Exception $e) {
} catch (Exception $e) {
IssueLog::Error($e->getMessage());
}
}
@@ -187,12 +187,9 @@ abstract class Controller extends AbstractController
$sModulePath = dirname(dirname($this->GetDir()));
$this->SetModuleName(basename($sModulePath));
$this->SetViewPath($sModulePath.'/view');
try
{
$this->aDefaultParams = array('sIndexURL' => utils::GetAbsoluteUrlModulePage($this->m_sModule, 'index.php'));
}
catch (Exception $e)
{
try {
$this->aDefaultParams = ['sIndexURL' => utils::GetAbsoluteUrlModulePage($this->m_sModule, 'index.php')];
} catch (Exception $e) {
IssueLog::Error($e->getMessage());
}
}
@@ -242,8 +239,7 @@ abstract class Controller extends AbstractController
*/
public function HandleOperation()
{
try
{
try {
$this->CheckAccess();
$this->m_sOperation = utils::ReadParam('operation', $this->sDefaultOperation);
@@ -257,9 +253,7 @@ abstract class Controller extends AbstractController
}
$this->DisplayBadRequest();
}
catch (Exception $e)
{
} catch (Exception $e) {
http_response_code(500);
$oP = new ErrorPage(Dict::S('UI:PageTitle:FatalError'));
$oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
@@ -277,8 +271,7 @@ abstract class Controller extends AbstractController
*/
public function HandleAjaxOperation()
{
try
{
try {
$this->CheckAccess();
$this->m_sOperation = utils::ReadParam('operation', $this->sDefaultOperation);
@@ -292,11 +285,9 @@ abstract class Controller extends AbstractController
}
$this->DisplayPageNotFound();
}
catch (Exception $e)
{
} catch (Exception $e) {
http_response_code(500);
$aResponse = array('sError' => $e->getMessage());
$aResponse = ['sError' => $e->getMessage()];
echo json_encode($aResponse);
}
}
@@ -336,8 +327,7 @@ abstract class Controller extends AbstractController
*/
protected function CheckAccess()
{
if ($this->bCheckDemoMode && MetaModel::GetConfig()->Get('demo_mode'))
{
if ($this->bCheckDemoMode && MetaModel::GetConfig()->Get('demo_mode')) {
throw new Exception("Sorry, iTop is in <b>demonstration mode</b>: this feature is disabled.");
}
@@ -345,31 +335,32 @@ abstract class Controller extends AbstractController
$sConfiguredAccessTokenValue = empty($this->sAccessTokenConfigParamId) ? "" : trim(MetaModel::GetConfig()->GetModuleSetting($sExecModule, $this->sAccessTokenConfigParamId));
if (empty($sExecModule) || empty($sConfiguredAccessTokenValue)){
if (empty($sExecModule) || empty($sConfiguredAccessTokenValue)) {
LoginWebPage::DoLogin($this->bMustBeAdmin);
} else {
//token mode without login required
//N°7147 - Error HTTP 500 due to access_token not URL decoded
$sPassedToken = utils::ReadPostedParam($this->sAccessTokenConfigParamId, null, false, 'raw_data');
if (is_null($sPassedToken)){
if (is_null($sPassedToken)) {
$sPassedToken = utils::ReadParam($this->sAccessTokenConfigParamId, null, false, 'raw_data');
}
$sDecodedPassedToken = urldecode($sPassedToken);
if ($sDecodedPassedToken !== $sConfiguredAccessTokenValue){
if ($sDecodedPassedToken !== $sConfiguredAccessTokenValue) {
$sMsg = "Invalid token passed under '$this->sAccessTokenConfigParamId' http param to reach '$sExecModule' page.";
IssueLog::Error($sMsg, null,
IssueLog::Error(
$sMsg,
null,
[
'sHtmlDecodedToken' => $sDecodedPassedToken,
'conf param ID' => $this->sAccessTokenConfigParamId
'conf param ID' => $this->sAccessTokenConfigParamId,
]
);
throw new Exception("Invalid token");
}
}
if (!empty($this->sMenuId))
{
if (!empty($this->sMenuId)) {
ApplicationMenu::CheckMenuIdEnabled($this->sMenuId);
}
}
@@ -459,7 +450,7 @@ abstract class Controller extends AbstractController
*
* @throws \Exception
*/
public function DisplayAjaxPage($aParams = array(), $sTemplateName = null)
public function DisplayAjaxPage($aParams = [], $sTemplateName = null)
{
$this->DisplayPage($aParams, $sTemplateName, 'ajax');
}
@@ -474,7 +465,7 @@ abstract class Controller extends AbstractController
*
* @throws \Exception
*/
public function DisplaySetupPage($aParams = array(), $sTemplateName = null)
public function DisplaySetupPage($aParams = [], $sTemplateName = null)
{
$this->DisplayPage($aParams, $sTemplateName, 'setup');
}
@@ -490,7 +481,7 @@ abstract class Controller extends AbstractController
*
* @throws \Exception
*/
public function DisplayPage($aParams = array(), $sTemplateName = null, $sPageType = 'html')
public function DisplayPage($aParams = [], $sTemplateName = null, $sPageType = 'html')
{
if (empty($sTemplateName)) {
$sTemplateName = $this->m_sOperation;
@@ -554,13 +545,12 @@ abstract class Controller extends AbstractController
* @param int $iResponseCode HTTP response code
* @param array $aHeaders additional HTTP headers
*/
public function DisplayJSONPage($aParams = array(), $iResponseCode = 200, $aHeaders = array())
public function DisplayJSONPage($aParams = [], $iResponseCode = 200, $aHeaders = [])
{
$oKpi = new ExecutionKPI();
http_response_code($iResponseCode);
header('Content-Type: application/json');
foreach ($aHeaders as $sHeader)
{
foreach ($aHeaders as $sHeader) {
header($sHeader);
}
$sJSON = json_encode($aParams);
@@ -583,7 +573,7 @@ abstract class Controller extends AbstractController
*
* @since 3.0.1 3.1.0 Add $sReportFileName parameter
*/
public function DownloadZippedPage($aParams = array(), $sTemplateName = null, $sReportFileName = 'itop-system-information-report')
public function DownloadZippedPage($aParams = [], $sTemplateName = null, $sReportFileName = 'itop-system-information-report')
{
if (empty($sTemplateName)) {
$sTemplateName = $this->m_sOperation;
@@ -598,7 +588,7 @@ abstract class Controller extends AbstractController
file_put_contents($sHTMLReport, ob_get_contents());
ob_end_clean();
$this->ZipDownloadRemoveFile(array($sHTMLReport), $sZIPReportFile, true);
$this->ZipDownloadRemoveFile([$sHTMLReport], $sZIPReportFile, true);
}
/**
@@ -613,16 +603,13 @@ abstract class Controller extends AbstractController
$sArchiveFileFullPath = tempnam(SetupUtils::GetTmpDir(), 'itop_download-').'.zip';
$oArchive = new ZipArchive();
$oArchive->open($sArchiveFileFullPath, ZipArchive::CREATE);
foreach ($aFiles as $sFile)
{
foreach ($aFiles as $sFile) {
$oArchive->addFile($sFile, basename($sFile));
}
$oArchive->close();
if ($bUnlinkFiles)
{
foreach ($aFiles as $sFile)
{
if ($bUnlinkFiles) {
foreach ($aFiles as $sFile) {
unlink($sFile);
}
}
@@ -630,13 +617,12 @@ abstract class Controller extends AbstractController
$this->SendFileContent($sArchiveFileFullPath, $sDownloadArchiveName.'.zip', true, true);
}
final protected function SendFileContent($sFilePath, $sDownloadArchiveName = null, $bFileTransfer = true, $bRemoveFile = false, $aHeaders = array())
final protected function SendFileContent($sFilePath, $sDownloadArchiveName = null, $bFileTransfer = true, $bRemoveFile = false, $aHeaders = [])
{
$sFileMimeType = utils::GetFileMimeType($sFilePath);
header('Content-Type: '.$sFileMimeType);
if ($bFileTransfer)
{
if ($bFileTransfer) {
header('Content-Disposition: attachment; filename="'.$sDownloadArchiveName.'"');
}
@@ -652,8 +638,7 @@ abstract class Controller extends AbstractController
readfile($sFilePath);
if ($bRemoveFile)
{
if ($bRemoveFile) {
unlink($sFilePath);
}
exit(0);
@@ -713,7 +698,7 @@ abstract class Controller extends AbstractController
if (is_null($sLabel)) {
$sLabel = Dict::S($sCode);
}
$this->aAjaxTabs[$sCode] = array('label' => $sLabel, 'url' => $sURL, 'cache' => $bCache);
$this->aAjaxTabs[$sCode] = ['label' => $sLabel, 'url' => $sURL, 'cache' => $bCache];
}
/**
@@ -729,7 +714,8 @@ abstract class Controller extends AbstractController
* @since 2.7.7 3.0.1 3.1.0 N°4760 method creation
* @see Controller::SetBreadCrumbEntry() to set breadcrumb content (by default will be title)
*/
public function DisableBreadCrumb() {
public function DisableBreadCrumb()
{
$this->bIsBreadCrumbEnabled = false;
}
@@ -737,7 +723,8 @@ abstract class Controller extends AbstractController
* @since 2.7.7 3.0.1 3.1.0 N°4760 method creation
* @see iTopWebPage::SetBreadCrumbEntry()
*/
public function SetBreadCrumbEntry($sId, $sLabel, $sDescription, $sUrl = '', $sIcon = '') {
public function SetBreadCrumbEntry($sId, $sLabel, $sDescription, $sUrl = '', $sIcon = '')
{
$this->aBreadCrumbEntry = [$sId, $sLabel, $sDescription, $sUrl, $sIcon];
}
@@ -758,7 +745,7 @@ abstract class Controller extends AbstractController
*/
public function GetFormBuilder(string $type = FormType::class, mixed $data = null, array $options = []): FormBuilderInterface
{
return $this->oFormFactoryBuilder->getFormFactory()->createBuilder($type, $data,$options);
return $this->oFormFactoryBuilder->getFormFactory()->createBuilder($type, $data, $options);
}
/**
@@ -776,7 +763,7 @@ abstract class Controller extends AbstractController
if (is_null($data)) {
$data = $type::GetDefaultData();
}
return $this->GetFormBuilder($type, $data,$options)->getForm();
return $this->GetFormBuilder($type, $data, $options)->getForm();
}
/**
@@ -790,26 +777,21 @@ abstract class Controller extends AbstractController
private function RenderTemplate(array $aParams, string $sName, string $sTemplateFileExtension, string &$sErrorMsg = null): string|false
{
$sTemplateFile = $sName.'.'.$sTemplateFileExtension.'.twig';
if (empty($this->oTwig))
{
if (empty($this->oTwig)) {
throw new Exception('Not initialized. Call Controller::InitFromModule() or Controller::SetViewPath() before any display');
}
try
{
try {
return $this->oTwig->render($sTemplateFile, $aParams);
}
catch (SyntaxError $e) {
} catch (SyntaxError $e) {
IssueLog::Error($e->getMessage().' - file: '.$e->getFile().'('.$e->getLine().')');
return $this->oTwig->render('application/forms/itop_error.html.twig', ['sControllerError' => $e->getMessage()]);
}
catch (Exception $e) {
} catch (Exception $e) {
$sExceptionMessage = $e->getMessage();
if (str_contains($sExceptionMessage, 'at line')) {
IssueLog::Error($sExceptionMessage);
return $this->oTwig->render('application/forms/itop_error.html.twig', ['sControllerError' => $sExceptionMessage]);
}
if (!str_contains($sExceptionMessage, 'Unable to find template'))
{
if (!str_contains($sExceptionMessage, 'Unable to find template')) {
IssueLog::Error($sExceptionMessage);
}
if (is_null($sErrorMsg)) {
@@ -828,8 +810,7 @@ abstract class Controller extends AbstractController
*/
private function CreatePage(string $sPageType): void
{
switch ($sPageType)
{
switch ($sPageType) {
case self::ENUM_PAGE_TYPE_HTML:
$this->oPage = new iTopWebPage($this->GetOperationTitle(), false);
$this->oPage->add_http_headers();

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2025 Combodo SARL
* @license http://opensource.org/licenses/AGPL-3.0
@@ -17,4 +18,4 @@ interface iProfilerExtension
public function GetLinkedScripts(): null|array;
public function GetLinkedStylesheets(): null|array;
public function GetSaas(): null|array;
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -75,7 +76,7 @@ class DataTableUIBlockFactory extends AbstractUIBlockFactory
* @throws \OQLException
* @throws \ReflectionException
*/
public static function MakeForResult(WebPage $oPage, string $sListId, DBObjectSet $oSet, $aExtraParams = array())
public static function MakeForResult(WebPage $oPage, string $sListId, DBObjectSet $oSet, $aExtraParams = [])
{
$oDataTable = DataTableUIBlockFactory::MakeForRendering($sListId, $oSet, $aExtraParams);
if ($oPage->IsPrintableVersion()) {
@@ -105,7 +106,7 @@ class DataTableUIBlockFactory extends AbstractUIBlockFactory
* @throws \OQLException
* @throws \ReflectionException
*/
public static function MakeForObject(WebPage $oPage, string $sListId, DBObjectSet $oSet, $aExtraParams = array())
public static function MakeForObject(WebPage $oPage, string $sListId, DBObjectSet $oSet, $aExtraParams = [])
{
$oDataTable = DataTableUIBlockFactory::MakeForRendering($sListId, $oSet, $aExtraParams);
if ($oPage->IsPrintableVersion()) {
@@ -190,7 +191,7 @@ class DataTableUIBlockFactory extends AbstractUIBlockFactory
}
// Panel subtitle
if(!empty($oDataTable->GetInitDisplayData()) && isset($oDataTable->GetInitDisplayData()['recordsTotal'])){
if (!empty($oDataTable->GetInitDisplayData()) && isset($oDataTable->GetInitDisplayData()['recordsTotal'])) {
$iCount = $oDataTable->GetInitDisplayData()['recordsTotal'];
} else {
$iCount = $oSet->Count();
@@ -200,7 +201,7 @@ class DataTableUIBlockFactory extends AbstractUIBlockFactory
$sSubTitle = Dict::Format('UI:Pagination:HeaderSelection', $sCountHtml, '<span class="ibo-datatable--selected-count">0</span>');
} else {
$sSubTitle = Dict::Format('UI:Pagination:HeaderNoSelection', $sCountHtml);
}
}
if (utils::IsNotNullOrEmptyString($sFilterListUrl)) {
$sSubTitle = '<a href="'.$sFilterListUrl.'" title="'.Dict::S('UI:Menu:FilterList').'">'.$sSubTitle.'</a>';
@@ -292,15 +293,15 @@ class DataTableUIBlockFactory extends AbstractUIBlockFactory
* @throws \DictExceptionMissingString
* @throws \MySQLException
*/
public static function MakeForRendering(string $sListId, DBObjectSet $oSet, $aExtraParams = array())
public static function MakeForRendering(string $sListId, DBObjectSet $oSet, $aExtraParams = [])
{
$oDataTable = new DataTable('datatable_'.$sListId);
$aLists = array();
$aLists = [];
// Initialize and check the parameters
$bViewLink = isset($aExtraParams['view_link']) ? $aExtraParams['view_link'] : true;
// Check if there is a list of aliases to limit the display to...
$aDisplayAliases = isset($aExtraParams['display_aliases']) ? explode(',', $aExtraParams['display_aliases']) : array();
$aDisplayAliases = isset($aExtraParams['display_aliases']) ? explode(',', $aExtraParams['display_aliases']) : [];
$sZListName = isset($aExtraParams['zlist']) ? ($aExtraParams['zlist']) : 'list';
$sLinkageAttribute = isset($aExtraParams['link_attr']) ? $aExtraParams['link_attr'] : '';
@@ -317,9 +318,11 @@ class DataTableUIBlockFactory extends AbstractUIBlockFactory
}
}
$aExtraFieldsRaw = isset($aExtraParams['extra_fields']) ? explode(',',
trim($aExtraParams['extra_fields'])) : array();
$aExtraFields = array();
$aExtraFieldsRaw = isset($aExtraParams['extra_fields']) ? explode(
',',
trim($aExtraParams['extra_fields'])
) : [];
$aExtraFields = [];
$sAttCode = '';
foreach ($aExtraFieldsRaw as $sFieldName) {
// Ignore attributes not of the main queried class
@@ -332,10 +335,10 @@ class DataTableUIBlockFactory extends AbstractUIBlockFactory
} else {
$aExtraFields['*'][] = $sFieldName;
}
}
}
$aClassAliases = $oSet->GetFilter()->GetSelectedClasses();
$aAuthorizedClasses = array();
$aAuthorizedClasses = [];
foreach ($aClassAliases as $sAlias => $sClassName) {
if ((UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) != UR_ALLOWED_NO) &&
((count($aDisplayAliases) == 0) || (in_array($sAlias, $aDisplayAliases)))) {
@@ -345,65 +348,65 @@ class DataTableUIBlockFactory extends AbstractUIBlockFactory
foreach ($aAuthorizedClasses as $sAlias => $sClassName) {
// In case there is only 1 "alias" for the extra fields and it is the fallback ("*"), then consider that all fields are for the current alias.
// This is for the particular use case when the zlist is set to false and extra fields are specified.
if ( (count($aExtraFields) === 1) && (array_keys($aExtraFields)[0] === '*') ) {
if ((count($aExtraFields) === 1) && (array_keys($aExtraFields)[0] === '*')) {
$aLists[$sAlias] = $aExtraFields['*'];
}
// Regular use case, dispatch fields to their corresponding aliases
else if (array_key_exists($sAlias, $aExtraFields)) {
elseif (array_key_exists($sAlias, $aExtraFields)) {
$aLists[$sAlias] = $aExtraFields[$sAlias];
}
}
// Finally, if unknown alias, ignore fields
else {
$aLists[$sAlias] = array();
$aLists[$sAlias] = [];
}
// If zlist specified, merge its fields with the currently present
if ($sZListName !== false) {
if ($sZListName !== false) {
$aDefaultList = MetaModel::FlattenZList(MetaModel::GetZListItems($sClassName, $sZListName));
$aLists[$sAlias] = array_merge($aDefaultList, $aLists[$sAlias]);
}
}
// Filter the list to removed linked set since we are not able to display them here
// Filter the list to removed linked set since we are not able to display them here
foreach ($aLists[$sAlias] as $index => $sAttCode) {
$oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
if ($oAttDef instanceof AttributeLinkedSet) {
// Removed from the display list
$oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
if ($oAttDef instanceof AttributeLinkedSet) {
// Removed from the display list
unset($aLists[$sAlias][$index]);
}
}
if (empty($aLists[$sAlias])) {
unset($aLists[$sAlias], $aAuthorizedClasses[$sAlias]);
}
}
// Only for main class
if (!empty($sLinkageAttribute) && $sClassName === $oSet->GetFilter()->GetClass()) {
// The set to display is in fact a set of links between the object specified in the $sLinkageAttribute
// and other objects...
// The display will then group all the attributes related to the link itself:
// | Link_attr1 | link_attr2 | ... || Object_attr1 | Object_attr2 | Object_attr3 | .. | Object_attr_n |
$aDisplayList = array();
$aAttDefs = MetaModel::ListAttributeDefs($sClassName);
assert(isset($aAttDefs[$sLinkageAttribute]));
$oAttDef = $aAttDefs[$sLinkageAttribute];
assert($oAttDef->IsExternalKey());
// First display all the attributes specific to the link record
// The set to display is in fact a set of links between the object specified in the $sLinkageAttribute
// and other objects...
// The display will then group all the attributes related to the link itself:
// | Link_attr1 | link_attr2 | ... || Object_attr1 | Object_attr2 | Object_attr3 | .. | Object_attr_n |
$aDisplayList = [];
$aAttDefs = MetaModel::ListAttributeDefs($sClassName);
assert(isset($aAttDefs[$sLinkageAttribute]));
$oAttDef = $aAttDefs[$sLinkageAttribute];
assert($oAttDef->IsExternalKey());
// First display all the attributes specific to the link record
foreach ($aLists[$sAlias] as $sLinkAttCode) {
$oLinkAttDef = $aAttDefs[$sLinkAttCode];
if ((!$oLinkAttDef->IsExternalKey()) && (!$oLinkAttDef->IsExternalField())) {
$aDisplayList[] = $sLinkAttCode;
$oLinkAttDef = $aAttDefs[$sLinkAttCode];
if ((!$oLinkAttDef->IsExternalKey()) && (!$oLinkAttDef->IsExternalField())) {
$aDisplayList[] = $sLinkAttCode;
}
}
}
// Then display all the attributes neither specific to the link record nor to the 'linkage' object (because the latter are constant)
// Then display all the attributes neither specific to the link record nor to the 'linkage' object (because the latter are constant)
foreach ($aLists[$sAlias] as $sLinkAttCode) {
$oLinkAttDef = $aAttDefs[$sLinkAttCode];
if (($oLinkAttDef->IsExternalKey() && ($sLinkAttCode != $sLinkageAttribute))
|| ($oLinkAttDef->IsExternalField() && ($oLinkAttDef->GetKeyAttCode() != $sLinkageAttribute))) {
$aDisplayList[] = $sLinkAttCode;
$oLinkAttDef = $aAttDefs[$sLinkAttCode];
if (($oLinkAttDef->IsExternalKey() && ($sLinkAttCode != $sLinkageAttribute))
|| ($oLinkAttDef->IsExternalField() && ($oLinkAttDef->GetKeyAttCode() != $sLinkageAttribute))) {
$aDisplayList[] = $sLinkAttCode;
}
}
}
// First display all the attributes specific to the link
// Then display all the attributes linked to the other end of the relationship
// First display all the attributes specific to the link
// Then display all the attributes linked to the other end of the relationship
$aLists[$sAlias] = $aDisplayList;
}
}
@@ -460,7 +463,7 @@ class DataTableUIBlockFactory extends AbstractUIBlockFactory
$sIdName = isset($aExtraParams["id_for_select"]) ? $aExtraParams["id_for_select"] : "";
// Load only the requested columns
$aColumnsToLoad = array();
$aColumnsToLoad = [];
foreach ($oCustomSettings->aColumns as $sAlias => $aColumnsInfo) {
foreach ($aColumnsInfo as $sAttCode => $aData) {
$bForceLoad = false;
@@ -488,7 +491,7 @@ class DataTableUIBlockFactory extends AbstractUIBlockFactory
$oSet->OptimizeColumnLoad($aColumnsToLoad);
$aColumnDefinition = [];
$iIndexColumn=0;
$iIndexColumn = 0;
$bSelectMode = isset($aExtraParams['selection_mode']) ? $aExtraParams['selection_mode'] == true : false;
$bSingleSelectMode = isset($aExtraParams['selection_type']) ? ($aExtraParams['selection_type'] == 'single') : false;
@@ -509,12 +512,11 @@ class DataTableUIBlockFactory extends AbstractUIBlockFactory
$sCode = ($aData['code'] == '_key_') ? 'friendlyname' : $aData['code'];
if ($aData['sort'] != 'none') {
$aSortOrder[$sClassAlias.'.'.$sCode] = ($aData['sort'] == 'asc'); // true for ascending, false for descending
$aSortDatable=[$iIndexColumn,$aData['sort']];
}
elseif (isset($oCustomSettings->aSortOrder[$sAttCode])){
$aSortDatable = [$iIndexColumn,$aData['sort']];
} elseif (isset($oCustomSettings->aSortOrder[$sAttCode])) {
$aSortOrder[$sClassAlias.'.'.$sCode] = $oCustomSettings->aSortOrder[$sAttCode]; // true for ascending, false for descending
}
if ($aData['checked']) {
if ($sAttCode == '_key_') {
if ($bViewLink) {
@@ -557,7 +559,7 @@ class DataTableUIBlockFactory extends AbstractUIBlockFactory
$aOptions = [];
if ($oDefaultSettings != null) {
$aOptions['oDefaultSettings'] = json_encode(array('iDefaultPageSize' => $oDefaultSettings->iDefaultPageSize, 'oColumns' => $oDefaultSettings->aColumns));
$aOptions['oDefaultSettings'] = json_encode(['iDefaultPageSize' => $oDefaultSettings->iDefaultPageSize, 'oColumns' => $oDefaultSettings->aColumns]);
}
// Selection mode
@@ -568,7 +570,7 @@ class DataTableUIBlockFactory extends AbstractUIBlockFactory
$aOptions['select_mode'] = "single";
}
}
$aOptions['selectionMode'] = $aExtraParams['selectionMode']?? 'positive';
$aOptions['selectionMode'] = $aExtraParams['selectionMode'] ?? 'positive';
// Sort
$aOptions['sort'] = $aSortDatable;
@@ -600,9 +602,8 @@ class DataTableUIBlockFactory extends AbstractUIBlockFactory
} else {
$aOptions['sSelectedRows'] = '[]';
}
$aExtraParams['table_id']=$sTableId;
$aExtraParams['list_id']=$sListId;
$aExtraParams['table_id'] = $sTableId;
$aExtraParams['list_id'] = $sListId;
$oDataTable->SetOptions($aOptions);
$oDataTable->SetAjaxUrl(utils::GetAbsoluteUrlAppRoot()."pages/ajax.render.php");
@@ -623,7 +624,7 @@ class DataTableUIBlockFactory extends AbstractUIBlockFactory
$oDataTable->SetRowActions($aExtraParams['row_actions']);
}
if (isset($aExtraParams['creation_in_modal_js_handler'])){
if (isset($aExtraParams['creation_in_modal_js_handler'])) {
$oDataTable->SetModalCreationHandler($aExtraParams['creation_in_modal_js_handler']);
}
@@ -671,18 +672,17 @@ class DataTableUIBlockFactory extends AbstractUIBlockFactory
$aColumnDefinition["data"] = "";
$aColumnDefinition["render"]["display"] = "";
if ($sSelectMode != "single") {
$aColumnDefinition["render"]["display"] = $aColumnDefinition["render"]["display"] . " var oCheckboxElem = $('<span class=\"row_input\"><input type=\"checkbox\" class=\"selectList".$sTableId."\" name=\"selectObject[]\" value='+row.id+' /></span>');";
$aColumnDefinition["render"]["display"] = $aColumnDefinition["render"]["display"]." var oCheckboxElem = $('<span class=\"row_input\"><input type=\"checkbox\" class=\"selectList".$sTableId."\" name=\"selectObject[]\" value='+row.id+' /></span>');";
} else {
$aColumnDefinition["render"]["display"] = $aColumnDefinition["render"]["display"]." var oCheckboxElem = $('<span class=\"row_input\"><input type=\"radio\" class=\"selectList".$sTableId."\" name=\"selectObject[]\" value='+ row.id +' /></span>');";
}
else {
$aColumnDefinition["render"]["display"] = $aColumnDefinition["render"]["display"] . " var oCheckboxElem = $('<span class=\"row_input\"><input type=\"radio\" class=\"selectList".$sTableId."\" name=\"selectObject[]\" value='+ row.id +' /></span>');";
}
$aColumnDefinition["render"]["display"] = $aColumnDefinition["render"]["display"] . " if (row.limited_access) { oCheckboxElem.html('-'); } else { oCheckboxElem.find(':input').attr('data-object-id', row.id).attr('data-target-object-id', row.target_id); }";
$aColumnDefinition["render"]["display"] = $aColumnDefinition["render"]["display"]. " return oCheckboxElem.prop('outerHTML'); ";
$aColumnDefinition["render"]["display"] = $aColumnDefinition["render"]["display"]." if (row.limited_access) { oCheckboxElem.html('-'); } else { oCheckboxElem.find(':input').attr('data-object-id', row.id).attr('data-target-object-id', row.target_id); }";
$aColumnDefinition["render"]["display"] = $aColumnDefinition["render"]["display"]." return oCheckboxElem.prop('outerHTML'); ";
array_push($aColumnsDefinitions, $aColumnDefinition);
}
foreach ($aColumns as $sClassAlias => $aClassColumns) {
$sClassName=$aClassAliases[$sClassAlias];
$sClassName = $aClassAliases[$sClassAlias];
foreach ($aClassColumns as $sAttCode => $aData) {
if ($aData['checked'] == "true") {
$aColumnDefinition["width"] = "auto";
@@ -803,7 +803,7 @@ JS;
"data": '.$sAjaxData.',
"method": "post",
"pages": 5 // number of pages to cache
} )'
} )',
]);
if (count($aJsFiles) > 0) {
foreach ($aJsFiles as $sJsFile) {
@@ -954,4 +954,4 @@ JS;
/** Don't provide the standard object creation feature */
];
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* Copyright (C) 2013-2024 Combodo SAS
*
@@ -19,7 +20,6 @@
namespace Combodo\iTop\Application\UI\Base\Component\QuickCreate;
use appUserPreferences;
use DBObject;
use MetaModel;
@@ -60,10 +60,8 @@ class QuickCreateHelper
$aHistoryEntries = appUserPreferences::GetPref(static::USER_PREF_CODE, []);
// Remove same entry from history to avoid duplicates
for ($iIdx = 0; $iIdx < count($aHistoryEntries); $iIdx++)
{
if ($aHistoryEntries[$iIdx]['class'] === $sClass)
{
for ($iIdx = 0; $iIdx < count($aHistoryEntries); $iIdx++) {
if ($aHistoryEntries[$iIdx]['class'] === $sClass) {
unset($aHistoryEntries[$iIdx]);
}
}
@@ -92,33 +90,28 @@ class QuickCreateHelper
static::Truncate($aHistoryEntries, 'quick_create.max_history_results');
for($iIdx = 0; $iIdx < count($aHistoryEntries); $iIdx++)
{
for ($iIdx = 0; $iIdx < count($aHistoryEntries); $iIdx++) {
$sClass = $aHistoryEntries[$iIdx]['class'];
if (!MetaModel::IsValidClass($sClass)) {
continue;
}
// Add class icon
if(!isset($aHistoryEntries[$iIdx]['icon_url']))
{
if (!isset($aHistoryEntries[$iIdx]['icon_url'])) {
$sClassIconUrl = MetaModel::GetClassIcon($sClass, false);
// Mind that some classes don't have an icon
if(!empty($sClassIconUrl))
{
if (!empty($sClassIconUrl)) {
$aHistoryEntries[$iIdx]['icon_url'] = $sClassIconUrl;
}
}
// Add class label
if(!isset($aHistoryEntries[$iIdx]['label_html']))
{
if (!isset($aHistoryEntries[$iIdx]['label_html'])) {
$aHistoryEntries[$iIdx]['label_html'] = utils::EscapeHtml(MetaModel::GetName($sClass));
}
// Add URL
if(!isset($aHistoryEntries[$iIdx]['target_url']))
{
if (!isset($aHistoryEntries[$iIdx]['target_url'])) {
$aHistoryEntries[$iIdx]['target_url'] = DBObject::ComputeStandardUIPage($sClass).'?operation=new&class='.$sClass;
}
}
@@ -138,20 +131,18 @@ class QuickCreateHelper
{
$aHistoryEntries = appUserPreferences::GetPref(static::USER_PREF_CODE, []);
static::Truncate($aHistoryEntries, 'quick_create.max_history_results');
$aPopularClassesNames = UserRights::GetAllowedClasses(UR_ACTION_CREATE, array('popular'), false);
$aPopularClassesNames = UserRights::GetAllowedClasses(UR_ACTION_CREATE, ['popular'], false);
// Prevent classes in both Popular and Recent to appear twice
for($iIdx = 0; $iIdx < count($aHistoryEntries); $iIdx++)
{
for ($iIdx = 0; $iIdx < count($aHistoryEntries); $iIdx++) {
if (($key = array_search($aHistoryEntries[$iIdx]['class'], $aPopularClassesNames)) !== false) {
unset($aPopularClassesNames[$key]);
}
}
//die(var_dump($aPopularClassesNames));
static::Truncate($aPopularClassesNames, 'quick_create.max_popular_results');
$aPopularClasses = array();
foreach($aPopularClassesNames as $sClass)
{
$aPopularClasses = [];
foreach ($aPopularClassesNames as $sClass) {
if (!MetaModel::IsValidClass($sClass)) {
continue;
}
@@ -167,12 +158,12 @@ class QuickCreateHelper
// Add URL
$sTargetUrl = DBObject::ComputeStandardUIPage($sClass).'?operation=new&class='.$sClass;
$aPopularClasses[] = array(
$aPopularClasses[] = [
'class' => $sClass,
'icon_url' => $sClassIconUrl,
'label_html' => $sLabelHtml,
'target_url' => $sTargetUrl
);
'target_url' => $sTargetUrl,
];
}
return $aPopularClasses;
}
@@ -186,11 +177,9 @@ class QuickCreateHelper
protected static function Truncate(array &$aEntries, string $sMaxEntriesParam = 'global_search.max_history_results'): void
{
$iMaxResults = (int) MetaModel::GetConfig()->Get($sMaxEntriesParam);
if(count($aEntries) > $iMaxResults)
{
if (count($aEntries) > $iMaxResults) {
$aEntries = array_slice($aEntries, 0, $iMaxResults);
}
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* Copyright (C) 2013-2024 Combodo SAS
*
@@ -19,7 +20,6 @@
namespace Combodo\iTop\Application\UI\Base\Layout\ActivityPanel;
use appUserPreferences;
use AttributeDateTime;
use cmdbAbstractObject;
@@ -102,7 +102,6 @@ class ActivityPanel extends UIBlock
/** @var bool */
protected $bPrefilterEditsOnLogs;
/**
* ActivityPanel constructor.
*
@@ -166,7 +165,6 @@ class ActivityPanel extends UIBlock
$this->AddCaseLogTab($sCaseLogAttCode);
}
return $this;
}
@@ -185,7 +183,8 @@ class ActivityPanel extends UIBlock
*
* @return int
*/
public function GetObjectId(): int {
public function GetObjectId(): int
{
return $this->oObject->GetKey();
}
@@ -194,7 +193,8 @@ class ActivityPanel extends UIBlock
*
* @return string
*/
public function GetObjectClass(): string {
public function GetObjectClass(): string
{
return get_class($this->oObject);
}
@@ -210,7 +210,7 @@ class ActivityPanel extends UIBlock
public function SetObjectMode(string $sMode)
{
// Consistency check
if(!in_array($sMode, cmdbAbstractObject::EnumDisplayModes())){
if (!in_array($sMode, cmdbAbstractObject::EnumDisplayModes())) {
throw new Exception("Activity panel: Object mode '$sMode' not allowed, should be either ".implode(' / ', cmdbAbstractObject::EnumDisplayModes()));
}
@@ -300,8 +300,7 @@ class ActivityPanel extends UIBlock
// Reset entries
$this->aEntries = [];
foreach ($aEntries as $oEntry)
{
foreach ($aEntries as $oEntry) {
$this->AddEntry($oEntry);
}
@@ -315,8 +314,7 @@ class ActivityPanel extends UIBlock
*/
public function GetEntries(): array
{
if ($this->bAreEntriesSorted === false)
{
if ($this->bAreEntriesSorted === false) {
$this->SortEntries();
}
@@ -335,18 +333,15 @@ class ActivityPanel extends UIBlock
$aCurrentGroup = ['author_login' => null, 'origin' => null, 'entries' => []];
$aPreviousEntryData = ['author_login' => null, 'origin' => null];
foreach($this->GetEntries() as $sId => $oEntry)
{
foreach ($this->GetEntries() as $sId => $oEntry) {
// New entry data
$sAuthorLogin = $oEntry->GetAuthorLogin();
$sOrigin = $oEntry->GetOrigin();
// Check if it's time to change of group
if(($sAuthorLogin !== $aPreviousEntryData['author_login']) || ($sOrigin !== $aPreviousEntryData['origin']))
{
if (($sAuthorLogin !== $aPreviousEntryData['author_login']) || ($sOrigin !== $aPreviousEntryData['origin'])) {
// Flush current group if necessary
if(empty($aCurrentGroup['entries']) === false)
{
if (empty($aCurrentGroup['entries']) === false) {
$aGroupedEntries[] = $aCurrentGroup;
}
@@ -359,8 +354,7 @@ class ActivityPanel extends UIBlock
}
// Flush last group
if(empty($aCurrentGroup['entries']) === false)
{
if (empty($aCurrentGroup['entries']) === false) {
$aGroupedEntries[] = $aCurrentGroup;
}
@@ -374,16 +368,14 @@ class ActivityPanel extends UIBlock
*/
protected function SortEntries()
{
if(count($this->aEntries) > 1)
{
uasort($this->aEntries, function($oEntryA, $oEntryB){
if (count($this->aEntries) > 1) {
uasort($this->aEntries, function ($oEntryA, $oEntryB) {
/** @var ActivityEntry $oEntryA */
/** @var ActivityEntry $oEntryB */
$sDateTimeA = $oEntryA->GetRawDateTime();
$sDateTimeB = $oEntryB->GetRawDateTime();
if ($sDateTimeA === $sDateTimeB)
{
if ($sDateTimeA === $sDateTimeB) {
return 0;
}
@@ -409,14 +401,12 @@ class ActivityPanel extends UIBlock
$this->bAreEntriesSorted = false;
// Add case log to the panel and update metadata when necessary
if ($oEntry instanceof CaseLogEntry)
{
if ($oEntry instanceof CaseLogEntry) {
$sCaseLogAttCode = $oEntry->GetAttCode();
$sAuthorLogin = $oEntry->GetAuthorLogin();
// Initialize case log metadata
if ($this->HasCaseLogTab($sCaseLogAttCode) === false)
{
if ($this->HasCaseLogTab($sCaseLogAttCode) === false) {
$this->AddCaseLogTab($sCaseLogAttCode);
}
@@ -427,8 +417,7 @@ class ActivityPanel extends UIBlock
// - Message count
$this->aCaseLogs[$sCaseLogAttCode]['total_messages_count']++;
// - Authors
if(array_key_exists($sAuthorLogin, $this->aCaseLogs[$sCaseLogAttCode]['authors']) === false)
{
if (array_key_exists($sAuthorLogin, $this->aCaseLogs[$sCaseLogAttCode]['authors']) === false) {
$this->aCaseLogs[$sCaseLogAttCode]['authors'][$sAuthorLogin] = [
'messages_count' => 0,
];
@@ -449,12 +438,10 @@ class ActivityPanel extends UIBlock
*/
public function RemoveEntry(string $sEntryId)
{
if (array_key_exists($sEntryId, $this->aEntries))
{
if (array_key_exists($sEntryId, $this->aEntries)) {
// Recompute case logs metadata only if necessary
$oEntry = $this->aEntries[$sEntryId];
if ($oEntry instanceof CaseLogEntry)
{
if ($oEntry instanceof CaseLogEntry) {
$sCaseLogAttCode = $oEntry->GetAttCode();
$sAuthorLogin = $oEntry->GetAuthorLogin();
@@ -463,8 +450,7 @@ class ActivityPanel extends UIBlock
$this->aCaseLogs[$sCaseLogAttCode]['total_messages_count']--;
// - Authors
$this->aCaseLogs[$sCaseLogAttCode]['authors'][$sAuthorLogin]['messages_count']--;
if($this->aCaseLogs[$sCaseLogAttCode]['authors'][$sAuthorLogin]['messages_count'] === 0)
{
if ($this->aCaseLogs[$sCaseLogAttCode]['authors'][$sAuthorLogin]['messages_count'] === 0) {
unset($this->aCaseLogs[$sCaseLogAttCode]['authors'][$sAuthorLogin]);
}
}
@@ -563,8 +549,7 @@ class ActivityPanel extends UIBlock
protected function AddCaseLogTab(string $sAttCode)
{
// Add case log only if not already existing
if (!array_key_exists($sAttCode, $this->aCaseLogs))
{
if (!array_key_exists($sAttCode, $this->aCaseLogs)) {
$iFlags = ($this->GetObject()->IsNew()) ? $this->GetObject()->GetInitialStateAttributeFlags($sAttCode) : $this->GetObject()->GetAttributeFlags($sAttCode);
$bIsHidden = (OPT_ATT_HIDDEN === ($iFlags & OPT_ATT_HIDDEN));
$bIsReadOnly = (OPT_ATT_READONLY === ($iFlags & OPT_ATT_READONLY));
@@ -614,8 +599,7 @@ class ActivityPanel extends UIBlock
*/
protected function RemoveCaseLogTab(string $sAttCode)
{
if (array_key_exists($sAttCode, $this->aCaseLogs))
{
if (array_key_exists($sAttCode, $this->aCaseLogs)) {
unset($this->aCaseLogs[$sAttCode]);
}
@@ -693,7 +677,7 @@ class ActivityPanel extends UIBlock
*/
public function SetCaseLogTabEntryForm(string $sCaseLogId, CaseLogEntryForm $oCaseLogEntryForm)
{
if ($this->HasCaseLogTab($sCaseLogId)){
if ($this->HasCaseLogTab($sCaseLogId)) {
$this->aCaseLogTabsEntryForms[$sCaseLogId] = $oCaseLogEntryForm;
}
@@ -743,8 +727,7 @@ class ActivityPanel extends UIBlock
foreach ($this->GetCaseLogTabsEntryForms() as $oCaseLogEntryForm) {
if ($oCaseLogEntryForm->IsSubmitAutonomous()) {
$iAutonomousSubmission++;
}
else {
} else {
$iBridgedSubmissions++;
}
}
@@ -948,7 +931,7 @@ class ActivityPanel extends UIBlock
*/
public function GetSubBlocks(): array
{
$aSubBlocks = array();
$aSubBlocks = [];
foreach ($this->GetCaseLogTabsEntryForms() as $sCaseLogId => $oCaseLogEntryForm) {
$aSubBlocks[$oCaseLogEntryForm->GetId()] = $oCaseLogEntryForm;
@@ -967,4 +950,4 @@ class ActivityPanel extends UIBlock
{
return \UserRights::IsActionAllowed($this->GetObjectClass(), UR_ACTION_MODIFY);
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* Copyright (C) 2013-2024 Combodo SAS
*
@@ -61,9 +62,9 @@ class NiceWebPage extends WebPage
'js/searchformforeignkeys.js',
];
const DEFAULT_PAGE_TEMPLATE_REL_PATH = 'pages/backoffice/nicewebpage/layout';
public const DEFAULT_PAGE_TEMPLATE_REL_PATH = 'pages/backoffice/nicewebpage/layout';
var $m_sRootUrl;
public $m_sRootUrl;
public function __construct($s_title, $bPrintable = false)
{
@@ -145,8 +146,7 @@ JS
$this->LinkScriptFromAppRoot('node_modules/jquery/dist/jquery.min.js');
$this->LinkScriptFromAppRoot('js/ajax_hook.js');
$this->LinkScriptFromAppRoot('js/jquery.blockUI.js');
if (utils::IsDevelopmentEnvironment()) // Needed since many other plugins still rely on oldies like $.browser
{
if (utils::IsDevelopmentEnvironment()) { // Needed since many other plugins still rely on oldies like $.browser
$this->LinkScriptFromAppRoot('js/jquery-migrate.dev-params.js');
$this->LinkScriptFromAppRoot('node_modules/jquery-migrate/dist/jquery-migrate.js');
} else {
@@ -170,11 +170,10 @@ JS
$this->add_dict_entries('UI:Combo');
}
public function SetRootUrl($sRootUrl)
{
$this->m_sRootUrl = $sRootUrl;
}
{
$this->m_sRootUrl = $sRootUrl;
}
public function small_p($sText)
{
@@ -191,7 +190,7 @@ JS
return utils::GetAbsoluteUrlModulesRoot();
}
function GetApplicationContext()
public function GetApplicationContext()
{
$oAppContext = new ApplicationContext();
return $oAppContext->GetForLink();
@@ -203,11 +202,9 @@ JS
// $aTopLevelClasses = array('bizService', 'bizContact', 'logInfra', 'bizDocument');
// These are classes wich root class is cmdbAbstractObject !
$this->add("<select id=\"select_$sName\" name=\"$sName\">");
$aValidClasses = array();
foreach(MetaModel::GetClasses('bizmodel') as $sClassName)
{
if (is_null($iActionCode) || UserRights::IsActionAllowed($sClassName, $iActionCode))
{
$aValidClasses = [];
foreach (MetaModel::GetClasses('bizmodel') as $sClassName) {
if (is_null($iActionCode) || UserRights::IsActionAllowed($sClassName, $iActionCode)) {
$sSelected = ($sClassName == $sDefaultValue) ? " SELECTED" : "";
$sDescription = MetaModel::GetClassDescription($sClassName);
$sDisplayName = MetaModel::GetName($sClassName);
@@ -224,8 +221,7 @@ JS
public function add_select($aChoices, $sName, $sDefaultValue, $iWidthPx)
{
$this->add("<select id=\"select_$sName\" name=\"$sName\">");
foreach($aChoices as $sKey => $sValue)
{
foreach ($aChoices as $sKey => $sValue) {
$sSelected = ($sKey == $sDefaultValue) ? " SELECTED" : "";
$this->add("<option style=\"width: ".$iWidthPx." px;\" value=\"".htmlspecialchars($sKey)."\"$sSelected>".utils::EscapeHtml($sValue)."</option>");
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -30,10 +31,10 @@ use MetaModel;
use Symfony\Component\HttpFoundation\Response;
use UserRights;
use utils;
use const APPROOT;
use const MODULESROOT;
/**
* <p>Simple helper class to ease the production of HTML pages
*
@@ -64,7 +65,7 @@ class WebPage implements Page
/**
* @since 2.7.0 N°2529
*/
const PAGES_CHARSET = 'utf-8';
public const PAGES_CHARSET = 'utf-8';
/**
* @var string
@@ -149,7 +150,7 @@ class WebPage implements Page
* @var string Rel. path to the template to use for the rendering. File name must be without the extension.
* @since 3.0.0
*/
const DEFAULT_PAGE_TEMPLATE_REL_PATH = 'pages/backoffice/webpage/layout';
public const DEFAULT_PAGE_TEMPLATE_REL_PATH = 'pages/backoffice/webpage/layout';
protected $s_title;
protected $s_content;
@@ -210,7 +211,6 @@ class WebPage implements Page
protected $oContentLayout;
protected $sTemplateRelPath;
/**
* @var bool|string|string[]
*/
@@ -341,7 +341,7 @@ class WebPage implements Page
* @return void
* @throws \Exception
*/
public function add_twig_template($sViewPath, $sTemplateName, $aParams = array(), $sDefaultType = 'html')
public function add_twig_template($sViewPath, $sTemplateName, $aParams = [], $sDefaultType = 'html')
{
TwigHelper::RenderIntoPage($this, $sViewPath, $sTemplateName, $aParams, $sDefaultType);
}
@@ -399,7 +399,7 @@ class WebPage implements Page
* @inheritDoc
* @throws \Exception
*/
public function table($aConfig, $aData, $aParams = array())
public function table($aConfig, $aData, $aParams = [])
{
$oDataTable = $this->GetTableBlock($aConfig, $aData);
$oDataTable->AddOption("bFullscreen", true);
@@ -421,7 +421,7 @@ class WebPage implements Page
* @return string
* @throws \Exception
*/
public function GetTable($aConfig, $aData, $aParams = array())
public function GetTable($aConfig, $aData, $aParams = [])
{
static $iNbTables = 0;
$iNbTables++;
@@ -429,15 +429,13 @@ class WebPage implements Page
$sHtml .= "<table class=\"listResults\">\n";
$sHtml .= "<thead>\n";
$sHtml .= "<tr>\n";
foreach ($aConfig as $sName => $aDef)
{
foreach ($aConfig as $sName => $aDef) {
$sHtml .= "<th title=\"".$aDef['description']."\">".$aDef['label']."</th>\n";
}
$sHtml .= "</tr>\n";
$sHtml .= "</thead>\n";
$sHtml .= "<tbody>\n";
foreach ($aData as $aRow)
{
foreach ($aData as $aRow) {
$sHtml .= $this->GetTableRow($aRow, $aConfig);
}
$sHtml .= "</tbody>\n";
@@ -455,25 +453,19 @@ class WebPage implements Page
public function GetTableRow($aRow, $aConfig)
{
$sHtml = '';
if (isset($aRow['@class'])) // Row specific class, for hilighting certain rows
{
if (isset($aRow['@class'])) { // Row specific class, for hilighting certain rows
$sHtml .= "<tr class=\"{$aRow['@class']}\">";
}
else
{
} else {
$sHtml .= "<tr>";
}
foreach ($aConfig as $sName => $aAttribs)
{
foreach ($aConfig as $sName => $aAttribs) {
$sClass = isset($aAttribs['class']) ? 'class="'.$aAttribs['class'].'"' : '';
// Prepare metadata
// - From table config.
$sMetadata = '';
if(isset($aAttribs['metadata']))
{
foreach($aAttribs['metadata'] as $sMetadataProp => $sMetadataValue)
{
if (isset($aAttribs['metadata'])) {
foreach ($aAttribs['metadata'] as $sMetadataProp => $sMetadataValue) {
$sMetadataPropSanitized = str_replace('_', '-', $sMetadataProp);
$sMetadataValueSanitized = utils::HtmlEntities($sMetadataValue);
$sMetadata .= 'data-'.$sMetadataPropSanitized.'="'.$sMetadataValueSanitized.'" ';
@@ -481,13 +473,10 @@ class WebPage implements Page
}
// Prepare value
if(is_array($aRow[$sName]))
{
if (is_array($aRow[$sName])) {
$sValueHtml = ($aRow[$sName]['value_html'] === '') ? '&nbsp;' : $aRow[$sName]['value_html'];
$sMetadata .= 'data-value-raw="'.utils::HtmlEntities($aRow[$sName]['value_raw']).'" ';
}
else
{
} else {
$sValueHtml = ($aRow[$sName] === '') ? '&nbsp;' : $aRow[$sName];
}
@@ -555,7 +544,7 @@ class WebPage implements Page
// Ensure file is within the app folder
$sFileRelPathWithoutQueryParams = explode("?", $sFileRelPath)[0];
if (false === utils::RealPath(APPROOT . $sFileRelPathWithoutQueryParams, APPROOT)) {
if (false === utils::RealPath(APPROOT.$sFileRelPathWithoutQueryParams, APPROOT)) {
IssueLog::Warning("Linked resource added to page with a path from outside app directory, it will be ignored.", LogChannels::CONSOLE, [
"linked_resource_uri" => $sFileRelPath,
"request_uri" => $_SERVER['REQUEST_URI'] ?? '' /* CLI */,
@@ -570,7 +559,7 @@ class WebPage implements Page
$sAppRootUrl .= '/';
}
$this->LinkResourceFromURI($sAppRootUrl . $sFileRelPath, $sResourceType);
$this->LinkResourceFromURI($sAppRootUrl.$sFileRelPath, $sResourceType);
}
/**
@@ -593,7 +582,7 @@ class WebPage implements Page
// Ensure file is within the app folder
$sFileRelPathWithoutQueryParams = explode("?", $sFileRelPath)[0];
$sFileAbsPath = MODULESROOT . $sFileRelPathWithoutQueryParams;
$sFileAbsPath = MODULESROOT.$sFileRelPathWithoutQueryParams;
// For modules only, we don't check real path if symlink as the file would not be in under MODULESROOT
if (false === is_link($sFileAbsPath) && false === utils::RealPath($sFileAbsPath, MODULESROOT)) {
IssueLog::Warning("Linked resource added to page with a path from outside current env. directory, it will be ignored.", LogChannels::CONSOLE, [
@@ -603,7 +592,7 @@ class WebPage implements Page
return;
}
$this->LinkResourceFromURI(utils::GetAbsoluteUrlModulesRoot() . $sFileRelPath, $sResourceType);
$this->LinkResourceFromURI(utils::GetAbsoluteUrlModulesRoot().$sFileRelPath, $sResourceType);
}
/**
@@ -1019,8 +1008,10 @@ class WebPage implements Page
*/
protected function get_dict_signature()
{
return str_replace('_', '', Dict::GetUserLanguage()).'-'.md5(implode(',',
$this->a_dict_entries).'|'.implode(',', $this->a_dict_entries_prefixes));
return str_replace('_', '', Dict::GetUserLanguage()).'-'.md5(implode(
',',
$this->a_dict_entries
).'|'.implode(',', $this->a_dict_entries_prefixes));
}
/**
@@ -1028,13 +1019,11 @@ class WebPage implements Page
*/
protected function get_dict_file_content()
{
$aEntries = array();
foreach ($this->a_dict_entries as $sCode)
{
$aEntries = [];
foreach ($this->a_dict_entries as $sCode) {
$aEntries[$sCode] = Dict::S($sCode);
}
foreach ($this->a_dict_entries_prefixes as $sPrefix)
{
foreach ($this->a_dict_entries_prefixes as $sPrefix) {
$aEntries = array_merge($aEntries, Dict::ExportEntries($sPrefix));
}
@@ -1168,8 +1157,7 @@ JS;
{
$sCssRelPath = utils::GetCSSFromSASS($sSaasRelPath);
$sRootUrl = utils::GetAbsoluteUrlAppRoot();
if ($sRootUrl === '')
{
if ($sRootUrl === '') {
// We're running the setup of the first install...
$sRootUrl = '../';
}
@@ -1323,8 +1311,7 @@ JS;
$aPossibleAttFlags = MetaModel::EnumPossibleAttributeFlags();
$sHtml = "<div class=\"ibo-details\">\n";
foreach ($aFields as $aAttrib)
{
foreach ($aFields as $aAttrib) {
$sLayout = isset($aAttrib['layout']) ? $aAttrib['layout'] : 'small';
// Prepare metadata attributes
@@ -1335,13 +1322,10 @@ JS;
$sDataInputType = isset($aAttrib['inputtype']) ? 'data-input-type="'.utils::HtmlEntities($aAttrib['inputtype']).'"' : '';
// - Attribute flags
$sDataAttributeFlags = '';
if(isset($aAttrib['attflags']))
{
foreach($aPossibleAttFlags as $sFlagCode => $iFlagValue)
{
if (isset($aAttrib['attflags'])) {
foreach ($aPossibleAttFlags as $sFlagCode => $iFlagValue) {
// Note: Skip normal flag as we don't need it.
if($sFlagCode === 'normal')
{
if ($sFlagCode === 'normal') {
continue;
}
$sFormattedFlagCode = str_ireplace('_', '-', $sFlagCode);
@@ -1356,23 +1340,18 @@ JS;
$sHtml .= "<div class=\"ibo-field--label\">{$aAttrib['label']}</div>\n";
// By Rom, for csv import, proposed to show several values for column selection
if (is_array($aAttrib['value']))
{
if (is_array($aAttrib['value'])) {
$sHtml .= "<div class=\"ibo-field--value\">".implode("</div><div>", $aAttrib['value'])."</div>\n";
}
else
{
} else {
$sHtml .= "<div class=\"ibo-field--value\">".$aAttrib['value']."</div>\n";
}
// Checking if we should add comments & infos
$sComment = (isset($aAttrib['comments'])) ? $aAttrib['comments'] : '';
$sInfo = (isset($aAttrib['infos'])) ? $aAttrib['infos'] : '';
if ($sComment !== '')
{
if ($sComment !== '') {
$sHtml .= "<div class=\"ibo-field--comments\">$sComment</div>\n";
}
if ($sInfo !== '')
{
if ($sInfo !== '') {
$sHtml .= "<div class=\"ibo-field--infos\">$sInfo</div>\n";
}
@@ -1397,26 +1376,26 @@ JS;
* @return string The HTML fragment corresponding to the radio buttons
*/
public function GetRadioButtons(
$aAllowedValues, $value, $iId, $sFieldName, $bMandatory, $bVertical, $sValidationField
$aAllowedValues,
$value,
$iId,
$sFieldName,
$bMandatory,
$bVertical,
$sValidationField
) {
$idx = 0;
$sHTMLValue = '';
foreach ($aAllowedValues as $key => $display_value)
{
if ((count($aAllowedValues) == 1) && ($bMandatory == 'true'))
{
foreach ($aAllowedValues as $key => $display_value) {
if ((count($aAllowedValues) == 1) && ($bMandatory == 'true')) {
// When there is only once choice, select it by default
$sSelected = 'checked';
}
else
{
} else {
$sSelected = ($value == $key) ? 'checked' : '';
}
$sHTMLValue .= "<input type=\"radio\" id=\"{$iId}_{$key}\" name=\"radio_$sFieldName\" onChange=\"$('#{$iId}').val(this.value).trigger('change');\" value=\"$key\" $sSelected><label class=\"radio\" for=\"{$iId}_{$key}\">&nbsp;$display_value</label>&nbsp;";
if ($bVertical)
{
if ($idx == 0)
{
if ($bVertical) {
if ($idx == 0) {
// Validation icon at the end of the first line
$sHTMLValue .= "&nbsp;{$sValidationField}\n";
}
@@ -1425,8 +1404,7 @@ JS;
$idx++;
}
$sHTMLValue .= "<input type=\"hidden\" id=\"$iId\" name=\"$sFieldName\" value=\"$value\"/>";
if (!$bVertical)
{
if (!$bVertical) {
// Validation icon at the end of the line
$sHTMLValue .= "&nbsp;{$sValidationField}\n";
}
@@ -1457,26 +1435,18 @@ JS;
protected function ob_get_clean_safe()
{
$sOutput = ob_get_contents();
if ($sOutput === false)
{
if ($sOutput === false) {
$sMsg = "Design/integration issue: No output buffer. Some piece of code has called ob_get_clean() or ob_end_clean() without calling ob_start()";
if ($this->bTrashUnexpectedOutput)
{
if ($this->bTrashUnexpectedOutput) {
IssueLog::Error($sMsg);
$sOutput = '';
}
else
{
} else {
$sOutput = $sMsg;
}
}
else
{
} else {
ob_end_clean(); // on some versions of PHP doing so when the output buffering is stopped can cause a notice
if ($this->bTrashUnexpectedOutput)
{
if (trim($sOutput) != '')
{
if ($this->bTrashUnexpectedOutput) {
if (trim($sOutput) != '') {
if (Utils::GetConfig() && Utils::GetConfig()->Get('debug_report_spurious_chars')) {
IssueLog::Error("Trashing unexpected output:'$sOutput'\n");
}
@@ -1706,11 +1676,10 @@ JS;
*
* @return bool True if the format is Ok, false otherwise
*/
function IsOutputFormatAvailable($sOutputFormat)
public function IsOutputFormatAvailable($sOutputFormat)
{
$bResult = false;
switch ($sOutputFormat)
{
switch ($sOutputFormat) {
case 'html':
$bResult = true; // Always supported
break;
@@ -1743,8 +1712,7 @@ JS;
*/
public function GetOutputOption($sFormat, $sOptionName)
{
if (isset($this->a_OutputOptions[$sFormat][$sOptionName]))
{
if (isset($this->a_OutputOptions[$sFormat][$sOptionName])) {
return $this->a_OutputOptions[$sFormat][$sOptionName];
}
@@ -1760,12 +1728,9 @@ JS;
*/
public function SetOutputOption($sFormat, $sOptionName, $sValue)
{
if (!isset($this->a_OutputOptions[$sFormat]))
{
$this->a_OutputOptions[$sFormat] = array($sOptionName => $sValue);
}
else
{
if (!isset($this->a_OutputOptions[$sFormat])) {
$this->a_OutputOptions[$sFormat] = [$sOptionName => $sValue];
} else {
$this->a_OutputOptions[$sFormat][$sOptionName] = $sValue;
}
}
@@ -1776,7 +1741,7 @@ JS;
*
* @return string
*/
public function RenderPopupMenuItems($aActions, $aFavoriteActions = array())
public function RenderPopupMenuItems($aActions, $aFavoriteActions = [])
{
$sPrevUrl = '';
$sHtml = '';
@@ -1784,12 +1749,14 @@ JS;
foreach ($aActions as $sActionId => $aAction) {
$sDataActionId = 'data-action-id="'.$sActionId.'"';
$sClass = isset($aAction['css_classes']) ? 'class="'.implode(' ', $aAction['css_classes']).'"' : '';
$sOnClick = isset($aAction['onclick']) ? 'onclick="'.htmlspecialchars($aAction['onclick'], ENT_QUOTES,
"UTF-8").'"' : '';
$sOnClick = isset($aAction['onclick']) ? 'onclick="'.htmlspecialchars(
$aAction['onclick'],
ENT_QUOTES,
"UTF-8"
).'"' : '';
$sTarget = isset($aAction['target']) ? "target=\"{$aAction['target']}\"" : "";
if (empty($aAction['url'])) {
if ($sPrevUrl != '') // Don't output consecutively two separators...
{
if ($sPrevUrl != '') { // Don't output consecutively two separators...
$sHtml .= "<li $sDataActionId>{$aAction['label']}</li>";
}
$sPrevUrl = '';
@@ -1859,8 +1826,6 @@ JS;
}
}
/**
* Return the language for the page metadata based on the current user
*

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -48,11 +49,11 @@ use utils;
class iTopWebPage extends NiceWebPage implements iTabbedPage
{
/** @var string ENUM_BREADCRUMB_ENTRY_ICON_TYPE_IMAGE */
const ENUM_BREADCRUMB_ENTRY_ICON_TYPE_IMAGE = 'image';
public const ENUM_BREADCRUMB_ENTRY_ICON_TYPE_IMAGE = 'image';
/** @var string ENUM_BREADCRUMB_ENTRY_ICON_TYPE_CSS_CLASSES */
const ENUM_BREADCRUMB_ENTRY_ICON_TYPE_CSS_CLASSES = 'css_classes';
public const ENUM_BREADCRUMB_ENTRY_ICON_TYPE_CSS_CLASSES = 'css_classes';
/** @var string DEFAULT_BREADCRUMB_ENTRY_ICON_TYPE */
const DEFAULT_BREADCRUMB_ENTRY_ICON_TYPE = self::ENUM_BREADCRUMB_ENTRY_ICON_TYPE_IMAGE;
public const DEFAULT_BREADCRUMB_ENTRY_ICON_TYPE = self::ENUM_BREADCRUMB_ENTRY_ICON_TYPE_IMAGE;
/** @inheritDoc */
protected const COMPATIBILITY_MOVED_LINKED_SCRIPTS_REL_PATH = [
@@ -79,7 +80,7 @@ class iTopWebPage extends NiceWebPage implements iTabbedPage
];
/** @var string DEFAULT_PAGE_TEMPLATE_REL_PATH The relative path (from <ITOP>/templates/) to the default page template */
const DEFAULT_PAGE_TEMPLATE_REL_PATH = 'pages/backoffice/itopwebpage/layout';
public const DEFAULT_PAGE_TEMPLATE_REL_PATH = 'pages/backoffice/itopwebpage/layout';
private $m_aMessages;
@@ -145,7 +146,7 @@ class iTopWebPage extends NiceWebPage implements iTabbedPage
utils::InitArchiveMode();
$this->m_aMessages = array();
$this->m_aMessages = [];
$this->SetRootUrl(utils::GetAbsoluteUrlAppRoot());
$this->add_header("Content-type: text/html; charset=".self::PAGES_CHARSET);
$this->no_cache();
@@ -283,7 +284,7 @@ class iTopWebPage extends NiceWebPage implements iTabbedPage
*/
protected function PrepareLayout()
{
$aDaysMin = array(
$aDaysMin = [
Dict::S('DayOfWeek-Sunday-Min'),
Dict::S('DayOfWeek-Monday-Min'),
Dict::S('DayOfWeek-Tuesday-Min'),
@@ -291,8 +292,8 @@ class iTopWebPage extends NiceWebPage implements iTabbedPage
Dict::S('DayOfWeek-Thursday-Min'),
Dict::S('DayOfWeek-Friday-Min'),
Dict::S('DayOfWeek-Saturday-Min'),
);
$aMonthsShort = array(
];
$aMonthsShort = [
Dict::S('Month-01-Short'),
Dict::S('Month-02-Short'),
Dict::S('Month-03-Short'),
@@ -305,12 +306,12 @@ class iTopWebPage extends NiceWebPage implements iTabbedPage
Dict::S('Month-10-Short'),
Dict::S('Month-11-Short'),
Dict::S('Month-12-Short'),
);
];
$sTimeFormat = AttributeDateTime::GetFormat()->ToTimeFormat();
$oTimeFormat = new DateTimeFormat($sTimeFormat);
// Date picker options
$aPickerOptions = array(
$aPickerOptions = [
'showOn' => 'button',
'buttonText' => '', // N°6455 class will be added after JQuery UI widget
'dateFormat' => AttributeDate::GetFormat()->ToDatePicker(),
@@ -320,7 +321,7 @@ class iTopWebPage extends NiceWebPage implements iTabbedPage
'dayNamesMin' => $aDaysMin,
'monthNamesShort' => $aMonthsShort,
'firstDay' => (int)Dict::S('Calendar-FirstDayOfWeek'),
);
];
$sJSDatePickerOptions = json_encode($aPickerOptions);
// Time picker additional options
@@ -339,8 +340,7 @@ class iTopWebPage extends NiceWebPage implements iTabbedPage
$aPickerOptions['controlType'] = 'select';
$aPickerOptions['closeText'] = Dict::S('UI:Button:Ok');
$sJSDateTimePickerOptions = json_encode($aPickerOptions);
if ($sTimePickerLang != '"en"')
{
if ($sTimePickerLang != '"en"') {
// More options that cannot be passed via json_encode since they must be evaluated client-side
$aMoreJSOptions = ",
'timeText': $.timepicker.regional[$sTimePickerLang].timeText,
@@ -428,19 +428,18 @@ JS
$.blockUI.defaults.message= '<i class="fas fa-fw fa-spin fa-sync-alt"></i>';
$.blockUI.defaults.overlayCSS = {}
JS
);
);
// TODO 3.0.0: To preserve
$this->add_ready_script(InlineImage::FixImagesWidth());
// TODO 3.0.0: To preserve
$this->add_ready_script(InlineImage::FixImagesWidth());
// user pref for client side
// see GetUserPreference() in utils.js
$sUserPrefs = appUserPreferences::GetAsJSON();
$this->add_script("var oUserPreferences = $sUserPrefs;");
// user pref for client side
// see GetUserPreference() in utils.js
$sUserPrefs = appUserPreferences::GetAsJSON();
$this->add_script("var oUserPreferences = $sUserPrefs;");
}
}
/**
* @see static::ENUM_BREADCRUMB_ENTRY_ICON_TYPE_IMAGE, static::ENUM_BREADCRUMB_ENTRY_ICON_TYPE_CSS_CLASSES
*
@@ -481,7 +480,6 @@ JS
$this->GetTopBarLayout()->SetBreadcrumbs(new Breadcrumbs($this->GetBreadCrumbsNewEntry(), Breadcrumbs::BLOCK_CODE));
}
/**
* @internal
* @return \Combodo\iTop\Application\UI\Base\Layout\NavigationMenu\NavigationMenu
@@ -592,11 +590,9 @@ JS
{
$aNewEntry = null;
if ($this->bBreadCrumbEnabled)
{
if ($this->bBreadCrumbEnabled) {
// Default entry values
if (is_null($this->sBreadCrumbEntryId))
{
if (is_null($this->sBreadCrumbEntryId)) {
$this->sBreadCrumbEntryId = $this->s_title;
$this->sBreadCrumbEntryLabel = $this->s_title;
$this->sBreadCrumbEntryDescription = $this->s_title;
@@ -632,8 +628,7 @@ JS
// Call the extensions to add content to the page, warning they can also add styles or scripts through as they have access to the iTopWebPage
/** @var \iPageUIBlockExtension $oExtensionInstance */
foreach (MetaModel::EnumPlugins('iPageUIBlockExtension') as $oExtensionInstance)
{
foreach (MetaModel::EnumPlugins('iPageUIBlockExtension') as $oExtensionInstance) {
$oBlock = $oExtensionInstance->GetBannerBlock();
if ($oBlock) {
$oBanner->AddSubBlock($oBlock);
@@ -643,7 +638,6 @@ JS
return $oBanner;
}
/**
* Render the header UIBlock which can come from both iTop itself and from extensions
*
@@ -673,11 +667,10 @@ JS
}
// Access mode
$sRestrictionMessage ='';
$sRestrictionMessage = '';
if (!MetaModel::DBHasAccess(ACCESS_ADMIN_WRITE)) {
$sRestrictionMessage = Dict::S('UI:AccessRO-All');
}
elseif (!MetaModel::DBHasAccess(ACCESS_USER_WRITE)) {
} elseif (!MetaModel::DBHasAccess(ACCESS_USER_WRITE)) {
$sRestrictionMessage = Dict::S('UI:AccessRO-Users');
}
@@ -707,8 +700,7 @@ HTML;
// Call the extensions to add content to the page, warning they can also add styles or scripts through as they have access to the iTopWebPage
/** @var \iPageUIBlockExtension $oExtensionInstance */
foreach (MetaModel::EnumPlugins('iPageUIBlockExtension') as $oExtensionInstance)
{
foreach (MetaModel::EnumPlugins('iPageUIBlockExtension') as $oExtensionInstance) {
$oBlock = $oExtensionInstance->GetHeaderBlock();
if ($oBlock) {
$oHeader->AddSubBlock($oBlock);
@@ -718,7 +710,6 @@ HTML;
return $oHeader;
}
/**
* Render the footer UIBlock which can come from both iTop itself and from extensions
*
@@ -875,7 +866,7 @@ HTML;
$aData['aLayouts']['oPageContent'] = $this->GetContentLayout();
$aData['aDeferredBlocks']['oPageContent'] = $this->GetDeferredBlocks($this->GetContentLayout());
// - Prepare generic templates
$aData['aTemplates'] = array();
$aData['aTemplates'] = [];
// TODO 3.1 Replace hardcoded 'Please wait' with dict entries
@@ -888,12 +879,12 @@ HTML;
// - Small loader template
$oSmallLoaderTemplateContentBlock = new UIContentBlock();
$oSmallLoaderTemplateContentBlock->AddSubBlock(SpinnerUIBlockFactory::MakeSmall(null , 'Please wait'));
$oSmallLoaderTemplateContentBlock->AddSubBlock(SpinnerUIBlockFactory::MakeSmall(null, 'Please wait'));
$aData['aTemplates'][] = TemplateUIBlockFactory::MakeForBlock('ibo-small-loading-placeholder-template', $oSmallLoaderTemplateContentBlock);
// - Large loader template
$oLargeLoaderTemplateContentBlock = new UIContentBlock();
$oLargeLoaderTemplateContentBlock->AddSubBlock(SpinnerUIBlockFactory::MakeLarge(null , 'Please wait'));
$oLargeLoaderTemplateContentBlock->AddSubBlock(SpinnerUIBlockFactory::MakeLarge(null, 'Please wait'));
$aData['aTemplates'][] = TemplateUIBlockFactory::MakeForBlock('ibo-large-loading-placeholder-template', $oLargeLoaderTemplateContentBlock);
// - Do not show again template
@@ -954,7 +945,7 @@ HTML;
*/
public function AddTabContainer($sTabContainer, $sPrefix = '', iUIContentBlock $oParentBlock = null)
{
if(is_null($oParentBlock)) {
if (is_null($oParentBlock)) {
$oParentBlock = PanelUIBlockFactory::MakeNeutral('');
$this->AddUiBlock($oParentBlock);
}
@@ -1056,14 +1047,11 @@ HTML;
$sCurrentTabContainer = $this->m_oTabs->GetCurrentTabContainer();
$sCurrentTab = $this->m_oTabs->GetCurrentTab();
if (!empty($sCurrentTabContainer) && !empty($sCurrentTab))
{
if (!empty($sCurrentTabContainer) && !empty($sCurrentTab)) {
$iOffset = $this->m_oTabs->GetCurrentTabLength();
return array('tc' => $sCurrentTabContainer, 'tab' => $sCurrentTab, 'offset' => $iOffset);
}
else
{
return ['tc' => $sCurrentTabContainer, 'tab' => $sCurrentTab, 'offset' => $iOffset];
} else {
return parent::start_capture();
}
}
@@ -1073,19 +1061,13 @@ HTML;
*/
public function end_capture($offset)
{
if (is_array($offset))
{
if ($this->m_oTabs->TabExists($offset['tc'], $offset['tab']))
{
if (is_array($offset)) {
if ($this->m_oTabs->TabExists($offset['tc'], $offset['tab'])) {
$sCaptured = $this->m_oTabs->TruncateTab($offset['tc'], $offset['tab'], $offset['offset']);
}
else
{
} else {
$sCaptured = '';
}
}
else
{
} else {
$sCaptured = parent::end_capture($offset);
}
@@ -1112,13 +1094,12 @@ HTML;
*/
public function AddApplicationMessage($sHtmlMessage, $sHtmlIcon = null, $sTip = null)
{
if (strlen($sHtmlMessage))
{
$this->m_aMessages[] = array(
if (strlen($sHtmlMessage)) {
$this->m_aMessages[] = [
'icon' => $sHtmlIcon,
'message' => $sHtmlMessage,
'tip' => $sTip,
);
];
}
}

View File

@@ -51,7 +51,6 @@ class iTopNewsroomController extends Controller
public const DEFAULT_NEWSROOM_MIN_DISPLAY_SIZE = 1;
public const DEFAULT_NEWSROOM_MAX_DISPLAY_SIZE = 20;
/**
* @return iTopWebPage
* @throws \ApplicationException

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -16,7 +17,7 @@ use ValueSetEnum;
*/
class AttributeApplicationLanguage extends AttributeString
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_STRING;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_STRING;
public static function ListExpectedParams()
{
@@ -27,7 +28,7 @@ class AttributeApplicationLanguage extends AttributeString
{
$this->m_sCode = $sCode;
$aAvailableLanguages = Dict::GetLanguages();
$aLanguageCodes = array();
$aLanguageCodes = [];
foreach ($aAvailableLanguages as $sLangCode => $aInfo) {
$aLanguageCodes[$sLangCode] = $aInfo['description'].' ('.$aInfo['localized_description'].')';
}
@@ -50,4 +51,4 @@ class AttributeApplicationLanguage extends AttributeString
{
return '=';
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -41,4 +42,4 @@ class AttributeArchiveDate extends AttributeDate
return parent::GetDescription($sDefault);
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -12,13 +13,13 @@ class AttributeArchiveFlag extends AttributeBoolean
{
public function __construct($sCode)
{
parent::__construct($sCode, array(
parent::__construct($sCode, [
"allowed_values" => null,
"sql" => $sCode,
"default_value" => false,
"is_null_allowed" => false,
"depends_on" => array(),
));
"depends_on" => [],
]);
}
public function RequiresIndex()
@@ -54,4 +55,4 @@ class AttributeArchiveFlag extends AttributeBoolean
return parent::GetDescription($sDefault);
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -22,7 +23,7 @@ use utils;
*/
class AttributeBlob extends AttributeDefinition
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_RAW;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_RAW;
/**
* Useless constructor, but if not present PHP 7.4.0/7.4.1 is crashing :( (N°2329)
@@ -43,7 +44,7 @@ class AttributeBlob extends AttributeDefinition
public static function ListExpectedParams()
{
return array_merge(parent::ListExpectedParams(), array("depends_on"));
return array_merge(parent::ListExpectedParams(), ["depends_on"]);
}
public function GetEditClass()
@@ -101,8 +102,7 @@ class AttributeBlob extends AttributeDefinition
try {
// Read the file from iTop, an URL (or the local file system - for admins only)
$proposedValue = utils::FileGetContentsAndMIMEType($proposedValue);
}
catch (Exception $e) {
} catch (Exception $e) {
IssueLog::Warning(get_class($this)."::MakeRealValue - ".$e->getMessage());
// Not a real document !! store is as text !!! (This was the default behavior before)
$proposedValue = new ormDocument($e->getMessage()." \n".$proposedValue, 'text/plain');
@@ -117,7 +117,7 @@ class AttributeBlob extends AttributeDefinition
if ($sPrefix == '') {
$sPrefix = $this->GetCode();
}
$aColumns = array();
$aColumns = [];
// Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
$aColumns[''] = $sPrefix.'_mimetype';
$aColumns['_data'] = $sPrefix.'_data';
@@ -167,7 +167,7 @@ class AttributeBlob extends AttributeDefinition
// We will have to remove the blobs from the list of attributes when doing the select
// then the use of Get() should finalize the load
if ($value instanceof ormDocument) {
$aValues = array();
$aValues = [];
if (!$value->IsEmpty()) {
$aValues[$this->GetCode().'_data'] = $value->GetData();
} else {
@@ -177,7 +177,7 @@ class AttributeBlob extends AttributeDefinition
$aValues[$this->GetCode().'_filename'] = $value->GetFileName();
$aValues[$this->GetCode().'_downloads_count'] = $value->GetDownloadsCount();
} else {
$aValues = array();
$aValues = [];
$aValues[$this->GetCode().'_data'] = '';
$aValues[$this->GetCode().'_mimetype'] = '';
$aValues[$this->GetCode().'_filename'] = '';
@@ -189,7 +189,7 @@ class AttributeBlob extends AttributeDefinition
public function GetSQLColumns($bFullSpec = false)
{
$aColumns = array();
$aColumns = [];
$aColumns[$this->GetCode().'_data'] = 'LONGBLOB'; // 2^32 (4 Gb)
$aColumns[$this->GetCode().'_mimetype'] = 'VARCHAR(255)'.CMDBSource::GetSqlStringColumnDefinition();
$aColumns[$this->GetCode().'_filename'] = 'VARCHAR(255)'.CMDBSource::GetSqlStringColumnDefinition();
@@ -200,7 +200,7 @@ class AttributeBlob extends AttributeDefinition
public function GetBasicFilterOperators()
{
return array();
return [];
}
public function GetBasicFilterLooseOperator()
@@ -233,10 +233,13 @@ class AttributeBlob extends AttributeDefinition
* @return string
*/
public function GetAsCSV(
$sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true,
$sValue,
$sSeparator = ',',
$sTextQualifier = '"',
$oHostObject = null,
$bLocalize = true,
$bConvertToPlainText = false
)
{
) {
$sAttCode = $this->GetCode();
if ($sValue instanceof ormDocument && !$sValue->IsEmpty()) {
return $sValue->GetDownloadURL(get_class($oHostObject), $oHostObject->GetKey(), $sAttCode);
@@ -271,7 +274,7 @@ class AttributeBlob extends AttributeDefinition
public function GetForJSON($value)
{
if ($value instanceof ormDocument) {
$aValues = array();
$aValues = [];
$aValues['data'] = base64_encode($value->GetData());
$aValues['mimetype'] = $value->GetMimeType();
$aValues['filename'] = $value->GetFileName();
@@ -383,4 +386,4 @@ class AttributeBlob extends AttributeDefinition
{
return CMDBChangeOpSetAttributeBlob::class;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -18,7 +19,7 @@ use Dict;
*/
class AttributeBoolean extends AttributeInteger
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_RAW;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_RAW;
/**
* Useless constructor, but if not present PHP 7.4.0/7.4.1 is crashing :( (N°2329)
@@ -97,8 +98,11 @@ class AttributeBoolean extends AttributeInteger
} else {
$sValue = $bValue ? 'yes' : 'no';
$sDefault = Dict::S('Core:'.get_class($this).'/Value:'.$sValue.'+');
$sDescription = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/Value:'.$sValue.'+', $sDefault,
true /*user lang*/);
$sDescription = $this->SearchLabel(
'/Attribute:'.$this->m_sCode.'/Value:'.$sValue.'+',
$sDefault,
true /*user lang*/
);
}
return $sDescription;
@@ -135,10 +139,13 @@ class AttributeBoolean extends AttributeInteger
}
public function GetAsCSV(
$bValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true,
$bValue,
$sSeparator = ',',
$sTextQualifier = '"',
$oHostObject = null,
$bLocalize = true,
$bConvertToPlainText = false
)
{
) {
if (is_null($bValue)) {
$sFinalValue = '';
} elseif ($bLocalize) {
@@ -170,7 +177,7 @@ class AttributeBoolean extends AttributeInteger
$oFormField = new $sFormFieldClass($this->GetCode());
}
$oFormField->SetChoices(array('yes' => $this->GetValueLabel(true), 'no' => $this->GetValueLabel(false)));
$oFormField->SetChoices(['yes' => $this->GetValueLabel(true), 'no' => $this->GetValueLabel(false)]);
parent::MakeFormField($oObject, $oFormField);
return $oFormField;
@@ -191,10 +198,13 @@ class AttributeBoolean extends AttributeInteger
}
public function MakeValueFromString(
$sProposedValue, $bLocalizedValue = false, $sSepItem = null, $sSepAttribute = null, $sSepValue = null,
$sProposedValue,
$bLocalizedValue = false,
$sSepItem = null,
$sSepAttribute = null,
$sSepValue = null,
$sAttributeQualifier = null
)
{
) {
$sInput = mb_strtolower(trim($sProposedValue));
if ($bLocalizedValue) {
switch ($sInput) {
@@ -238,7 +248,7 @@ class AttributeBoolean extends AttributeInteger
return CMDBChangeOpSetAttributeScalar::class;
}
public function GetAllowedValues($aArgs = array(), $sContains = ''): array
public function GetAllowedValues($aArgs = [], $sContains = ''): array
{
return [
0 => $this->GetValueLabel(false),
@@ -250,4 +260,4 @@ class AttributeBoolean extends AttributeInteger
{
return $this->GetOptional('display_style', 'select');
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -25,7 +26,7 @@ use utils;
*/
class AttributeCaseLog extends AttributeLongText
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_STRING;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_STRING;
/**
* Useless constructor, but if not present PHP 7.4.0/7.4.1 is crashing :( (N°2329)
@@ -74,16 +75,15 @@ class AttributeCaseLog extends AttributeLongText
return $proposedValue->GetEntryCount() > 0;
}
public function ScalarToSQL($value)
{
if (!is_string($value) && !is_null($value)) {
throw new CoreWarning('Expected the attribute value to be a string', array(
throw new CoreWarning('Expected the attribute value to be a string', [
'found_type' => gettype($value),
'value' => $value,
'class' => $this->GetCode(),
'attribute' => $this->GetHostClass(),
));
]);
}
return $value;
@@ -131,7 +131,6 @@ class AttributeCaseLog extends AttributeLongText
return ($val1->GetText() == $val2->GetText());
}
/**
* Facilitate things: allow the user to Set the value from a string
*
@@ -153,7 +152,8 @@ class AttributeCaseLog extends AttributeLongText
if ($oHostObj != null) {
$oPreviousLog = $oHostObj->Get($this->GetCode());
if (!is_object($oPreviousLog)) {
$oPreviousLog = $oHostObj->GetOriginal($this->GetCode());;
$oPreviousLog = $oHostObj->GetOriginal($this->GetCode());
;
}
}
@@ -187,7 +187,7 @@ class AttributeCaseLog extends AttributeLongText
if ($sPrefix == '') {
$sPrefix = $this->Get('sql');
}
$aColumns = array();
$aColumns = [];
// Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
$aColumns[''] = $sPrefix;
$aColumns['_index'] = $sPrefix.'_index';
@@ -232,7 +232,7 @@ class AttributeCaseLog extends AttributeLongText
if (!($value instanceof ormCaseLog)) {
$value = new ormCaseLog('');
}
$aValues = array();
$aValues = [];
$aValues[$this->GetCode()] = $value->GetText();
$aValues[$this->GetCode().'_index'] = serialize($value->GetIndex());
@@ -241,7 +241,7 @@ class AttributeCaseLog extends AttributeLongText
public function GetSQLColumns($bFullSpec = false)
{
$aColumns = array();
$aColumns = [];
$aColumns[$this->GetCode()] = 'LONGTEXT' // 2^32 (4 Gb)
.CMDBSource::GetSqlStringColumnDefinition();
$aColumns[$this->GetCode().'_index'] = 'BLOB';
@@ -252,11 +252,11 @@ class AttributeCaseLog extends AttributeLongText
public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
{
if ($value instanceof ormCaseLog) {
$sContent = $value->GetAsHTML(null, false, array(__class__, 'RenderWikiHtml'));
$sContent = $value->GetAsHTML(null, false, [__class__, 'RenderWikiHtml']);
} else {
$sContent = '';
}
$aStyles = array();
$aStyles = [];
if ($this->GetWidth() != '') {
$aStyles[] = 'width:'.$this->GetWidth();
}
@@ -271,15 +271,23 @@ class AttributeCaseLog extends AttributeLongText
return "<div class=\"caselog\" $sStyle>".$sContent.'</div>';
}
public function GetAsCSV(
$value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true,
$value,
$sSeparator = ',',
$sTextQualifier = '"',
$oHostObject = null,
$bLocalize = true,
$bConvertToPlainText = false
)
{
) {
if ($value instanceof ormCaseLog) {
return parent::GetAsCSV($value->GetText($bConvertToPlainText), $sSeparator, $sTextQualifier, $oHostObject,
$bLocalize, $bConvertToPlainText);
return parent::GetAsCSV(
$value->GetText($bConvertToPlainText),
$sSeparator,
$sTextQualifier,
$oHostObject,
$bLocalize,
$bConvertToPlainText
);
} else {
return '';
}
@@ -299,12 +307,12 @@ class AttributeCaseLog extends AttributeLongText
*/
public function EnumTemplateVerbs()
{
return array(
return [
'' => 'Plain text representation of all the log entries',
'head' => 'Plain text representation of the latest entry',
'head_html' => 'HTML representation of the latest entry',
'html' => 'HTML representation of all the log entries',
);
];
}
/**
@@ -410,4 +418,4 @@ class AttributeCaseLog extends AttributeLongText
{
return CMDBChangeOpSetAttributeCaseLog::class;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -17,11 +18,11 @@ use ValueSetEnumClasses;
*/
class AttributeClass extends AttributeString
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_ENUM;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_ENUM;
public static function ListExpectedParams()
{
return array_merge(parent::ListExpectedParams(), array('class_category', 'more_values'));
return array_merge(parent::ListExpectedParams(), ['class_category', 'more_values']);
}
public function __construct($sCode, $aParams)
@@ -53,7 +54,7 @@ class AttributeClass extends AttributeString
* @return array|null
* @throws \CoreException
*/
public function GetAllowedValues($aArgs = array(), $sContains = '')
public function GetAllowedValues($aArgs = [], $sContains = '')
{
$oValSetDef = $this->GetValuesDef();
if (!$oValSetDef) {
@@ -91,4 +92,4 @@ class AttributeClass extends AttributeString
return '=';
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -15,9 +16,9 @@ use utils;
class AttributeClassAttCodeSet extends AttributeSet
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_STRING;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_STRING;
const DEFAULT_PARAM_INCLUDE_CHILD_CLASSES_ATTRIBUTES = false;
public const DEFAULT_PARAM_INCLUDE_CHILD_CLASSES_ATTRIBUTES = false;
public function __construct($sCode, array $aParams)
{
@@ -27,7 +28,7 @@ class AttributeClassAttCodeSet extends AttributeSet
public static function ListExpectedParams()
{
return array_merge(parent::ListExpectedParams(), array('class_field', 'attribute_definition_list', 'attribute_definition_exclusion_list'));
return array_merge(parent::ListExpectedParams(), ['class_field', 'attribute_definition_list', 'attribute_definition_exclusion_list']);
}
public function GetMaxSize()
@@ -42,7 +43,7 @@ class AttributeClassAttCodeSet extends AttributeSet
* @return array|null
* @throws \CoreException
*/
public function GetAllowedValues($aArgs = array(), $sContains = '')
public function GetAllowedValues($aArgs = [], $sContains = '')
{
if (!isset($aArgs['this'])) {
return null;
@@ -53,7 +54,7 @@ class AttributeClassAttCodeSet extends AttributeSet
$sRootClass = $oHostObj->Get($sTargetClass);
$bIncludeChildClasses = $this->GetOptional('include_child_classes_attributes', static::DEFAULT_PARAM_INCLUDE_CHILD_CLASSES_ATTRIBUTES);
$aExcludeDefs = array();
$aExcludeDefs = [];
$sAttDefExclusionList = $this->Get('attribute_definition_exclusion_list');
if (!empty($sAttDefExclusionList)) {
foreach (explode(',', $sAttDefExclusionList) as $sAttDefName) {
@@ -62,7 +63,7 @@ class AttributeClassAttCodeSet extends AttributeSet
}
}
$aAllowedDefs = array();
$aAllowedDefs = [];
$sAttDefList = $this->Get('attribute_definition_list');
if (!empty($sAttDefList)) {
foreach (explode(',', $sAttDefList) as $sAttDefName) {
@@ -71,9 +72,9 @@ class AttributeClassAttCodeSet extends AttributeSet
}
}
$aAllAttributes = array();
$aAllAttributes = [];
if (!empty($sRootClass)) {
$aClasses = array($sRootClass);
$aClasses = [$sRootClass];
if ($bIncludeChildClasses === true) {
$aClasses = $aClasses + MetaModel::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_EXCLUDETOP);
}
@@ -94,9 +95,9 @@ class AttributeClassAttCodeSet extends AttributeSet
continue;
}
$aAllAttributes[$sAttCode] = array(
'classes' => array($sClass),
);
$aAllAttributes[$sAttCode] = [
'classes' => [$sClass],
];
} else {
$aAllAttributes[$sAttCode]['classes'][] = $sClass;
}
@@ -104,7 +105,7 @@ class AttributeClassAttCodeSet extends AttributeSet
}
}
$aAllowedAttributes = array();
$aAllowedAttributes = [];
foreach ($aAllAttributes as $sAttCode => $aAttData) {
$iAttClassesCount = count($aAttData['classes']);
$sAttFirstClass = $aAttData['classes'][0];
@@ -141,18 +142,18 @@ class AttributeClassAttCodeSet extends AttributeSet
public function MakeRealValue($proposedValue, $oHostObj, $bIgnoreErrors = false)
{
$oSet = new ormSet(MetaModel::GetAttributeOrigin($this->GetHostClass(), $this->GetCode()), $this->GetCode(), $this->GetMaxItems());
$aArgs = array();
$aArgs = [];
if (!empty($oHostObj)) {
$aArgs['this'] = $oHostObj;
}
$aAllowedAttributes = $this->GetAllowedValues($aArgs);
$aInvalidAttCodes = array();
$aInvalidAttCodes = [];
if (is_string($proposedValue) && !empty($proposedValue)) {
$aJsonFromWidget = json_decode($proposedValue, true);
if (is_null($aJsonFromWidget)) {
$proposedValue = trim($proposedValue);
$aProposedValues = $this->FromStringToArray($proposedValue);
$aValues = array();
$aValues = [];
foreach ($aProposedValues as $sValue) {
$sAttCode = trim($sValue);
if (empty($aAllowedAttributes) || isset($aAllowedAttributes[$sAttCode])) {
@@ -194,7 +195,7 @@ class AttributeClassAttCodeSet extends AttributeSet
$sTargetClass = $this->Get('class_field');
$sClass = $oHostObject->Get($sTargetClass);
$aLocalizedValues = array();
$aLocalizedValues = [];
foreach ($value as $sAttCode) {
try {
$sAttClass = $sClass;
@@ -209,8 +210,7 @@ class AttributeClassAttCodeSet extends AttributeSet
$sLabelForHtmlAttribute = utils::HtmlEntities(MetaModel::GetLabel($sAttClass, $sAttCode)." ($sAttCode)");
$aLocalizedValues[] = '<span class="attribute-set-item" data-code="'.$sAttCode.'" data-label="'.$sLabelForHtmlAttribute.'" data-description="" data-tooltip-content="'.$sLabelForHtmlAttribute.'">'.$sAttCode.'</span>';
}
catch (Exception $e) {
} catch (Exception $e) {
// Ignore bad values
}
}
@@ -226,4 +226,4 @@ class AttributeClassAttCodeSet extends AttributeSet
{
return (empty($proposedValue));
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -16,7 +17,7 @@ use utils;
*/
class AttributeClassState extends AttributeString
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_STRING;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_STRING;
/**
* Useless constructor, but if not present PHP 7.4.0/7.4.1 is crashing :( (N°2329)
@@ -37,17 +38,17 @@ class AttributeClassState extends AttributeString
public static function ListExpectedParams()
{
return array_merge(parent::ListExpectedParams(), array('class_field'));
return array_merge(parent::ListExpectedParams(), ['class_field']);
}
public function GetAllowedValues($aArgs = array(), $sContains = '')
public function GetAllowedValues($aArgs = [], $sContains = '')
{
if (isset($aArgs['this'])) {
$oHostObj = $aArgs['this'];
$sTargetClass = $this->Get('class_field');
$sClass = $oHostObj->Get($sTargetClass);
$aAllowedStates = array();
$aAllowedStates = [];
foreach (MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL) as $sChildClass) {
$aValues = MetaModel::EnumStates($sChildClass);
foreach (array_keys($aValues) as $sState) {
@@ -84,4 +85,4 @@ class AttributeClassState extends AttributeString
return $sValue;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -21,7 +22,7 @@ use utils;
*/
class AttributeCustomFields extends AttributeDefinition
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_RAW;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_RAW;
/**
* Useless constructor, but if not present PHP 7.4.0/7.4.1 is crashing :( (N°2329)
@@ -42,7 +43,7 @@ class AttributeCustomFields extends AttributeDefinition
public static function ListExpectedParams()
{
return array_merge(parent::ListExpectedParams(), array("handler_class"));
return array_merge(parent::ListExpectedParams(), ["handler_class"]);
}
public function GetEditClass()
@@ -67,7 +68,7 @@ class AttributeCustomFields extends AttributeDefinition
public function GetBasicFilterOperators()
{
return array();
return [];
}
public function GetBasicFilterLooseOperator()
@@ -198,8 +199,7 @@ class AttributeCustomFields extends AttributeDefinition
$sFormId = utils::IsNullOrEmptyString($sFormPrefix) ? 'cf_'.$this->GetCode() : $sFormPrefix.'_cf_'.$this->GetCode();
$oHandler->BuildForm($oHostObject, $sFormId);
$oForm = $oHandler->GetForm();
}
catch (Exception $e) {
} catch (Exception $e) {
$oForm = new \Combodo\iTop\Form\Form('');
$oField = new \Combodo\iTop\Form\Field\LabelField('');
$oField->SetLabel('Custom field error: '.$e->getMessage());
@@ -225,8 +225,7 @@ class AttributeCustomFields extends AttributeDefinition
$oHandler = $this->GetHandler();
$aValues = $oHandler->ReadValues($oHostObject);
$oRet = new ormCustomFieldsValue($oHostObject, $this->GetCode(), $aValues);
}
catch (Exception $e) {
} catch (Exception $e) {
$oRet = new ormCustomFieldsValue($oHostObject, $this->GetCode());
}
@@ -243,7 +242,7 @@ class AttributeCustomFields extends AttributeDefinition
$oValue = $oHostObject->Get($this->GetCode());
if (!($oValue instanceof ormCustomFieldsValue)) {
$oHandler = $this->GetHandler();
$aValues = array();
$aValues = [];
} else {
// Pass the values through the form to make sure that they are correct
$oHandler = $this->GetHandler($oValue->GetValues());
@@ -283,8 +282,7 @@ class AttributeCustomFields extends AttributeDefinition
$oHandler = $this->GetHandler($value->GetValues());
$oHandler->BuildForm($oHostObject, '');
$ret = $oHandler->Validate($oHostObject);
}
catch (Exception $e) {
} catch (Exception $e) {
$ret = $e->getMessage();
}
@@ -312,8 +310,7 @@ class AttributeCustomFields extends AttributeDefinition
try {
/** @var ormCustomFieldsValue $value */
$sRet = $value->GetAsHTML($bLocalize);
}
catch (Exception $e) {
} catch (Exception $e) {
$sRet = 'Custom field error: '.utils::EscapeHtml($e->getMessage());
}
@@ -324,8 +321,7 @@ class AttributeCustomFields extends AttributeDefinition
{
try {
$sRet = $value->GetAsXML($bLocalize);
}
catch (Exception $e) {
} catch (Exception $e) {
$sRet = Str::pure2xml('Custom field error: '.$e->getMessage());
}
@@ -344,16 +340,18 @@ class AttributeCustomFields extends AttributeDefinition
* @noinspection PhpParameterNameChangedDuringInheritanceInspection
*/
public function GetAsCSV(
$value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true,
$value,
$sSeparator = ',',
$sTextQualifier = '"',
$oHostObject = null,
$bLocalize = true,
$bConvertToPlainText = false
)
{
) {
try {
$sRet = $value->GetAsCSV($sSeparator, $sTextQualifier, $bLocalize, $bConvertToPlainText);
}
catch (Exception $e) {
$sFrom = array("\r\n", $sTextQualifier);
$sTo = array("\n", $sTextQualifier.$sTextQualifier);
} catch (Exception $e) {
$sFrom = ["\r\n", $sTextQualifier];
$sTo = ["\n", $sTextQualifier.$sTextQualifier];
$sEscaped = str_replace($sFrom, $sTo, 'Custom field error: '.$e->getMessage());
$sRet = $sTextQualifier.$sEscaped.$sTextQualifier;
}
@@ -385,8 +383,7 @@ class AttributeCustomFields extends AttributeDefinition
{
try {
$sRet = $value->GetForTemplate($sVerb, $bLocalize);
}
catch (Exception $e) {
} catch (Exception $e) {
$sRet = 'Custom field error: '.$e->getMessage();
}
@@ -394,10 +391,13 @@ class AttributeCustomFields extends AttributeDefinition
}
public function MakeValueFromString(
$sProposedValue, $bLocalizedValue = false, $sSepItem = null, $sSepAttribute = null, $sSepValue = null,
$sProposedValue,
$bLocalizedValue = false,
$sSepItem = null,
$sSepAttribute = null,
$sSepValue = null,
$sAttributeQualifier = null
)
{
) {
return null;
}
@@ -414,8 +414,7 @@ class AttributeCustomFields extends AttributeDefinition
{
try {
$sRet = $value->GetForJSON();
}
catch (Exception $e) {
} catch (Exception $e) {
$sRet = 'Custom field error: '.$e->getMessage();
}
@@ -438,8 +437,7 @@ class AttributeCustomFields extends AttributeDefinition
{
try {
$bEquals = $val1->Equals($val2);
}
catch (Exception $e) {
} catch (Exception $e) {
$bEquals = false;
}
@@ -468,4 +466,4 @@ class AttributeCustomFields extends AttributeDefinition
{
return CMDBChangeOpSetAttributeCustomFields::class;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -17,7 +18,7 @@ class AttributeDBField extends AttributeDBFieldVoid
{
public static function ListExpectedParams()
{
return array_merge(parent::ListExpectedParams(), array("default_value", "is_null_allowed"));
return array_merge(parent::ListExpectedParams(), ["default_value", "is_null_allowed"]);
}
public function GetDefaultValue(DBObject $oHostObject = null)
@@ -29,4 +30,4 @@ class AttributeDBField extends AttributeDBFieldVoid
{
return $this->Get("is_null_allowed");
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -18,7 +19,7 @@ class AttributeDBFieldVoid extends AttributeDefinition
{
public static function ListExpectedParams()
{
return array_merge(parent::ListExpectedParams(), array("allowed_values", "depends_on", "sql"));
return array_merge(parent::ListExpectedParams(), ["allowed_values", "depends_on", "sql"]);
}
// To be overriden, used in GetSQLColumns
@@ -100,7 +101,7 @@ class AttributeDBFieldVoid extends AttributeDefinition
public function GetSQLExpressions($sPrefix = '')
{
$aColumns = array();
$aColumns = [];
// Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
$aColumns[''] = $this->Get("sql");
@@ -116,7 +117,7 @@ class AttributeDBFieldVoid extends AttributeDefinition
public function GetSQLValues($value)
{
$aValues = array();
$aValues = [];
$aValues[$this->Get("sql")] = $this->ScalarToSQL($value);
return $aValues;
@@ -124,7 +125,7 @@ class AttributeDBFieldVoid extends AttributeDefinition
public function GetSQLColumns($bFullSpec = false)
{
$aColumns = array();
$aColumns = [];
$aColumns[$this->Get("sql")] = $this->GetSQLCol($bFullSpec);
return $aColumns;
@@ -132,7 +133,7 @@ class AttributeDBFieldVoid extends AttributeDefinition
public function GetBasicFilterOperators()
{
return array("=" => "equals", "!=" => "differs from");
return ["=" => "equals", "!=" => "differs from"];
}
public function GetBasicFilterLooseOperator()
@@ -152,4 +153,4 @@ class AttributeDBFieldVoid extends AttributeDefinition
return $this->GetSQLExpr()." = $sQValue";
}
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -32,8 +33,10 @@ class AttributeDashboard extends AttributeDefinition
public static function ListExpectedParams()
{
return array_merge(parent::ListExpectedParams(),
array("definition_file", "is_user_editable"));
return array_merge(
parent::ListExpectedParams(),
["definition_file", "is_user_editable"]
);
}
public function GetDashboard()
@@ -67,7 +70,7 @@ class AttributeDashboard extends AttributeDefinition
public function GetBasicFilterOperators()
{
return array();
return [];
}
public function GetBasicFilterLooseOperator()
@@ -107,4 +110,4 @@ class AttributeDashboard extends AttributeDefinition
// Always return false for now, we don't consider a custom version of a dashboard
return false;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -17,7 +18,7 @@ use DBObject;
*/
class AttributeDate extends AttributeDateTime
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_DATE;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_DATE;
public static $oDateFormat = null;
@@ -91,13 +92,12 @@ class AttributeDate extends AttributeDateTime
public function GetImportColumns()
{
// Allow an empty string to be a valid value (synonym for "reset")
$aColumns = array();
$aColumns = [];
$aColumns[$this->GetCode()] = 'VARCHAR(10)'.CMDBSource::GetSqlStringColumnDefinition();
return $aColumns;
}
/**
* Override to specify Field class
*
@@ -112,4 +112,4 @@ class AttributeDate extends AttributeDateTime
return $oFormField;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -30,7 +31,7 @@ use VariableExpression;
*/
class AttributeDateTime extends AttributeDBField
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_DATE_TIME;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_DATE_TIME;
public static $oFormat = null;
@@ -75,7 +76,7 @@ class AttributeDateTime extends AttributeDBField
$sTimeFormat = isset($aFormats[$sLang]['time']) ? $aFormats[$sLang]['time'] : (isset($aFormats['default']['time']) ? $aFormats['default']['time'] : 'H:i:s');
$sDateAndTimeFormat = isset($aFormats[$sLang]['date_time']) ? $aFormats[$sLang]['date_time'] : (isset($aFormats['default']['date_time']) ? $aFormats['default']['date_time'] : '$date $time');
$sFullFormat = str_replace(array('$date', '$time'), array($sDateFormat, $sTimeFormat), $sDateAndTimeFormat);
$sFullFormat = str_replace(['$date', '$time'], [$sDateFormat, $sTimeFormat], $sDateAndTimeFormat);
self::SetFormat(new DateTimeFormat($sFullFormat));
AttributeDate::SetFormat(new DateTimeFormat($sDateFormat));
@@ -123,8 +124,7 @@ class AttributeDateTime extends AttributeDBField
try {
$oDateTime = $this->GetFormat()->Parse($sSearchString);
$sSearchString = $oDateTime->format($this->GetInternalFormat());
}
catch (Exception $e) {
} catch (Exception $e) {
$sFormatString = '!'.(string)AttributeDate::GetFormat(); // BEWARE: ! is needed to set non-parsed fields to zero !!!
$oDateTime = DateTime::createFromFormat($sFormatString, $sSearchString);
if ($oDateTime !== false) {
@@ -164,7 +164,6 @@ class AttributeDateTime extends AttributeDBField
}
$oFormField->SetCurrentValue($this->GetFormat()->Format($oValue));
return $oFormField;
}
@@ -173,10 +172,10 @@ class AttributeDateTime extends AttributeDBField
*/
public function EnumTemplateVerbs()
{
return array(
return [
'' => 'Formatted representation',
'raw' => 'Not formatted representation',
);
];
}
/**
@@ -213,7 +212,6 @@ class AttributeDateTime extends AttributeDBField
return "DateTime";
}
public function GetEditValue($sValue, $oHostObj = null)
{
return (string)static::GetFormat()->format($sValue);
@@ -232,7 +230,7 @@ class AttributeDateTime extends AttributeDBField
public function GetImportColumns()
{
// Allow an empty string to be a valid value (synonym for "reset")
$aColumns = array();
$aColumns = [];
$aColumns[$this->GetCode()] = 'VARCHAR(19)'.CMDBSource::GetSqlStringColumnDefinition();
return $aColumns;
@@ -252,12 +250,10 @@ class AttributeDateTime extends AttributeDBField
if (utils::IsNotNullOrEmptyString($sDefaultValue)) {
try {
$sDefaultDate = Expression::FromOQL($sDefaultValue)->Evaluate([]);
}
catch (Exception $e) {
} catch (Exception $e) {
try {
$sDefaultDate = Expression::FromOQL('"'.$sDefaultValue.'"')->Evaluate([]);
}
catch (Exception $e) {
} catch (Exception $e) {
IssueLog::Error("Invalid default value '$sDefaultValue' for field '{$this->GetCode()}' on class '{$this->GetHostClass()}', defaulting to null");
return $this->GetNullValue();
@@ -265,8 +261,7 @@ class AttributeDateTime extends AttributeDBField
}
try {
$oDate = new DateTimeImmutable($sDefaultDate);
}
catch (Exception $e) {
} catch (Exception $e) {
IssueLog::Error("Invalid default value '$sDefaultValue' for field '{$this->GetCode()}' on class '{$this->GetHostClass()}', defaulting to null");
return $this->GetNullValue();
@@ -285,7 +280,7 @@ class AttributeDateTime extends AttributeDBField
public function GetBasicFilterOperators()
{
return array(
return [
"=" => "equals",
"!=" => "differs from",
"<" => "before",
@@ -299,7 +294,7 @@ class AttributeDateTime extends AttributeDBField
">|" => "after today + N days",
"<|" => "before today + N days",
"=|" => "equals today + N days",
);
];
}
public function GetBasicFilterLooseOperator()
@@ -370,8 +365,7 @@ class AttributeDateTime extends AttributeDBField
try {
$oFormat = new DateTimeFormat(static::GetInternalFormat());
$oFormat->Parse($proposedValue);
}
catch (Exception $e) {
} catch (Exception $e) {
throw new CoreUnexpectedValue('Wrong format for date attribute '.$this->GetCode().', expecting "'.$this->GetInternalFormat().'" and got "'.$proposedValue.'"');
}
@@ -401,10 +395,13 @@ class AttributeDateTime extends AttributeDBField
}
public function GetAsCSV(
$sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true,
$sValue,
$sSeparator = ',',
$sTextQualifier = '"',
$oHostObject = null,
$bLocalize = true,
$bConvertToPlainText = false
)
{
) {
if (empty($sValue) || ($sValue === '0000-00-00 00:00:00') || ($sValue === '0000-00-00')) {
return '';
} else {
@@ -416,8 +413,8 @@ class AttributeDateTime extends AttributeDBField
}
}
}
$sFrom = array("\r\n", $sTextQualifier);
$sTo = array("\n", $sTextQualifier.$sTextQualifier);
$sFrom = ["\r\n", $sTextQualifier];
$sTo = ["\n", $sTextQualifier.$sTextQualifier];
$sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
return $sTextQualifier.$sEscaped.$sTextQualifier;
@@ -437,20 +434,22 @@ class AttributeDateTime extends AttributeDBField
* @throws CoreException
*/
public function GetSmartConditionExpression(
$sSearchText, FieldExpression $oField, &$aParams, $bParseSearchString = false
)
{
$sSearchText,
FieldExpression $oField,
&$aParams,
$bParseSearchString = false
) {
// Possible smart patterns
$aPatterns = array(
'between' => array('pattern' => '/^\[(.*),(.*)\]$/', 'operator' => 'n/a'),
'greater than or equal' => array('pattern' => '/^>=(.*)$/', 'operator' => '>='),
'greater than' => array('pattern' => '/^>(.*)$/', 'operator' => '>'),
'less than or equal' => array('pattern' => '/^<=(.*)$/', 'operator' => '<='),
'less than' => array('pattern' => '/^<(.*)$/', 'operator' => '<'),
);
$aPatterns = [
'between' => ['pattern' => '/^\[(.*),(.*)\]$/', 'operator' => 'n/a'],
'greater than or equal' => ['pattern' => '/^>=(.*)$/', 'operator' => '>='],
'greater than' => ['pattern' => '/^>(.*)$/', 'operator' => '>'],
'less than or equal' => ['pattern' => '/^<=(.*)$/', 'operator' => '<='],
'less than' => ['pattern' => '/^<(.*)$/', 'operator' => '<'],
];
$sPatternFound = '';
$aMatches = array();
$aMatches = [];
foreach ($aPatterns as $sPatName => $sPattern) {
if (preg_match($sPattern['pattern'], $sSearchText, $aMatches)) {
$sPatternFound = $sPatName;
@@ -506,7 +505,6 @@ class AttributeDateTime extends AttributeDBField
return $oNewCondition;
}
public function GetHelpOnSmartSearch()
{
$sDict = parent::GetHelpOnSmartSearch();
@@ -514,6 +512,6 @@ class AttributeDateTime extends AttributeDBField
$oFormat = static::GetFormat();
$sExample = $oFormat->Format(new DateTime('2015-07-19 18:40:00'));
return vsprintf($sDict, array($oFormat->ToPlaceholder(), $sExample));
return vsprintf($sDict, [$oFormat->ToPlaceholder(), $sExample]);
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -54,13 +55,13 @@ class AttributeDeadline extends AttributeDateTime
$sDifference = Dict::Format('UI:DeadlineMissedBy_duration', self::FormatDuration(-$difference));
}
$sFormat = MetaModel::GetConfig()->Get('deadline_format');
$sResult = str_replace(array('$date$', '$difference$'), array($sDate, $sDifference), $sFormat);
$sResult = str_replace(['$date$', '$difference$'], [$sDate, $sDifference], $sFormat);
}
return $sResult;
}
static function FormatDuration($duration)
public static function FormatDuration($duration)
{
$days = floor($duration / 86400);
$hours = floor(($duration - (86400 * $days)) / 3600);
@@ -86,4 +87,4 @@ class AttributeDeadline extends AttributeDateTime
return $sResult;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -20,7 +21,7 @@ use utils;
*/
class AttributeDecimal extends AttributeDBField
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_NUMERIC;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_NUMERIC;
/**
* Useless constructor, but if not present PHP 7.4.0/7.4.1 is crashing :( (N°2329)
@@ -41,7 +42,7 @@ class AttributeDecimal extends AttributeDBField
public static function ListExpectedParams()
{
return array_merge(parent::ListExpectedParams(), array('digits', 'decimals' /* including precision */));
return array_merge(parent::ListExpectedParams(), ['digits', 'decimals' /* including precision */]);
}
public function GetEditClass()
@@ -76,7 +77,7 @@ class AttributeDecimal extends AttributeDBField
public function GetBasicFilterOperators()
{
return array(
return [
"!=" => "differs from",
"=" => "equals",
">" => "greater (strict) than",
@@ -84,7 +85,7 @@ class AttributeDecimal extends AttributeDBField
"<" => "less (strict) than",
"<=" => "less than",
"in" => "in",
);
];
}
public function GetBasicFilterLooseOperator()
@@ -166,4 +167,4 @@ class AttributeDecimal extends AttributeDBField
return $value; // null or string
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -63,7 +64,6 @@ define('DEL_MOVEUP', 3);
*/
define('DEL_NONE', 4);
/**
* For Link sets: tracking_level
*
@@ -87,11 +87,9 @@ define('LINKSET_EDITWHEN_ON_HOST_EDITION', 1); // The only possible action is to
define('LINKSET_EDITWHEN_ON_HOST_DISPLAY', 2); // Show the usual 'Actions' popup menu
define('LINKSET_EDITWHEN_ALWAYS', 3); // Show the usual 'Actions' popup menu
define('LINKSET_DISPLAY_STYLE_PROPERTY', 'property');
define('LINKSET_DISPLAY_STYLE_TAB', 'tab');
/**
* Wiki formatting - experimental
*
@@ -113,22 +111,21 @@ define('WIKI_OBJECT_REGEXP', '/\[\[(.+):(.+)(\|(.+))?\]\]/U');
*/
abstract class AttributeDefinition
{
const SEARCH_WIDGET_TYPE_RAW = 'raw';
const SEARCH_WIDGET_TYPE_STRING = 'string';
const SEARCH_WIDGET_TYPE_NUMERIC = 'numeric';
const SEARCH_WIDGET_TYPE_ENUM = 'enum';
const SEARCH_WIDGET_TYPE_EXTERNAL_KEY = 'external_key';
const SEARCH_WIDGET_TYPE_HIERARCHICAL_KEY = 'hierarchical_key';
const SEARCH_WIDGET_TYPE_EXTERNAL_FIELD = 'external_field';
const SEARCH_WIDGET_TYPE_DATE_TIME = 'date_time';
const SEARCH_WIDGET_TYPE_DATE = 'date';
const SEARCH_WIDGET_TYPE_SET = 'set';
const SEARCH_WIDGET_TYPE_TAG_SET = 'tag_set';
public const SEARCH_WIDGET_TYPE_RAW = 'raw';
public const SEARCH_WIDGET_TYPE_STRING = 'string';
public const SEARCH_WIDGET_TYPE_NUMERIC = 'numeric';
public const SEARCH_WIDGET_TYPE_ENUM = 'enum';
public const SEARCH_WIDGET_TYPE_EXTERNAL_KEY = 'external_key';
public const SEARCH_WIDGET_TYPE_HIERARCHICAL_KEY = 'hierarchical_key';
public const SEARCH_WIDGET_TYPE_EXTERNAL_FIELD = 'external_field';
public const SEARCH_WIDGET_TYPE_DATE_TIME = 'date_time';
public const SEARCH_WIDGET_TYPE_DATE = 'date';
public const SEARCH_WIDGET_TYPE_SET = 'set';
public const SEARCH_WIDGET_TYPE_TAG_SET = 'tag_set';
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_RAW;
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_RAW;
const INDEX_LENGTH = 95;
public const INDEX_LENGTH = 95;
protected $aCSSClasses;
@@ -223,7 +220,7 @@ abstract class AttributeDefinition
$this->m_sCode = $sCode;
$this->m_aParams = $aParams;
$this->ConsistencyCheck();
$this->aCSSClasses = array('attribute');
$this->aCSSClasses = ['attribute'];
}
public function GetParams()
@@ -253,7 +250,7 @@ abstract class AttributeDefinition
*/
public function ListSubItems()
{
$aSubItems = array();
$aSubItems = [];
foreach (MetaModel::ListAttributeDefs($this->m_sHostClass) as $sAttCode => $oAttDef) {
if ($oAttDef instanceof AttributeSubItem) {
if ($oAttDef->Get('target_attcode') == $this->m_sCode) {
@@ -269,7 +266,7 @@ abstract class AttributeDefinition
// to be overloaded
public static function ListExpectedParams()
{
return array();
return [];
}
/**
@@ -604,8 +601,7 @@ abstract class AttributeDefinition
$sSepAttribute = null,
$sSepValue = null,
$sAttributeQualifier = null
)
{
) {
return $this->MakeRealValue($sProposedValue, null);
}
@@ -692,7 +688,7 @@ abstract class AttributeDefinition
public function GetHelpOnSmartSearch()
{
$aParents = array_merge(array(get_class($this) => get_class($this)), class_parents($this));
$aParents = array_merge([get_class($this) => get_class($this)], class_parents($this));
foreach ($aParents as $sClass) {
$sHelp = Dict::S("Core:$sClass?SmartSearch", '-missing-');
if ($sHelp != '-missing-') {
@@ -733,7 +729,7 @@ abstract class AttributeDefinition
public function GetPrerequisiteAttributes($sClass = null)
{
return array();
return [];
}
public function GetNullValue()
@@ -783,7 +779,7 @@ abstract class AttributeDefinition
*/
public function GetSQLExpressions($sPrefix = '')
{
return array();
return [];
}
/**
@@ -806,7 +802,7 @@ abstract class AttributeDefinition
*/
public function GetSQLColumns($bFullSpec = false)
{
return array();
return [];
}
/**
@@ -816,7 +812,7 @@ abstract class AttributeDefinition
*/
public function GetSQLValues($value)
{
return array();
return [];
}
public function RequiresIndex()
@@ -837,7 +833,7 @@ abstract class AttributeDefinition
public function GetOrderBySQLExpressions($sClassAlias)
{
// Note: This is the responsibility of this function to place backticks around column aliases
return array('`'.$sClassAlias.$this->GetCode().'`');
return ['`'.$sClassAlias.$this->GetCode().'`'];
}
public function GetOrderByHint()
@@ -854,7 +850,7 @@ abstract class AttributeDefinition
public function FromImportToValue($aCols, $sPrefix = '')
{
$aValues = array();
$aValues = [];
foreach ($this->GetSQLExpressions($sPrefix) as $sAlias => $sExpr) {
// This is working, based on the assumption that importable fields
// are not computed fields => the expression is the name of a column
@@ -991,10 +987,13 @@ abstract class AttributeDefinition
* @return string
*/
public function GetAsCSV(
$sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true,
$sValue,
$sSeparator = ',',
$sTextQualifier = '"',
$oHostObject = null,
$bLocalize = true,
$bConvertToPlainText = false
)
{
) {
return (string)$sValue;
}
@@ -1110,12 +1109,12 @@ abstract class AttributeDefinition
*/
public function EnumTemplateVerbs()
{
return array(
return [
'' => 'Plain text (unlocalized) representation',
'html' => 'HTML representation',
'label' => 'Localized representation',
'text' => 'Plain text representation (without any markup)',
);
];
}
/**
@@ -1163,7 +1162,7 @@ abstract class AttributeDefinition
* @throws CoreException
* @throws OQLException
*/
public function GetAllowedValues($aArgs = array(), $sContains = '')
public function GetAllowedValues($aArgs = [], $sContains = '')
{
$oValSetDef = $this->GetValuesDef();
if (!$oValSetDef) {
@@ -1183,7 +1182,7 @@ abstract class AttributeDefinition
* @throws CoreException
* @throws OQLException
*/
public function GetAllowedValuesForSelect($aArgs = array(), $sContains = '')
public function GetAllowedValuesForSelect($aArgs = [], $sContains = '')
{
return $this->GetAllowedValues($aArgs, $sContains);
}
@@ -1220,13 +1219,11 @@ abstract class AttributeDefinition
if ((($this->GetType() == 'String') || ($this->GetType() == 'Text')) &&
(strlen($sNewValue) > strlen($sOldValue))) {
// Check if some text was not appended to the field
if (substr($sNewValue, 0, strlen($sOldValue)) == $sOldValue) // Text added at the end
{
if (substr($sNewValue, 0, strlen($sOldValue)) == $sOldValue) { // Text added at the end
$sDelta = $this->GetAsHTML(substr($sNewValue, strlen($sOldValue)));
$sResult = Dict::Format('Change:Text_AppendedTo_AttName', $sDelta, $sLabel);
} else {
if (substr($sNewValue, -strlen($sOldValue)) == $sOldValue) // Text added at the beginning
{
if (substr($sNewValue, -strlen($sOldValue)) == $sOldValue) { // Text added at the beginning
$sDelta = $this->GetAsHTML(substr($sNewValue, 0, strlen($sNewValue) - strlen($sOldValue)));
$sResult = Dict::Format('Change:Text_AppendedTo_AttName', $sDelta, $sLabel);
} else {
@@ -1236,8 +1233,12 @@ abstract class AttributeDefinition
if (is_null($sNewValue)) {
$sNewValueHtml = Dict::S('UI:UndefinedObject');
}
$sResult = Dict::Format('Change:AttName_SetTo_NewValue_PreviousValue_OldValue', $sLabel,
$sNewValueHtml, $sOldValueHtml);
$sResult = Dict::Format(
'Change:AttName_SetTo_NewValue_PreviousValue_OldValue',
$sLabel,
$sNewValueHtml,
$sOldValueHtml
);
}
}
}
@@ -1248,8 +1249,12 @@ abstract class AttributeDefinition
if (is_null($sNewValue)) {
$sNewValueHtml = Dict::S('UI:UndefinedObject');
}
$sResult = Dict::Format('Change:AttName_SetTo_NewValue_PreviousValue_OldValue', $sLabel, $sNewValueHtml,
$sOldValueHtml);
$sResult = Dict::Format(
'Change:AttName_SetTo_NewValue_PreviousValue_OldValue',
$sLabel,
$sNewValueHtml,
$sOldValueHtml
);
}
}
@@ -1379,4 +1384,4 @@ abstract class AttributeDefinition
return $sRenderFunction;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -92,12 +93,21 @@ class AttributeDuration extends AttributeInteger
} else {
if ($duration < 86400) {
// Less than 1 day, display it in hours/minutes/seconds
$sResult = Dict::Format('Core:Duration_Hours_Minutes_Seconds', $aDuration['hours'],
$aDuration['minutes'], $aDuration['seconds']);
$sResult = Dict::Format(
'Core:Duration_Hours_Minutes_Seconds',
$aDuration['hours'],
$aDuration['minutes'],
$aDuration['seconds']
);
} else {
// more than 1 day, display it in days/hours/minutes/seconds
$sResult = Dict::Format('Core:Duration_Days_Hours_Minutes_Seconds', $aDuration['days'],
$aDuration['hours'], $aDuration['minutes'], $aDuration['seconds']);
$sResult = Dict::Format(
'Core:Duration_Days_Hours_Minutes_Seconds',
$aDuration['days'],
$aDuration['hours'],
$aDuration['minutes'],
$aDuration['seconds']
);
}
}
}
@@ -105,7 +115,7 @@ class AttributeDuration extends AttributeInteger
return $sResult;
}
static function SplitDuration($duration)
public static function SplitDuration($duration)
{
$duration = (int)$duration;
$days = floor($duration / 86400);
@@ -113,7 +123,7 @@ class AttributeDuration extends AttributeInteger
$minutes = floor(($duration - (86400 * $days + 3600 * $hours)) / 60);
$seconds = ($duration % 60); // modulo
return array('days' => $days, 'hours' => $hours, 'minutes' => $minutes, 'seconds' => $seconds);
return ['days' => $days, 'hours' => $hours, 'minutes' => $minutes, 'seconds' => $seconds];
}
public static function GetFormFieldClass()
@@ -137,4 +147,4 @@ class AttributeDuration extends AttributeInteger
return $oFormField;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -52,4 +53,4 @@ class AttributeEmailAddress extends AttributeString
return '<a class="mailto" href="mailto:'.$sValue.'"><span class="text_decoration '.$sUrlDecorationClass.'"></span>'.parent::GetAsHTML($sValue).'</a>';
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -22,7 +23,7 @@ use SimpleCrypt;
*/
class AttributeEncryptedString extends AttributeString implements iAttributeNoGroupBy
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_RAW;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_RAW;
protected function GetSQLCol($bFullSpec = false)
{
@@ -73,7 +74,7 @@ class AttributeEncryptedString extends AttributeString implements iAttributeNoGr
$oSimpleCrypt = new SimpleCrypt(MetaModel::GetConfig()->GetEncryptionLibrary());
$encryptedValue = $oSimpleCrypt->Encrypt(MetaModel::GetConfig()->GetEncryptionKey(), $value);
$aValues = array();
$aValues = [];
$aValues[$this->Get("sql")] = $encryptedValue;
return $aValues;
@@ -92,5 +93,4 @@ class AttributeEncryptedString extends AttributeString implements iAttributeNoGr
return CMDBChangeOpSetAttributeEncrypted::class;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -22,7 +23,7 @@ use ormStyle;
*/
class AttributeEnum extends AttributeString
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_ENUM;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_ENUM;
/**
* Useless constructor, but if not present PHP 7.4.0/7.4.1 is crashing :( (N°2329)
@@ -93,9 +94,9 @@ class AttributeEnum extends AttributeString
{
$oValDef = $this->GetValuesDef();
if ($oValDef) {
$aValues = CMDBSource::Quote(array_keys($oValDef->GetValues(array(), "")), true);
$aValues = CMDBSource::Quote(array_keys($oValDef->GetValues([], "")), true);
} else {
$aValues = array();
$aValues = [];
}
// Preserve the values already present in the database to ease migrations
@@ -134,7 +135,7 @@ class AttributeEnum extends AttributeString
// Right now the function is not passed the "target" SQL table, but if we improve this in the future
// we may call $this->GetSQLColHelper(true, true, $sDBTable); to take into account the actual 'enum' values
// in this table
return array($this->GetCode() => $this->GetSQLColHelper(false, false));
return [$this->GetCode() => $this->GetSQLColHelper(false, false)];
}
/**
@@ -145,7 +146,7 @@ class AttributeEnum extends AttributeString
*/
protected function GetActualValuesInDB(string $sDBTable)
{
$aValues = array();
$aValues = [];
try {
$sSQL = "SELECT DISTINCT `".$this->GetSQLExpr()."` AS value FROM `$sDBTable`;";
$aValuesInDB = CMDBSource::QueryToArray($sSQL);
@@ -154,8 +155,7 @@ class AttributeEnum extends AttributeString
$aValues[] = $aRow['value'];
}
}
}
catch (MySQLException $e) {
} catch (MySQLException $e) {
// Never mind, maybe the table does not exist yet (new installation from scratch)
// It seems more efficient to try and ignore errors than to test if the table & column really exists
}
@@ -214,8 +214,10 @@ class AttributeEnum extends AttributeString
{
if (is_null($sValue)) {
// Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
$sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue,
Dict::S('Enum:Undefined'));
$sLabel = Dict::S(
'Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue,
Dict::S('Enum:Undefined')
);
} else {
$sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/Value:'.$sValue, null, true /*user lang*/);
if (is_null($sLabel)) {
@@ -232,11 +234,16 @@ class AttributeEnum extends AttributeString
{
if (is_null($sValue)) {
// Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
$sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+',
Dict::S('Enum:Undefined'));
$sDescription = Dict::S(
'Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+',
Dict::S('Enum:Undefined')
);
} else {
$sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+',
'', true /* user language only */);
$sDescription = Dict::S(
'Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+',
'',
true /* user language only */
);
if (strlen($sDescription) == 0) {
$sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
if ($sParentClass) {
@@ -284,10 +291,13 @@ class AttributeEnum extends AttributeString
}
public function GetAsCSV(
$sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true,
$sValue,
$sSeparator = ',',
$sTextQualifier = '"',
$oHostObject = null,
$bLocalize = true,
$bConvertToPlainText = false
)
{
) {
if (is_null($sValue)) {
$sFinalValue = '';
} elseif ($bLocalize) {
@@ -333,13 +343,13 @@ class AttributeEnum extends AttributeString
return $value;
}
public function GetAllowedValues($aArgs = array(), $sContains = '')
public function GetAllowedValues($aArgs = [], $sContains = '')
{
$aRawValues = parent::GetAllowedValues($aArgs, $sContains);
if (is_null($aRawValues)) {
return null;
}
$aLocalizedValues = array();
$aLocalizedValues = [];
foreach ($aRawValues as $sKey => $sValue) {
$aLocalizedValues[$sKey] = $this->GetValueLabel($sKey);
}
@@ -364,10 +374,13 @@ class AttributeEnum extends AttributeString
* An enum can be localized
*/
public function MakeValueFromString(
$sProposedValue, $bLocalizedValue = false, $sSepItem = null, $sSepAttribute = null, $sSepValue = null,
$sProposedValue,
$bLocalizedValue = false,
$sSepItem = null,
$sSepAttribute = null,
$sSepValue = null,
$sAttributeQualifier = null
)
{
) {
if ($bLocalizedValue) {
// Lookup for the value matching the input
//
@@ -388,8 +401,14 @@ class AttributeEnum extends AttributeString
return $this->MakeRealValue($sFoundValue, null);
} else {
return parent::MakeValueFromString($sProposedValue, $bLocalizedValue, $sSepItem, $sSepAttribute, $sSepValue,
$sAttributeQualifier);
return parent::MakeValueFromString(
$sProposedValue,
$bLocalizedValue,
$sSepItem,
$sSepAttribute,
$sSepValue,
$sAttributeQualifier
);
}
}
@@ -416,4 +435,4 @@ class AttributeEnum extends AttributeString
return Dict::Format('UI:OrderByHint_Values', implode(', ', $aValues));
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -16,18 +17,18 @@ use ValueSetEnumPadded;
*/
class AttributeEnumSet extends AttributeSet
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_TAG_SET;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_TAG_SET;
public static function ListExpectedParams()
{
return array_merge(parent::ListExpectedParams(), array('possible_values', 'is_null_allowed', 'max_items'));
return array_merge(parent::ListExpectedParams(), ['possible_values', 'is_null_allowed', 'max_items']);
}
public function GetMaxSize()
{
$aRawValues = $this->GetRawPossibleValues();
$iMaxItems = $this->GetMaxItems();
$aLengths = array();
$aLengths = [];
foreach (array_keys($aRawValues) as $sKey) {
$aLengths[] = strlen($sKey);
}
@@ -40,21 +41,21 @@ class AttributeEnumSet extends AttributeSet
return max(255, $iMaxSize);
}
private function GetRawPossibleValues($aArgs = array(), $sContains = '')
private function GetRawPossibleValues($aArgs = [], $sContains = '')
{
/** @var ValueSetEnumPadded $oValSetDef */
$oValSetDef = $this->Get('possible_values');
if (!$oValSetDef) {
return array();
return [];
}
return $oValSetDef->GetValues($aArgs, $sContains);
}
public function GetPossibleValues($aArgs = array(), $sContains = '')
public function GetPossibleValues($aArgs = [], $sContains = '')
{
$aRawValues = $this->GetRawPossibleValues($aArgs, $sContains);
$aLocalizedValues = array();
$aLocalizedValues = [];
foreach ($aRawValues as $sKey => $sValue) {
$aLocalizedValues[$sKey] = $this->GetValueLabel($sKey);
}
@@ -75,8 +76,10 @@ class AttributeEnumSet extends AttributeSet
if (is_null($sValue)) {
// Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
$sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue,
Dict::S('Enum:Undefined'));
$sLabel = Dict::S(
'Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue,
Dict::S('Enum:Undefined')
);
} else {
$sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/Value:'.$sValue, null, true /*user lang*/);
if (is_null($sLabel)) {
@@ -97,11 +100,16 @@ class AttributeEnumSet extends AttributeSet
{
if (is_null($sValue)) {
// Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
$sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+',
Dict::S('Enum:Undefined'));
$sDescription = Dict::S(
'Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+',
Dict::S('Enum:Undefined')
);
} else {
$sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+',
'', true /* user language only */);
$sDescription = Dict::S(
'Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+',
'',
true /* user language only */
);
if (strlen($sDescription) == 0) {
$sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
if ($sParentClass) {
@@ -133,7 +141,6 @@ class AttributeEnumSet extends AttributeSet
return $sRes;
}
/**
* @param ormSet $value
* @param string $sSeparator
@@ -151,7 +158,7 @@ class AttributeEnumSet extends AttributeSet
if (is_object($value) && ($value instanceof ormSet)) {
$aValues = $value->GetValues();
if ($bLocalize) {
$aLocalizedValues = array();
$aLocalizedValues = [];
foreach ($aValues as $sValue) {
$aLocalizedValues[] = $this->GetValueLabel($sValue);
}
@@ -184,7 +191,7 @@ class AttributeEnumSet extends AttributeSet
// Lookup for the values matching the input
//
$aValues = $this->FromStringToArray($sProposedValue);
$aFoundValues = array();
$aFoundValues = [];
$aRawValues = $this->GetPossibleValues();
foreach ($aValues as $sValue) {
$bFound = false;
@@ -217,7 +224,7 @@ class AttributeEnumSet extends AttributeSet
*/
public function FromStringToArray($proposedValue, $sDefaultSepItem = ',')
{
$aValues = array();
$aValues = [];
if (!empty($proposedValue)) {
$sSepItem = MetaModel::GetConfig()->Get('tag_set_item_separator');
// convert also other separators
@@ -240,4 +247,4 @@ class AttributeEnumSet extends AttributeSet
{
return $val1->Equals($val2);
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -56,14 +57,13 @@ class AttributeExternalField extends AttributeDefinition
case ($oRemoteAtt instanceof AttributeExternalKey):
return self::SEARCH_WIDGET_TYPE_EXTERNAL_KEY;
}
}
catch (CoreException $e) {
} catch (CoreException $e) {
}
return self::SEARCH_WIDGET_TYPE_RAW;
}
function IsSearchable()
public function IsSearchable()
{
if ($this->IsFriendlyName()) {
return true;
@@ -74,7 +74,7 @@ class AttributeExternalField extends AttributeDefinition
public static function ListExpectedParams()
{
return array_merge(parent::ListExpectedParams(), array("extkey_attcode", "target_attcode"));
return array_merge(parent::ListExpectedParams(), ["extkey_attcode", "target_attcode"]);
}
public function GetEditClass()
@@ -104,7 +104,7 @@ class AttributeExternalField extends AttributeDefinition
public function GetSQLExpressions($sPrefix = '')
{
if ($sPrefix == '') {
return array('' => $this->GetCode()); // Warning: Use GetCode() since AttributeExternalField does not have any 'sql' property
return ['' => $this->GetCode()]; // Warning: Use GetCode() since AttributeExternalField does not have any 'sql' property
} else {
return $sPrefix;
}
@@ -295,10 +295,9 @@ class AttributeExternalField extends AttributeDefinition
public function GetPrerequisiteAttributes($sClass = null)
{
return array($this->Get("extkey_attcode"));
return [$this->Get("extkey_attcode")];
}
/**
* @return AttributeExternalField
* @throws CoreException
@@ -417,7 +416,6 @@ class AttributeExternalField extends AttributeDefinition
return $oExtAttDef->ScalarToSQL($value);
}
// Do not overload GetSQLExpression here because this is handled in the joins
//public function GetSQLExpressions($sPrefix = '') {return array();}
@@ -444,10 +442,13 @@ class AttributeExternalField extends AttributeDefinition
}
public function GetAsCSV(
$value, $sSeparator = ',', $sTestQualifier = '"', $oHostObject = null, $bLocalize = true,
$value,
$sSeparator = ',',
$sTestQualifier = '"',
$oHostObject = null,
$bLocalize = true,
$bConvertToPlainText = false
)
{
) {
$oExtAttDef = $this->GetExtAttDef();
return $oExtAttDef->GetAsCSV($value, $sSeparator, $sTestQualifier, null, $bLocalize, $bConvertToPlainText);
@@ -522,4 +523,4 @@ class AttributeExternalField extends AttributeDefinition
return 'text';
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -26,7 +27,7 @@ use ValueSetObjects;
*/
class AttributeExternalKey extends AttributeDBFieldVoid
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_EXTERNAL_KEY;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_EXTERNAL_KEY;
/**
* Useless constructor, but if not present PHP 7.4.0/7.4.1 is crashing :( (N°2329)
@@ -60,8 +61,7 @@ class AttributeExternalKey extends AttributeDBFieldVoid
}
return self::SEARCH_WIDGET_TYPE_EXTERNAL_KEY;
}
catch (CoreException $e) {
} catch (CoreException $e) {
}
return self::SEARCH_WIDGET_TYPE_RAW;
@@ -69,7 +69,7 @@ class AttributeExternalKey extends AttributeDBFieldVoid
public static function ListExpectedParams()
{
return array_merge(parent::ListExpectedParams(), array("targetclass", "is_null_allowed", "on_target_delete"));
return array_merge(parent::ListExpectedParams(), ["targetclass", "is_null_allowed", "on_target_delete"]);
}
public function GetEditClass()
@@ -112,7 +112,6 @@ class AttributeExternalKey extends AttributeDBFieldVoid
return $this->GetOptional('display_style', 'select');
}
public function GetDefaultValue(DBObject $oHostObject = null)
{
return 0;
@@ -127,7 +126,6 @@ class AttributeExternalKey extends AttributeDBFieldVoid
return $this->Get("is_null_allowed");
}
public function GetBasicFilterOperators()
{
return parent::GetBasicFilterOperators();
@@ -156,13 +154,12 @@ class AttributeExternalKey extends AttributeDBFieldVoid
return $oValSetDef;
}
public function GetAllowedValues($aArgs = array(), $sContains = '')
public function GetAllowedValues($aArgs = [], $sContains = '')
{
//throw new Exception("GetAllowedValues on ext key has been deprecated");
try {
return parent::GetAllowedValues($aArgs, $sContains);
}
catch (Exception $e) {
} catch (Exception $e) {
// Some required arguments could not be found, enlarge to any existing value
$oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
@@ -170,7 +167,7 @@ class AttributeExternalKey extends AttributeDBFieldVoid
}
}
public function GetAllowedValuesForSelect($aArgs = array(), $sContains = '')
public function GetAllowedValuesForSelect($aArgs = [], $sContains = '')
{
//$this->GetValuesDef();
$oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
@@ -178,8 +175,7 @@ class AttributeExternalKey extends AttributeDBFieldVoid
return $oValSetDef->GetValuesForAutocomplete($aArgs, $sContains);
}
public function GetAllowedValuesAsObjectSet($aArgs = array(), $sContains = '', $iAdditionalValue = null)
public function GetAllowedValuesAsObjectSet($aArgs = [], $sContains = '', $iAdditionalValue = null)
{
$oValSetDef = $this->GetValuesDef();
$oSet = $oValSetDef->ToObjectSet($aArgs, $sContains, $iAdditionalValue);
@@ -187,7 +183,7 @@ class AttributeExternalKey extends AttributeDBFieldVoid
return $oSet;
}
public function GetAllowedValuesAsFilter($aArgs = array(), $sContains = '', $iAdditionalValue = null)
public function GetAllowedValuesAsFilter($aArgs = [], $sContains = '', $iAdditionalValue = null)
{
return DBObjectSearch::FromOQL($this->GetValuesDef()->GetFilterExpression());
}
@@ -282,8 +278,10 @@ class AttributeExternalKey extends AttributeDBFieldVoid
if (!$oRemoteAttDef->IsLinkSet()) {
continue;
}
if (!is_subclass_of($this->GetHostClass(),
$oRemoteAttDef->GetLinkedClass()) && $oRemoteAttDef->GetLinkedClass() != $this->GetHostClass()) {
if (!is_subclass_of(
$this->GetHostClass(),
$oRemoteAttDef->GetLinkedClass()
) && $oRemoteAttDef->GetLinkedClass() != $this->GetHostClass()) {
continue;
}
if ($oRemoteAttDef->GetExtKeyToMe() != $this->GetCode()) {
@@ -328,13 +326,13 @@ class AttributeExternalKey extends AttributeDBFieldVoid
// We set search object only if it has not already been set (overrided)
if ($oTmpField->GetSearch() === null) {
$oSearch = DBSearch::FromOQL($oTmpAttDef->GetValuesDef()->GetFilterExpression());
$oSearch->SetInternalParams(array('this' => $oObject));
$oSearch->SetInternalParams(['this' => $oObject]);
$oTmpField->SetSearch($oSearch);
}
});
} else {
$oSearch = DBSearch::FromOQL($this->GetValuesDef()->GetFilterExpression());
$oSearch->SetInternalParams(array('this' => $oObject));
$oSearch->SetInternalParams(['this' => $oObject]);
$oFormField->SetSearch($oSearch);
}
@@ -351,4 +349,4 @@ class AttributeExternalKey extends AttributeDBFieldVoid
return DBObject::MakeHyperLink($this->GetTargetClass(), $sValue);
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -17,7 +18,7 @@ use Str;
*/
class AttributeFinalClass extends AttributeString
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_STRING;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_STRING;
public $m_sValue;
public function __construct($sCode, $aParams)
@@ -81,10 +82,13 @@ class AttributeFinalClass extends AttributeString
* @throws OQLException
*/
public function MakeValueFromString(
$sProposedValue, $bLocalizedValue = false, $sSepItem = null, $sSepAttribute = null, $sSepValue = null,
$sProposedValue,
$bLocalizedValue = false,
$sSepItem = null,
$sSepAttribute = null,
$sSepValue = null,
$sAttributeQualifier = null
)
{
) {
if ($bLocalizedValue) {
// Lookup for the value matching the input
//
@@ -104,12 +108,17 @@ class AttributeFinalClass extends AttributeString
return $this->MakeRealValue($sFoundValue, null);
} else {
return parent::MakeValueFromString($sProposedValue, $bLocalizedValue, $sSepItem, $sSepAttribute, $sSepValue,
$sAttributeQualifier);
return parent::MakeValueFromString(
$sProposedValue,
$bLocalizedValue,
$sSepItem,
$sSepAttribute,
$sSepValue,
$sAttributeQualifier
);
}
}
// Because this is sometimes used to get a localized/string version of an attribute...
public function GetEditValue($sValue, $oHostObj = null)
{
@@ -139,10 +148,13 @@ class AttributeFinalClass extends AttributeString
* @throws DictExceptionMissingString
*/
public function GetAsCSV(
$value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true,
$value,
$sSeparator = ',',
$sTextQualifier = '"',
$oHostObject = null,
$bLocalize = true,
$bConvertToPlainText = false
)
{
) {
if ($bLocalize && $value != '') {
$sRawValue = MetaModel::GetName($value);
} else {
@@ -180,10 +192,10 @@ class AttributeFinalClass extends AttributeString
return MetaModel::GetName($sValue);
}
public function GetAllowedValues($aArgs = array(), $sContains = '')
public function GetAllowedValues($aArgs = [], $sContains = '')
{
$aRawValues = MetaModel::EnumChildClasses($this->GetHostClass(), ENUM_CHILD_CLASSES_ALL);
$aLocalizedValues = array();
$aLocalizedValues = [];
foreach ($aRawValues as $sClass) {
$aLocalizedValues[$sClass] = MetaModel::GetName($sClass);
}
@@ -205,4 +217,4 @@ class AttributeFinalClass extends AttributeString
return true;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -19,13 +20,13 @@ use Str;
*/
class AttributeFriendlyName extends AttributeDefinition
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_STRING;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_STRING;
public $m_sValue;
public function __construct($sCode)
{
$this->m_sCode = $sCode;
$aParams = array();
$aParams = [];
$aParams["default_value"] = '';
parent::__construct($sCode, $aParams);
@@ -45,7 +46,7 @@ class AttributeFriendlyName extends AttributeDefinition
public function GetPrerequisiteAttributes($sClass = null)
{
// Code duplicated with AttributeObsolescenceFlag
$aAttributes = $this->GetOptional("depends_on", array());
$aAttributes = $this->GetOptional("depends_on", []);
$oExpression = $this->GetOQLExpression();
foreach ($oExpression->ListRequiredFields() as $sAttCode) {
if (!in_array($sAttCode, $aAttributes)) {
@@ -72,7 +73,7 @@ class AttributeFriendlyName extends AttributeDefinition
$sPrefix = $this->GetCode(); // Warning AttributeComputedFieldVoid does not have any sql property
}
return array('' => $sPrefix);
return ['' => $sPrefix];
}
public static function IsBasedOnOQLExpression()
@@ -143,18 +144,21 @@ class AttributeFriendlyName extends AttributeDefinition
}
public function GetAsCSV(
$sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true,
$sValue,
$sSeparator = ',',
$sTextQualifier = '"',
$oHostObject = null,
$bLocalize = true,
$bConvertToPlainText = false
)
{
$sFrom = array("\r\n", $sTextQualifier);
$sTo = array("\n", $sTextQualifier.$sTextQualifier);
) {
$sFrom = ["\r\n", $sTextQualifier];
$sTo = ["\n", $sTextQualifier.$sTextQualifier];
$sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
return $sTextQualifier.$sEscaped.$sTextQualifier;
}
static function GetFormFieldClass()
public static function GetFormFieldClass()
{
return '\\Combodo\\iTop\\Form\\Field\\StringField';
}
@@ -179,7 +183,7 @@ class AttributeFriendlyName extends AttributeDefinition
public function GetBasicFilterOperators()
{
return array("=" => "equals", "!=" => "differs from");
return ["=" => "equals", "!=" => "differs from"];
}
public function GetBasicFilterLooseOperator()
@@ -208,4 +212,4 @@ class AttributeFriendlyName extends AttributeDefinition
{
return false;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -32,7 +33,7 @@ class AttributeHTML extends AttributeLongText
public function GetSQLColumns($bFullSpec = false)
{
$aColumns = array();
$aColumns = [];
$aColumns[$this->Get('sql')] = $this->GetSQLCol();
if ($this->GetOptional('format', null) != null) {
// Add the extra column only if the property 'format' is specified for the attribute
@@ -54,4 +55,4 @@ class AttributeHTML extends AttributeLongText
{
return $this->GetOptional('format', 'html'); // Defaults to HTML
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -13,7 +14,7 @@ use DBObjectSearch;
*/
class AttributeHierarchicalKey extends AttributeExternalKey
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_HIERARCHICAL_KEY;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_HIERARCHICAL_KEY;
protected $m_sTargetClass;
@@ -98,7 +99,7 @@ class AttributeHierarchicalKey extends AttributeExternalKey
public function GetSQLColumns($bFullSpec = false)
{
$aColumns = array();
$aColumns = [];
$aColumns[$this->GetCode()] = 'INT(11)'.($bFullSpec ? ' DEFAULT 0' : '');
$aColumns[$this->GetSQLLeft()] = 'INT(11)'.($bFullSpec ? ' DEFAULT 0' : '');
$aColumns[$this->GetSQLRight()] = 'INT(11)'.($bFullSpec ? ' DEFAULT 0' : '');
@@ -121,7 +122,7 @@ class AttributeHierarchicalKey extends AttributeExternalKey
if (!is_array($value)) {
$aValues[$this->GetCode()] = $value;
} else {
$aValues = array();
$aValues = [];
$aValues[$this->GetCode()] = $value[$this->GetCode()];
$aValues[$this->GetSQLRight()] = $value[$this->GetSQLRight()];
$aValues[$this->GetSQLLeft()] = $value[$this->GetSQLLeft()];
@@ -130,7 +131,7 @@ class AttributeHierarchicalKey extends AttributeExternalKey
return $aValues;
}
public function GetAllowedValues($aArgs = array(), $sContains = '')
public function GetAllowedValues($aArgs = [], $sContains = '')
{
$oFilter = $this->GetHierachicalFilter($aArgs, $sContains);
if ($oFilter) {
@@ -143,7 +144,7 @@ class AttributeHierarchicalKey extends AttributeExternalKey
}
}
public function GetAllowedValuesAsObjectSet($aArgs = array(), $sContains = '', $iAdditionalValue = null)
public function GetAllowedValuesAsObjectSet($aArgs = [], $sContains = '', $iAdditionalValue = null)
{
$oValSetDef = $this->GetValuesDef();
$oFilter = $this->GetHierachicalFilter($aArgs, $sContains, $iAdditionalValue);
@@ -155,7 +156,7 @@ class AttributeHierarchicalKey extends AttributeExternalKey
return $oSet;
}
public function GetAllowedValuesAsFilter($aArgs = array(), $sContains = '', $iAdditionalValue = null)
public function GetAllowedValuesAsFilter($aArgs = [], $sContains = '', $iAdditionalValue = null)
{
$oFilter = $this->GetHierachicalFilter($aArgs, $sContains, $iAdditionalValue);
if ($oFilter) {
@@ -165,14 +166,13 @@ class AttributeHierarchicalKey extends AttributeExternalKey
return parent::GetAllowedValuesAsFilter($aArgs, $sContains, $iAdditionalValue);
}
private function GetHierachicalFilter($aArgs = array(), $sContains = '', $iAdditionalValue = null)
private function GetHierachicalFilter($aArgs = [], $sContains = '', $iAdditionalValue = null)
{
if (array_key_exists('this', $aArgs)) {
// Hierarchical keys have one more constraint: the "parent value" cannot be
// "under" themselves
$iRootId = $aArgs['this']->GetKey();
if ($iRootId > 0) // ignore objects that do no exist in the database...
{
if ($iRootId > 0) { // ignore objects that do no exist in the database...
$sClass = $this->m_sTargetClass;
return DBObjectSearch::FromOQL("SELECT $sClass AS node JOIN $sClass AS root ON node.".$this->GetCode()." NOT BELOW root.id WHERE root.id = $iRootId");
@@ -191,4 +191,4 @@ class AttributeHierarchicalKey extends AttributeExternalKey
{
return null;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -40,6 +41,6 @@ class AttributeIPAddress extends AttributeString
public function GetOrderBySQLExpressions($sClassAlias)
{
// Note: This is the responsibility of this function to place backticks around column aliases
return array('INET_ATON(`'.$sClassAlias.$this->GetCode().'`)');
return ['INET_ATON(`'.$sClassAlias.$this->GetCode().'`)'];
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -204,4 +205,4 @@ class AttributeImage extends AttributeBlob
return $oFormField;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -17,7 +18,7 @@ use utils;
*/
class AttributeInteger extends AttributeDBField
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_NUMERIC;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_NUMERIC;
/**
* Useless constructor, but if not present PHP 7.4.0/7.4.1 is crashing :( (N°2329)
@@ -59,7 +60,7 @@ class AttributeInteger extends AttributeDBField
public function GetBasicFilterOperators()
{
return array(
return [
"!=" => "differs from",
"=" => "equals",
">" => "greater (strict) than",
@@ -67,7 +68,7 @@ class AttributeInteger extends AttributeDBField
"<" => "less (strict) than",
"<=" => "less than",
"in" => "in",
);
];
}
public function GetBasicFilterLooseOperator()
@@ -145,4 +146,4 @@ class AttributeInteger extends AttributeDBField
return $value; // supposed to be an int
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -51,8 +52,10 @@ class AttributeLinkedSet extends AttributeDefinition
public static function ListExpectedParams()
{
return array_merge(parent::ListExpectedParams(),
array("allowed_values", "depends_on", "linked_class", "ext_key_to_me", "count_min", "count_max"));
return array_merge(
parent::ListExpectedParams(),
["allowed_values", "depends_on", "linked_class", "ext_key_to_me", "count_min", "count_max"]
);
}
public function GetEditClass()
@@ -228,7 +231,7 @@ class AttributeLinkedSet extends AttributeDefinition
public function GetBasicFilterOperators()
{
return array();
return [];
}
public function GetBasicFilterLooseOperator()
@@ -255,10 +258,10 @@ class AttributeLinkedSet extends AttributeDefinition
{
if (is_object($sValue) && ($sValue instanceof ormLinkSet)) {
$sValue->Rewind();
$aItems = array();
$aItems = [];
while ($oObj = $sValue->Fetch()) {
// Show only relevant information (hide the external key to the current object)
$aAttributes = array();
$aAttributes = [];
foreach (MetaModel::ListAttributeDefs($this->GetLinkedClass()) as $sAttCode => $oAttDef) {
if ($sAttCode == $this->GetExtKeyToMe()) {
continue;
@@ -293,8 +296,7 @@ class AttributeLinkedSet extends AttributeDefinition
$oLinkSetBlock = new BlockLinkSetDisplayAsProperty($this->GetCode(), $this, $sValue);
return ConsoleBlockRenderer::RenderBlockTemplates($oLinkSetBlock);
}
catch (Exception $e) {
} catch (Exception $e) {
$sMessage = "Error while displaying attribute {$this->GetCode()}";
IssueLog::Error($sMessage, IssueLog::CHANNEL_DEFAULT, [
'host_object_class' => $this->GetHostClass(),
@@ -375,10 +377,13 @@ class AttributeLinkedSet extends AttributeDefinition
* @throws CoreException
*/
public function GetAsCSV(
$sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true,
$sValue,
$sSeparator = ',',
$sTextQualifier = '"',
$oHostObject = null,
$bLocalize = true,
$bConvertToPlainText = false
)
{
) {
$sSepItem = MetaModel::GetConfig()->Get('link_set_item_separator');
$sSepAttribute = MetaModel::GetConfig()->Get('link_set_attribute_separator');
$sSepValue = MetaModel::GetConfig()->Get('link_set_value_separator');
@@ -386,11 +391,11 @@ class AttributeLinkedSet extends AttributeDefinition
if (is_object($sValue) && ($sValue instanceof ormLinkSet)) {
$sValue->Rewind();
$aItems = array();
$aItems = [];
while ($oObj = $sValue->Fetch()) {
$sObjClass = get_class($oObj);
// Show only relevant information (hide the external key to the current object)
$aAttributes = array();
$aAttributes = [];
foreach (MetaModel::ListAttributeDefs($sObjClass) as $sAttCode => $oAttDef) {
if ($sAttCode == 'finalclass') {
if ($sObjClass == $this->GetLinkedClass()) {
@@ -412,8 +417,11 @@ class AttributeLinkedSet extends AttributeDefinition
}
$sAttValue = $oObj->GetAsCSV($sAttCode, $sSepValue, '', $bLocalize);
if (strlen($sAttValue) > 0) {
$sAttributeData = str_replace($sAttributeQualifier, $sAttributeQualifier.$sAttributeQualifier,
$sAttCode.$sSepValue.$sAttValue);
$sAttributeData = str_replace(
$sAttributeQualifier,
$sAttributeQualifier.$sAttributeQualifier,
$sAttCode.$sSepValue.$sAttValue
);
$aAttributes[] = $sAttributeQualifier.$sAttributeData.$sAttributeQualifier;
}
}
@@ -435,10 +443,10 @@ class AttributeLinkedSet extends AttributeDefinition
*/
public function EnumTemplateVerbs()
{
return array(
return [
'' => 'Plain text (unlocalized) representation',
'html' => 'HTML representation (unordered list)',
);
];
}
/**
@@ -461,7 +469,7 @@ class AttributeLinkedSet extends AttributeDefinition
$oLinkSet = clone $value; // Workaround/Safety net for Trac #887
$iLimit = MetaModel::GetConfig()->Get('max_linkset_output');
$iCount = 0;
$aNames = array();
$aNames = [];
foreach ($oLinkSet as $oItem) {
if (($iLimit > 0) && ($iCount == $iLimit)) {
$iTotal = $oLinkSet->Count();
@@ -491,7 +499,7 @@ class AttributeLinkedSet extends AttributeDefinition
public function GetImportColumns()
{
$aColumns = array();
$aColumns = [];
$aColumns[$this->GetCode()] = 'MEDIUMTEXT'.CMDBSource::GetSqlStringColumnDefinition();
return $aColumns;
@@ -515,10 +523,13 @@ class AttributeLinkedSet extends AttributeDefinition
* @throws Exception
*/
public function MakeValueFromString(
$sProposedValue, $bLocalizedValue = false, $sSepItem = null, $sSepAttribute = null, $sSepValue = null,
$sProposedValue,
$bLocalizedValue = false,
$sSepItem = null,
$sSepAttribute = null,
$sSepValue = null,
$sAttributeQualifier = null
)
{
) {
if (is_null($sSepItem) || empty($sSepItem)) {
$sSepItem = MetaModel::GetConfig()->Get('link_set_item_separator');
}
@@ -539,16 +550,16 @@ class AttributeLinkedSet extends AttributeDefinition
$aInput = $oCSVParser->ToArray(0 /* do not skip lines */);
$aLinks = array();
$aLinks = [];
foreach ($aInput as $aRow) {
// 1st - get the values, split the extkey->searchkey specs, and eventually get the finalclass value
$aExtKeys = array();
$aValues = array();
$aExtKeys = [];
$aValues = [];
foreach ($aRow as $sCell) {
$iSepPos = strpos($sCell, $sSepValue);
if ($iSepPos === false) {
// Houston...
throw new CoreException('Wrong format for link attribute specification', array('value' => $sCell));
throw new CoreException('Wrong format for link attribute specification', ['value' => $sCell]);
}
$sAttCode = trim(substr($sCell, 0, $iSepPos));
@@ -559,24 +570,36 @@ class AttributeLinkedSet extends AttributeDefinition
$sRemoteAttCode = $aMatches[2];
$aExtKeys[$sKeyAttCode][$sRemoteAttCode] = $sValue;
if (!MetaModel::IsValidAttCode($sTargetClass, $sKeyAttCode)) {
throw new CoreException('Wrong attribute code for link attribute specification',
array('class' => $sTargetClass, 'attcode' => $sKeyAttCode));
throw new CoreException(
'Wrong attribute code for link attribute specification',
['class' => $sTargetClass, 'attcode' => $sKeyAttCode]
);
}
/** @var \AttributeExternalKey $oKeyAttDef */
$oKeyAttDef = MetaModel::GetAttributeDef($sTargetClass, $sKeyAttCode);
$sRemoteClass = $oKeyAttDef->GetTargetClass();
if (!MetaModel::IsValidAttCode($sRemoteClass, $sRemoteAttCode)) {
throw new CoreException('Wrong attribute code for link attribute specification',
array('class' => $sRemoteClass, 'attcode' => $sRemoteAttCode));
throw new CoreException(
'Wrong attribute code for link attribute specification',
['class' => $sRemoteClass, 'attcode' => $sRemoteAttCode]
);
}
} else {
if (!MetaModel::IsValidAttCode($sTargetClass, $sAttCode)) {
throw new CoreException('Wrong attribute code for link attribute specification',
array('class' => $sTargetClass, 'attcode' => $sAttCode));
throw new CoreException(
'Wrong attribute code for link attribute specification',
['class' => $sTargetClass, 'attcode' => $sAttCode]
);
}
$oAttDef = MetaModel::GetAttributeDef($sTargetClass, $sAttCode);
$aValues[$sAttCode] = $oAttDef->MakeValueFromString($sValue, $bLocalizedValue, $sSepItem,
$sSepAttribute, $sSepValue, $sAttributeQualifier);
$aValues[$sAttCode] = $oAttDef->MakeValueFromString(
$sValue,
$bLocalizedValue,
$sSepItem,
$sSepAttribute,
$sSepValue,
$sAttributeQualifier
);
}
}
@@ -584,8 +607,10 @@ class AttributeLinkedSet extends AttributeDefinition
if (isset($aValues['finalclass'])) {
$sLinkClass = $aValues['finalclass'];
if (!is_subclass_of($sLinkClass, $sTargetClass)) {
throw new CoreException('Wrong class for link attribute specification',
array('requested_class' => $sLinkClass, 'expected_class' => $sTargetClass));
throw new CoreException(
'Wrong class for link attribute specification',
['requested_class' => $sLinkClass, 'expected_class' => $sTargetClass]
);
}
} elseif (MetaModel::IsAbstract($sTargetClass)) {
throw new CoreException('Missing finalclass for link attribute specification');
@@ -603,7 +628,7 @@ class AttributeLinkedSet extends AttributeDefinition
$oKeyAttDef = MetaModel::GetAttributeDef($sTargetClass, $sKeyAttCode);
$sKeyClass = $oKeyAttDef->GetTargetClass();
$oExtKeyFilter = new DBObjectSearch($sKeyClass);
$aReconciliationDesc = array();
$aReconciliationDesc = [];
foreach ($aReconciliation as $sRemoteAttCode => $sValue) {
$oExtKeyFilter->AddCondition($sRemoteAttCode, $sValue, '=');
$aReconciliationDesc[] = "$sRemoteAttCode=$sValue";
@@ -612,8 +637,10 @@ class AttributeLinkedSet extends AttributeDefinition
switch ($oExtKeySet->Count()) {
case 0:
$sReconciliationDesc = implode(', ', $aReconciliationDesc);
throw new CoreException("Found no match",
array('ext_key' => $sKeyAttCode, 'reconciliation' => $sReconciliationDesc));
throw new CoreException(
"Found no match",
['ext_key' => $sKeyAttCode, 'reconciliation' => $sReconciliationDesc]
);
break;
case 1:
$oRemoteObj = $oExtKeySet->Fetch();
@@ -621,19 +648,23 @@ class AttributeLinkedSet extends AttributeDefinition
break;
default:
$sReconciliationDesc = implode(', ', $aReconciliationDesc);
throw new CoreException("Found several matches",
array('ext_key' => $sKeyAttCode, 'reconciliation' => $sReconciliationDesc));
// Found several matches, ambiguous
throw new CoreException(
"Found several matches",
['ext_key' => $sKeyAttCode, 'reconciliation' => $sReconciliationDesc]
);
// Found several matches, ambiguous
}
}
// Check (roughly) if such a link is valid
$aErrors = array();
$aErrors = [];
foreach (MetaModel::ListAttributeDefs($sTargetClass) as $sAttCode => $oAttDef) {
if ($oAttDef->IsExternalKey()) {
/** @var \AttributeExternalKey $oAttDef */
if (($oAttDef->GetTargetClass() == $this->GetHostClass()) || (is_subclass_of($this->GetHostClass(),
$oAttDef->GetTargetClass()))) {
if (($oAttDef->GetTargetClass() == $this->GetHostClass()) || (is_subclass_of(
$this->GetHostClass(),
$oAttDef->GetTargetClass()
))) {
continue; // Don't check the key to self
}
}
@@ -660,13 +691,13 @@ class AttributeLinkedSet extends AttributeDefinition
*/
public function GetForJSON($value)
{
$aRet = array();
$aRet = [];
if (is_object($value) && ($value instanceof ormLinkSet)) {
$value->Rewind();
while ($oObj = $value->Fetch()) {
$sObjClass = get_class($oObj);
// Show only relevant information (hide the external key to the current object)
$aAttributes = array();
$aAttributes = [];
foreach (MetaModel::ListAttributeDefs($sObjClass) as $sAttCode => $oAttDef) {
if ($sAttCode == 'finalclass') {
if ($sObjClass == $this->GetLinkedClass()) {
@@ -708,13 +739,15 @@ class AttributeLinkedSet extends AttributeDefinition
{
$sTargetClass = $this->Get('linked_class');
$aLinks = array();
$aLinks = [];
foreach ($json as $aValues) {
if (isset($aValues['finalclass'])) {
$sLinkClass = $aValues['finalclass'];
if (!is_subclass_of($sLinkClass, $sTargetClass)) {
throw new CoreException('Wrong class for link attribute specification',
array('requested_class' => $sLinkClass, 'expected_class' => $sTargetClass));
throw new CoreException(
'Wrong class for link attribute specification',
['requested_class' => $sLinkClass, 'expected_class' => $sTargetClass]
);
}
} elseif (MetaModel::IsAbstract($sTargetClass)) {
throw new CoreException('Missing finalclass for link attribute specification');
@@ -728,12 +761,14 @@ class AttributeLinkedSet extends AttributeDefinition
}
// Check (roughly) if such a link is valid
$aErrors = array();
$aErrors = [];
foreach (MetaModel::ListAttributeDefs($sTargetClass) as $sAttCode => $oAttDef) {
if ($oAttDef->IsExternalKey()) {
/** @var AttributeExternalKey $oAttDef */
if (($oAttDef->GetTargetClass() == $this->GetHostClass()) || (is_subclass_of($this->GetHostClass(),
$oAttDef->GetTargetClass()))) {
if (($oAttDef->GetTargetClass() == $this->GetHostClass()) || (is_subclass_of(
$this->GetHostClass(),
$oAttDef->GetTargetClass()
))) {
continue; // Don't check the key to self
}
}
@@ -764,7 +799,7 @@ class AttributeLinkedSet extends AttributeDefinition
{
if ($proposedValue === null) {
$sLinkedClass = $this->GetLinkedClass();
$aLinkedObjectsArray = array();
$aLinkedObjectsArray = [];
$oSet = DBObjectSet::FromArray($sLinkedClass, $aLinkedObjectsArray);
return new ormLinkSet(
@@ -848,10 +883,10 @@ class AttributeLinkedSet extends AttributeDefinition
// - Adding friendlyname attribute to the list is not already in it
$sTitleAttCode = MetaModel::GetFriendlyNameAttributeCode($sTargetClass);
if (($sTitleAttCode !== null) && !in_array($sTitleAttCode, $aAttCodesToDisplay)) {
$aAttCodesToDisplay = array_merge(array($sTitleAttCode), $aAttCodesToDisplay);
$aAttCodesToDisplay = array_merge([$sTitleAttCode], $aAttCodesToDisplay);
}
// - Adding attribute properties
$aAttributesToDisplay = array();
$aAttributesToDisplay = [];
foreach ($aAttCodesToDisplay as $sAttCodeToDisplay) {
$oAttDefToDisplay = MetaModel::GetAttributeDef($sTargetClass, $sAttCodeToDisplay);
$aAttributesToDisplay[$sAttCodeToDisplay] = [
@@ -864,7 +899,7 @@ class AttributeLinkedSet extends AttributeDefinition
// Append lnk attributes (filtered from zlist)
if ($this->IsIndirect()) {
$aLnkAttDefToDisplay = MetaModel::GetZListAttDefsFilteredForIndirectLinkClass($this->m_sHostClass, $this->m_sCode);
$aLnkAttributesToDisplay = array();
$aLnkAttributesToDisplay = [];
foreach ($aLnkAttDefToDisplay as $oLnkAttDefToDisplay) {
$aLnkAttributesToDisplay[$oLnkAttDefToDisplay->GetCode()] = [
'att_code' => $oLnkAttDefToDisplay->GetCode(),
@@ -930,11 +965,10 @@ class AttributeLinkedSet extends AttributeDefinition
} else {
return $sDefault;
}
}
catch (Exception $e) {
} catch (Exception $e) {
ExceptionLog::LogException($e);
return $sDefault;
}
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -36,7 +37,7 @@ class AttributeLinkedSetIndirect extends AttributeLinkedSet
public static function ListExpectedParams()
{
return array_merge(parent::ListExpectedParams(), array("ext_key_to_remote"));
return array_merge(parent::ListExpectedParams(), ["ext_key_to_remote"]);
}
public function IsIndirect()
@@ -61,8 +62,10 @@ class AttributeLinkedSetIndirect extends AttributeLinkedSet
public function GetTrackingLevel()
{
return $this->GetOptional('tracking_level',
MetaModel::GetConfig()->Get('tracking_level_linked_set_indirect_default'));
return $this->GetOptional(
'tracking_level',
MetaModel::GetConfig()->Get('tracking_level_linked_set_indirect_default')
);
}
/**
@@ -103,4 +106,4 @@ class AttributeLinkedSetIndirect extends AttributeLinkedSet
return true;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -53,4 +54,4 @@ class AttributeLongText extends AttributeText
? CMDBChangeOpSetAttributeHTML::class
: CMDBChangeOpSetAttributeLongText::class;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -37,7 +38,7 @@ class AttributeMetaEnum extends AttributeEnum
public static function ListExpectedParams()
{
return array('allowed_values', 'sql', 'default_value', 'mapping');
return ['allowed_values', 'sql', 'default_value', 'mapping'];
}
public function IsNullAllowed()
@@ -62,9 +63,9 @@ class AttributeMetaEnum extends AttributeEnum
}
$aMappingData = $this->GetMapRule($sClass);
if ($aMappingData == null) {
$aRet = array();
$aRet = [];
} else {
$aRet = array($aMappingData['attcode']);
$aRet = [$aMappingData['attcode']];
}
return $aRet;
@@ -78,7 +79,7 @@ class AttributeMetaEnum extends AttributeEnum
*
* @return array|null
*/
public function GetAllowedValues($aArgs = array(), $sContains = '')
public function GetAllowedValues($aArgs = [], $sContains = '')
{
$oValSetDef = $this->GetValuesDef();
if (!$oValSetDef) {
@@ -89,7 +90,7 @@ class AttributeMetaEnum extends AttributeEnum
if (is_null($aRawValues)) {
return null;
}
$aLocalizedValues = array();
$aLocalizedValues = [];
foreach ($aRawValues as $sKey => $sValue) {
$aLocalizedValues[$sKey] = $this->GetValueLabel($sKey);
}
@@ -119,8 +120,10 @@ class AttributeMetaEnum extends AttributeEnum
} elseif ($this->GetDefaultValue() != '') {
$sRet = $this->GetDefaultValue();
} else {
throw new Exception('AttributeMetaEnum::MapValue(): mapping not found for value "'.$value.'" in '.get_class($oObject).', on attribute '.MetaModel::GetAttributeOrigin($this->GetHostClass(),
$this->GetCode()).'::'.$this->GetCode());
throw new Exception('AttributeMetaEnum::MapValue(): mapping not found for value "'.$value.'" in '.get_class($oObject).', on attribute '.MetaModel::GetAttributeOrigin(
$this->GetHostClass(),
$this->GetCode()
).'::'.$this->GetCode());
}
}
@@ -143,4 +146,4 @@ class AttributeMetaEnum extends AttributeEnum
return $aMappingData;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -15,7 +16,7 @@ use Exception;
*/
class AttributeOQL extends AttributeText
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_STRING;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_STRING;
/**
* Useless constructor, but if not present PHP 7.4.0/7.4.1 is crashing :( (N°2329)
@@ -38,4 +39,4 @@ class AttributeOQL extends AttributeText
{
return "OQLExpression";
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -17,7 +18,7 @@ use MetaModel;
*/
class AttributeObjectKey extends AttributeDBFieldVoid
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_EXTERNAL_KEY;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_EXTERNAL_KEY;
/**
* Useless constructor, but if not present PHP 7.4.0/7.4.1 is crashing :( (N°2329)
@@ -38,7 +39,7 @@ class AttributeObjectKey extends AttributeDBFieldVoid
public static function ListExpectedParams()
{
return array_merge(parent::ListExpectedParams(), array('class_attcode', 'is_null_allowed'));
return array_merge(parent::ListExpectedParams(), ['class_attcode', 'is_null_allowed']);
}
public function GetEditClass()
@@ -61,7 +62,6 @@ class AttributeObjectKey extends AttributeDBFieldVoid
return $this->Get("is_null_allowed");
}
public function GetBasicFilterOperators()
{
return parent::GetBasicFilterOperators();
@@ -114,4 +114,4 @@ class AttributeObjectKey extends AttributeDBFieldVoid
return (int)$proposedValue;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -41,4 +42,4 @@ class AttributeObsolescenceDate extends AttributeDate
return parent::GetDescription($sDefault);
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -14,13 +15,13 @@ class AttributeObsolescenceFlag extends AttributeBoolean
{
public function __construct($sCode)
{
parent::__construct($sCode, array(
parent::__construct($sCode, [
"allowed_values" => null,
"sql" => $sCode,
"default_value" => "",
"is_null_allowed" => false,
"depends_on" => array(),
));
"depends_on" => [],
]);
}
public function IsWritable()
@@ -56,17 +57,17 @@ class AttributeObsolescenceFlag extends AttributeBoolean
public function GetSQLExpressions($sPrefix = '')
{
return array();
return [];
}
public function GetSQLColumns($bFullSpec = false)
{
return array();
return [];
} // returns column/spec pairs (1 in most of the cases), for STRUCTURING (DB creation)
public function GetSQLValues($value)
{
return array();
return [];
} // returns column/value pairs (1 in most of the cases), for WRITING (Insert, Update)
public function GetEditClass()
@@ -82,7 +83,7 @@ class AttributeObsolescenceFlag extends AttributeBoolean
public function GetPrerequisiteAttributes($sClass = null)
{
// Code duplicated with AttributeFriendlyName
$aAttributes = $this->GetOptional("depends_on", array());
$aAttributes = $this->GetOptional("depends_on", []);
$oExpression = $this->GetOQLExpression();
foreach ($oExpression->ListRequiredFields() as $sClass => $sAttCode) {
if (!in_array($sAttCode, $aAttributes)) {
@@ -131,4 +132,4 @@ class AttributeObsolescenceFlag extends AttributeBoolean
return parent::GetDescription($sDefault);
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -19,7 +20,7 @@ use utils;
*/
class AttributeOneWayPassword extends AttributeDefinition implements iAttributeNoGroupBy
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_RAW;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_RAW;
/**
* Useless constructor, but if not present PHP 7.4.0/7.4.1 is crashing :( (N°2329)
@@ -40,7 +41,7 @@ class AttributeOneWayPassword extends AttributeDefinition implements iAttributeN
public static function ListExpectedParams()
{
return array_merge(parent::ListExpectedParams(), array("depends_on"));
return array_merge(parent::ListExpectedParams(), ["depends_on"]);
}
public function GetEditClass()
@@ -92,7 +93,7 @@ class AttributeOneWayPassword extends AttributeDefinition implements iAttributeN
if ($sPrefix == '') {
$sPrefix = $this->GetCode(); // Warning: AttributeOneWayPassword does not have any sql property so code = sql !
}
$aColumns = array();
$aColumns = [];
// Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
$aColumns[''] = $sPrefix.'_hash';
$aColumns['_salt'] = $sPrefix.'_salt';
@@ -128,11 +129,11 @@ class AttributeOneWayPassword extends AttributeDefinition implements iAttributeN
// We will have to remove the blobs from the list of attributes when doing the select
// then the use of Get() should finalize the load
if ($value instanceof ormPassword) {
$aValues = array();
$aValues = [];
$aValues[$this->GetCode().'_hash'] = $value->GetHash();
$aValues[$this->GetCode().'_salt'] = $value->GetSalt();
} else {
$aValues = array();
$aValues = [];
$aValues[$this->GetCode().'_hash'] = '';
$aValues[$this->GetCode().'_salt'] = '';
}
@@ -142,7 +143,7 @@ class AttributeOneWayPassword extends AttributeDefinition implements iAttributeN
public function GetSQLColumns($bFullSpec = false)
{
$aColumns = array();
$aColumns = [];
$aColumns[$this->GetCode().'_hash'] = 'TINYBLOB';
$aColumns[$this->GetCode().'_salt'] = 'TINYBLOB';
@@ -151,7 +152,7 @@ class AttributeOneWayPassword extends AttributeDefinition implements iAttributeN
public function GetImportColumns()
{
$aColumns = array();
$aColumns = [];
$aColumns[$this->GetCode()] = 'TINYTEXT'.CMDBSource::GetSqlStringColumnDefinition();
return $aColumns;
@@ -173,7 +174,7 @@ class AttributeOneWayPassword extends AttributeDefinition implements iAttributeN
public function GetBasicFilterOperators()
{
return array();
return [];
}
public function GetBasicFilterLooseOperator()
@@ -196,10 +197,13 @@ class AttributeOneWayPassword extends AttributeDefinition implements iAttributeN
}
public function GetAsCSV(
$sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true,
$sValue,
$sSeparator = ',',
$sTextQualifier = '"',
$oHostObject = null,
$bLocalize = true,
$bConvertToPlainText = false
)
{
) {
return ''; // Not exportable in CSV
}
@@ -244,4 +248,4 @@ class AttributeOneWayPassword extends AttributeDefinition implements iAttributeN
{
return CMDBChangeOpSetAttributeOneWayPassword::class;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -17,7 +18,7 @@ use utils;
*/
class AttributePassword extends AttributeString implements iAttributeNoGroupBy
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_RAW;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_RAW;
/**
* Useless constructor, but if not present PHP 7.4.0/7.4.1 is crashing :( (N°2329)
@@ -72,4 +73,4 @@ class AttributePassword extends AttributeString implements iAttributeNoGroupBy
{
return false;
} // Cannot reliably compare two encrypted passwords since the same password will be encrypted in diffferent manners depending on the random 'salt'
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -15,7 +16,7 @@ use Exception;
*/
class AttributePercentage extends AttributeInteger
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_NUMERIC;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_NUMERIC;
/**
* Useless constructor, but if not present PHP 7.4.0/7.4.1 is crashing :( (N°2329)
@@ -58,4 +59,4 @@ class AttributePercentage extends AttributeInteger
return "<div style=\"width:{$iWidth}em;-moz-border-radius: 3px;-webkit-border-radius: 3px;border-radius: 3px;display:inline-block;border: 1px #ccc solid;\"><div style=\"width:{$iPercentWidth}em; display:inline-block;background-color:$sColor;\">&nbsp;</div></div>&nbsp;$sValue %";
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -35,8 +36,10 @@ class AttributePhoneNumber extends AttributeString
public function GetValidationPattern()
{
return $this->GetOptional('validation_pattern',
'^'.utils::GetConfig()->Get('phone_number_validation_pattern').'$');
return $this->GetOptional(
'validation_pattern',
'^'.utils::GetConfig()->Get('phone_number_validation_pattern').'$'
);
}
public static function GetFormFieldClass()
@@ -57,4 +60,4 @@ class AttributePhoneNumber extends AttributeString
return '<a class="tel" href="'.$sUrl.'"><span class="text_decoration '.$sUrlDecorationClass.'"></span>'.parent::GetAsHTML($sValue).'</a>';
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -38,7 +39,7 @@ class AttributePropertySet extends AttributeTable
public function MakeRealValue($proposedValue, $oHostObj)
{
if (!is_array($proposedValue)) {
return array('?' => (string)$proposedValue);
return ['?' => (string)$proposedValue];
}
return $proposedValue;
@@ -47,7 +48,7 @@ class AttributePropertySet extends AttributeTable
public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
{
if (!is_array($value)) {
throw new CoreException('Expecting an array', array('found' => get_class($value)));
throw new CoreException('Expecting an array', ['found' => get_class($value)]);
}
if (count($value) == 0) {
return "";
@@ -71,27 +72,30 @@ class AttributePropertySet extends AttributeTable
}
public function GetAsCSV(
$value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true,
$value,
$sSeparator = ',',
$sTextQualifier = '"',
$oHostObject = null,
$bLocalize = true,
$bConvertToPlainText = false
)
{
) {
if (!is_array($value) || count($value) == 0) {
return "";
}
$aRes = array();
$aRes = [];
foreach ($value as $sProperty => $sValue) {
if ($sProperty == 'auth_pwd') {
$sValue = '*****';
}
$sFrom = array(',', '=');
$sTo = array('\,', '\=');
$sFrom = [',', '='];
$sTo = ['\,', '\='];
$aRes[] = $sProperty.'='.str_replace($sFrom, $sTo, (string)$sValue);
}
$sRaw = implode(',', $aRes);
$sFrom = array("\r\n", $sTextQualifier);
$sTo = array("\n", $sTextQualifier.$sTextQualifier);
$sFrom = ["\r\n", $sTextQualifier];
$sTo = ["\n", $sTextQualifier.$sTextQualifier];
$sEscaped = str_replace($sFrom, $sTo, $sRaw);
return $sTextQualifier.$sEscaped.$sTextQualifier;
@@ -115,4 +119,4 @@ class AttributePropertySet extends AttributeTable
return $sRes;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -19,7 +20,7 @@ use utils;
class AttributeQueryAttCodeSet extends AttributeSet
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_STRING;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_STRING;
public function __construct($sCode, array $aParams)
{
@@ -29,7 +30,7 @@ class AttributeQueryAttCodeSet extends AttributeSet
public static function ListExpectedParams()
{
return array_merge(parent::ListExpectedParams(), array('query_field'));
return array_merge(parent::ListExpectedParams(), ['query_field']);
}
protected function GetSQLCol($bFullSpec = false)
@@ -55,28 +56,27 @@ class AttributeQueryAttCodeSet extends AttributeSet
$sQueryField = $this->Get('query_field');
$sQuery = $oHostObj->Get($sQueryField);
if (empty($sQuery)) {
return array();
return [];
}
$oFilter = DBSearch::FromOQL($sQuery);
return $oFilter->GetSelectedClasses();
}
catch (OQLException $e) {
} catch (OQLException $e) {
IssueLog::Warning($e->getMessage());
}
return array();
return [];
}
public function GetAllowedValues($aArgs = array(), $sContains = '')
public function GetAllowedValues($aArgs = [], $sContains = '')
{
if (isset($aArgs['this'])) {
$oHostObj = $aArgs['this'];
$aClasses = $this->GetClassList($oHostObj);
$aAllowedAttributes = array();
$aAllAttributes = array();
$aAllowedAttributes = [];
$aAllAttributes = [];
if ((count($aClasses) == 1) && (array_keys($aClasses)[0] == array_values($aClasses)[0])) {
$sClass = reset($aClasses);
@@ -90,7 +90,7 @@ class AttributeQueryAttCodeSet extends AttributeSet
foreach ($aClasses as $sAlias => $sClass) {
$aAttributes = MetaModel::GetAttributesList($sClass);
foreach ($aAttributes as $sAttCode) {
$aAllAttributes[] = array('alias' => $sAlias, 'class' => $sClass, 'att_code' => $sAttCode);
$aAllAttributes[] = ['alias' => $sAlias, 'class' => $sClass, 'att_code' => $sAttCode];
}
}
}
@@ -125,16 +125,16 @@ class AttributeQueryAttCodeSet extends AttributeSet
public function MakeRealValue($proposedValue, $oHostObj, $bIgnoreErrors = false)
{
$oSet = new ormSet(MetaModel::GetAttributeOrigin($this->GetHostClass(), $this->GetCode()), $this->GetCode(), $this->GetMaxItems());
$aArgs = array();
$aArgs = [];
if (!empty($oHostObj)) {
$aArgs['this'] = $oHostObj;
}
$aAllowedAttributes = $this->GetAllowedValues($aArgs);
$aInvalidAttCodes = array();
$aInvalidAttCodes = [];
if (is_string($proposedValue) && !empty($proposedValue)) {
$proposedValue = trim($proposedValue);
$aProposedValues = $this->FromStringToArray($proposedValue);
$aValues = array();
$aValues = [];
foreach ($aProposedValues as $sValue) {
$sAttCode = trim($sValue);
if (empty($aAllowedAttributes) || isset($aAllowedAttributes[$sAttCode])) {
@@ -174,7 +174,7 @@ class AttributeQueryAttCodeSet extends AttributeSet
$aArgs['this'] = $oHostObject;
$aAllowedAttributes = $this->GetAllowedValues($aArgs);
$aLocalizedValues = array();
$aLocalizedValues = [];
foreach ($value as $sAttCode) {
if (isset($aAllowedAttributes[$sAttCode])) {
$sLabelForHtmlAttribute = utils::HtmlEntities($aAllowedAttributes[$sAttCode]);
@@ -188,4 +188,4 @@ class AttributeQueryAttCodeSet extends AttributeSet
return '<span class="'.implode(' ', $this->aCSSClasses).'">'.$value.'</span>';
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -26,7 +27,7 @@ use utils;
*/
class AttributeRedundancySettings extends AttributeDBField
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_RAW;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_RAW;
/**
* Useless constructor, but if not present PHP 7.4.0/7.4.1 is crashing :( (N°2329)
@@ -47,7 +48,7 @@ class AttributeRedundancySettings extends AttributeDBField
public static function ListExpectedParams()
{
return array(
return [
'sql',
'relation_code',
'from_class',
@@ -57,7 +58,7 @@ class AttributeRedundancySettings extends AttributeDBField
'min_up',
'min_up_type',
'min_up_mode',
);
];
}
public function GetValuesDef()
@@ -67,7 +68,7 @@ class AttributeRedundancySettings extends AttributeDBField
public function GetPrerequisiteAttributes($sClass = null)
{
return array();
return [];
}
public function GetEditClass()
@@ -82,7 +83,6 @@ class AttributeRedundancySettings extends AttributeDBField
.($bFullSpec ? $this->GetSQLColSpec() : '');
}
public function GetValidationPattern()
{
return "^[0-9]{1,3}|[0-9]{1,2}%|disabled$";
@@ -99,8 +99,7 @@ class AttributeRedundancySettings extends AttributeDBField
if ($this->Get('enabled')) {
if ($this->Get('min_up_type') == 'count') {
$sRet = (string)$this->Get('min_up');
} else // percent
{
} else { // percent
$sRet = $this->Get('min_up').'%';
}
}
@@ -135,12 +134,12 @@ class AttributeRedundancySettings extends AttributeDBField
public function ScalarToSQL($value)
{
if (!is_string($value)) {
throw new CoreException('Expected the attribute value to be a string', array(
throw new CoreException('Expected the attribute value to be a string', [
'found_type' => gettype($value),
'value' => $value,
'class' => $this->GetHostClass(),
'attribute' => $this->GetCode(),
));
]);
}
return $value;
@@ -148,8 +147,11 @@ class AttributeRedundancySettings extends AttributeDBField
public function GetRelationQueryData()
{
foreach (MetaModel::EnumRelationQueries($this->GetHostClass(), $this->Get('relation_code'),
false) as $sDummy => $aQueryInfo) {
foreach (MetaModel::EnumRelationQueries(
$this->GetHostClass(),
$this->Get('relation_code'),
false
) as $sDummy => $aQueryInfo) {
if ($aQueryInfo['sFromClass'] == $this->Get('from_class')) {
if ($aQueryInfo['sNeighbour'] == $this->Get('neighbour_id')) {
return $aQueryInfo;
@@ -157,7 +159,7 @@ class AttributeRedundancySettings extends AttributeDBField
}
}
return array();
return [];
}
/**
@@ -200,17 +202,23 @@ class AttributeRedundancySettings extends AttributeDBField
$sCurrentOption = $this->GetCurrentOption($sValue);
$sClass = $oHostObject ? get_class($oHostObject) : $this->m_sHostClass;
return sprintf($this->GetUserOptionFormat($sCurrentOption), $this->GetMinUpValue($sValue),
MetaModel::GetName($sClass));
return sprintf(
$this->GetUserOptionFormat($sCurrentOption),
$this->GetMinUpValue($sValue),
MetaModel::GetName($sClass)
);
}
public function GetAsCSV(
$sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true,
$sValue,
$sSeparator = ',',
$sTextQualifier = '"',
$oHostObject = null,
$bLocalize = true,
$bConvertToPlainText = false
)
{
$sFrom = array("\r\n", $sTextQualifier);
$sTo = array("\n", $sTextQualifier.$sTextQualifier);
) {
$sFrom = ["\r\n", $sTextQualifier];
$sTo = ["\n", $sTextQualifier.$sTextQualifier];
$sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
return $sTextQualifier.$sEscaped.$sTextQualifier;
@@ -305,24 +313,30 @@ class AttributeRedundancySettings extends AttributeDBField
foreach ($aUserOptions as $sUserOption) {
$bSelected = ($sUserOption == $sCurrentOption);
$sRet .= '<div>';
$sRet .= $this->GetDisplayOption($sCurrentValue, $oPage, $sFormPrefix, $bEditOption, $sUserOption,
$bSelected);
$sRet .= $this->GetDisplayOption(
$sCurrentValue,
$oPage,
$sFormPrefix,
$bEditOption,
$sUserOption,
$bSelected
);
$sRet .= '</div>';
}
return $sRet;
}
const USER_OPTION_DISABLED = 'disabled';
const USER_OPTION_ENABLED_COUNT = 'count';
const USER_OPTION_ENABLED_PERCENT = 'percent';
public const USER_OPTION_DISABLED = 'disabled';
public const USER_OPTION_ENABLED_COUNT = 'count';
public const USER_OPTION_ENABLED_PERCENT = 'percent';
/**
* Depending on the xxx_mode parameters, build the list of options that are allowed to the end-user
*/
protected function GetUserOptions($sValue)
{
$aRet = array();
$aRet = [];
if ($this->Get('enabled_mode') == 'user') {
$aRet[] = self::USER_OPTION_DISABLED;
}
@@ -374,9 +388,13 @@ class AttributeRedundancySettings extends AttributeDBField
* @throws Exception
*/
protected function GetDisplayOption(
$sCurrentValue, $oPage, $sFormPrefix, $bEditMode, $sUserOption, $bSelected = true
)
{
$sCurrentValue,
$oPage,
$sFormPrefix,
$bEditMode,
$sUserOption,
$bSelected = true
) {
$sRet = '';
$iCurrentValue = $this->GetMinUpValue($sCurrentValue);
@@ -412,8 +430,11 @@ class AttributeRedundancySettings extends AttributeDBField
}
break;
}
$sLabel = sprintf($this->GetUserOptionFormat($sUserOption), $sValue,
MetaModel::GetName($this->GetHostClass()));
$sLabel = sprintf(
$this->GetUserOptionFormat($sUserOption),
$sValue,
MetaModel::GetName($this->GetHostClass())
);
$sOptionName = $sHtmlNamesPrefix.'_user_option';
$sOptionId = $sOptionName.'_'.$sUserOption;
@@ -422,8 +443,11 @@ class AttributeRedundancySettings extends AttributeDBField
} else {
// Read-only: display only the currently selected option
if ($bSelected) {
$sRet = sprintf($this->GetUserOptionFormat($sUserOption), $iCurrentValue,
MetaModel::GetName($this->GetHostClass()));
$sRet = sprintf(
$this->GetUserOptionFormat($sUserOption),
$iCurrentValue,
MetaModel::GetName($this->GetHostClass())
);
}
}
@@ -457,4 +481,4 @@ class AttributeRedundancySettings extends AttributeDBField
return $sRet;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -27,8 +28,8 @@ use utils;
*/
abstract class AttributeSet extends AttributeDBFieldVoid
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_RAW;
const EDITABLE_INPUT_ID_SUFFIX = '-setwidget-values'; // used client side, see js/jquery.itop-set-widget.js
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_RAW;
public const EDITABLE_INPUT_ID_SUFFIX = '-setwidget-values'; // used client side, see js/jquery.itop-set-widget.js
protected $bDisplayLink; // Display search link in readonly mode
public function __construct($sCode, array $aParams)
@@ -48,7 +49,7 @@ abstract class AttributeSet extends AttributeDBFieldVoid
public static function ListExpectedParams()
{
return array_merge(parent::ListExpectedParams(), array('is_null_allowed', 'max_items'));
return array_merge(parent::ListExpectedParams(), ['is_null_allowed', 'max_items']);
}
/**
@@ -61,7 +62,7 @@ abstract class AttributeSet extends AttributeDBFieldVoid
* @throws \CoreException
* @throws \OQLException
*/
public function GetPossibleValues($aArgs = array(), $sContains = '')
public function GetPossibleValues($aArgs = [], $sContains = '')
{
return $this->GetAllowedValues($aArgs, $sContains);
}
@@ -75,13 +76,13 @@ abstract class AttributeSet extends AttributeDBFieldVoid
* @throws \CoreException
* @throws \OQLException
*/
public function GetJsonForWidget($oValue, $aArgs = array())
public function GetJsonForWidget($oValue, $aArgs = [])
{
$aJson = array();
$aJson = [];
// possible_values
$aAllowedValues = $this->GetPossibleValues($aArgs);
$aSetKeyValData = array();
$aSetKeyValData = [];
foreach ($aAllowedValues as $sCode => $sLabel) {
$aSetKeyValData[] = [
'code' => $sCode,
@@ -89,10 +90,10 @@ abstract class AttributeSet extends AttributeDBFieldVoid
];
}
$aJson['possible_values'] = $aSetKeyValData;
$aRemoved = array();
$aRemoved = [];
if (is_null($oValue)) {
$aJson['partial_values'] = array();
$aJson['orig_value'] = array();
$aJson['partial_values'] = [];
$aJson['orig_value'] = [];
} else {
$aPartialValues = $oValue->GetModified();
foreach ($aPartialValues as $key => $value) {
@@ -111,7 +112,7 @@ abstract class AttributeSet extends AttributeDBFieldVoid
}
$aJson['orig_value'] = array_values($aOrigValues);
}
$aJson['added'] = array();
$aJson['added'] = [];
$aJson['removed'] = $aRemoved;
$iMaxTags = $this->GetMaxItems();
@@ -176,7 +177,7 @@ abstract class AttributeSet extends AttributeDBFieldVoid
public function FromStringToArray($proposedValue, $sDefaultSepItem = ',')
{
$aValues = array();
$aValues = [];
if (!empty($proposedValue)) {
$sSepItem = MetaModel::GetConfig()->Get('tag_set_item_separator');
// convert also , separated strings
@@ -466,7 +467,8 @@ HTML;
{
/** @var \ormSet $original */
/** @var \ormSet $value */
parent::RecordAttChange($oObject,
parent::RecordAttChange(
$oObject,
implode(' ', $original->GetValues()),
implode(' ', $value->GetValues())
);
@@ -476,4 +478,4 @@ HTML;
{
return CMDBChangeOpSetAttributeTagSet::class;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -23,7 +24,7 @@ use Str;
*/
class AttributeStopWatch extends AttributeDefinition
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_RAW;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_RAW;
/**
* Useless constructor, but if not present PHP 7.4.0/7.4.1 is crashing :( (N°2329)
@@ -45,8 +46,10 @@ class AttributeStopWatch extends AttributeDefinition
public static function ListExpectedParams()
{
// The list of thresholds must be an array of iPercent => array of 'option' => value
return array_merge(parent::ListExpectedParams(),
array("states", "goal_computing", "working_time_computing", "thresholds"));
return array_merge(
parent::ListExpectedParams(),
["states", "goal_computing", "working_time_computing", "thresholds"]
);
}
public function GetEditClass()
@@ -124,7 +127,7 @@ class AttributeStopWatch extends AttributeDefinition
if ($sPrefix == '') {
$sPrefix = $this->GetCode(); // Warning: a stopwatch does not have any 'sql' property, so its SQL column is equal to its attribute code !!
}
$aColumns = array();
$aColumns = [];
// Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
$aColumns[''] = $sPrefix.'_timespent';
$aColumns['_started'] = $sPrefix.'_started';
@@ -163,7 +166,7 @@ class AttributeStopWatch extends AttributeDefinition
public function FromSQLToValue($aCols, $sPrefix = '')
{
$aExpectedCols = array($sPrefix, $sPrefix.'_started', $sPrefix.'_laststart', $sPrefix.'_stopped');
$aExpectedCols = [$sPrefix, $sPrefix.'_started', $sPrefix.'_laststart', $sPrefix.'_stopped'];
foreach ($this->ListThresholds() as $iThreshold => $aFoo) {
$sThPrefix = '_'.$iThreshold;
$aExpectedCols[] = $sPrefix.$sThPrefix.'_deadline';
@@ -203,7 +206,7 @@ class AttributeStopWatch extends AttributeDefinition
public function GetSQLValues($value)
{
if ($value instanceof ormStopWatch) {
$aValues = array();
$aValues = [];
$aValues[$this->GetCode().'_timespent'] = $value->GetTimeSpent();
$aValues[$this->GetCode().'_started'] = self::SecondsToDate($value->GetStartDate());
$aValues[$this->GetCode().'_laststart'] = self::SecondsToDate($value->GetLastStartDate());
@@ -217,7 +220,7 @@ class AttributeStopWatch extends AttributeDefinition
$aValues[$sPrefix.'_overrun'] = $value->GetOverrun($iThreshold);
}
} else {
$aValues = array();
$aValues = [];
$aValues[$this->GetCode().'_timespent'] = '';
$aValues[$this->GetCode().'_started'] = '';
$aValues[$this->GetCode().'_laststart'] = '';
@@ -229,7 +232,7 @@ class AttributeStopWatch extends AttributeDefinition
public function GetSQLColumns($bFullSpec = false)
{
$aColumns = array();
$aColumns = [];
$aColumns[$this->GetCode().'_timespent'] = 'INT(11) UNSIGNED';
$aColumns[$this->GetCode().'_started'] = 'DATETIME';
$aColumns[$this->GetCode().'_laststart'] = 'DATETIME';
@@ -265,7 +268,7 @@ class AttributeStopWatch extends AttributeDefinition
public function GetBasicFilterOperators()
{
return array();
return [];
}
public function GetBasicFilterLooseOperator()
@@ -305,10 +308,13 @@ class AttributeStopWatch extends AttributeDefinition
* @return string
*/
public function GetAsCSV(
$value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true,
$value,
$sSeparator = ',',
$sTextQualifier = '"',
$oHostObject = null,
$bLocalize = true,
$bConvertToPlainText = false
)
{
) {
return $value->GetTimeSpent();
}
@@ -353,13 +359,13 @@ class AttributeStopWatch extends AttributeDefinition
$sPrefix = $this->GetCode();
switch ($sItemCode) {
case 'timespent':
return array('' => $sPrefix.'_timespent');
return ['' => $sPrefix.'_timespent'];
case 'started':
return array('' => $sPrefix.'_started');
return ['' => $sPrefix.'_started'];
case 'laststart':
return array('' => $sPrefix.'_laststart');
return ['' => $sPrefix.'_laststart'];
case 'stopped':
return array('' => $sPrefix.'_stopped');
return ['' => $sPrefix.'_stopped'];
}
foreach ($this->ListThresholds() as $iThreshold => $aFoo) {
@@ -369,13 +375,13 @@ class AttributeStopWatch extends AttributeDefinition
$sThresholdCode = substr($sItemCode, strlen($sThPrefix));
switch ($sThresholdCode) {
case 'deadline':
return array('' => $sPrefix.'_'.$iThreshold.'_deadline');
return ['' => $sPrefix.'_'.$iThreshold.'_deadline'];
case 'passed':
return array('' => $sPrefix.'_'.$iThreshold.'_passed');
return ['' => $sPrefix.'_'.$iThreshold.'_passed'];
case 'triggered':
return array('' => $sPrefix.'_'.$iThreshold.'_triggered');
return ['' => $sPrefix.'_'.$iThreshold.'_triggered'];
case 'overrun':
return array('' => $sPrefix.'_'.$iThreshold.'_overrun');
return ['' => $sPrefix.'_'.$iThreshold.'_overrun'];
}
}
}
@@ -425,7 +431,6 @@ class AttributeStopWatch extends AttributeDefinition
throw new CoreException("Unknown item code '$sItemCode' for attribute ".$this->GetHostClass().'::'.$this->GetCode());
}
public function GetSubItemSearchType($sItemCode)
{
switch ($sItemCode) {
@@ -457,7 +462,7 @@ class AttributeStopWatch extends AttributeDefinition
return static::SEARCH_WIDGET_TYPE_RAW;
}
public function GetSubItemAllowedValues($sItemCode, $aArgs = array(), $sContains = '')
public function GetSubItemAllowedValues($sItemCode, $aArgs = [], $sContains = '')
{
foreach ($this->ListThresholds() as $iThreshold => $aFoo) {
$sThPrefix = $iThreshold.'_';
@@ -467,10 +472,10 @@ class AttributeStopWatch extends AttributeDefinition
switch ($sThresholdCode) {
case 'passed':
case 'triggered':
return array(
return [
0 => $this->GetBooleanLabel(0),
1 => $this->GetBooleanLabel(1),
);
];
}
}
}
@@ -524,8 +529,10 @@ class AttributeStopWatch extends AttributeDefinition
$sThresholdCode = substr($sItemCode, strlen($sThPrefix));
switch ($sThresholdCode) {
case 'deadline':
$sHtml = (int)$sValue ? date((string)AttributeDateTime::GetFormat(),
(int)$sValue) : null;
$sHtml = (int)$sValue ? date(
(string)AttributeDateTime::GetFormat(),
(int)$sValue
) : null;
break;
case 'passed':
case 'triggered':
@@ -648,11 +655,14 @@ class AttributeStopWatch extends AttributeDefinition
}
public function GetSubItemAsCSV(
$sItemCode, $value, $sSeparator = ',', $sTextQualifier = '"', $bConvertToPlainText = false
)
{
$sFrom = array("\r\n", $sTextQualifier);
$sTo = array("\n", $sTextQualifier.$sTextQualifier);
$sItemCode,
$value,
$sSeparator = ',',
$sTextQualifier = '"',
$bConvertToPlainText = false
) {
$sFrom = ["\r\n", $sTextQualifier];
$sTo = ["\n", $sTextQualifier.$sTextQualifier];
$sEscaped = str_replace($sFrom, $sTo, (string)$value);
$sRet = $sTextQualifier.$sEscaped.$sTextQualifier;
@@ -821,4 +831,4 @@ class AttributeStopWatch extends AttributeDefinition
}
}
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -19,7 +20,7 @@ use utils;
*/
class AttributeString extends AttributeDBField
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_STRING;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_STRING;
/**
* Useless constructor, but if not present PHP 7.4.0/7.4.1 is crashing :( (N°2329)
@@ -85,7 +86,7 @@ class AttributeString extends AttributeDBField
public function GetBasicFilterOperators()
{
return array(
return [
"=" => "equals",
"!=" => "differs from",
"Like" => "equals (no case)",
@@ -93,7 +94,7 @@ class AttributeString extends AttributeDBField
"Contains" => "contains",
"Begins with" => "begins with",
"Finishes with" => "finishes with",
);
];
}
public function GetBasicFilterLooseOperator()
@@ -152,24 +153,27 @@ class AttributeString extends AttributeDBField
public function ScalarToSQL($value)
{
if (!is_string($value) && !is_null($value)) {
throw new CoreWarning('Expected the attribute value to be a string', array(
throw new CoreWarning('Expected the attribute value to be a string', [
'found_type' => gettype($value),
'value' => $value,
'class' => $this->GetHostClass(),
'attribute' => $this->GetCode(),
));
]);
}
return $value;
}
public function GetAsCSV(
$sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true,
$sValue,
$sSeparator = ',',
$sTextQualifier = '"',
$oHostObject = null,
$bLocalize = true,
$bConvertToPlainText = false
)
{
$sFrom = array("\r\n", $sTextQualifier);
$sTo = array("\n", $sTextQualifier.$sTextQualifier);
) {
$sFrom = ["\r\n", $sTextQualifier];
$sTo = ["\n", $sTextQualifier.$sTextQualifier];
$sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
return $sTextQualifier.$sEscaped.$sTextQualifier;
@@ -196,4 +200,4 @@ class AttributeString extends AttributeDBField
return $oFormField;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -52,7 +53,7 @@ class AttributeSubItem extends AttributeDefinition
return $oParent->GetSubItemSearchType($this->Get('item_code'));
}
public function GetAllowedValues($aArgs = array(), $sContains = '')
public function GetAllowedValues($aArgs = [], $sContains = '')
{
/** @var AttributeStopWatch $oParent */
$oParent = $this->GetTargetAttDef();
@@ -72,7 +73,7 @@ class AttributeSubItem extends AttributeDefinition
public static function ListExpectedParams()
{
return array_merge(parent::ListExpectedParams(), array('target_attcode', 'item_code'));
return array_merge(parent::ListExpectedParams(), ['target_attcode', 'item_code']);
}
public function GetParentAttCode()
@@ -121,7 +122,7 @@ class AttributeSubItem extends AttributeDefinition
return null;
}
// public function IsNullAllowed() {return false;}
// public function IsNullAllowed() {return false;}
public static function LoadInObject()
{
@@ -147,7 +148,7 @@ class AttributeSubItem extends AttributeDefinition
}
//
// protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
// protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
public function FromSQLToValue($aCols, $sPrefix = '')
{
@@ -155,12 +156,12 @@ class AttributeSubItem extends AttributeDefinition
public function GetSQLColumns($bFullSpec = false)
{
return array();
return [];
}
public function GetBasicFilterOperators()
{
return array();
return [];
}
public function GetBasicFilterLooseOperator()
@@ -214,13 +215,21 @@ class AttributeSubItem extends AttributeDefinition
}
public function GetAsCSV(
$value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true,
$value,
$sSeparator = ',',
$sTextQualifier = '"',
$oHostObject = null,
$bLocalize = true,
$bConvertToPlainText = false
)
{
) {
$oParent = $this->GetTargetAttDef();
$res = $oParent->GetSubItemAsCSV($this->Get('item_code'), $value, $sSeparator, $sTextQualifier,
$bConvertToPlainText);
$res = $oParent->GetSubItemAsCSV(
$this->Get('item_code'),
$value,
$sSeparator,
$sTextQualifier,
$bConvertToPlainText
);
return $res;
}
@@ -270,4 +279,4 @@ class AttributeSubItem extends AttributeDefinition
return $oFormField;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -13,7 +14,7 @@ use Str;
class AttributeTable extends AttributeDBField
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_RAW;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_RAW;
/**
* Useless constructor, but if not present PHP 7.4.0/7.4.1 is crashing :( (N°2329)
@@ -49,7 +50,7 @@ class AttributeTable extends AttributeDBField
public function GetNullValue()
{
return array();
return [];
}
public function IsNull($proposedValue)
@@ -65,7 +66,6 @@ class AttributeTable extends AttributeDBField
return count($proposedValue) > 0;
}
public function GetEditValue($sValue, $oHostObj = null)
{
return '';
@@ -75,10 +75,10 @@ class AttributeTable extends AttributeDBField
public function MakeRealValue($proposedValue, $oHostObj)
{
if (is_null($proposedValue)) {
return array();
return [];
} else {
if (!is_array($proposedValue)) {
return array(0 => array(0 => $proposedValue));
return [0 => [0 => $proposedValue]];
}
}
@@ -98,8 +98,7 @@ class AttributeTable extends AttributeDBField
if ($value === false) {
$value = $this->MakeRealValue($aCols[$sPrefix.''], null);
}
}
catch (Exception $e) {
} catch (Exception $e) {
$value = $this->MakeRealValue($aCols[$sPrefix.''], null);
}
@@ -108,11 +107,10 @@ class AttributeTable extends AttributeDBField
public function GetSQLValues($value)
{
$aValues = array();
$aValues = [];
try {
$sSerializedValue = serialize($value);
}
catch (Exception $e) {
} catch (Exception $e) {
$sSerializedValue = json_encode($value);
}
$aValues[$this->Get("sql")] = $sSerializedValue;
@@ -123,7 +121,7 @@ class AttributeTable extends AttributeDBField
public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
{
if (!is_array($value)) {
throw new CoreException('Expecting an array', array('found' => get_class($value)));
throw new CoreException('Expecting an array', ['found' => get_class($value)]);
}
if (count($value) == 0) {
return "";
@@ -148,10 +146,13 @@ class AttributeTable extends AttributeDBField
}
public function GetAsCSV(
$sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true,
$sValue,
$sSeparator = ',',
$sTextQualifier = '"',
$oHostObject = null,
$bLocalize = true,
$bConvertToPlainText = false
)
{
) {
// Not implemented
return '';
}
@@ -174,4 +175,4 @@ class AttributeTable extends AttributeDBField
return $sRes;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -27,7 +28,7 @@ use utils;
*/
class AttributeTagSet extends AttributeSet
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_TAG_SET;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_TAG_SET;
public function __construct($sCode, array $aParams)
{
@@ -42,7 +43,7 @@ class AttributeTagSet extends AttributeSet
public static function ListExpectedParams()
{
return array_merge(parent::ListExpectedParams(), array('tag_code_max_len'));
return array_merge(parent::ListExpectedParams(), ['tag_code_max_len']);
}
/**
@@ -52,13 +53,13 @@ class AttributeTagSet extends AttributeSet
*
* @return string JSON to be used in the itop.tagset_widget JQuery widget
*/
public function GetJsonForWidget($oValue, $aArgs = array())
public function GetJsonForWidget($oValue, $aArgs = [])
{
$aJson = array();
$aJson = [];
// possible_values
$aTagSetObjectData = $this->GetAllowedValues($aArgs);
$aTagSetKeyValData = array();
$aTagSetKeyValData = [];
foreach ($aTagSetObjectData as $sTagCode => $sTagLabel) {
$aTagSetKeyValData[] = [
'code' => $sTagCode,
@@ -68,10 +69,10 @@ class AttributeTagSet extends AttributeSet
$aJson['possible_values'] = $aTagSetKeyValData;
if (is_null($oValue)) {
$aJson['partial_values'] = array();
$aJson['orig_value'] = array();
$aJson['added'] = array();
$aJson['removed'] = array();
$aJson['partial_values'] = [];
$aJson['orig_value'] = [];
$aJson['added'] = [];
$aJson['removed'] = [];
} else {
$aJson['orig_value'] = array_merge($oValue->GetValues(), $oValue->GetModified());
$aJson['added'] = $oValue->GetAdded();
@@ -82,11 +83,10 @@ class AttributeTagSet extends AttributeSet
$aJson['partial_values'] = $oValue->GetModified();
} else {
// For simple updates
$aJson['partial_values'] = array();
$aJson['partial_values'] = [];
}
}
$iMaxTags = $this->GetMaxItems();
$aJson['max_items_allowed'] = $iMaxTags;
@@ -95,7 +95,7 @@ class AttributeTagSet extends AttributeSet
public function FromStringToArray($proposedValue, $sDefaultSepItem = ',')
{
$aValues = array();
$aValues = [];
if (!empty($proposedValue)) {
foreach (explode(' ', $proposedValue) as $sCode) {
$sValue = trim($sCode);
@@ -126,7 +126,7 @@ class AttributeTagSet extends AttributeSet
} else {
$oTagSet = new ormTagSet($sClass, $sAttCode, $this->GetMaxItems());
}
$aGoodTags = array();
$aGoodTags = [];
foreach ($aTagCodes as $sTagCode) {
if ($sTagCode === '') {
continue;
@@ -177,12 +177,12 @@ class AttributeTagSet extends AttributeSet
return ($val1 == $val2);
}
public function GetAllowedValues($aArgs = array(), $sContains = '')
public function GetAllowedValues($aArgs = [], $sContains = '')
{
$sAttCode = $this->GetCode();
$sClass = MetaModel::GetAttributeOrigin($this->GetHostClass(), $sAttCode);
$aAllowedTags = TagSetFieldData::GetAllowedValues($sClass, $sAttCode);
$aAllowedValues = array();
$aAllowedValues = [];
foreach ($aAllowedTags as $oAllowedTag) {
$aAllowedValues[$oAllowedTag->Get('code')] = $oAllowedTag->Get('label');
}
@@ -253,10 +253,13 @@ class AttributeTagSet extends AttributeSet
$sSepItem = MetaModel::GetConfig()->Get('tag_set_item_separator');
}
if (!empty($sProposedValue)) {
$oTagSet = new ormTagSet(MetaModel::GetAttributeOrigin($this->GetHostClass(), $this->GetCode()),
$this->GetCode(), $this->GetMaxItems());
$oTagSet = new ormTagSet(
MetaModel::GetAttributeOrigin($this->GetHostClass(), $this->GetCode()),
$this->GetCode(),
$this->GetMaxItems()
);
$aLabels = explode($sSepItem, $sProposedValue);
$aCodes = array();
$aCodes = [];
foreach ($aLabels as $sTagLabel) {
if (!empty($sTagLabel)) {
$aCodes[] = ($bLocalizedValue) ? $oTagSet->GetTagFromLabel($sTagLabel) : $sTagLabel;
@@ -313,12 +316,12 @@ class AttributeTagSet extends AttributeSet
return implode(', ', $aValues);
}
throw new CoreWarning('Expected the attribute value to be a TagSet', array(
throw new CoreWarning('Expected the attribute value to be a TagSet', [
'found_type' => gettype($sValue),
'value' => $sValue,
'class' => $this->GetHostClass(),
'attribute' => $this->GetCode(),
));
]);
}
/**
@@ -337,12 +340,12 @@ class AttributeTagSet extends AttributeSet
return implode(' ', $aValues);
}
throw new CoreWarning('Expected the attribute value to be a TagSet', array(
throw new CoreWarning('Expected the attribute value to be a TagSet', [
'found_type' => gettype($value),
'value' => $value,
'class' => $this->GetHostClass(),
'attribute' => $this->GetCode(),
));
]);
}
/**
@@ -374,19 +377,20 @@ class AttributeTagSet extends AttributeSet
$oValue = $this->MakeRealValue($value, $oHostObject);
return $this->GetAsHTML($oValue, $oHostObject, $bLocalize);
}
catch (Exception $e) {
} catch (Exception $e) {
// unknown tags are present display the code instead
}
$aTagCodes = $this->FromStringToArray($value);
$aValues = array();
$oTagSet = new ormTagSet(MetaModel::GetAttributeOrigin($this->GetHostClass(), $this->GetCode()),
$this->GetCode(), $this->GetMaxItems());
$aValues = [];
$oTagSet = new ormTagSet(
MetaModel::GetAttributeOrigin($this->GetHostClass(), $this->GetCode()),
$this->GetCode(),
$this->GetMaxItems()
);
foreach ($aTagCodes as $sTagCode) {
try {
$oTagSet->Add($sTagCode);
}
catch (Exception $e) {
} catch (Exception $e) {
$aValues[] = $sTagCode;
}
}
@@ -419,7 +423,7 @@ class AttributeTagSet extends AttributeSet
$aAllowedTags = TagSetFieldData::GetAllowedValues(MetaModel::GetAttributeOrigin($this->GetHostClass(), $this->GetCode()), $this->GetCode());
if (!empty($aDelta['removed'])) {
$aRemoved = array();
$aRemoved = [];
foreach ($aDelta['removed'] as $idx => $sTagCode) {
if (empty($sTagCode)) {
continue;
@@ -444,7 +448,7 @@ class AttributeTagSet extends AttributeSet
$sResult .= ', ';
}
$aAdded = array();
$aAdded = [];
foreach ($aDelta['added'] as $idx => $sTagCode) {
if (empty($sTagCode)) {
continue;
@@ -562,10 +566,10 @@ HTML;
*/
public function EnumTemplateVerbs()
{
return array(
return [
'' => 'Plain text representation',
'html' => 'HTML representation (unordered list)',
);
];
}
/**
@@ -613,7 +617,7 @@ HTML;
*/
public function GetForJSON($value)
{
$aRet = array();
$aRet = [];
if (is_object($value) && ($value instanceof ormTagSet)) {
$aRet = $value->GetValues();
}
@@ -659,4 +663,4 @@ HTML;
{
return '\\Combodo\\iTop\\Form\\Field\\TagSetField';
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -15,7 +16,7 @@ use Exception;
*/
class AttributeTemplateHTML extends AttributeText
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_STRING;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_STRING;
/**
* Useless constructor, but if not present PHP 7.4.0/7.4.1 is crashing :( (N°2329)
@@ -36,7 +37,7 @@ class AttributeTemplateHTML extends AttributeText
public function GetSQLColumns($bFullSpec = false)
{
$aColumns = array();
$aColumns = [];
$aColumns[$this->Get('sql')] = $this->GetSQLCol();
if ($this->GetOptional('format', null) != null) {
// Add the extra column only if the property 'format' is specified for the attribute
@@ -58,4 +59,4 @@ class AttributeTemplateHTML extends AttributeText
{
return $this->GetOptional('format', 'html'); // Defaults to HTML
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -15,7 +16,7 @@ use Exception;
*/
class AttributeTemplateString extends AttributeString
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_STRING;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_STRING;
/**
* Useless constructor, but if not present PHP 7.4.0/7.4.1 is crashing :( (N°2329)
@@ -33,4 +34,4 @@ class AttributeTemplateString extends AttributeString
{
parent::__construct($sCode, $aParams);
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -15,7 +16,7 @@ use Exception;
*/
class AttributeTemplateText extends AttributeText
{
const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_STRING;
public const SEARCH_WIDGET_TYPE = self::SEARCH_WIDGET_TYPE_STRING;
/**
* Useless constructor, but if not present PHP 7.4.0/7.4.1 is crashing :( (N°2329)
@@ -33,4 +34,4 @@ class AttributeTemplateText extends AttributeText
{
parent::__construct($sCode, $aParams);
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -58,7 +59,7 @@ class AttributeText extends AttributeString
public function GetSQLColumns($bFullSpec = false)
{
$aColumns = array();
$aColumns = [];
$aColumns[$this->Get('sql')] = $this->GetSQLCol($bFullSpec);
if ($this->GetOptional('format', null) != null) {
// Add the extra column only if the property 'format' is specified for the attribute
@@ -76,7 +77,7 @@ class AttributeText extends AttributeString
if ($sPrefix == '') {
$sPrefix = $this->Get('sql');
}
$aColumns = array();
$aColumns = [];
// Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
$aColumns[''] = $sPrefix;
if ($this->GetOptional('format', null) != null) {
@@ -98,8 +99,12 @@ class AttributeText extends AttributeString
{
if (!$bWikiOnly) {
$sPattern = '/'.str_replace('/', '\/', utils::GetConfig()->Get('url_validation_pattern')).'/i';
if (preg_match_all($sPattern, $sText, $aAllMatches,
PREG_SET_ORDER /* important !*/ | PREG_OFFSET_CAPTURE /* important ! */)) {
if (preg_match_all(
$sPattern,
$sText,
$aAllMatches,
PREG_SET_ORDER /* important !*/ | PREG_OFFSET_CAPTURE /* important ! */
)) {
$i = count($aAllMatches);
// Replace the URLs by an actual hyperlink <a href="...">...</a>
// Let's do it backwards so that the initial positions are not modified by the replacement
@@ -153,7 +158,7 @@ class AttributeText extends AttributeString
public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
{
$aStyles = array();
$aStyles = [];
if ($this->GetWidth() != '') {
$aStyles[] = 'width:'.$this->GetWidth();
}
@@ -356,7 +361,7 @@ class AttributeText extends AttributeString
public function GetSQLValues($value)
{
$aValues = array();
$aValues = [];
$aValues[$this->Get("sql")] = $this->ScalarToSQL($value);
if ($this->GetOptional('format', null) != null) {
// Add the extra column only if the property 'format' is specified for the attribute
@@ -367,17 +372,20 @@ class AttributeText extends AttributeString
}
public function GetAsCSV(
$sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true,
$sValue,
$sSeparator = ',',
$sTextQualifier = '"',
$oHostObject = null,
$bLocalize = true,
$bConvertToPlainText = false
)
{
) {
switch ($this->GetFormat()) {
case 'html':
if ($bConvertToPlainText) {
$sValue = utils::HtmlToText((string)$sValue);
}
$sFrom = array("\r\n", $sTextQualifier);
$sTo = array("\n", $sTextQualifier.$sTextQualifier);
$sFrom = ["\r\n", $sTextQualifier];
$sTo = ["\n", $sTextQualifier.$sTextQualifier];
$sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
return $sTextQualifier.$sEscaped.$sTextQualifier;
@@ -385,8 +393,14 @@ class AttributeText extends AttributeString
case 'text':
default:
return parent::GetAsCSV($sValue, $sSeparator, $sTextQualifier, $oHostObject, $bLocalize,
$bConvertToPlainText);
return parent::GetAsCSV(
$sValue,
$sSeparator,
$sTextQualifier,
$oHostObject,
$bLocalize,
$bConvertToPlainText
);
}
}
@@ -405,4 +419,4 @@ class AttributeText extends AttributeString
? CMDBChangeOpSetAttributeHTML::class
: CMDBChangeOpSetAttributeText::class;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -53,7 +54,7 @@ class AttributeURL extends AttributeString
public static function ListExpectedParams()
{
//return parent::ListExpectedParams();
return array_merge(parent::ListExpectedParams(), array("target"));
return array_merge(parent::ListExpectedParams(), ["target"]);
}
protected function GetSQLCol($bFullSpec = false)
@@ -122,4 +123,4 @@ class AttributeURL extends AttributeString
{
return CMDBChangeOpSetAttributeURL::class;
}
}
}

View File

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

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -14,4 +15,4 @@ namespace Combodo\iTop\Core\AttributeDefinition;
interface iAttributeNoGroupBy
{
//no method, just a contract on implement
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -8,120 +9,120 @@ namespace Combodo\iTop\Core\Kpi;
class KpiLogData
{
const TYPE_REPORT = 'report';
const TYPE_STATS = 'stats';
const TYPE_REQUEST = 'request';
public const TYPE_REPORT = 'report';
public const TYPE_STATS = 'stats';
public const TYPE_REQUEST = 'request';
/** @var string */
public $sType;
/** @var string */
public $sOperation;
/** @var string */
public $sArguments;
/** @var float */
public $fStartTime;
/** @var float */
public $fStopTime;
/** @var string */
public $sExtension;
/** @var int */
public $iInitialMemory;
/** @var int */
public $iCurrentMemory;
/** @var int */
public $iPeakMemory;
/** @var array */
public $aData;
/** @var string */
public $sType;
/** @var string */
public $sOperation;
/** @var string */
public $sArguments;
/** @var float */
public $fStartTime;
/** @var float */
public $fStopTime;
/** @var string */
public $sExtension;
/** @var int */
public $iInitialMemory;
/** @var int */
public $iCurrentMemory;
/** @var int */
public $iPeakMemory;
/** @var array */
public $aData;
// Computed
public float $fDuration;
/**
* @param string $sType
* @param string $sOperation
* @param string $sArguments
* @param float $fStartTime
* @param float $fStopTime
* @param string $sExtension
* @param int $iInitialMemory
* @param int $iCurrentMemory
* @param array $aData
*/
public function __construct($sType, $sOperation, $sArguments, $fStartTime, $fStopTime, $sExtension, $iInitialMemory = 0, $iCurrentMemory = 0, $iPeakMemory = 0, $aData = [])
{
$this->sType = $sType;
$this->sOperation = $sOperation;
$this->sArguments = @iconv(mb_detect_encoding($sArguments, mb_detect_order(), true), 'UTF-8', $sArguments);
$this->fStartTime = $fStartTime;
$this->fStopTime = $fStopTime;
$this->sExtension = $sExtension;
$this->iInitialMemory = $iInitialMemory;
$this->iCurrentMemory = $iCurrentMemory;
$this->iPeakMemory = $iPeakMemory;
$this->aData = $aData;
$this->fDuration = sprintf('%01.4f', $this->fStopTime - $this->fStartTime);
}
/**
* @param string $sType
* @param string $sOperation
* @param string $sArguments
* @param float $fStartTime
* @param float $fStopTime
* @param string $sExtension
* @param int $iInitialMemory
* @param int $iCurrentMemory
* @param array $aData
*/
public function __construct($sType, $sOperation, $sArguments, $fStartTime, $fStopTime, $sExtension, $iInitialMemory = 0, $iCurrentMemory = 0, $iPeakMemory = 0, $aData = [])
{
$this->sType = $sType;
$this->sOperation = $sOperation;
$this->sArguments = @iconv(mb_detect_encoding($sArguments, mb_detect_order(), true), 'UTF-8', $sArguments);
$this->fStartTime = $fStartTime;
$this->fStopTime = $fStopTime;
$this->sExtension = $sExtension;
$this->iInitialMemory = $iInitialMemory;
$this->iCurrentMemory = $iCurrentMemory;
$this->iPeakMemory = $iPeakMemory;
$this->aData = $aData;
$this->fDuration = sprintf('%01.4f', $this->fStopTime - $this->fStartTime);
}
/**
* Return the CSV Header
*
* @return string
*/
public static function GetCSVHeader()
{
return "Type,Operation,Arguments,StartTime,StopTime,Duration,Extension,InitialMemory,CurrentMemory,PeakMemory";
}
/**
* Return the CSV Header
*
* @return string
*/
public static function GetCSVHeader()
{
return "Type,Operation,Arguments,StartTime,StopTime,Duration,Extension,InitialMemory,CurrentMemory,PeakMemory";
}
/**
* Return the CSV line for the values
* @return string
*/
public function GetCSV()
{
$sType = $this->RemoveQuotes($this->sType);
$sOperation = $this->RemoveQuotes($this->sOperation);
$sArguments = $this->RemoveQuotes($this->sArguments);
$sExtension = $this->RemoveQuotes($this->sExtension);
return "\"$sType\",\"$sOperation\",\"$sArguments\",$this->fStartTime,$this->fStopTime,$this->fDuration,\"$sExtension\",$this->iInitialMemory,$this->iCurrentMemory,$this->iPeakMemory";
}
/**
* Return the CSV line for the values
* @return string
*/
public function GetCSV()
{
$sType = $this->RemoveQuotes($this->sType);
$sOperation = $this->RemoveQuotes($this->sOperation);
$sArguments = $this->RemoveQuotes($this->sArguments);
$sExtension = $this->RemoveQuotes($this->sExtension);
return "\"$sType\",\"$sOperation\",\"$sArguments\",$this->fStartTime,$this->fStopTime,$this->fDuration,\"$sExtension\",$this->iInitialMemory,$this->iCurrentMemory,$this->iPeakMemory";
}
private function RemoveQuotes(string $sEntry): string
{
return str_replace('"', "'", $sEntry);
}
private function RemoveQuotes(string $sEntry): string
{
return str_replace('"', "'", $sEntry);
}
/**
* @param \Combodo\iTop\Core\Kpi\KpiLogData $oOther
*
* @return float
*/
public function Compare(KpiLogData $oOther): float
{
if ($oOther->fStartTime > $this->fStartTime) {
return -1;
}
return 1;
}
/**
* @param \Combodo\iTop\Core\Kpi\KpiLogData $oOther
*
* @return float
*/
public function Compare(KpiLogData $oOther): float
{
if ($oOther->fStartTime > $this->fStartTime) {
return -1;
}
return 1;
}
public function Contains(KpiLogData $oOther): bool
{
if ($oOther->fStartTime < $this->fStartTime) {
return false;
}
public function Contains(KpiLogData $oOther): bool
{
if ($oOther->fStartTime < $this->fStartTime) {
return false;
}
if ($oOther->fStartTime > $this->fStopTime) {
return false;
}
if ($oOther->fStartTime > $this->fStopTime) {
return false;
}
return true;
}
return true;
}
public function __toString()
{
return "$this->sType:$this->sOperation:$this->sArguments";
}
public function __toString()
{
return "$this->sType:$this->sOperation:$this->sArguments";
}
public function GetUUID(): string
{
return sha1($this->__toString());
}
}
public function GetUUID(): string
{
return sha1($this->__toString());
}
}

View File

@@ -38,9 +38,9 @@ use MetaModel;
class SelectObjectField extends AbstractSimpleField
{
/** @var int CONTROL_SELECT */
const CONTROL_SELECT = 1;
public const CONTROL_SELECT = 1;
/** @var int CONTROL_RADIO_VERTICAL */
const CONTROL_RADIO_VERTICAL = 2;
public const CONTROL_RADIO_VERTICAL = 2;
/** @var \DBSearch $oSearch */
protected $oSearch;
@@ -176,7 +176,8 @@ class SelectObjectField extends AbstractSimpleField
/**
* @return \DBSearch
*/
public function GetSearch() {
public function GetSearch()
{
return $this->oSearch;
}
@@ -217,14 +218,16 @@ class SelectObjectField extends AbstractSimpleField
/**
* @return int
*/
public function GetControlType() {
public function GetControlType()
{
return $this->iControlType;
}
/**
* @return string|null
*/
public function GetSearchEndpoint() {
public function GetSearchEndpoint()
{
return $this->sSearchEndpoint;
}
@@ -241,7 +244,8 @@ class SelectObjectField extends AbstractSimpleField
*
* @since 3.1.0 N°6414 replaces VerifyCurrentValue$
*/
public function ResetCurrentValueIfNotAmongAllowedValues(bool $bAlways = false) {
public function ResetCurrentValueIfNotAmongAllowedValues(bool $bAlways = false)
{
if (!$this->GetReadOnly() || $bAlways) {
$oValuesSet = FieldHelper::GetObjectsSetFromSearchAndCurrentValueId($this->oSearch, $this->currentValue);

View File

@@ -39,9 +39,9 @@ class FormCompatibilityExtension extends AbstractExtension
// Alias of dict_s, to be compatible with Symfony/Twig standard
new TwigFilter('trans', function ($sStringCode, $aData = null, $sTransDomain = false) {
return Dict::S($sStringCode);
})
}),
];
}
}
}

View File

@@ -2,26 +2,28 @@
namespace Combodo\iTop\PhpParser\Evaluation;
use \Combodo\iTop\Setup\ModuleDiscovery\ModuleFileParser;
use \Combodo\iTop\Setup\ModuleDiscovery\ModuleFileReaderException;
use Combodo\iTop\Setup\ModuleDiscovery\ModuleFileParser;
use Combodo\iTop\Setup\ModuleDiscovery\ModuleFileReaderException;
use PhpParser\ConstExprEvaluator;
use PhpParser\Node\Expr;
use PhpParser\ParserFactory;
/**
* Used at runtime/setup time
*/
class PhpExpressionEvaluator {
class PhpExpressionEvaluator
{
/** @var ConstExprEvaluator $oConstExprEvaluator */
private $oConstExprEvaluator;
public function __construct(array $functionsWhiteList=[], array $staticCallsWhitelist=[]) {
public function __construct(array $functionsWhiteList = [], array $staticCallsWhitelist = [])
{
$this->oConstExprEvaluator = new ConstExprEvaluator();
$this->oConstExprEvaluator->setStaticcallsWhitelist($staticCallsWhitelist);
$this->oConstExprEvaluator->setFunctionsWhitelist($functionsWhiteList);
}
public function EvaluateExpression(Expr $oExpression) : mixed
public function EvaluateExpression(Expr $oExpression): mixed
{
return $this->oConstExprEvaluator->evaluateDirectly($oExpression);
}
@@ -32,18 +34,18 @@ class PhpExpressionEvaluator {
* @return bool
* @throws ModuleFileReaderException
*/
public function ParseAndEvaluateBooleanExpression(string $sBooleanExpr) : bool
public function ParseAndEvaluateBooleanExpression(string $sBooleanExpr): bool
{
return $this->ParseAndEvaluateExpression($sBooleanExpr);
}
public function ParseAndEvaluateExpression(string $sExpr) : mixed
public function ParseAndEvaluateExpression(string $sExpr): mixed
{
$sPhpContent = <<<PHP
<?php
$sExpr;
PHP;
try{
try {
$oParser = (new ParserFactory())->createForNewestSupportedVersion();
$aNodes = $oParser->parse($sPhpContent);
$oExpr = $aNodes[0];
@@ -52,4 +54,4 @@ PHP;
throw new ModuleFileReaderException("Eval of '$sExpr' caused an error:".$t->getMessage());
}
}
}
}

View File

@@ -42,7 +42,6 @@ use utils;
*/
class BsSelectObjectFieldRenderer extends BsFieldRenderer
{
/**
* @inheritDoc
*/
@@ -59,23 +58,20 @@ class BsSelectObjectFieldRenderer extends BsFieldRenderer
$this->oField->SetHierarchical(false);
// Rendering field in edition mode
if (!$this->oField->GetReadOnly() && !$this->oField->GetHidden())
{
if (!$this->oField->GetReadOnly() && !$this->oField->GetHidden()) {
// Debug trace: This is very useful when this kind of field doesn't return the expected values.
if(ContextTag::Check('debug'))
{
if (ContextTag::Check('debug')) {
IssueLog::Info('Form field #'.$this->oField->GetId().' OQL query: '.$this->oField->GetSearch()->ToOQL(true));
}
// Rendering field
// - Opening container
$oOutput->AddHtml('<div class="form-group form_group_small ' . $sFieldMandatoryClass . '">');
$oOutput->AddHtml('<div class="form-group form_group_small '.$sFieldMandatoryClass.'">');
// Label
$oOutput->AddHtml('<div class="form_field_label">');
if ($this->oField->GetLabel() !== '')
{
$oOutput->AddHtml('<label for="' . $this->oField->GetGlobalId() . '" class="control-label" '.$sFieldDescriptionForHTMLTag.'>')->AddHtml($this->oField->GetLabel(), true)->AddHtml('</label>');
if ($this->oField->GetLabel() !== '') {
$oOutput->AddHtml('<label for="'.$this->oField->GetGlobalId().'" class="control-label" '.$sFieldDescriptionForHTMLTag.'>')->AddHtml($this->oField->GetLabel(), true)->AddHtml('</label>');
}
$oOutput->AddHtml('</div>');
@@ -85,47 +81,43 @@ class BsSelectObjectFieldRenderer extends BsFieldRenderer
// - As a select
// TODO : This should be changed when we do the radio button display. For now we display everything with select
//if ($iFieldControlType === SelectObjectField::CONTROL_SELECT)
if (true)
{
if (true) {
// Checking if regular select or autocomplete
$oSearch = $this->oField->GetSearch()->DeepClone();
$oCountSet = new DBObjectSet($oSearch);
$iSetCount = $oCountSet->Count();
// Note : Autocomplete/Search is disabled for template fields as they are not external keys, thus they will just be displayed as regular select.
$bRegularSelect = ( ($iSetCount < $this->oField->GetMaximumComboLength()) || ($this->oField->GetSearchEndpoint() === null) || ($this->oField->GetSearchEndpoint() === '') );
$bRegularSelect = (($iSetCount < $this->oField->GetMaximumComboLength()) || ($this->oField->GetSearchEndpoint() === null) || ($this->oField->GetSearchEndpoint() === ''));
unset($oCountSet);
// - For regular select
if ($bRegularSelect)
{
if ($bRegularSelect) {
// HTML for select part
// - Opening row
$oOutput->AddHtml('<div class="row">');
// - Rendering select
$oOutput->AddHtml('<div class="col-xs-' . ( $this->oField->GetHierarchical() ? 10 : 12 ) . ' col-sm-' . ( $this->oField->GetHierarchical() ? 9 : 12 ) . ' col-md-' . ( $this->oField->GetHierarchical() ? 10 : 12 ) . '">');
$oOutput->AddHtml('<select id="' . $this->oField->GetGlobalId() . '" name="' . $this->oField->GetId() . '" class="form-control">');
$oOutput->AddHtml('<div class="col-xs-'.($this->oField->GetHierarchical() ? 10 : 12).' col-sm-'.($this->oField->GetHierarchical() ? 9 : 12).' col-md-'.($this->oField->GetHierarchical() ? 10 : 12).'">');
$oOutput->AddHtml('<select id="'.$this->oField->GetGlobalId().'" name="'.$this->oField->GetId().'" class="form-control">');
$oOutput->AddHtml('<option value="">')->AddHtml(Dict::S('UI:SelectOne'), false)->AddHtml('</option>');
if (defined('PORTAL_ID'))
{
$oModuleDesign = new ModuleDesign(PORTAL_ID);
$oScopeValidatorHelper = new ScopeValidatorHelper($oModuleDesign, PORTAL_ID);
$oScopeValidatorHelper->AddScopeToQuery($oSearch, $oSearch->GetClass());
}
if (defined('PORTAL_ID')) {
$oModuleDesign = new ModuleDesign(PORTAL_ID);
$oScopeValidatorHelper = new ScopeValidatorHelper($oModuleDesign, PORTAL_ID);
$oScopeValidatorHelper->AddScopeToQuery($oSearch, $oSearch->GetClass());
}
$oChoicesSet = new DBObjectSet($oSearch);
$oChoicesSet->OptimizeColumnLoad(array($oSearch->GetClassAlias() => array('friendlyname')));
while ($oChoice = $oChoicesSet->Fetch())
{
$oChoicesSet = new DBObjectSet($oSearch);
$oChoicesSet->OptimizeColumnLoad([$oSearch->GetClassAlias() => ['friendlyname']]);
while ($oChoice = $oChoicesSet->Fetch()) {
// Note : The test is a double equal on purpose as the type of the value received from the XHR is not always the same as the type of the allowed values. (eg : string vs int)
$sSelectedAtt = ($this->oField->GetCurrentValue() == $oChoice->GetKey()) ? 'selected' : '';
$oOutput->AddHtml('<option value="' . $oChoice->GetKey() . '" ' . $sSelectedAtt . ' >')->AddHtml($oChoice->GetName(), false)->AddHtml('</option>');
$oOutput->AddHtml('<option value="'.$oChoice->GetKey().'" '.$sSelectedAtt.' >')->AddHtml($oChoice->GetName(), false)->AddHtml('</option>');
}
unset($oChoicesSet);
$oOutput->AddHtml('</select>');
$oOutput->AddHtml('</div>');
// - Closing col for autocomplete & opening col for hierarchy, rendering hierarchy button, closing col and row
$oOutput->AddHtml('<div class="col-xs-' . ( $this->oField->GetHierarchical() ? 2 : 0 ) . ' col-sm-' . ( $this->oField->GetHierarchical() ? 3 : 0 ) . ' col-md-' . ( $this->oField->GetHierarchical() ? 2 : 0 ) . ' text-right">');
$oOutput->AddHtml('<div class="col-xs-'.($this->oField->GetHierarchical() ? 2 : 0).' col-sm-'.($this->oField->GetHierarchical() ? 3 : 0).' col-md-'.($this->oField->GetHierarchical() ? 2 : 0).' text-right">');
$this->RenderHierarchicalSearch($oOutput);
$oOutput->AddHtml('</div>');
// - Closing row
@@ -133,7 +125,7 @@ class BsSelectObjectFieldRenderer extends BsFieldRenderer
// JS FieldChange trigger (:input are not always at the same depth)
$oOutput->AddJs(
<<<EOF
<<<EOF
$("#{$this->oField->GetGlobalId()}").off("change keyup").on("change keyup", function(){
var me = this;
@@ -148,7 +140,7 @@ EOF
// Attaching JS widget
$oOutput->AddJs(
<<<EOF
<<<EOF
$("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").portal_form_field({
'validators': {$this->GetValidatorsAsJson()}
});
@@ -156,30 +148,23 @@ EOF
);
}
// - For autocomplete
else
{
$sAutocompleteFieldId = 's_ac_' . $this->oField->GetGlobalId();
else {
$sAutocompleteFieldId = 's_ac_'.$this->oField->GetGlobalId();
$sEndpoint = str_replace('-sMode-', 'autocomplete', $this->oField->GetSearchEndpoint());
$sNoResultText = Dict::S('Portal:Autocomplete:NoResult');
// Retrieving field value
$currentValue = $this->oField->GetCurrentValue();
if (!empty($currentValue))
{
try
{
if (!empty($currentValue)) {
try {
// Note : AllowAllData set to true here instead of checking scope's flag because we are displaying a value that has been set and validated
$oFieldValue = MetaModel::GetObject($sFieldValueClass, $this->oField->GetCurrentValue(), true, true);
}
catch (CoreException $e)
{
IssueLog::Error('Could not retrieve object ' . $sFieldValueClass . '::' . $this->oField->GetCurrentValue() . ' for "' . $this->oField->GetId() . '" field.');
} catch (CoreException $e) {
IssueLog::Error('Could not retrieve object '.$sFieldValueClass.'::'.$this->oField->GetCurrentValue().' for "'.$this->oField->GetId().'" field.');
throw new Exception($e->getMessage(), $e->getCode(), $e->getPrevious());
}
$sFieldValue = $oFieldValue->GetName();
}
else
{
} else {
$sFieldValue = '';
}
@@ -187,8 +172,8 @@ EOF
// - Opening input group
$oOutput->AddHtml('<div class="input-group selectobject">');
// - Rendering autocomplete search
$oOutput->AddHtml('<input type="text" id="' . $sAutocompleteFieldId . '" name="' . $sAutocompleteFieldId . '" value="')->AddHtml($sFieldValue)->AddHtml('" data-target-id="' . $this->oField->GetGlobalId() . '" class="form-control" />');
$oOutput->AddHtml('<input type="hidden" id="' . $this->oField->GetGlobalId() . '" name="' . $this->oField->GetId() . '" value="' . $this->oField->GetCurrentValue() . '" />');
$oOutput->AddHtml('<input type="text" id="'.$sAutocompleteFieldId.'" name="'.$sAutocompleteFieldId.'" value="')->AddHtml($sFieldValue)->AddHtml('" data-target-id="'.$this->oField->GetGlobalId().'" class="form-control" />');
$oOutput->AddHtml('<input type="hidden" id="'.$this->oField->GetGlobalId().'" name="'.$this->oField->GetId().'" value="'.$this->oField->GetCurrentValue().'" />');
// - Rendering buttons
// - Rendering hierarchy button
$this->RenderHierarchicalSearch($oOutput);
@@ -201,7 +186,7 @@ EOF
// Note : Not used for that field type
// Attaching JS widget
$oOutput->AddJs(
<<<EOF
<<<EOF
$("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").portal_form_field({
'validators': {$this->GetValidatorsAsJson()},
'get_current_value_callback': function(me, oEvent, oData){
@@ -234,7 +219,7 @@ EOF
// Preparing JS part for autocomplete
$oOutput->AddJs(
<<<EOF
<<<EOF
var oAutocompleteSource_{$this->oField->GetId()} = new Bloodhound({
queryTokenizer: Bloodhound.tokenizers.whitespace,
datumTokenizer: Bloodhound.tokenizers.whitespace,
@@ -323,29 +308,21 @@ EOF
$oOutput->AddHtml('</div>');
}
// ... and in read-only mode (or hidden)
else
{
else {
// Retrieving field value
if ($this->oField->GetCurrentValue() !== null && $this->oField->GetCurrentValue() !== 0 && $this->oField->GetCurrentValue() !== '')
{
if ($this->oField->GetCurrentValue() !== null && $this->oField->GetCurrentValue() !== 0 && $this->oField->GetCurrentValue() !== '') {
// Note : AllowAllData set to true here instead of checking scope's flag because we are displaying a value that has been set and validated
$oFieldValue = MetaModel::GetObjectWithArchive($sFieldValueClass, $this->oField->GetCurrentValue(), true, true);
$sFieldHtmlValue = $oFieldValue->GetName();
if($oFieldValue->IsArchived())
{
$sFieldHtmlValue = '<span class="text_decoration"><span class="fas fa-archive"></span></span>' . $sFieldHtmlValue;
}
else
{
if ($oFieldValue->IsArchived()) {
$sFieldHtmlValue = '<span class="text_decoration"><span class="fas fa-archive"></span></span>'.$sFieldHtmlValue;
} else {
$sFieldUrl = ApplicationContext::MakeObjectUrl($sFieldValueClass, $this->oField->GetCurrentValue());
if (!empty($sFieldUrl))
{
$sFieldHtmlValue = '<a href="' . $sFieldUrl . '" data-toggle="itop-portal-modal">' . $sFieldHtmlValue . '</a>';
if (!empty($sFieldUrl)) {
$sFieldHtmlValue = '<a href="'.$sFieldUrl.'" data-toggle="itop-portal-modal">'.$sFieldHtmlValue.'</a>';
}
}
}
else
{
} else {
$sFieldHtmlValue = Dict::S('UI:UndefinedObject');
}
@@ -353,13 +330,11 @@ EOF
$oOutput->AddHtml('<div class="form-group form_group_small">');
// Showing label / value only if read-only but not hidden
if (!$this->oField->GetHidden())
{
if (!$this->oField->GetHidden()) {
// Label
$oOutput->AddHtml('<div class="form_field_label">');
if ($this->oField->GetLabel() !== '')
{
$oOutput->AddHtml('<label for="' . $this->oField->GetGlobalId() . '" class="control-label" '.$sFieldDescriptionForHTMLTag.'>')->AddHtml($this->oField->GetLabel(), true)->AddHtml('</label>');
if ($this->oField->GetLabel() !== '') {
$oOutput->AddHtml('<label for="'.$this->oField->GetGlobalId().'" class="control-label" '.$sFieldDescriptionForHTMLTag.'>')->AddHtml($this->oField->GetLabel(), true)->AddHtml('</label>');
}
$oOutput->AddHtml('</div>');
@@ -370,7 +345,7 @@ EOF
}
// Adding hidden value
$oOutput->AddHtml('<input type="hidden" id="' . $this->oField->GetGlobalId() . '" name="' . $this->oField->GetId() . '" value="' . $this->oField->GetCurrentValue() . '" class="form-control" />');
$oOutput->AddHtml('<input type="hidden" id="'.$this->oField->GetGlobalId().'" name="'.$this->oField->GetId().'" value="'.$this->oField->GetCurrentValue().'" class="form-control" />');
// Closing container
$oOutput->AddHtml('</div>');
@@ -386,15 +361,14 @@ EOF
*/
protected function RenderHierarchicalSearch(RenderingOutput &$oOutput)
{
if ($this->oField->GetHierarchical())
{
$sHierarchicalButtonId = 's_hi_' . $this->oField->GetGlobalId();
if ($this->oField->GetHierarchical()) {
$sHierarchicalButtonId = 's_hi_'.$this->oField->GetGlobalId();
$sEndpoint = str_replace('-sMode-', 'hierarchy', $this->oField->GetSearchEndpoint());
$oOutput->AddHtml('<div class="input-group-addon" id="' . $sHierarchicalButtonId . '"><span class="fas fa-sitemap"></span></div>');
$oOutput->AddHtml('<div class="input-group-addon" id="'.$sHierarchicalButtonId.'"><span class="fas fa-sitemap"></span></div>');
$oOutput->AddJs(
<<<JS
<<<JS
$('#{$sHierarchicalButtonId}').off('click').on('click', function(){
// Creating a new modal
CombodoModal.OpenModal({
@@ -423,13 +397,13 @@ JS
*/
protected function RenderRegularSearch(RenderingOutput &$oOutput)
{
$sSearchButtonId = 's_rg_' . $this->oField->GetGlobalId();
$sSearchButtonId = 's_rg_'.$this->oField->GetGlobalId();
$sEndpoint = str_replace('-sMode-', 'from-attribute', $this->oField->GetSearchEndpoint());
$oOutput->AddHtml('<div class="input-group-addon" id="' . $sSearchButtonId . '"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></div>');
$oOutput->AddHtml('<div class="input-group-addon" id="'.$sSearchButtonId.'"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></div>');
$oOutput->AddJs(
<<<JS
<<<JS
$('#{$sSearchButtonId}').off('click').on('click', function(){
// Creating a new modal
var oOptions =

View File

@@ -45,11 +45,11 @@ use utils;
*/
class BsSimpleFieldRenderer extends BsFieldRenderer
{
/**
* @inheritDoc
*/
public function Render() {
public function Render()
{
$oOutput = parent::Render();
$sFieldClass = get_class($this->oField);
@@ -72,68 +72,70 @@ class BsSimpleFieldRenderer extends BsFieldRenderer
case 'Combodo\\iTop\\Form\\Field\\SelectField':
case 'Combodo\\iTop\\Form\\Field\\MultipleSelectField':
// Opening container
$oOutput->AddHtml('<div class="form-group form_group_small '.$sFieldMandatoryClass.'">');
$oOutput->AddHtml('<div class="form-group form_group_small '.$sFieldMandatoryClass.'">');
// Label
$oOutput->AddHtml('<div class="form_field_label">');
if ($this->oField->GetLabel() !== '') {
$oOutput->AddHtml('<label for="'.$this->oField->GetGlobalId().'" class="control-label" '.$sFieldDescriptionForHTMLTag.'>')->AddHtml($this->oField->GetLabel(), true)->AddHtml('</label>');
}
$oOutput->AddHtml('</div>');
// Label
$oOutput->AddHtml('<div class="form_field_label">');
if ($this->oField->GetLabel() !== '') {
$oOutput->AddHtml('<label for="'.$this->oField->GetGlobalId().'" class="control-label" '.$sFieldDescriptionForHTMLTag.'>')->AddHtml($this->oField->GetLabel(), true)->AddHtml('</label>');
}
$oOutput->AddHtml('</div>');
// Value
$oOutput->AddHtml('<div class="form_field_control">');
// - Help block
$oOutput->AddHtml('<div class="help-block"></div>');
// Value
$oOutput->AddHtml('<div class="form_field_control">');
// - Help block
$oOutput->AddHtml('<div class="help-block"></div>');
// - Value regarding the field type
switch ($sFieldClass) {
case 'Combodo\\iTop\\Form\\Field\\DateTimeField':
// - Value regarding the field type
switch ($sFieldClass) {
case 'Combodo\\iTop\\Form\\Field\\DateTimeField':
/* @see N°803 - Allow display & edition of attributes on n:n relations on Portal
* LinkedSetFieldRenderer allow modification of link attributes, the default widget positioning truncates the popup.
*/
$sParent = '';
if ($this->oField->GetDateTimePickerWidgetParent() != null) {
$sParent = ", widgetParent: '{$this->oField->GetDateTimePickerWidgetParent()}'";
}
/* @see N°803 - Allow display & edition of attributes on n:n relations on Portal
* LinkedSetFieldRenderer allow modification of link attributes, the default widget positioning truncates the popup.
*/
$sParent = '';
if ($this->oField->GetDateTimePickerWidgetParent() != null) {
$sParent = ", widgetParent: '{$this->oField->GetDateTimePickerWidgetParent()}'";
}
$oOutput->AddHtml('<div class="input-group date" id="datepicker_'.$this->oField->GetGlobalId().'">');
$oOutput->AddHtml('<input type="text" id="'.$this->oField->GetGlobalId().'" name="'.$this->oField->GetId().'" value="')->AddHtml($this->oField->GetDisplayValue(), true)->AddHtml('" class="form-control" maxlength="255" '.$sInputTags.'/>');
$oOutput->AddHtml('<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span>');
$oOutput->AddHtml('</div>');
$sJSFormat = json_encode($this->oField->GetJSDateTimeFormat());
$sLocale = Dict::S('Portal:Calendar-FirstDayOfWeek');
$oOutput->AddJs(
<<<EOF
$oOutput->AddHtml('<div class="input-group date" id="datepicker_'.$this->oField->GetGlobalId().'">');
$oOutput->AddHtml('<input type="text" id="'.$this->oField->GetGlobalId().'" name="'.$this->oField->GetId().'" value="')->AddHtml($this->oField->GetDisplayValue(), true)->AddHtml('" class="form-control" maxlength="255" '.$sInputTags.'/>');
$oOutput->AddHtml('<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span>');
$oOutput->AddHtml('</div>');
$sJSFormat = json_encode($this->oField->GetJSDateTimeFormat());
$sLocale = Dict::S('Portal:Calendar-FirstDayOfWeek');
$oOutput->AddJs(
<<<EOF
$('#datepicker_{$this->oField->GetGlobalId()}').datetimepicker({format: $sJSFormat, locale: '$sLocale' $sParent});
EOF
);
break;
);
break;
case 'Combodo\\iTop\\Form\\Field\\PasswordField':
$oOutput->AddHtml('<input type="password" id="'.$this->oField->GetGlobalId().'" name="'.$this->oField->GetId().'" value="')->AddHtml($this->oField->GetCurrentValue(), true)->AddHtml('" class="form-control" maxlength="255" autocomplete="off" '.$sInputTags.'/>');
break;
case 'Combodo\\iTop\\Form\\Field\\PasswordField':
$oOutput->AddHtml('<input type="password" id="'.$this->oField->GetGlobalId().'" name="'.$this->oField->GetId().'" value="')->AddHtml($this->oField->GetCurrentValue(), true)->AddHtml('" class="form-control" maxlength="255" autocomplete="off" '.$sInputTags.'/>');
break;
case 'Combodo\\iTop\\Form\\Field\\StringField':
case 'Combodo\\iTop\\Form\\Field\\UrlField':
case 'Combodo\\iTop\\Form\\Field\\EmailField':
case 'Combodo\\iTop\\Form\\Field\\PhoneField':
$oOutput->AddHtml('<input type="text" id="'.$this->oField->GetGlobalId().'" name="'.$this->oField->GetId().'" value="')->AddHtml($this->oField->GetCurrentValue(),
true)->AddHtml('" class="form-control" maxlength="255" '.$sInputTags.'/>');
break;
case 'Combodo\\iTop\\Form\\Field\\StringField':
case 'Combodo\\iTop\\Form\\Field\\UrlField':
case 'Combodo\\iTop\\Form\\Field\\EmailField':
case 'Combodo\\iTop\\Form\\Field\\PhoneField':
$oOutput->AddHtml('<input type="text" id="'.$this->oField->GetGlobalId().'" name="'.$this->oField->GetId().'" value="')->AddHtml(
$this->oField->GetCurrentValue(),
true
)->AddHtml('" class="form-control" maxlength="255" '.$sInputTags.'/>');
break;
case 'Combodo\\iTop\\Form\\Field\\SelectField':
case 'Combodo\\iTop\\Form\\Field\\MultipleSelectField':
$oOutput->AddHtml('<select id="'.$this->oField->GetGlobalId().'" name="'.$this->oField->GetId().'" '.(($this->oField->GetMultipleValuesEnabled()) ? 'multiple' : '').' class="form-control" '.$sInputTags.'>');
foreach ($this->oField->GetChoices() as $sChoice => $sLabel) {
// Note : The test is a double equal on purpose as the type of the value received from the XHR is not always the same as the type of the allowed values. (eg : string vs int)
$sSelectedAtt = ($this->oField->GetCurrentValue() == $sChoice) ? 'selected' : '';
$oOutput->AddHtml('<option value="'.$sChoice.'" '.$sSelectedAtt.' >')->AddHtml($sLabel)->AddHtml('</option>');
}
$oOutput->AddHtml('</select>');
break;
}
case 'Combodo\\iTop\\Form\\Field\\SelectField':
case 'Combodo\\iTop\\Form\\Field\\MultipleSelectField':
$oOutput->AddHtml('<select id="'.$this->oField->GetGlobalId().'" name="'.$this->oField->GetId().'" '.(($this->oField->GetMultipleValuesEnabled()) ? 'multiple' : '').' class="form-control" '.$sInputTags.'>');
foreach ($this->oField->GetChoices() as $sChoice => $sLabel) {
// Note : The test is a double equal on purpose as the type of the value received from the XHR is not always the same as the type of the allowed values. (eg : string vs int)
$sSelectedAtt = ($this->oField->GetCurrentValue() == $sChoice) ? 'selected' : '';
$oOutput->AddHtml('<option value="'.$sChoice.'" '.$sSelectedAtt.' >')->AddHtml($sLabel)->AddHtml('</option>');
}
$oOutput->AddHtml('</select>');
break;
}
$oOutput->AddHtml('</div>');
// Closing container
@@ -145,34 +147,34 @@ EOF
$bRichEditor = ($this->oField->GetFormat() === TextAreaField::ENUM_FORMAT_HTML);
// Opening container
$oOutput->AddHtml('<div class="form-group ' . $sFieldMandatoryClass . '">');
$oOutput->AddHtml('<div class="form-group '.$sFieldMandatoryClass.'">');
// Label
$oOutput->AddHtml('<div class="form_field_label">');
if ($this->oField->GetLabel() !== '') {
$oOutput->AddHtml('<label for="'.$this->oField->GetGlobalId().'" class="control-label" '.$sFieldDescriptionForHTMLTag.'>')->AddHtml($this->oField->GetLabel(), true)->AddHtml('</label>');
}
$oOutput->AddHtml('</div>');
if ($this->oField->GetLabel() !== '') {
$oOutput->AddHtml('<label for="'.$this->oField->GetGlobalId().'" class="control-label" '.$sFieldDescriptionForHTMLTag.'>')->AddHtml($this->oField->GetLabel(), true)->AddHtml('</label>');
}
$oOutput->AddHtml('</div>');
// Value
$oOutput->AddHtml('<div class="form_field_control">');
// - Help block
$oOutput->AddHtml('<div class="help-block"></div>');
// First the edition area
$oOutput->AddHtml('<div>');
$sEditorClasses = $bRichEditor ? 'htmlEditor' : '';
$oOutput->AddHtml('<textarea id="'.$this->oField->GetGlobalId().'" name="'.$this->oField->GetId().'" class="' . $sEditorClasses . ' form-control" rows="8" '.$sInputTags.'>'. CKEditorHelper::PrepareCKEditorValueTextEncodingForTextarea($this->oField->GetCurrentValue()) .'</textarea>');
$oOutput->AddHtml('</div>');
// Then the previous entries if necessary
if ($sFieldClass === 'Combodo\\iTop\\Form\\Field\\CaseLogField') {
$this->PreparingCaseLogEntries($oOutput);
}
$oOutput->AddHtml('</div>');
// Value
$oOutput->AddHtml('<div class="form_field_control">');
// - Help block
$oOutput->AddHtml('<div class="help-block"></div>');
// First the edition area
$oOutput->AddHtml('<div>');
$sEditorClasses = $bRichEditor ? 'htmlEditor' : '';
$oOutput->AddHtml('<textarea id="'.$this->oField->GetGlobalId().'" name="'.$this->oField->GetId().'" class="'.$sEditorClasses.' form-control" rows="8" '.$sInputTags.'>'.CKEditorHelper::PrepareCKEditorValueTextEncodingForTextarea($this->oField->GetCurrentValue()).'</textarea>');
$oOutput->AddHtml('</div>');
// Then the previous entries if necessary
if ($sFieldClass === 'Combodo\\iTop\\Form\\Field\\CaseLogField') {
$this->PreparingCaseLogEntries($oOutput);
}
$oOutput->AddHtml('</div>');
// Closing container
$oOutput->AddHtml('</div>');
// Closing container
$oOutput->AddHtml('</div>');
// Some additional stuff if we are displaying it with a rich editor
// Some additional stuff if we are displaying it with a rich editor
if ($bRichEditor) {
// Enable CKEditor
@@ -189,7 +191,7 @@ EOF
$sFieldType = ($sFieldClass === 'Combodo\\iTop\\Form\\Field\\RadioField') ? 'radio' : 'checkbox';
// Opening container
$oOutput->AddHtml('<div class="form-group ' . $sFieldMandatoryClass . '" id="' . $this->oField->GetGlobalId() . '">');
$oOutput->AddHtml('<div class="form-group '.$sFieldMandatoryClass.'" id="'.$this->oField->GetGlobalId().'">');
// Label
$oOutput->AddHtml('<div class="form_field_label">');
@@ -208,7 +210,7 @@ EOF
// Note : The test is a double equal on purpose as the type of the value received from the XHR is not always the same as the type of the allowed values. (eg : string vs int)
$sCheckedAtt = ($this->oField->IsAmongValues($sChoice)) ? 'checked' : '';
$sCheckedClass = ($this->oField->IsAmongValues($sChoice)) ? 'active' : '';
$oOutput->AddHtml('<label class="btn btn-default ' . $sCheckedClass . '"><input type="' . $sFieldType . '" name="' . $this->oField->GetId() . '" id="' . $this->oField->GetId() . $i . '" value="' . $sChoice . '" ' . $sCheckedAtt . ' />' . $sLabel . '</label>');
$oOutput->AddHtml('<label class="btn btn-default '.$sCheckedClass.'"><input type="'.$sFieldType.'" name="'.$this->oField->GetId().'" id="'.$this->oField->GetId().$i.'" value="'.$sChoice.'" '.$sCheckedAtt.' />'.$sLabel.'</label>');
$i++;
}
$oOutput->AddHtml('</div>');
@@ -219,7 +221,7 @@ EOF
break;
case 'Combodo\\iTop\\Form\\Field\\HiddenField':
$oOutput->AddHtml('<input type="hidden" id="' . $this->oField->GetGlobalId() . '" name="' . $this->oField->GetId() . '" value="')->AddHtml($this->oField->GetCurrentValue(), true)->AddHtml('"/>');
$oOutput->AddHtml('<input type="hidden" id="'.$this->oField->GetGlobalId().'" name="'.$this->oField->GetId().'" value="')->AddHtml($this->oField->GetCurrentValue(), true)->AddHtml('"/>');
break;
}
@@ -233,7 +235,8 @@ EOF
case 'Combodo\\iTop\\Form\\Field\\SelectField':
case 'Combodo\\iTop\\Form\\Field\\MultipleSelectField':
case 'Combodo\\iTop\\Form\\Field\\HiddenField':
$oOutput->AddJs(<<<JS
$oOutput->AddJs(
<<<JS
$("#{$this->oField->GetGlobalId()}").off("change keyup").on("change keyup", function(){
var me = this;
@@ -250,7 +253,8 @@ JS
case 'Combodo\\iTop\\Form\\Field\\TextAreaField':
case 'Combodo\\iTop\\Form\\Field\\CaseLogField':
if ($this->oField->GetFormat() === TextAreaField::ENUM_FORMAT_HTML) {
$oOutput->AddJs(<<<JS
$oOutput->AddJs(
<<<JS
CombodoCKEditorHandler.GetInstance("#{$this->oField->GetGlobalId()}")
.then((oCKEditor) => {
oCKEditor.model.document.on("change:data", () => {
@@ -266,7 +270,8 @@ JS
JS
);
} else {
$oOutput->AddJs(<<<JS
$oOutput->AddJs(
<<<JS
$("#{$this->oField->GetGlobalId()}").off("change keyup").on("change keyup", function(){
var me = this;
@@ -340,21 +345,21 @@ EOF
// Label
$oOutput->AddHtml('<div class="form_field_label">');
if ($this->oField->GetLabel() !== '') {
$oOutput->AddHtml('<label for="' . $this->oField->GetGlobalId() . '" class="control-label" '.$sFieldDescriptionForHTMLTag.'>')->AddHtml($this->oField->GetLabel(), true)->AddHtml('</label>');
$oOutput->AddHtml('<label for="'.$this->oField->GetGlobalId().'" class="control-label" '.$sFieldDescriptionForHTMLTag.'>')->AddHtml($this->oField->GetLabel(), true)->AddHtml('</label>');
}
$oOutput->AddHtml('</div>');
// Value
$bEncodeHtmlEntities = ( in_array($sFieldClass, array('Combodo\\iTop\\Form\\Field\\UrlField', 'Combodo\\iTop\\Form\\Field\\EmailField', 'Combodo\\iTop\\Form\\Field\\PhoneField')) ) ? false : true;
$bEncodeHtmlEntities = (in_array($sFieldClass, ['Combodo\\iTop\\Form\\Field\\UrlField', 'Combodo\\iTop\\Form\\Field\\EmailField', 'Combodo\\iTop\\Form\\Field\\PhoneField'])) ? false : true;
$oOutput->AddHtml('<div class="form_field_control">');
$oOutput->AddHtml('<div class="form-control-static">')->AddHtml($this->oField->GetDisplayValue(), $bEncodeHtmlEntities)->AddHtml('</div>');
$oOutput->AddHtml('</div>');
}
// Adding hidden input if not a label
if($sFieldClass !== 'Combodo\\iTop\\Form\\Field\\LabelField') {
if ($sFieldClass !== 'Combodo\\iTop\\Form\\Field\\LabelField') {
$sValueForInput = ($sFieldClass === 'Combodo\\iTop\\Form\\Field\\DateTimeField') ? $this->oField->GetDisplayValue() : $this->oField->GetCurrentValue();
$oOutput->AddHtml('<input type="hidden" id="' . $this->oField->GetGlobalId() . '" name="' . $this->oField->GetId() . '" value="')->AddHtml($sValueForInput, true)->AddHtml('" class="form-control" />');
$oOutput->AddHtml('<input type="hidden" id="'.$this->oField->GetGlobalId().'" name="'.$this->oField->GetId().'" value="')->AddHtml($sValueForInput, true)->AddHtml('" class="form-control" />');
}
// Closing container
@@ -370,7 +375,7 @@ EOF
// Label
$oOutput->AddHtml('<div class="form_field_label">');
if ($this->oField->GetLabel() !== '') {
$oOutput->AddHtml('<label for="' . $this->oField->GetGlobalId() . '" class="control-label" '.$sFieldDescriptionForHTMLTag.'>')->AddHtml($this->oField->GetLabel(), true)->AddHtml('</label>');
$oOutput->AddHtml('<label for="'.$this->oField->GetGlobalId().'" class="control-label" '.$sFieldDescriptionForHTMLTag.'>')->AddHtml($this->oField->GetLabel(), true)->AddHtml('</label>');
}
$oOutput->AddHtml('</div>');
@@ -381,7 +386,7 @@ EOF
}
// Adding hidden input
$oOutput->AddHtml('<input type="hidden" id="' . $this->oField->GetGlobalId() . '" name="' . $this->oField->GetId() . '" value="')->AddHtml($this->oField->GetCurrentValue(), true)->AddHtml('" class="form-control" />');
$oOutput->AddHtml('<input type="hidden" id="'.$this->oField->GetGlobalId().'" name="'.$this->oField->GetId().'" value="')->AddHtml($this->oField->GetCurrentValue(), true)->AddHtml('" class="form-control" />');
// Closing container
$oOutput->AddHtml('</div>');
@@ -389,12 +394,12 @@ EOF
case 'Combodo\\iTop\\Form\\Field\\CaseLogField':
// Opening container
$oOutput->AddHtml('<div class="form-group ' . $sFieldMandatoryClass . '">');
$oOutput->AddHtml('<div class="form-group '.$sFieldMandatoryClass.'">');
// Label
$oOutput->AddHtml('<div class="form_field_label">');
if ($this->oField->GetLabel() !== '') {
$oOutput->AddHtml('<label for="' . $this->oField->GetGlobalId() . '" class="control-label" '.$sFieldDescriptionForHTMLTag.'>')->AddHtml($this->oField->GetLabel(), true)->AddHtml('</label>');
$oOutput->AddHtml('<label for="'.$this->oField->GetGlobalId().'" class="control-label" '.$sFieldDescriptionForHTMLTag.'>')->AddHtml($this->oField->GetLabel(), true)->AddHtml('</label>');
}
$oOutput->AddHtml('</div>');
@@ -418,23 +423,22 @@ EOF
// Label
$oOutput->AddHtml('<div class="form_field_label">');
if ($this->oField->GetLabel() !== '') {
$oOutput->AddHtml('<label for="' . $this->oField->GetGlobalId() . '" class="control-label" '.$sFieldDescriptionForHTMLTag.'>')->AddHtml($this->oField->GetLabel(), true)->AddHtml('</label>');
$oOutput->AddHtml('<label for="'.$this->oField->GetGlobalId().'" class="control-label" '.$sFieldDescriptionForHTMLTag.'>')->AddHtml($this->oField->GetLabel(), true)->AddHtml('</label>');
}
$oOutput->AddHtml('</div>');
// Value
$oOutput->AddHtml('<div class="form_field_control">');
$oOutput->AddHtml('<div class="form-control-static">');
if($sFieldClass === 'Combodo\\iTop\\Form\\Field\\ImageField') {
$oOutput->AddHtml('<img src="' . $this->oField->GetDisplayUrl() . '" />', false);
}
else {
if ($sFieldClass === 'Combodo\\iTop\\Form\\Field\\ImageField') {
$oOutput->AddHtml('<img src="'.$this->oField->GetDisplayUrl().'" />', false);
} else {
$oOutput->AddHtml($this->oField->GetDisplayValue(), false);
}
$oOutput->AddHtml('</div>');
$oOutput->AddHtml('</div>');
}
$oOutput->AddHtml('<input type="hidden" id="' . $this->oField->GetGlobalId() . '" name="' . $this->oField->GetId() . '" value="')->AddHtml($this->oField->GetCurrentValue(), true)->AddHtml('" class="form-control" />');
$oOutput->AddHtml('<input type="hidden" id="'.$this->oField->GetGlobalId().'" name="'.$this->oField->GetId().'" value="')->AddHtml($this->oField->GetCurrentValue(), true)->AddHtml('" class="form-control" />');
// Closing container
$oOutput->AddHtml('</div>');
@@ -454,50 +458,50 @@ EOF
// Label
$oOutput->AddHtml('<div class="form_field_label">');
if ($this->oField->GetLabel() !== '') {
$oOutput->AddHtml('<label for="' . $this->oField->GetGlobalId() . '" class="control-label" '.$sFieldDescriptionForHTMLTag.'>')->AddHtml($this->oField->GetLabel(), true)->AddHtml('</label>');
$oOutput->AddHtml('<label for="'.$this->oField->GetGlobalId().'" class="control-label" '.$sFieldDescriptionForHTMLTag.'>')->AddHtml($this->oField->GetLabel(), true)->AddHtml('</label>');
}
$oOutput->AddHtml('</div>');
// Value
$oOutput->AddHtml('<div class="form_field_control">');
$oOutput->AddHtml('<div class="form-control-static">' . $sFieldValue . '</div>');
$oOutput->AddHtml('<div class="form-control-static">'.$sFieldValue.'</div>');
$oOutput->AddHtml('</div>');
}
// Adding hidden value
$oOutput->AddHtml('<input type="hidden" id="' . $this->oField->GetGlobalId() . '" name="' . $this->oField->GetId() . '" value="' . $this->oField->GetCurrentValue() . '" class="form-control" />');
$oOutput->AddHtml('<input type="hidden" id="'.$this->oField->GetGlobalId().'" name="'.$this->oField->GetId().'" value="'.$this->oField->GetCurrentValue().'" class="form-control" />');
// Closing container
$oOutput->AddHtml('</div>');
break;
case 'Combodo\\iTop\\Form\\Field\\HiddenField':
$oOutput->AddHtml('<input type="hidden" id="' . $this->oField->GetGlobalId() . '" name="' . $this->oField->GetId() . '" value="')->AddHtml($this->oField->GetCurrentValue(), true)->AddHtml('"/>');
$oOutput->AddHtml('<input type="hidden" id="'.$this->oField->GetGlobalId().'" name="'.$this->oField->GetId().'" value="')->AddHtml($this->oField->GetCurrentValue(), true)->AddHtml('"/>');
break;
}
}
}
// Attaching JS widget only if field is hidden or NOT read only
if($this->oField->GetHidden() || !$this->oField->GetReadOnly()) {
if ($this->oField->GetHidden() || !$this->oField->GetReadOnly()) {
// JS Form field widget construct
$aValidators = array();
$aValidators = [];
foreach ($this->oField->GetValidators() as $oValidator) {
if (false === ($oValidator instanceof AbstractRegexpValidator)) {
// no JS counterpart, so skipping !
continue;
}
$aValidators[$oValidator::GetName()] = array(
$aValidators[$oValidator::GetName()] = [
'reg_exp' => $oValidator->GetRegExp(),
'message' => Dict::S($oValidator->GetErrorMessage()),
);
];
}
$sFormFieldOptions = json_encode(array(
'validators' => $aValidators
));
$sFormFieldOptions = json_encode([
'validators' => $aValidators,
]);
switch ($sFieldClass) {
case 'Combodo\\iTop\\Form\\Field\\PasswordField':
@@ -520,7 +524,7 @@ EOF
case 'Combodo\\iTop\\Form\\Field\\TextAreaField':
case 'Combodo\\iTop\\Form\\Field\\CaseLogField':
$bRichEditor = ($this->oField->GetFormat() === TextAreaField::ENUM_FORMAT_HTML);
if($bRichEditor) {
if ($bRichEditor) {
// Overloading $sFormFieldOptions to include the set_current_value_callback. It would have been nicer to refactor the variable for all field types, but as this is a fix for a maintenance release, we rather be safe.
$sValidators = json_encode($aValidators);
$oOutput->AddJs(
@@ -531,8 +535,7 @@ EOF
});
EOF
);
}
else {
} else {
$oOutput->AddJs(
<<<EOF
$("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").portal_form_field($sFormFieldOptions);
@@ -548,11 +551,12 @@ EOF
case 'Combodo\\iTop\\Form\\Field\\TextAreaField':
case 'Combodo\\iTop\\Form\\Field\\CaseLogField':
$bRichEditor = ($this->oField->GetFormat() === TextAreaField::ENUM_FORMAT_HTML);
if($bRichEditor) {
if ($bRichEditor) {
// MagnificPopup on images
$oOutput->AddJs(InlineImage::FixImagesWidth());
// Trigger highlighter for all code blocks in this caselog
$oOutput->AddJs(<<<JS
$oOutput->AddJs(
<<<JS
$("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}'] pre").each(function(i, block) {
hljs.highlightBlock(block);
});
@@ -572,7 +576,8 @@ JS
*
* @throws \Exception
*/
protected function PreparingCaseLogEntries(RenderingOutput &$oOutput) {
protected function PreparingCaseLogEntries(RenderingOutput &$oOutput)
{
$aEntries = $this->oField->GetEntries();
$iNbEntries = count($aEntries);
@@ -585,7 +590,7 @@ JS
$sCloseEntryTooltip = utils::HtmlEntities(Dict::S('Portal:Form:Caselog:Entry:Close:Tooltip'));
// First pass to retrieve number of users
$aUserIds = array();
$aUserIds = [];
for ($i = 0; $i < $iNbEntries; $i++) {
$iEntryUserId = $aEntries[$i]['user_id'];
if (!in_array($iEntryUserId, $aUserIds)) {
@@ -595,12 +600,14 @@ JS
$iNbUsers = count($aUserIds);
// Opening thread
$oOutput->AddHtml(<<<HTML
$oOutput->AddHtml(
<<<HTML
<div class="ipb-caselog-thread ipb-is-html-content">
HTML
);
// - Header
$oOutput->AddHtml(<<<HTML
$oOutput->AddHtml(
<<<HTML
<div class="ipb-caselog-thread--header">
<span class="ipb-caselog-thread--header-togglers">
<a href="#" class="ipb-caselog-thread--header-toggler ipb-caselog-thread--open-all-toggler" data-tooltip-content="{$sOpenAllEntriesTooltip}"><span class="fas fa-book-open"></span></a>
@@ -614,7 +621,8 @@ HTML
HTML
);
// - Content
$oOutput->AddHtml(<<<HTML
$oOutput->AddHtml(
<<<HTML
<div class="ipb-caselog-thread--content">
HTML
);
@@ -625,13 +633,12 @@ HTML
$iLastLoopIndex = $iNbEntries - 1;
// Caching profile picture url as it is resource consuming
$aContactPicturesCache = array();
$aPeerColorClassCache = array();
$aContactPicturesCache = [];
$aPeerColorClassCache = [];
// Note: Yes, the config. param. is named after the backoffice element but we hope that we will "soon" have some kind of "light" activity panel in the portal too, so we keep this name.
$bHideContactPicture = false;
if (defined('PORTAL_ID'))
{
$bHideContactPicture= in_array(PORTAL_ID, utils::GetConfig()->Get('activity_panel.hide_avatars'));
if (defined('PORTAL_ID')) {
$bHideContactPicture = in_array(PORTAL_ID, utils::GetConfig()->Get('activity_panel.hide_avatars'));
}
// Current user
$iCurrentUserId = UserRights::GetUserId();
@@ -645,7 +652,7 @@ HTML
// - Friendlyname
if (false === empty($iEntryUserId)) {
$oEntryUser = MetaModel::GetObject('User', $iEntryUserId, false /* Necessary in case user has been deleted */, true);
if(!is_null($oEntryUser)) {
if (!is_null($oEntryUser)) {
$sEntryUserLogin = UserRights::GetUserFriendlyName($oEntryUser->Get('login'));
}
@@ -658,10 +665,9 @@ HTML
}
// Otherwise try to retrieve one for the current contact
else {
if(is_null($oEntryUser)) {
if (is_null($oEntryUser)) {
$sEntryContactPictureAbsoluteUrl = null;
}
else {
} else {
$sEntryContactPictureAbsoluteUrl = UserRights::GetUserPictureAbsUrl($oEntryUser->Get('login'), false);
}
}
@@ -673,7 +679,8 @@ HTML
// Open user block if previous user was different or if previous date was different
if (($iEntryUserId !== $sLastUserId) || ($sEntryDate !== $sLastDate)) {
if ($sEntryDate !== $sLastDate) {
$oOutput->AddHtml(<<<HTML
$oOutput->AddHtml(
<<<HTML
<div class="ipb-caselog-thread--date">{$sEntryDate}</div>
HTML
);
@@ -682,15 +689,15 @@ HTML
// Open block
if ($iEntryUserId === $iCurrentUserId) {
$sEntryBlockClass = 'ipb-caselog-thread--block-me';
}
else {
} else {
if (!array_key_exists($iEntryUserId, $aPeerColorClassCache)) {
$iPeerClassNumber = (count($aPeerColorClassCache) % 5) + 1;
$aPeerColorClassCache[$iEntryUserId] = 'ipb-caselog-thread--block-color-'.$iPeerClassNumber;
}
$sEntryBlockClass = $aPeerColorClassCache[$iEntryUserId];
}
$oOutput->AddHtml(<<<HTML
$oOutput->AddHtml(
<<<HTML
<div class="ipb-caselog-thread--block {$sEntryBlockClass}">
HTML
);
@@ -702,7 +709,8 @@ HTML
// - Entry tooltip
$sEntryMedallionTooltip = utils::HtmlEntities($sEntryUserLogin);
$sEntryMedallionTooltipPlacement = ($iEntryUserId === $iCurrentUserId) ? 'left' : 'right';
$oOutput->AddHtml(<<<HTML
$oOutput->AddHtml(
<<<HTML
<div class="ipb-caselog-thread--block-medallion" style="{$sEntryMedallionStyle}" data-tooltip-content="{$sEntryMedallionTooltip}" data-placement="{$sEntryMedallionTooltipPlacement}">
$sEntryMedallionContent
</div>
@@ -711,7 +719,8 @@ HTML
);
// Open entries
$oOutput->AddHtml(<<<HTML
$oOutput->AddHtml(
<<<HTML
<div class="ipb-caselog-thread--block-entries">
HTML
);
@@ -723,7 +732,8 @@ HTML
$sEntryHtml = InlineImage::FixUrls($sEntryHtml);
// Add entry
$oOutput->AddHtml(<<<HTML
$oOutput->AddHtml(
<<<HTML
<div class="ipb-caselog-thread--block-entry" id="{$sEntryId}">
<div class="ipb-caselog-thread--block-entry-content">{$sEntryHtml}</div>
<div class="ipb-caselog-thread--block-entry-date">{$sEntryDatetime}</div>
@@ -737,7 +747,8 @@ HTML
|| ($i < $iLastLoopIndex && $iEntryUserId !== $aEntries[$i + 1]['user_id'])
|| ($i < $iLastLoopIndex && $sEntryDate !== AttributeDate::GetFormat()->Format($aEntries[$i + 1]['date']))) {
// Close entries and block
$oOutput->AddHtml(<<<HTML
$oOutput->AddHtml(
<<<HTML
</div>
</div>
HTML
@@ -750,14 +761,16 @@ HTML
}
// Close thread content and thread
$oOutput->AddHtml(<<<HTML
$oOutput->AddHtml(
<<<HTML
</div>
</div>
HTML
);
// Add JS handlers
$oOutput->AddJs(<<<JS
$oOutput->AddJs(
<<<JS
$('[data-field-id="{$this->oField->GetId()}"][data-form-path="{$this->oField->GetFormPath()}"]')
.on('click', '.ipb-caselog-thread--block-entry-toggler, .ipb-caselog-thread--block-entry.closed', function(){
$(this).closest('.ipb-caselog-thread--block-entry').toggleClass('closed');

View File

@@ -193,7 +193,7 @@ class CSVImportPageProcessor
$aSynchroUpdate,
$sChosenDateFormat, // date format
true, // localize
$iNbSkippedLines+count($aFieldsMapping) // advanced mode
$iNbSkippedLines + count($aFieldsMapping) // advanced mode
);
$oPage->AddSubBlock(InputUIBlockFactory::MakeForHidden("csvdata_truncated", $sCSVDataTruncated, "csvdata_truncated"));

View File

@@ -61,7 +61,7 @@ class EventNotificationNewsroomService
$oEvent->Set('trigger_id', $iTriggerId);
$oEvent->Set('action_id', $oAction->GetKey());
$oEvent->Set('object_id', $iObjectId);
$oEvent->Set('object_class', $sObjectClass);
$oEvent->Set('object_class', $sObjectClass);
$oEvent->Set('url', $sUrl);
if ($sDate !== null) {
$oEvent->Set('date', $sDate);

View File

@@ -94,4 +94,4 @@ class_alias(\Combodo\iTop\Core\AttributeDefinition\AttributeTemplateText::class,
class_alias(\Combodo\iTop\Core\AttributeDefinition\AttributeText::class, 'AttributeText');
class_alias(\Combodo\iTop\Core\AttributeDefinition\AttributeURL::class, 'AttributeURL');
class_alias(\Combodo\iTop\Core\AttributeDefinition\iAttributeNoGroupBy::class, 'iAttributeNoGroupBy');
class_alias(\Combodo\iTop\Core\AttributeDefinition\MissingColumnException::class, 'MissingColumnException');
class_alias(\Combodo\iTop\Core\AttributeDefinition\MissingColumnException::class, 'MissingColumnException');