value) * * @param array $aRow * @param string $sClassAlias * @param array $aAttToLoad * @param array $aExtendedDataSpec * * @throws \CoreException */ public function __construct($aRow = null, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null) { parent::__construct($aRow, $sClassAlias, $aAttToLoad, $aExtendedDataSpec); $this->sDisplayMode = static::DEFAULT_DISPLAY_MODE; $this->bAllowWrite = false; $this->bAllowDelete = false; } /** * Return the allowed display modes * * @see static::ENUM_DISPLAY_MODE_XXX * * @return string[] * @since 3.0.0 */ public static function EnumDisplayModes(): array { return [ static::ENUM_DISPLAY_MODE_VIEW, static::ENUM_DISPLAY_MODE_EDIT, static::ENUM_DISPLAY_MODE_CREATE, static::ENUM_DISPLAY_MODE_STIMULUS, static::ENUM_DISPLAY_MODE_PRINT, static::ENUM_DISPLAY_MODE_BULK_EDIT, ]; } /** * @see static::$sDisplayMode * @return string * @since 3.0.0 */ public function GetDisplayMode(): string { return $this->sDisplayMode; } /** * @param string $sMode * * @see static::$sDisplayMode * @return $this * @since 3.0.0 */ public function SetDisplayMode(string $sMode) { $this->sDisplayMode = $sMode; return $this; } /** * returns what will be the next ID for the forms */ public static function GetNextFormId() { return 1 + self::$iGlobalFormId; } public static function GetUIPage() { return 'UI.php'; } /** * @param WebPage $oPage * @param \cmdbAbstractObject $oObj * @param array $aParams * * @throws \Exception */ public static function ReloadAndDisplay($oPage, $oObj, $aParams) { $oAppContext = new ApplicationContext(); // Reload the page to let the "calling" page execute its 'onunload' method. // Note 1: The redirection MUST NOT be made via an HTTP "header" since onunload is only called when the actual content of the DOM // is replaced by some other content. So the "bouncing" page must provide some content (in our case a script making the redirection). // Note 2: make sure that the URL below is different from the one of the "Modify" button, otherwise the button will have no effect. This is why we add "&a=1" at the end !!! // Note 3: we use the toggle of a flag in the sessionStorage object to prevent an infinite loop of reloads in case the object is actually locked by another window $sSessionStorageKey = get_class($oObj).'_'.$oObj->GetKey(); $sParams = ''; foreach($aParams as $sName => $value) { $sParams .= $sName.'='.urlencode($value).'&'; // Always add a trailing & } $sUrl = utils::GetAbsoluteUrlAppRoot().'pages/'.$oObj->GetUIPage().'?'.$sParams.'class='.get_class($oObj).'&id='.$oObj->getKey().'&'.$oAppContext->GetForLink().'&a=1'; $oPage->add_early_script(<<Reload(); $oObj->SetDisplayMode(static::ENUM_DISPLAY_MODE_VIEW); $oObj->DisplayDetails($oPage, false); } /** * @param $sMessageId * @param $sMessage * @param $sSeverity * @param $fRank * @param bool $bMustNotExist * * @see SetSessionMessage() * @since 2.6.0 */ protected function SetSessionMessageFromInstance($sMessageId, $sMessage, $sSeverity, $fRank, $bMustNotExist = false) { $sObjectClass = get_class($this); $iObjectId = $this->GetKey(); self::SetSessionMessage($sObjectClass, $iObjectId, $sMessageId, $sMessage, $sSeverity, $fRank); } /** * Set a message displayed to the end-user next time this object will be displayed * Messages are uniquely identified so that plugins can override standard messages (the final work is given to the * last plugin to set the message for a given message id) In practice, standard messages are recorded at the end * but they will not overwrite existing messages * * @see SetSessionMessageFromInstance() to call from within an instance * * @param string $sClass The class of the object (must be the final class) * @param int $iKey The identifier of the object * @param string $sMessageId Your id or one of the well-known ids: 'create', 'update' and 'apply_stimulus' * @param string $sMessage The HTML message (must be correctly escaped) * @param string $sSeverity Any of the WebPage::ENUM_SESSION_MESSAGE_SEVERITY_XXX constants * @param float $fRank Ordering of the message: smallest displayed first (can be negative) * @param bool $bMustNotExist Do not alter any existing message (considering the id) * * @return void */ public static function SetSessionMessage($sClass, $iKey, $sMessageId, $sMessage, $sSeverity, $fRank, $bMustNotExist = false) { $sMessageKey = $sClass.'::'.$iKey; if (!Session::IsSet(['obj_messages', $sMessageKey])) { Session::Set(['obj_messages', $sMessageKey], []); } if (!$bMustNotExist || !Session::IsSet(['obj_messages', $sMessageKey, $sMessageId])) { Session::Set(['obj_messages', $sMessageKey, $sMessageId], [ 'rank' => $fRank, 'severity' => $sSeverity, 'message' => $sMessage, ]); } } /** * @param WebPage $oPage Warning, since 3.0.0 this parameter was kept for compatibility reason. You shouldn't write directly on the page! * When writing to the page, markup will be put above the real header of the panel. * To insert something IN the panel, we now need to add UIBlocks in either the "subtitle" or "toolbar" sections of the array that will be returned. * @param bool $bEditMode Deprecated parameter in iTop 3.0.0, use {@see GetDisplayMode()} and ENUM_DISPLAY_MODE_* constants instead * * @return array{ * subtitle: \Combodo\iTop\Application\UI\Base\UIBlock[], * toolbar: \Combodo\iTop\Application\UI\Base\UIBlock[] * } * blocks to be inserted in the "subtitle" and the "toolbar" sections of the ObjectDetails block. * eg. ['subtitle' => [, ], 'toolbar' => []] * * @throws \ApplicationException * @throws \ArchivedObjectException * @throws \CoreException * @throws \CoreUnexpectedValue * @throws \MySQLException * @throws \OQLException * * @since 3.0.0 $bEditMode is deprecated, see param documentation above * @since 3.0.0 Changed signature: Method must return header content in an array (no more writing directly to the $oPage) * * @noinspection PhpUnusedParameterInspection */ public function DisplayBareHeader(WebPage $oPage, $bEditMode = false) { $aHeaderBlocks = [ 'subtitle' => [], 'toolbar' => [], ]; // Standard Header with name, actions menu and history block if (!$oPage->IsPrintableVersion()) { // Is there a message for this object ?? $aMessages = []; $aRanks = []; if (MetaModel::GetConfig()->Get('concurrent_lock_enabled')) { $aLockInfo = iTopOwnershipLock::IsLocked(get_class($this), $this->GetKey()); if ($aLockInfo['locked']) { $aRanks[] = 0; $sName = $aLockInfo['owner']->GetName(); if ($aLockInfo['owner']->Get('contactid') != 0) { $sName .= ' ('.$aLockInfo['owner']->Get('contactid_friendlyname').')'; } $aMessages[] = AlertUIBlockFactory::MakeForDanger('', Dict::Format('UI:CurrentObjectIsLockedBy_User', $sName)); } } $sMessageKey = get_class($this).'::'.$this->GetKey(); $oPage->AddSessionMessages($sMessageKey, $aRanks, $aMessages); } if (!$oPage->IsPrintableVersion() && ($this->GetDisplayMode() === static::ENUM_DISPLAY_MODE_VIEW)) { // action menu $oSingletonFilter = new DBObjectSearch(get_class($this)); $oSingletonFilter->AddCondition('id', $this->GetKey(), '='); $oBlock = new MenuBlock($oSingletonFilter, 'details', false); $sActionMenuId = utils::Sanitize(uniqid('', true), '', utils::ENUM_SANITIZATION_FILTER_ELEMENT_IDENTIFIER); $oActionMenuBlock = $oBlock->GetRenderContent($oPage, [], $sActionMenuId); $aHeaderBlocks['toolbar'][$oActionMenuBlock->GetId()] = $oActionMenuBlock; } $aTags = array(); // Master data sources if (!$oPage->IsPrintableVersion()) { $oCreatorTask = null; $bCanBeDeletedByTask = false; $bCanBeDeletedByUser = true; $aMasterSources = array(); $aSyncData = $this->GetSynchroData(MetaModel::GetConfig()->Get('synchro_obsolete_replica_locks_object')); if (count($aSyncData) > 0) { foreach ($aSyncData as $iSourceId => $aSourceData) { $oDataSource = $aSourceData['source']; $oReplica = reset($aSourceData['replica']); // Take the first one! $sApplicationURL = $oDataSource->GetApplicationUrl($this, $oReplica); $sLink = $oDataSource->GetName(); if (!empty($sApplicationURL)) { $sLink = "".$oDataSource->GetName().""; } if ($oReplica->Get('status_dest_creator') == 1) { $oCreatorTask = $oDataSource; $bCreatedByTask = true; } else { $bCreatedByTask = false; } if ($bCreatedByTask) { $sDeletePolicy = $oDataSource->Get('delete_policy'); if (($sDeletePolicy == 'delete') || ($sDeletePolicy == 'update_then_delete')) { $bCanBeDeletedByTask = true; } $sUserDeletePolicy = $oDataSource->Get('user_delete_policy'); if ($sUserDeletePolicy == 'nobody') { $bCanBeDeletedByUser = false; } elseif (($sUserDeletePolicy == 'administrators') && !UserRights::IsAdministrator()) { $bCanBeDeletedByUser = false; } } $aMasterSources[$iSourceId]['datasource'] = $oDataSource; $aMasterSources[$iSourceId]['url'] = $sLink; $aMasterSources[$iSourceId]['last_synchro'] = $oReplica->Get('status_last_seen'); } if (is_object($oCreatorTask)) { $sTaskUrl = $aMasterSources[$oCreatorTask->GetKey()]['url']; if (!$bCanBeDeletedByUser) { $sTip = "
".Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sTaskUrl)."
"; } else { $sTip = "
".Dict::Format('Core:Synchro:TheObjectWasCreatedBy_Source', $sTaskUrl)."
"; } if ($bCanBeDeletedByTask) { $sTip .= "
".Dict::Format('Core:Synchro:TheObjectCanBeDeletedBy_Source', $sTaskUrl)."
"; } } else { $sTip = "
".Dict::S('Core:Synchro:ThisObjectIsSynchronized')."
"; } $sTip .= "
".Dict::S('Core:Synchro:ListOfDataSources')."
"; foreach($aMasterSources as $aStruct) { // Formatting last synchro date $oDateTime = DateTime::createFromFormat('Y-m-d H:i:s', $aStruct['last_synchro']); $oDateTimeFormat = AttributeDateTime::GetFormat(); $sLastSynchro = $oDateTimeFormat->Format($oDateTime); $oDataSource = $aStruct['datasource']; $sLink = $aStruct['url']; $sTip .= "
".$oDataSource->GetIcon(true, '')."$sLink
"; $sTip .= Dict::S('Core:Synchro:LastSynchro').'
'.$sLastSynchro."
"; } $sLabel = Dict::S('Tag:Synchronized'); $sSynchroTagId = 'synchro_icon-'.$this->GetKey(); $aTags[$sSynchroTagId] = ['title' => $sTip, 'css_classes' => 'ibo-object-details--tag--synchronized', 'decoration_classes' => 'fas fa-lock', 'label' => $sLabel]; } } if ($this->IsArchived()) { $sLabel = Dict::S('Tag:Archived'); $sTitle = Dict::S('Tag:Archived+'); $aTags['archived'] = ['title' => $sTitle, 'css_classes' => 'ibo-object-details--tag--archived', 'decoration_classes' => 'fas fa-archive', 'label' => $sLabel]; } elseif ($this->IsObsolete()) { $sLabel = Dict::S('Tag:Obsolete'); $sTitle = Dict::S('Tag:Obsolete+'); $aTags['obsolete'] = ['title' => $sTitle, 'css_classes' => 'ibo-object-details--tag--obsolete', 'decoration_classes' => 'fas fa-eye-slash', 'label' => $sLabel]; } foreach ($aTags as $sIconId => $aIconData) { $sTagTooltipContent = utils::EscapeHtml($aIconData['title']); $aHeaderBlocks['subtitle'][static::HEADER_BLOCKS_SUBTITLE_TAG_PREFIX.$sIconId] = new Html(<<{$aIconData['label']} HTML ); } return $aHeaderBlocks; } /** * Display properties tab of an object * * @param WebPage $oPage * @param bool $bEditMode Note that this parameter is no longer used in this method. Use {@see static::$sDisplayMode} instead * @param string $sPrefix * @param array $aExtraParams * * @return array * @throws \CoreException * * @since 3.0.0 $bEditMode is deprecated and no longer used */ public function DisplayBareProperties(WebPage $oPage, $bEditMode = false, $sPrefix = '', $aExtraParams = array()) { $aFieldsMap = $this->GetBareProperties($oPage, $bEditMode, $sPrefix, $aExtraParams); if (!isset($aExtraParams['disable_plugins']) || !$aExtraParams['disable_plugins']) { /** @var iApplicationUIExtension $oExtensionInstance */ foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance) { $oExtensionInstance->OnDisplayProperties($this, $oPage, $bEditMode); } } return $aFieldsMap; } /** * Add a field to the map: attcode => id used when building a form * * @param string $sAttCode The attribute code of the field being edited * @param string $sInputId The unique ID of the control/widget in the page */ protected function AddToFieldsMap($sAttCode, $sInputId) { $this->aFieldsMap[$sAttCode] = $sInputId; } /** * @param WebPage $oPage * @param $sAttCode * * @throws \Exception */ public function DisplayDashboard($oPage, $sAttCode) { // Retrieve parameters /** @var bool $bIsContainerInEdition True if the container of the dashboard is currently in edition; meaning that the dashboard could not be up-to-date with data changed in the container (eg. when editing an object and adding linkedset items) */ $bIsContainerInEdition = (utils::ReadParam('host_container_in_edition', 'false') === 'true'); $sClass = get_class($this); $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode); // Consistency checks if (!$oAttDef instanceof AttributeDashboard) { throw new CoreException(Dict::S('UI:Error:InvalidDashboard')); } // Load the dashboard $oDashboard = $oAttDef->GetDashboard(); if (is_null($oDashboard)) { throw new CoreException(Dict::S('UI:Error:InvalidDashboard')); } $bCanEdit = UserRights::IsAdministrator() || $oAttDef->IsUserEditable(); $sDivId = $oDashboard->GetId(); if ($bIsContainerInEdition) { $oPage->AddUiBlock(AlertUIBlockFactory::MakeForInformation(Dict::S('UI:Dashboard:NotUpToDateUntilContainerSaved'))); } $oPage->add('
'); $aExtraParams = array( 'query_params' => $this->ToArgsForQuery(), 'dashboard_div_id' => $sDivId, ); $oDashboard->Render($oPage, false, $aExtraParams, $bCanEdit); $oPage->add('
'); } /** * @param WebPage $oPage * @param bool $bEditMode Note that this parameter is no longer used in this method. Use {@see static::$sDisplayMode} instead * * @throws \CoreException * @throws \CoreUnexpectedValue * @throws \DictExceptionMissingString * @throws \MissingQueryArgument * @throws \MySQLException * @throws \MySQLHasGoneAwayException * @throws \OQLException * @throws \Exception * * @since 3.0.0 $bEditMode is deprecated and no longer used */ public function DisplayBareRelations(WebPage $oPage, $bEditMode = false) { $aRedundancySettings = $this->FindVisibleRedundancySettings(); // Related objects: display all the linkset attributes, each as a separate tab // In the order described by the 'display' ZList $aList = $this->FlattenZList(MetaModel::GetZListItems(get_class($this), 'details')); if (count($aList) == 0) { // Empty ZList defined, display all the linkedset attributes defined $aList = array_keys(MetaModel::ListAttributeDefs(get_class($this))); } $sClass = get_class($this); foreach($aList as $sAttCode) { $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode); if ($oAttDef instanceof AttributeDashboard) { if (!$this->IsNew()) { $sHostContainerInEditionUrlParam = ($bEditMode) ? '&host_container_in_edition=true' : ''; $oPage->AddAjaxTab( 'Class:'.$sClass.'/Attribute:'.$sAttCode, utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php?operation=dashboard&class=' .get_class($this) .'&id='.$this->GetKey() .'&attcode='.$oAttDef->GetCode() .$sHostContainerInEditionUrlParam, true, $oAttDef->GetLabel(), AjaxTab::ENUM_TAB_PLACEHOLDER_DASHBOARD ); // Add graphs dependencies WebResourcesHelper::EnableC3JSToWebPage($oPage); } continue; } // Process only link set attributes with tab display style $bIsLinkSetWithDisplayStyleTab = is_a($oAttDef, AttributeLinkedSet::class) && $oAttDef->GetDisplayStyle() === LINKSET_DISPLAY_STYLE_TAB; if (!$oAttDef->IsLinkset() || !$bIsLinkSetWithDisplayStyleTab) { continue; } $sLinkedClass = $oAttDef->GetLinkedClass(); // Filter out links pointing to obsolete objects (if relevant) $oOrmLinkSet = $this->Get($sAttCode); $oLinkSet = $oOrmLinkSet->ToDBObjectSet(utils::ShowObsoleteData()); $iCount = $oLinkSet->Count(); if ($this->IsNew()) { $iFlags = $this->GetInitialStateAttributeFlags($sAttCode); } else { $iFlags = $this->GetAttributeFlags($sAttCode); } // Adjust the flags according to user rights if ($oAttDef->IsIndirect()) { $oLinkingAttDef = MetaModel::GetAttributeDef($sLinkedClass, $oAttDef->GetExtKeyToRemote()); $sTargetClass = $oLinkingAttDef->GetTargetClass(); // n:n links => must be allowed to modify the linking class AND read the target class in order to edit the linkedset if (!UserRights::IsActionAllowed($sLinkedClass, UR_ACTION_MODIFY) || !UserRights::IsActionAllowed($sTargetClass, UR_ACTION_READ)) { $iFlags |= OPT_ATT_READONLY; } // n:n links => must be allowed to read the linking class AND the target class in order to display the linkedset if (!UserRights::IsActionAllowed($sLinkedClass, UR_ACTION_READ) || !UserRights::IsActionAllowed($sTargetClass, UR_ACTION_READ)) { $iFlags |= OPT_ATT_HIDDEN; } } else { // 1:n links => must be allowed to modify the linked class in order to edit the linkedset if (!UserRights::IsActionAllowed($sLinkedClass, UR_ACTION_MODIFY)) { $iFlags |= OPT_ATT_READONLY; } // 1:n links => must be allowed to read the linked class in order to display the linkedset if (!UserRights::IsActionAllowed($sLinkedClass, UR_ACTION_READ)) { $iFlags |= OPT_ATT_HIDDEN; } } // Non-readable/hidden linkedset... don't display anything if ($iFlags & OPT_ATT_HIDDEN) { continue; } $sTabCode = 'Class:'.$sClass.'/Attribute:'.$sAttCode; $sTabDescription = utils::IsNotNullOrEmptyString($oAttDef->GetDescription()) ? $oAttDef->GetDescription() : null; $sCount = ($iCount != 0) ? " ($iCount)" : ""; $oPage->SetCurrentTab($sTabCode, $oAttDef->GetLabel().$sCount, $sTabDescription); $aArgs = array('this' => $this); $sEditWhen = $oAttDef->GetEditWhen(); // Calculate if edit_when allows to edit based on current $bEditMode $bIsEditableBasedOnEditWhen = ($sEditWhen === LINKSET_EDITWHEN_ALWAYS) || ($bEditMode ? $sEditWhen === LINKSET_EDITWHEN_ON_HOST_EDITION : $sEditWhen === LINKSET_EDITWHEN_ON_HOST_DISPLAY); $bReadOnly = ($iFlags & (OPT_ATT_READONLY | OPT_ATT_SLAVE)) || !$bIsEditableBasedOnEditWhen; if ($bEditMode && (!$bReadOnly)) { $sInputId = $this->m_iFormId.'_'.$sAttCode; $sDisplayValue = ''; // not used $sHTMLValue = "".self::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $oLinkSet, $sDisplayValue, $sInputId, '', $iFlags, $aArgs).''; $this->AddToFieldsMap($sAttCode, $sInputId); $oPage->add($sHTMLValue); } else { if ($oAttDef->IsIndirect()) { $oBlockLinkSetViewTable = new BlockIndirectLinkSetViewTable($oPage, $this, $sClass, $sAttCode, $oAttDef, $bReadOnly, $iCount); } else { $oBlockLinkSetViewTable = new BlockDirectLinkSetViewTable($oPage, $this, $sClass, $sAttCode, $oAttDef, $bReadOnly, $iCount); } $oPage->AddUiBlock($oBlockLinkSetViewTable); } if (array_key_exists($sAttCode, $aRedundancySettings)) { foreach ($aRedundancySettings[$sAttCode] as $oRedundancyAttDef) { $sRedundancyAttCode = $oRedundancyAttDef->GetCode(); $sValue = $this->Get($sRedundancyAttCode); $iRedundancyFlags = $this->GetFormAttributeFlags($sRedundancyAttCode); $bRedundancyReadOnly = ($iRedundancyFlags & (OPT_ATT_READONLY | OPT_ATT_SLAVE)); $oFieldSet = FieldSetUIBlockFactory::MakeStandard($oRedundancyAttDef->GetLabel()); $oFieldSet->AddCSSClass('mt-5'); $oPage->AddSubBlock($oFieldSet); if ($bEditMode && (!$bRedundancyReadOnly)) { $sInputId = $this->m_iFormId.'_'.$sRedundancyAttCode; $oFieldSet->AddSubBlock(new Html("".self::GetFormElementForField($oPage, $sClass, $sRedundancyAttCode, $oRedundancyAttDef, $sValue, '', $sInputId, '', $iFlags, $aArgs).'')); } else { $oFieldSet->AddSubBlock(new Html($oRedundancyAttDef->GetDisplayForm($sValue, $oPage, false, $this->m_iFormId))); } } } } /** @var \iApplicationUIExtension $oExtensionInstance */ foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance) { $oExtensionInstance->OnDisplayRelations($this, $oPage, $bEditMode); } $oPage->SetCurrentTab(''); if (!$this->IsNew()) { // Look for any trigger that considers this object as "In Scope" // If any trigger has been found then display a tab with notifications // If all triggers on an object have been deleted, we consider that we no longer need the event notification information $aTriggers = $this->GetRelatedTriggersIDs(); if (count($aTriggers) > 0) { $iId = $this->GetKey(); $aParams = array('class' => get_class($this), 'id' => $iId); $aNotifSearches = array(); $iNotifsCount = 0; $aNotificationClasses = MetaModel::EnumChildClasses('EventNotification'); foreach ($aNotificationClasses as $sNotifClass) { $aNotifSearches[$sNotifClass] = DBObjectSearch::FromOQL("SELECT $sNotifClass AS Ev WHERE Ev.object_id = :id AND Ev.object_class = :class"); $aNotifSearches[$sNotifClass]->SetInternalParams($aParams); $oNotifSet = new DBObjectSet($aNotifSearches[$sNotifClass], array()); $iNotifsCount += $oNotifSet->Count(); } // Display notifications regarding the object: on block per subclass to have the interesting columns $sCount = ($iNotifsCount > 0) ? ' ('.$iNotifsCount.')' : ''; $oPage->SetCurrentTab('UI:NotificationsTab', Dict::S('UI:NotificationsTab').$sCount); foreach ($aNotificationClasses as $sNotifClass) { $oBlock = new DisplayBlock($aNotifSearches[$sNotifClass], 'list', false); $oBlock->Display($oPage, 'notifications_'.$sNotifClass, [ 'menu' => false, 'panel_title' => MetaModel::GetName($sNotifClass), 'panel_icon' => MetaModel::GetClassIcon($sNotifClass, false), ]); } } } // add hidden input for linkset transactions $oInputHidden = InputUIBlockFactory::MakeForHidden('linkset_transactions_id', utils::GetNewTransactionId(), 'linkset_transactions_id'); $oPage->AddUiBlock($oInputHidden); } /** * @return string[] IDs of the triggers that consider this object as "In Scope" * @throws \CoreException * @throws \CoreUnexpectedValue * @throws \MySQLException * @since 3.0.0 */ public function GetRelatedTriggersIDs(): array { $aTriggers = []; // Request only "leaf" classes to avoid reloads $aTriggerClasses = MetaModel::EnumChildClasses('Trigger'); foreach ($aTriggerClasses as $sTriggerClass) { $oReflectionClass = new ReflectionClass($sTriggerClass); if (false === $oReflectionClass->isAbstract()) { $oTriggerSet = new CMDBObjectSet(new DBObjectSearch($sTriggerClass)); while ($oTrigger = $oTriggerSet->Fetch()) { if ($oTrigger->IsInScope($this)) { $aTriggers[] = $oTrigger->GetKey(); } } } } return $aTriggers; } /** * @param WebPage $oPage * @param bool $bEditMode Note that this parameter is no longer used in this method. Use {@see static::$sDisplayMode} instead * @param string $sPrefix * @param array $aExtraParams * * @return array * @throws \ArchivedObjectException * @throws \CoreException * @throws \CoreUnexpectedValue * @throws \DictExceptionMissingString * @throws \MySQLException * @throws \OQLException * @throws \Exception * * @since 3.0.0 $bEditMode is deprecated and no longer used */ public function GetBareProperties(WebPage $oPage, $bEditMode, $sPrefix, $aExtraParams = array()) { $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this)); $sClass = get_class($this); $aDetailsList = MetaModel::GetZListItems($sClass, 'details'); $aDetailsStruct = self::ProcessZlist($aDetailsList, array('UI:PropertiesTab' => array()), 'UI:PropertiesTab', 'col1', ''); $aFieldsMap = array(); $aFieldsComments = (isset($aExtraParams['fieldsComments'])) ? $aExtraParams['fieldsComments'] : array(); $aExtraFlags = (isset($aExtraParams['fieldsFlags'])) ? $aExtraParams['fieldsFlags'] : array(); $bHasFieldsWithRichTextEditor = false; foreach ($aDetailsStruct as $sTab => $aCols) { ksort($aCols); $oPage->SetCurrentTab($sTab); $oMultiColumn = new MultiColumn(); $oPage->AddUiBlock($oMultiColumn); foreach ($aCols as $sColIndex => $aFieldsets) { $oColumn = new Column(); $oMultiColumn->AddColumn($oColumn); foreach ($aFieldsets as $sFieldsetName => $aFields) { if ($sFieldsetName[0] != '_') { $oFieldSet = new FieldSet(Dict::S($sFieldsetName)); $oColumn->AddSubBlock($oFieldSet); } $aDetails = []; foreach ($aFields as $sAttCode) { $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode); // Skip case logs as they will be handled by the activity panel if ($oAttDef instanceof AttributeCaseLog) { continue; } if (($oAttDef instanceof AttributeText) && ($oAttDef->GetFormat() === 'html')) { $bHasFieldsWithRichTextEditor = true; } $sAttDefClass = get_class($oAttDef); $sAttLabel = MetaModel::GetLabel($sClass, $sAttCode); if ($bEditMode) { $sComments = isset($aFieldsComments[$sAttCode]) ? $aFieldsComments[$sAttCode] : ''; $sInfos = ''; $iFlags = FormHelper::GetAttributeFlagsForObject($this, $sAttCode, $aExtraFlags); $bIsLinkSetWithDisplayStyleTab = is_a($oAttDef, AttributeLinkedSet::class) && $oAttDef->GetDisplayStyle() === LINKSET_DISPLAY_STYLE_TAB; if ((($iFlags & OPT_ATT_HIDDEN) == 0) && !($oAttDef instanceof AttributeDashboard) && !$bIsLinkSetWithDisplayStyleTab) { $sInputId = $this->m_iFormId.'_'.$sAttCode; if ($oAttDef->IsWritable()) { $sInputType = ''; if (($sStateAttCode === $sAttCode) && (MetaModel::HasLifecycle($sClass))) { // State attribute is always read-only from the UI $sHTMLValue = $this->GetAsHTML($sAttCode); $val = array( 'label' => '', 'value' => $sHTMLValue, 'input_id' => $sInputId, 'comments' => $sComments, 'infos' => $sInfos, ); } else { if ($iFlags & (OPT_ATT_READONLY | OPT_ATT_SLAVE)) { // Check if the attribute is not read-only because of a synchro... if ($iFlags & OPT_ATT_SLAVE) { $aReasons = array(); $this->GetSynchroReplicaFlags($sAttCode, $aReasons); $sTip = ''; foreach ($aReasons as $aRow) { $sDescription = utils::EscapeHtml($aRow['description']); $sDescription = str_replace(array("\r\n", "\n"), "
", $sDescription); $sTip .= "
"; $sTip .= "
Synchronized with {$aRow['name']}
"; $sTip .= "
$sDescription
"; } $sTip = utils::HtmlEntities($sTip); $sSynchroIcon = '
'; $sComments = $sSynchroIcon; } // Attribute is read-only $sHTMLValue = "".$this->GetAsHTML($sAttCode).''; } else { $sValue = $this->Get($sAttCode); $sDisplayValue = $this->GetEditValue($sAttCode); // transfer bulk context to components as it can be needed (linked set) $aArgs = array('this' => $this, 'formPrefix' => $sPrefix); if (array_key_exists('bulk_context', $aExtraParams)) { $aArgs['bulk_context'] = $aExtraParams['bulk_context']; } $sHTMLValue = "".self::GetFormElementForField( $oPage, $sClass, $sAttCode, $oAttDef, $sValue, $sDisplayValue, $sInputId, '', $iFlags, $aArgs, true, $sInputType ).''; } $aFieldsMap[$sAttCode] = $sInputId; // Attribute description $sDescription = $oAttDef->GetDescription(); $sDescriptionForHTMLTag = utils::HtmlEntities($sDescription); $sDescriptionHTMLTag = (empty($sDescriptionForHTMLTag) || $sDescription === $oAttDef->GetLabel()) ? '' : 'class="ibo-has-description" data-tooltip-content="'.$sDescriptionForHTMLTag.'" data-tooltip-max-width="600px"'; $val = array( 'label' => ''.$oAttDef->GetLabel().'', 'value' => $sHTMLValue, 'input_id' => $sInputId, 'input_type' => $sInputType, 'comments' => $sComments, 'infos' => $sInfos, ); } } else { // Attribute description $sDescription = $oAttDef->GetDescription(); $sDescriptionForHTMLTag = utils::HtmlEntities($sDescription); $sDescriptionHTMLTag = (empty($sDescriptionForHTMLTag) || $sDescription === $oAttDef->GetLabel()) ? '' : 'class="ibo-has-description" data-tooltip-content="'.$sDescriptionForHTMLTag.' "data-tooltip-max-width="600px"'; $val = array( 'label' => ''.$oAttDef->GetLabel().'', 'value' => "".$this->GetAsHTML($sAttCode)."", 'comments' => $sComments, 'infos' => $sInfos, ); $aFieldsMap[$sAttCode] = $sInputId; } } else { $val = null; // Skip this field } } else { // !bEditMode $val = $this->GetFieldAsHtml($sClass, $sAttCode, $sStateAttCode); } if ($val != null) { // Add extra data for markup generation // - Attribute code and AttributeDef. class $val['attcode'] = $sAttCode; $val['atttype'] = $sAttDefClass; $val['attlabel'] = $sAttLabel; $val['attflags'] = ($bEditMode) ? $this->GetFormAttributeFlags($sAttCode) : OPT_ATT_READONLY; // - How the field should be rendered $val['layout'] = (in_array($oAttDef->GetEditClass(), static::GetAttEditClassesToRenderAsLargeField())) ? Field::ENUM_FIELD_LAYOUT_LARGE : Field::ENUM_FIELD_LAYOUT_SMALL; // - For simple fields, we get the raw (stored) value as well $bExcludeRawValue = false; foreach (static::GetAttDefClassesToExcludeFromMarkupMetadataRawValue() as $sAttDefClassToExclude) { if (is_a($sAttDefClass, $sAttDefClassToExclude, true)) { $bExcludeRawValue = true; break; } } $val['value_raw'] = ($bExcludeRawValue === false) ? $this->Get($sAttCode) : ''; // The field is visible, add it to the current column $oField = FieldUIBlockFactory::MakeFromParams($val); if ($sFieldsetName[0] != '_') { $oFieldSet->AddSubBlock($oField); } else { $oColumn->AddSubBlock($oField); } } } } } } return $aFieldsMap; } /** * @param WebPage $oPage * @param bool $bEditMode Note that this parameter is no longer used in this method, {@see static::$sDisplayMode} is used instead, but we cannot remove it as it part of the base interface (iDisplay)... * * @throws \ApplicationException * @throws \ArchivedObjectException * @throws \CoreException * @throws \CoreUnexpectedValue * @throws \DictExceptionMissingString * @throws \MissingQueryArgument * @throws \MySQLException * @throws \MySQLHasGoneAwayException * @throws \OQLException * * @since 3.0.0 $bEditMode is deprecated and no longer used */ public function DisplayDetails(WebPage $oPage, $bEditMode = false) { // N°3786: As this can now be call recursively from the self::ReloadAndDisplay(), we need to make sure we don't fall into an infinite loop static $bBlockReentrance = false; $sClass = get_class($this); $iKey = $this->GetKey(); if ($this->GetDisplayMode() === static::ENUM_DISPLAY_MODE_VIEW) { // The concurrent access lock makes sense only for already existing objects $LockEnabled = MetaModel::GetConfig()->Get('concurrent_lock_enabled'); if ($LockEnabled) { $aLockInfo = iTopOwnershipLock::IsLocked($sClass, $iKey); if ($aLockInfo['locked'] === true && $aLockInfo['owner']->GetKey() == UserRights::GetUserId() && $bBlockReentrance === false) { // If the object is locked by the current user, it's worth trying again, since // the lock may be released by 'onunload' which is called AFTER loading the current page. //$bTryAgain = $oOwner->GetKey() == UserRights::GetUserId(); $bBlockReentrance = true; self::ReloadAndDisplay($oPage, $this, array('operation' => 'details')); return; } } } // Object's details $oObjectDetails = ObjectFactory::MakeDetails($this, $this->GetDisplayMode()); if ($oPage->IsPrintableVersion()) { $oObjectDetails->SetIsHeaderVisibleOnScroll(false); } // Note: DisplayBareHeader is called before adding $oObjectDetails to the page, so it can inject HTML before it through $oPage. /** @var \iTopWebPage $oPage */ $oKPI = new ExecutionKPI(); $aHeadersBlocks = $this->DisplayBareHeader($oPage, $bEditMode); $oKPI->ComputeStatsForExtension($this, 'DisplayBareHeader'); if (false === empty($aHeadersBlocks['subtitle'])) { $oObjectDetails->AddSubTitleBlocks($aHeadersBlocks['subtitle']); } if (false === empty($aHeadersBlocks['toolbar'])) { $oObjectDetails->AddToolbarBlocks($aHeadersBlocks['toolbar']); } $oPage->AddUiBlock($oObjectDetails); $oPage->AddTabContainer(OBJECT_PROPERTIES_TAB, '', $oObjectDetails); $oPage->SetCurrentTabContainer(OBJECT_PROPERTIES_TAB); $oPage->SetCurrentTab('UI:PropertiesTab'); $oKPI = new ExecutionKPI(); $this->DisplayBareProperties($oPage, $bEditMode); $oKPI->ComputeStatsForExtension($this, 'DisplayBareProperties'); $oKPI = new ExecutionKPI(); $this->DisplayBareRelations($oPage, $bEditMode); $oKPI->ComputeStatsForExtension($this, 'DisplayBareRelations'); // Note: Adding the JS snippet which enables the image upload should have been done directly by the ActivityPanel which would have kept the independance principle // of the UIBlock. For now we keep it this way in order to move on and trace this known limitation in N°3736. // // Note: Don't do it in modals as we don't display the activity panel if (false === ($oPage instanceof AjaxPage)) { /** @var ActivityPanel $oActivityPanel */ $oActivityPanel = $oPage->GetContentLayout()->GetSubBlock(ActivityPanel::BLOCK_CODE); // Note: Testing if block exists is necessary as during the 'release_lock_and_details' operation we don't have an activity panel if (!is_null($oActivityPanel) && $oActivityPanel->HasTransactionId()) { $iTransactionId = $oActivityPanel->GetTransactionId(); $sTempId = utils::GetUploadTempId($iTransactionId); $oPage->add_ready_script(InlineImage::EnableCKEditorImageUpload($this, $sTempId)); } } } /** * @param WebPage $oPage * * @throws \ArchivedObjectException * @throws \CoreException * @throws \DictExceptionMissingString * @throws \Exception */ public function DisplayPreview(WebPage $oPage) { $aDetails = array(); $sClass = get_class($this); $aList = MetaModel::GetZListItems($sClass, 'preview'); foreach($aList as $sAttCode) { $aDetails[] = array( 'label' => MetaModel::GetLabel($sClass, $sAttCode), 'value' => $this->GetAsHTML($sAttCode), ); } $oPage->details($aDetails); } /** * @param WebPage $oPage * @param \CMDBObjectSet $oSet * @param array $aExtraParams See possible values in {@see DataTableUIBlockFactory::RenderDataTable()} * * @throws \ApplicationException * @throws \CoreException */ public static function DisplaySet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array()) { $oPage->AddUiBlock(self::GetDisplaySetBlock($oPage, $oSet, $aExtraParams)); } /** * Simplified version of GetDisplaySet() with less "decoration" around the table (and no paging) * that fits better into a printed document (like a PDF or a printable view) * * @param WebPage $oPage * @param DBObjectSet $oSet * @param array $aExtraParams * * @return string The HTML representation of the table * @throws \CoreException */ public static function GetDisplaySetForPrinting(WebPage $oPage, DBObjectSet $oSet, $aExtraParams = array()) { $sTableId = isset($aExtraParams['table_id']) ? $aExtraParams['table_id'] : utils::GetUniqueId();; $aExtraParams['view_link'] = true; $aExtraParams['select_mode'] = 'none'; return DataTableUIBlockFactory::MakeForObject($oPage, $sTableId, $oSet, $aExtraParams); } /** * Get the HTML fragment corresponding to the display of a table representing a set of objects * * @param WebPage $oPage The page object is used for out-of-band information (mostly scripts) output * @param \DBObjectSet $oSet The set of objects to display * @param array $aExtraParams key used : *
    *
  • view_link : if true then for extkey will display links with friendly name and make column sortable, default true *
  • menu : if true prints DisplayBlock menu, default true *
  • display_aliases : list of query aliases that will be printed, defaults to [] (displays all) *
  • zlist : name of the zlist to use, false to disable zlist lookup, default to 'list' *
  • extra_fields : list of . to add to the result, separator ',', defaults to empty string *
* * @return String The HTML fragment representing the table of objects. Warning : no JS added to handled * pagination or table sorting ! * * @see DisplayBlock to get a similar table but with the JS for pagination & sorting * * @deprecated 3.0.0 use GetDisplaySetBlock */ public static function GetDisplaySet(WebPage $oPage, DBObjectSet $oSet, $aExtraParams = array()) { DeprecatedCallsLog::NotifyDeprecatedPhpMethod('use GetDisplaySetBlock'); $oPage->AddUiBlock(static::GetDisplaySetBlock($oPage, $oSet, $aExtraParams)); return ""; } /** * @param WebPage $oPage * @param \DBObjectSet $oSet * @param array $aExtraParams * * @return \Combodo\iTop\Application\UI\Base\Layout\UIContentBlock|string * @throws \ApplicationException * @throws \ArchivedObjectException * @throws \CoreException * @throws \CoreUnexpectedValue * @throws \DictExceptionMissingString * @throws \MissingQueryArgument * @throws \MySQLException * @throws \MySQLHasGoneAwayException * @throws \OQLException * @throws \ReflectionException * * @since 3.0.0 */ public static function GetDisplaySetBlock(WebPage $oPage, DBObjectSet $oSet, $aExtraParams = array()) { if ($oPage->IsPrintableVersion() || $oPage->is_pdf()) { return self::GetDisplaySetForPrinting($oPage, $oSet, $aExtraParams); } if (empty($aExtraParams['currentId'])) { $iListId = utils::GetUniqueId(); // Works only if not in an Ajax page !! } else { $iListId = $aExtraParams['currentId']; } return DataTableUIBlockFactory::MakeForResult($oPage, $iListId, $oSet, $aExtraParams); } public static function GetDataTableFromDBObjectSet(DBObjectSet $oSet, $aParams = array()) { $aFields = null; if (isset($aParams['fields']) && (strlen($aParams['fields']) > 0)) { $aFields = explode(',', $aParams['fields']); } $bFieldsAdvanced = false; if (isset($aParams['fields_advanced'])) { $bFieldsAdvanced = (bool)$aParams['fields_advanced']; } $bLocalize = true; if (isset($aParams['localize_values'])) { $bLocalize = (bool)$aParams['localize_values']; } $aList = array(); $aClasses = $oSet->GetFilter()->GetSelectedClasses(); $aAuthorizedClasses = array(); foreach ($aClasses as $sAlias => $sClassName) { if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) != UR_ALLOWED_NO) { $aAuthorizedClasses[$sAlias] = $sClassName; } } $aHeader = array(); foreach ($aAuthorizedClasses as $sAlias => $sClassName) { $aList[$sAlias] = array(); foreach (MetaModel::GetZListItems($sClassName, 'list') as $sAttCode) { $oAttDef = Metamodel::GetAttributeDef($sClassName, $sAttCode); if (is_null($aFields) || (count($aFields) == 0)) { // Standard list of attributes (no link sets) if ($oAttDef->IsScalar() && ($oAttDef->IsWritable() || $oAttDef->IsExternalField())) { $sAttCodeEx = $oAttDef->IsExternalField() ? $oAttDef->GetKeyAttCode().'->'.$oAttDef->GetExtAttCode() : $sAttCode; $aList[$sAlias][$sAttCodeEx] = $oAttDef; if ($bFieldsAdvanced && $oAttDef->IsExternalKey(EXTKEY_RELATIVE)) { $sRemoteClass = $oAttDef->GetTargetClass(); foreach (MetaModel::GetReconcKeys($sRemoteClass) as $sRemoteAttCode) { $aList[$sAlias][$sAttCode.'->'.$sRemoteAttCode] = MetaModel::GetAttributeDef($sRemoteClass, $sRemoteAttCode); } } } } else { // User defined list of attributes if (in_array($sAttCode, $aFields) || in_array($sAlias.'.'.$sAttCode, $aFields)) { $aList[$sAlias][$sAttCode] = $oAttDef; } } } // Replace external key by the corresponding friendly name (if not already in the list) foreach ($aList[$sAlias] as $sAttCode => $oAttDef) { if ($oAttDef->IsExternalKey()) { unset($aList[$sAlias][$sAttCode]); $sFriendlyNameAttCode = $sAttCode.'_friendlyname'; if (!array_key_exists($sFriendlyNameAttCode, $aList[$sAlias]) && MetaModel::IsValidAttCode($sClassName, $sFriendlyNameAttCode)) { $oFriendlyNameAtt = MetaModel::GetAttributeDef($sClassName, $sFriendlyNameAttCode); $aList[$sAlias][$sFriendlyNameAttCode] = $oFriendlyNameAtt; } } } foreach ($aList[$sAlias] as $sAttCodeEx => $oAttDef) { $sColLabel = $bLocalize ? MetaModel::GetLabel($sClassName, $sAttCodeEx) : $sAttCodeEx; $oFinalAttDef = $oAttDef->GetFinalAttDef(); if (get_class($oFinalAttDef) == 'AttributeDateTime') { $aHeader[$oAttDef->GetCode().'/D'] = ['label' => $sColLabel.' ('.Dict::S('UI:SplitDateTime-Date').')']; $aHeader[$oAttDef->GetCode().'/T'] = ['label' => $sColLabel.' ('.Dict::S('UI:SplitDateTime-Time').')']; } else { $aHeader[$oAttDef->GetCode()] = ['label' => $sColLabel]; } } } $oSet->Seek(0); $aRows = []; while ($aObjects = $oSet->FetchAssoc()) { $aRow = []; foreach ($aAuthorizedClasses as $sAlias => $sClassName) { $oObj = $aObjects[$sAlias]; foreach ($aList[$sAlias] as $sAttCodeEx => $oAttDef) { if (is_null($oObj)) { $aRow[$oAttDef->GetCode()] = ''; } else { $oFinalAttDef = $oAttDef->GetFinalAttDef(); if (get_class($oFinalAttDef) == 'AttributeDateTime') { $sDate = $oObj->Get($sAttCodeEx); if ($sDate === null) { $aRow[$oAttDef->GetCode().'/D'] = ''; $aRow[$oAttDef->GetCode().'/T'] = ''; } else { $iDate = AttributeDateTime::GetAsUnixSeconds($sDate); $aRow[$oAttDef->GetCode().'/D'] = date('Y-m-d', $iDate); // Format kept as-is for 100% backward compatibility of the exports $aRow[$oAttDef->GetCode().'/T'] = date('H:i:s', $iDate); // Format kept as-is for 100% backward compatibility of the exports } } else { if ($oAttDef instanceof AttributeCaseLog) { $rawValue = $oObj->Get($sAttCodeEx); $outputValue = str_replace("\n", "
", utils::EscapeHtml($rawValue->__toString())); // Trick for Excel: treat the content as text even if it begins with an equal sign $aRow[$oAttDef->GetCode()] = $outputValue; } else { $rawValue = $oObj->Get($sAttCodeEx); // Due to custom formatting rules, empty friendlynames may be rendered as non-empty strings // let's fix this and make sure we render an empty string if the key == 0 if ($oAttDef instanceof AttributeExternalField && $oAttDef->IsFriendlyName()) { $sKeyAttCode = $oAttDef->GetKeyAttCode(); if ($oObj->Get($sKeyAttCode) == 0) { $rawValue = ''; } } if ($bLocalize) { $outputValue = utils::EscapeHtml($oFinalAttDef->GetEditValue($rawValue)); } else { $outputValue = utils::EscapeHtml($rawValue); } $aRow[$oAttDef->GetCode()] = $outputValue; } } } } } $aRows[] = $aRow; } $oTable = new StaticTable(); $oTable->SetColumns($aHeader); $oTable->SetData($aRows); return $oTable; //DataTableUIBlockFactory::MakeForStaticData('', $aHeader, $aRows); } /** * @param WebPage $oPage * @param \CMDBObjectSet $oSet * @param array $aExtraParams key used : *
    *
  • view_link : if true then for extkey will display links with friendly name and make column sortable, default true *
  • menu : if true prints DisplayBlock menu, default true *
  • display_aliases : list of query aliases that will be printed, defaults to [] (displays all) *
  • zlist : name of the zlist to use, false to disable zlist lookup, default to 'list' *
  • extra_fields : list of . to add to the result, separator ',', defaults to empty string *
* * @return string * @throws \CoreException * @throws \DictExceptionMissingString * @throws \MissingQueryArgument * @throws \MySQLException * @throws \MySQLHasGoneAwayException * @deprecated 3.0.0 */ public static function GetDisplayExtendedSet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array()) { DeprecatedCallsLog::NotifyDeprecatedPhpMethod(); if (empty($aExtraParams['currentId'])) { $iListId = utils::GetUniqueId(); // Works only if not in an Ajax page !! } else { $iListId = $aExtraParams['currentId']; } $aList = array(); // Initialize and check the parameters $bViewLink = isset($aExtraParams['view_link']) ? $aExtraParams['view_link'] : true; $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true; // Check if there is a list of aliases to limit the display to... $aDisplayAliases = isset($aExtraParams['display_aliases']) ? explode(',', $aExtraParams['display_aliases']) : array(); $sZListName = isset($aExtraParams['zlist']) ? ($aExtraParams['zlist']) : 'list'; $aExtraFieldsRaw = isset($aExtraParams['extra_fields']) ? explode(',', trim($aExtraParams['extra_fields'])) : array(); $aExtraFields = array(); $sAttCode = ''; foreach($aExtraFieldsRaw as $sFieldName) { // Ignore attributes not of the main queried class if (preg_match('/^(.*)\.(.*)$/', $sFieldName, $aMatches)) { $sClassAlias = $aMatches[1]; $sAttCode = $aMatches[2]; if (array_key_exists($sClassAlias, $oSet->GetSelectedClasses())) { $aExtraFields[$sClassAlias][] = $sAttCode; } } else { $aExtraFields['*'] = $sAttCode; } } $aClasses = $oSet->GetFilter()->GetSelectedClasses(); $aAuthorizedClasses = array(); foreach($aClasses as $sAlias => $sClassName) { if ((UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) != UR_ALLOWED_NO) && ((count($aDisplayAliases) == 0) || (in_array($sAlias, $aDisplayAliases)))) { $aAuthorizedClasses[$sAlias] = $sClassName; } } foreach($aAuthorizedClasses as $sAlias => $sClassName) { if (array_key_exists($sAlias, $aExtraFields)) { $aList[$sAlias] = $aExtraFields[$sAlias]; } else { $aList[$sAlias] = array(); } if ($sZListName !== false) { $aDefaultList = self::FlattenZList(MetaModel::GetZListItems($sClassName, $sZListName)); $aList[$sAlias] = array_merge($aDefaultList, $aList[$sAlias]); } // Filter the list to removed linked set since we are not able to display them here foreach ($aList[$sAlias] as $index => $sAttCode) { $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode); if ($oAttDef instanceof AttributeLinkedSet) { // Removed from the display list unset($aList[$sAlias][$index]); } } if (empty($aList[$sAlias])) { unset($aList[$sAlias], $aAuthorizedClasses[$sAlias]); } } $sSelectMode = 'none'; $oDataTable = new DataTable($iListId, $oSet, $aAuthorizedClasses); $oSettings = DataTableSettings::GetDataModelSettings($aAuthorizedClasses, $bViewLink, $aList); $bDisplayLimit = isset($aExtraParams['display_limit']) ? $aExtraParams['display_limit'] : true; if ($bDisplayLimit) { $iDefaultPageSize = appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit()); $oSettings->iDefaultPageSize = $iDefaultPageSize; } $oSettings->aSortOrder = MetaModel::GetOrderByDefault($sClassName); return $oDataTable->Display($oPage, $oSettings, $bDisplayMenu, $sSelectMode, $bViewLink, $aExtraParams); } /** * @param WebPage $oPage * @param \CMDBObjectSet $oSet * @param array $aParams * @param string $sCharset * * @throws \CoreException * @throws \CoreUnexpectedValue * @throws \MissingQueryArgument * @throws \MySQLException * @throws \MySQLHasGoneAwayException */ public static function DisplaySetAsCSV(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array(), $sCharset = 'UTF-8') { $oPage->add(self::GetSetAsCSV($oSet, $aParams, $sCharset)); } /** * @param \DBObjectSet $oSet * @param array $aParams * @param string $sCharset * * @return string * @throws \CoreException * @throws \CoreUnexpectedValue * @throws \MissingQueryArgument * @throws \MySQLException * @throws \MySQLHasGoneAwayException * @throws \Exception */ public static function GetSetAsCSV(DBObjectSet $oSet, $aParams = array(), $sCharset = 'UTF-8') { $sSeparator = isset($aParams['separator']) ? $aParams['separator'] : ','; // default separator is comma $sTextQualifier = isset($aParams['text_qualifier']) ? $aParams['text_qualifier'] : '"'; // default text qualifier is double quote $aFields = null; if (isset($aParams['fields']) && (strlen($aParams['fields']) > 0)) { $aFields = explode(',', $aParams['fields']); } $bFieldsAdvanced = false; if (isset($aParams['fields_advanced'])) { $bFieldsAdvanced = (bool)$aParams['fields_advanced']; } $bLocalize = true; if (isset($aParams['localize_values'])) { $bLocalize = (bool)$aParams['localize_values']; } $aList = array(); $aClasses = $oSet->GetFilter()->GetSelectedClasses(); $aAuthorizedClasses = array(); foreach($aClasses as $sAlias => $sClassName) { if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) != UR_ALLOWED_NO) { $aAuthorizedClasses[$sAlias] = $sClassName; } } $aHeader = array(); foreach($aAuthorizedClasses as $sAlias => $sClassName) { $aList[$sAlias] = array(); foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef) { if (is_null($aFields) || (count($aFields) == 0)) { // Standard list of attributes (no link sets) if ($oAttDef->IsScalar() && ($oAttDef->IsWritable() || $oAttDef->IsExternalField())) { $sAttCodeEx = $oAttDef->IsExternalField() ? $oAttDef->GetKeyAttCode().'->'.$oAttDef->GetExtAttCode() : $sAttCode; if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) { if ($bFieldsAdvanced) { $aList[$sAlias][$sAttCodeEx] = $oAttDef; if ($oAttDef->IsExternalKey(EXTKEY_RELATIVE)) { $sRemoteClass = $oAttDef->GetTargetClass(); foreach(MetaModel::GetReconcKeys($sRemoteClass) as $sRemoteAttCode) { $aList[$sAlias][$sAttCode.'->'.$sRemoteAttCode] = MetaModel::GetAttributeDef($sRemoteClass, $sRemoteAttCode); } } } } else { // Any other attribute $aList[$sAlias][$sAttCodeEx] = $oAttDef; } } } else { // User defined list of attributes if (in_array($sAttCode, $aFields) || in_array($sAlias.'.'.$sAttCode, $aFields)) { $aList[$sAlias][$sAttCode] = $oAttDef; } } } if ($bFieldsAdvanced) { $aHeader[] = 'id'; } foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef) { $aHeader[] = $bLocalize ? MetaModel::GetLabel($sClassName, $sAttCodeEx, isset($aParams['showMandatoryFields'])) : $sAttCodeEx; } } $sHtml = implode($sSeparator, $aHeader)."\n"; $oSet->Seek(0); while ($aObjects = $oSet->FetchAssoc()) { $aRow = array(); foreach($aAuthorizedClasses as $sAlias => $sClassName) { $oObj = $aObjects[$sAlias]; if ($bFieldsAdvanced) { if (is_null($oObj)) { $aRow[] = ''; } else { $aRow[] = $oObj->GetKey(); } } foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef) { if (is_null($oObj)) { $aRow[] = ''; } else { $value = $oObj->Get($sAttCodeEx); $sCSVValue = $oAttDef->GetAsCSV($value, $sSeparator, $sTextQualifier, $oObj, $bLocalize); $aRow[] = iconv('UTF-8', $sCharset.'//IGNORE//TRANSLIT', $sCSVValue); } } } $sHtml .= implode($sSeparator, $aRow)."\n"; } return $sHtml; } /** * @param WebPage $oPage * @param \CMDBObjectSet $oSet * @param array $aParams * * @throws \Exception * only used in old and deprecated export.php * * @internal Only to be used by `/webservices/export.php` : this is a legacy method that produces wrong HTML (no TR on table body rows) */ public static function DisplaySetAsHTMLSpreadsheet(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array()) { $oPage->add(self::GetSetAsHTMLSpreadsheet($oSet, $aParams)); } /** * Spreadsheet output: designed for end users doing some reporting * Then the ids are excluded and replaced by the corresponding friendlyname * * @param \DBObjectSet $oSet * @param array $aParams * * @return string * @throws \CoreException * @throws \CoreUnexpectedValue * @throws \MissingQueryArgument * @throws \MySQLException * @throws \MySQLHasGoneAwayException * @throws \Exception * * @internal Only to be used by `/webservices/export.php` : this is a legacy method that produces wrong HTML (no TR on table body rows) */ public static function GetSetAsHTMLSpreadsheet(DBObjectSet $oSet, $aParams = array()) { $aFields = null; if (isset($aParams['fields']) && (strlen($aParams['fields']) > 0)) { $aFields = explode(',', $aParams['fields']); } $bFieldsAdvanced = false; if (isset($aParams['fields_advanced'])) { $bFieldsAdvanced = (bool)$aParams['fields_advanced']; } $bLocalize = true; if (isset($aParams['localize_values'])) { $bLocalize = (bool)$aParams['localize_values']; } $aList = array(); $aClasses = $oSet->GetFilter()->GetSelectedClasses(); $aAuthorizedClasses = array(); foreach($aClasses as $sAlias => $sClassName) { if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) != UR_ALLOWED_NO) { $aAuthorizedClasses[$sAlias] = $sClassName; } } $aHeader = array(); foreach($aAuthorizedClasses as $sAlias => $sClassName) { $aList[$sAlias] = array(); foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef) { if (is_null($aFields) || (count($aFields) == 0)) { // Standard list of attributes (no link sets) if ($oAttDef->IsScalar() && ($oAttDef->IsWritable() || $oAttDef->IsExternalField())) { $sAttCodeEx = $oAttDef->IsExternalField() ? $oAttDef->GetKeyAttCode().'->'.$oAttDef->GetExtAttCode() : $sAttCode; $aList[$sAlias][$sAttCodeEx] = $oAttDef; if ($bFieldsAdvanced && $oAttDef->IsExternalKey(EXTKEY_RELATIVE)) { $sRemoteClass = $oAttDef->GetTargetClass(); foreach(MetaModel::GetReconcKeys($sRemoteClass) as $sRemoteAttCode) { $aList[$sAlias][$sAttCode.'->'.$sRemoteAttCode] = MetaModel::GetAttributeDef($sRemoteClass, $sRemoteAttCode); } } } } else { // User defined list of attributes if (in_array($sAttCode, $aFields) || in_array($sAlias.'.'.$sAttCode, $aFields)) { $aList[$sAlias][$sAttCode] = $oAttDef; } } } // Replace external key by the corresponding friendly name (if not already in the list) foreach($aList[$sAlias] as $sAttCode => $oAttDef) { if ($oAttDef->IsExternalKey()) { unset($aList[$sAlias][$sAttCode]); $sFriendlyNameAttCode = $sAttCode.'_friendlyname'; if (!array_key_exists($sFriendlyNameAttCode, $aList[$sAlias]) && MetaModel::IsValidAttCode($sClassName, $sFriendlyNameAttCode)) { $oFriendlyNameAtt = MetaModel::GetAttributeDef($sClassName, $sFriendlyNameAttCode); $aList[$sAlias][$sFriendlyNameAttCode] = $oFriendlyNameAtt; } } } foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef) { $sColLabel = $bLocalize ? MetaModel::GetLabel($sClassName, $sAttCodeEx) : $sAttCodeEx; $oFinalAttDef = $oAttDef->GetFinalAttDef(); if (get_class($oFinalAttDef) == 'AttributeDateTime') { $aHeader[] = $sColLabel.' ('.Dict::S('UI:SplitDateTime-Date').')'; $aHeader[] = $sColLabel.' ('.Dict::S('UI:SplitDateTime-Time').')'; } else { $aHeader[] = $sColLabel; } } } $sHtml = "\n"; $sHtml .= "\n"; $sHtml .= "\n"; $sHtml .= "\n"; $oSet->Seek(0); while ($aObjects = $oSet->FetchAssoc()) { $aRow = array(); foreach($aAuthorizedClasses as $sAlias => $sClassName) { $oObj = $aObjects[$sAlias]; foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef) { if (is_null($oObj)) { $aRow[] = ''; } else { $oFinalAttDef = $oAttDef->GetFinalAttDef(); if (get_class($oFinalAttDef) == 'AttributeDateTime') { $sDate = $oObj->Get($sAttCodeEx); if ($sDate === null) { $aRow[] = ''; $aRow[] = ''; } else { $iDate = AttributeDateTime::GetAsUnixSeconds($sDate); $aRow[] = ''; // Format kept as-is for 100% backward compatibility of the exports $aRow[] = ''; // Format kept as-is for 100% backward compatibility of the exports } } else { if ($oAttDef instanceof AttributeCaseLog) { $rawValue = $oObj->Get($sAttCodeEx); $outputValue = str_replace("\n", "
", utils::EscapeHtml($rawValue->__toString())); // Trick for Excel: treat the content as text even if it begins with an equal sign $aRow[] = ''; } else { $rawValue = $oObj->Get($sAttCodeEx); // Due to custom formatting rules, empty friendlynames may be rendered as non-empty strings // let's fix this and make sure we render an empty string if the key == 0 if ($oAttDef instanceof AttributeExternalField && $oAttDef->IsFriendlyName()) { $sKeyAttCode = $oAttDef->GetKeyAttCode(); if ($oObj->Get($sKeyAttCode) == 0) { $rawValue = ''; } } if ($bLocalize) { $outputValue = utils::EscapeHtml($oFinalAttDef->GetEditValue($rawValue)); } else { $outputValue = utils::EscapeHtml($rawValue); } $aRow[] = ''; } } } } } $sHtml .= implode("\n", $aRow); $sHtml .= "\n"; } $sHtml .= "
".implode("", $aHeader)."
'.date('Y-m-d', $iDate).''.date('H:i:s', $iDate).''.$outputValue.''.$outputValue.'
\n"; return $sHtml; } /** * @param WebPage $oPage * @param \CMDBObjectSet $oSet * @param array $aParams * * @throws \CoreException * @throws \CoreUnexpectedValue * @throws \MissingQueryArgument * @throws \MySQLException * @throws \MySQLHasGoneAwayException */ public static function DisplaySetAsXML(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array()) { $bLocalize = true; if (isset($aParams['localize_values'])) { $bLocalize = (bool)$aParams['localize_values']; } $aClasses = $oSet->GetFilter()->GetSelectedClasses(); $aAuthorizedClasses = array(); foreach($aClasses as $sAlias => $sClassName) { if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) != UR_ALLOWED_NO) { $aAuthorizedClasses[$sAlias] = $sClassName; } } $aList = array(); $aList[$sAlias] = MetaModel::GetZListItems($sClassName, 'details'); $oPage->add("\n"); $oSet->Seek(0); while ($aObjects = $oSet->FetchAssoc()) { if (count($aAuthorizedClasses) > 1) { $oPage->add("\n"); } foreach($aAuthorizedClasses as $sAlias => $sClassName) { $oObj = $aObjects[$sAlias]; if (is_null($oObj)) { $oPage->add("<$sClassName alias=\"$sAlias\" id=\"null\">\n"); } else { $sClassName = get_class($oObj); $oPage->add("<$sClassName alias=\"$sAlias\" id=\"".$oObj->GetKey()."\">\n"); } foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef) { if (is_null($oObj)) { $oPage->add("<$sAttCode>null\n"); } else { if ($oAttDef->IsWritable()) { if (!$oAttDef->IsLinkSet()) { $sValue = $oObj->GetAsXML($sAttCode, $bLocalize); $oPage->add("<$sAttCode>$sValue\n"); } } } } $oPage->add("\n"); } if (count($aAuthorizedClasses) > 1) { $oPage->add("\n"); } } $oPage->add("\n"); } /** * @param WebPage $oPage * @param \CMDBObjectSet $oSet * @param array $aExtraParams * * @throws \CoreException * @throws \DictExceptionMissingString */ public static function DisplaySearchForm(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array()) { $oPage->add(self::GetSearchForm($oPage, $oSet, $aExtraParams)); } /** * @param WebPage $oPage * @param CMDBObjectSet $oSet * @param array $aExtraParams * * @return string * @throws CoreException * @throws DictExceptionMissingString */ public static function GetSearchForm(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array()) { $oSearchForm = new SearchForm(); return $oSearchForm->GetSearchForm($oPage, $oSet, $aExtraParams); } /** * @param WebPage $oPage * @param string $sClass * @param string $sAttCode * @param \AttributeDefinition $oAttDef * @param string $value * @param string $sDisplayValue * @param string $iId * @param string $sNameSuffix * @param int $iFlags * @param array{this: \DBObject, formPrefix: string} $aArgs * @param bool $bPreserveCurrentValue Preserve the current value even if not allowed * @param string $sInputType type of rendering used, see ENUM_INPUT_TYPE_* const * * @return string * * @throws \ArchivedObjectException * @throws \ConfigException * @throws \CoreException * @throws \CoreUnexpectedValue * @throws \DictExceptionMissingString * @throws \MySQLException * @throws \OQLException * @throws \ReflectionException * @throws \Twig\Error\LoaderError * @throws \Twig\Error\RuntimeError * @throws \Twig\Error\SyntaxError * @throws \Exception */ public static function GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $value = '', $sDisplayValue = '', $iId = '', $sNameSuffix = '', $iFlags = 0, $aArgs = array(), $bPreserveCurrentValue = true, &$sInputType = '') { $sFormPrefix = isset($aArgs['formPrefix']) ? $aArgs['formPrefix'] : ''; $sFieldPrefix = isset($aArgs['prefix']) ? $sFormPrefix.$aArgs['prefix'] : $sFormPrefix; if ($sDisplayValue == '') { $sDisplayValue = $value; } if (isset($aArgs[$sAttCode]) && empty($value)) { // default value passed by the context (either the app context of the operation) $value = $aArgs[$sAttCode]; } if (!empty($iId)) { $iInputId = $iId; } else { $iInputId = utils::GetUniqueId(); } $sHTMLValue = ''; // attributes not compatible with bulk modify $bAttNotCompatibleWithBulk = array_key_exists('bulk_context', $aArgs) && !$oAttDef->IsBulkModifyCompatible(); if ($bAttNotCompatibleWithBulk) { $oTagSetBlock = new Html(''.Dict::S('UI:Bulk:modify:IncompatibleAttribute').''); $sHTMLValue = ConsoleBlockRenderer::RenderBlockTemplateInPage($oPage, $oTagSetBlock); } if (!$oAttDef->IsExternalField() && !$bAttNotCompatibleWithBulk) { $bMandatory = 'false'; if ((!$oAttDef->IsNullAllowed()) || ($iFlags & OPT_ATT_MANDATORY)) { $bMandatory = 'true'; } $sValidationSpan = ""; $sReloadSpan = ""; $sHelpText = utils::EscapeHtml($oAttDef->GetHelpOnEdition()); // mandatory field control vars $aEventsList = array(); // contains any native event (like change), plus 'validate' for the form submission $sNullValue = $oAttDef->GetNullValue(); // used for the ValidateField() call in js/forms-json-utils.js $sFieldToValidateId = $iId; // can be different than the displayed field (for example in TagSet) // List of attributes that depend on the current one // Might be modified depending on the current field $sWizardHelperJsVarName = "oWizardHelper{$sFormPrefix}"; $aDependencies = MetaModel::GetDependentAttributes($sClass, $sAttCode); $sAttDefEditClass = $oAttDef->GetEditClass(); switch ($sAttDefEditClass) { case 'Date': $sInputType = self::ENUM_INPUT_TYPE_SINGLE_INPUT; $aEventsList[] = 'validate'; $aEventsList[] = 'keyup'; $aEventsList[] = 'change'; $sPlaceholderValue = 'placeholder="'.utils::EscapeHtml(AttributeDate::GetFormat()->ToPlaceholder()).'"'; $sDisplayValueForHtml = utils::EscapeHtml($sDisplayValue); $sHTMLValue = <<
{$sValidationSpan}{$sReloadSpan} HTML; break; case 'DateTime': $sInputType = self::ENUM_INPUT_TYPE_SINGLE_INPUT; $aEventsList[] = 'validate'; $aEventsList[] = 'keyup'; $aEventsList[] = 'change'; $sPlaceholderValue = 'placeholder="'.utils::EscapeHtml(AttributeDateTime::GetFormat()->ToPlaceholder()).'"'; $sDisplayValueForHtml = utils::EscapeHtml($sDisplayValue); $sHTMLValue = << {$sValidationSpan}{$sReloadSpan} HTML; break; case 'Duration': $sInputType = self::ENUM_INPUT_TYPE_MULTIPLE_INPUTS; $aEventsList[] = 'validate'; $aEventsList[] = 'change'; $oPage->add_ready_script("$('#{$iId}_d').on('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });"); $oPage->add_ready_script("$('#{$iId}_h').on('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });"); $oPage->add_ready_script("$('#{$iId}_m').on('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });"); $oPage->add_ready_script("$('#{$iId}_s').on('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });"); $aVal = AttributeDuration::SplitDuration($value); $sDays = ""; $sHours = ""; $sMinutes = ""; $sSeconds = ""; $sHidden = ""; $sHTMLValue = Dict::Format('UI:DurationForm_Days_Hours_Minutes_Seconds', $sDays, $sHours, $sMinutes, $sSeconds).$sHidden." ".$sValidationSpan.$sReloadSpan; $oPage->add_ready_script("$('#{$iId}').on('update', function(evt, sFormId) { return ToggleDurationField('$iId'); });"); break; case 'Password': $sInputType = self::ENUM_INPUT_TYPE_PASSWORD; $aEventsList[] = 'validate'; $aEventsList[] = 'keyup'; $aEventsList[] = 'change'; $sHTMLValue = "
{$sValidationSpan}{$sReloadSpan}"; break; case 'OQLExpression': case 'Text': $sInputType = self::ENUM_INPUT_TYPE_TEXTAREA; $aEventsList[] = 'validate'; $aEventsList[] = 'keyup'; $aEventsList[] = 'change'; $sEditValue = $oAttDef->GetEditValue($value); $sEditValueForHtml = utils::EscapeHtml($sEditValue); $sFullscreenLabelForHtml = utils::EscapeHtml(Dict::S('UI:ToggleFullScreen')); $aStyles = array(); $sStyle = ''; $sWidth = $oAttDef->GetWidth(); if (!empty($sWidth)) { $aStyles[] = 'width:'.$sWidth; } $sHeight = $oAttDef->GetHeight(); if (!empty($sHeight)) { $aStyles[] = 'height:'.$sHeight; } if (count($aStyles) > 0) { $sStyle = 'style="'.implode('; ', $aStyles).'"'; } $aTextareaCssClasses = []; if ($oAttDef->GetEditClass() == 'OQLExpression') { $aTextareaCssClasses[] = 'ibo-query-oql'; $aTextareaCssClasses[] = 'ibo-is-code'; // N°3227 button to open predefined queries dialog $sPredefinedBtnId = 'predef_btn_'.$sFieldPrefix.$sAttCode.$sNameSuffix; $sSearchQueryLbl = Dict::S('UI:Edit:SearchQuery'); $oPredefQueryButton = ButtonUIBlockFactory::MakeIconAction( 'fas fa-search', $sSearchQueryLbl, null, null, false, $sPredefinedBtnId ); $oPredefQueryButton->AddCSSClass('ibo-action-button') ->SetOnClickJsCode( <<RenderHtml(); $oPage->add_ready_script($oPredefQueryRenderer->RenderJsInline($oPredefQueryButton::ENUM_JS_TYPE_ON_INIT)); $oPage->add_ready_script(<<

Use the search form above to search for objects to be added.

"; if ($('#ac_dlg_{$iId}').length == 0) { $('body').append('
'); $('#ac_dlg_{$iId}').dialog({ width: $(window).width()*0.8, height: $(window).height()*0.8, autoOpen: false, modal: true, title: '$sSearchQueryLbl', resizeStop: oACWidget_{$iId}.UpdateSizes, close: oACWidget_{$iId}.OnClose }); } JS ); // test query link $sTestResId = 'query_res_'.$sFieldPrefix.$sAttCode.$sNameSuffix; //$oPage->GetUniqueId(); $sBaseUrl = utils::GetAbsoluteUrlAppRoot().'pages/run_query.php?expression='; $sTestQueryLbl = Dict::S('UI:Edit:TestQuery'); $oTestQueryButton = ButtonUIBlockFactory::MakeIconAction( 'fas fa-play', $sTestQueryLbl, null, null, false, $sTestResId ); $oTestQueryButton->AddCSSClass('ibo-action-button') ->SetOnClickJsCode( <<RenderHtml(); $oPage->add_ready_script($oTestQueryRenderer->RenderJsInline($oTestQueryButton::ENUM_JS_TYPE_ON_INIT)); } else { $sAdditionalStuff = ''; } // Ok, the text area is drawn here $sTextareCssClassesAsString = implode(' ', $aTextareaCssClasses); $sHTMLValue = <<
{$sValidationSpan}{$sReloadSpan} HTML; $oPage->add_ready_script( <<GetWidth(); if (!empty($sWidth)) { $aStyles[] = 'width:'.$sWidth; } $sHeight = $oAttDef->GetHeight(); if (!empty($sHeight)) { $aStyles[] = 'height:'.$sHeight; } if (count($aStyles) > 0) { $sStyle = 'style="'.implode('; ', $aStyles).'"'; } $sHeader = '
'; // will be hidden in CSS (via :empty) if it remains empty $sEditValue = is_object($value) ? $value->GetModifiedEntry('html') : ''; $sPreviousLog = is_object($value) ? $value->GetAsHTML($oPage, true /* bEditMode */, array('AttributeText', 'RenderWikiHtml')) : ''; $iEntriesCount = is_object($value) ? count($value->GetIndex()) : 0; $sHidden = ""; // To know how many entries the case log already contains $sHTMLValue = "$sHeader
"; $sHTMLValue .= ""; $sHTMLValue .= "$sPreviousLog
{$sValidationSpan}{$sReloadSpan}$sHidden"; // Note: This should be refactored for all types of attribute (see at the end of this function) but as we are doing this for a maintenance release, we are scheduling it for the next main release in to order to avoid regressions as much as possible. $sNullValue = $oAttDef->GetNullValue(); if (!is_numeric($sNullValue)) { $sNullValue = "'$sNullValue'"; // Add quotes to turn this into a JS string if it's not a number } $sOriginalValue = ($iFlags & OPT_ATT_MUSTCHANGE) ? json_encode($value->GetModifiedEntry('html')) : 'undefined'; $oPage->add_ready_script("$('#$iId').on('keyup change validate', function(evt, sFormId) { return ValidateCaseLogField('$iId', $bMandatory, sFormId, $sNullValue, $sOriginalValue) } );"); // Custom validation function // configure CKEditor CKEditorHelper::ConfigureCKEditorElementForWebPage($oPage, $iId, $sOriginalValue, true, [ 'placeholder' => Dict::S('UI:CaseLogTypeYourTextHere'), ]); break; case 'HTML': $sInputType = self::ENUM_INPUT_TYPE_HTML_EDITOR; $sEditValue = $oAttDef->GetEditValue($value); $oWidget = new UIHTMLEditorWidget($iId, $oAttDef, $sNameSuffix, $sFieldPrefix, $sHelpText, $sValidationSpan.$sReloadSpan, $sEditValue, $bMandatory); $sHTMLValue = $oWidget->Display($oPage, $aArgs); break; case 'LinkedSet': if ($oAttDef->GetDisplayStyle() === LINKSET_DISPLAY_STYLE_PROPERTY) { $sInputType = self::ENUM_INPUT_TYPE_TAGSET_LINKEDSET; if (array_key_exists('bulk_context', $aArgs)) { $oTagSetBlock = LinkSetUIBlockFactory::MakeForBulkLinkSet($iId, $oAttDef, $value, $sWizardHelperJsVarName, $aArgs['bulk_context']); } else { $oTagSetBlock = LinkSetUIBlockFactory::MakeForLinkSet($iId, $oAttDef, $value, $sWizardHelperJsVarName, $aArgs['this']); } $oTagSetBlock->SetName("attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}"); $aEventsList[] = 'validate'; $aEventsList[] = 'change'; $sHTMLValue = ConsoleBlockRenderer::RenderBlockTemplateInPage($oPage, $oTagSetBlock); } else { $sInputType = self::ENUM_INPUT_TYPE_LINKEDSET; $oObj = $aArgs['this'] ?? null; if ($oAttDef->IsIndirect()) { $oWidget = new UILinksWidget($sClass, $sAttCode, $iId, $sNameSuffix, $oAttDef->DuplicatesAllowed()); } else { $oWidget = new UILinksWidgetDirect($sClass, $sAttCode, $iId, $sNameSuffix); } $aEventsList[] = 'validate'; $aEventsList[] = 'change'; $sHTMLValue = $oWidget->Display($oPage, $value, array(), $sFormPrefix, $oObj); } break; case 'Document': $sInputType = self::ENUM_INPUT_TYPE_DOCUMENT; $aEventsList[] = 'validate'; $aEventsList[] = 'change'; $oDocument = $value; // Value is an ormDocument object $sFileName = ''; if (is_object($oDocument)) { $sFileName = $oDocument->GetFileName(); } $sFileNameForHtml = utils::EscapeHtml($sFileName); $bHasFile = !empty($sFileName); $iMaxFileSize = utils::ConvertToBytes(ini_get('upload_max_filesize')); $sRemoveBtnLabelForHtml = utils::EscapeHtml(Dict::S('UI:Button:RemoveDocument')); $sExtraCSSClassesForRemoveButton = $bHasFile ? '' : 'ibo-is-hidden'; $sHTMLValue = << {$sFileNameForHtml}   {$sValidationSpan}{$sReloadSpan} HTML; if ($sFileName == '') { $oPage->add_ready_script("$('#remove_attr_{$iId}').addClass('ibo-is-hidden');"); } break; case 'Image': $sInputType = self::ENUM_INPUT_TYPE_IMAGE; $aEventsList[] = 'validate'; $aEventsList[] = 'change'; $oPage->LinkScriptFromAppRoot('js/edit_image.js'); $oDocument = $value; // Value is an ormDocument objectm $sDefaultUrl = $oAttDef->Get('default_image'); if (is_object($oDocument) && !$oDocument->IsEmpty()) { $sUrl = 'data:'.$oDocument->GetMimeType().';base64,'.base64_encode($oDocument->GetData()); } else { $sUrl = null; } $sHTMLValue = "
\n"; $sHTMLValue .= "{$sValidationSpan}{$sReloadSpan}\n"; $aEditImage = array( 'input_name' => 'attr_'.$sFieldPrefix.$sAttCode.$sNameSuffix, 'max_file_size' => utils::ConvertToBytes(ini_get('upload_max_filesize')), 'max_width_px' => $oAttDef->Get('display_max_width'), 'max_height_px' => $oAttDef->Get('display_max_height'), 'current_image_url' => $sUrl, 'default_image_url' => $sDefaultUrl, 'labels' => array( 'reset_button' => utils::EscapeHtml(Dict::S('UI:Button:ResetImage')), 'remove_button' => utils::EscapeHtml(Dict::S('UI:Button:RemoveImage')), 'upload_button' => !empty($sHelpText) ? $sHelpText : utils::EscapeHtml(Dict::S('UI:Button:UploadImage')), ), ); $sEditImageOptions = json_encode($aEditImage); $oPage->add_ready_script("$('#edit_$iInputId').edit_image($sEditImageOptions);"); break; case 'StopWatch': $sHTMLValue = "The edition of a stopwatch is not allowed!!!"; break; case 'List': // Not editable for now... $sHTMLValue = ''; break; case 'One Way Password': $sInputType = self::ENUM_INPUT_TYPE_PASSWORD; $aEventsList[] = 'validate'; $oWidget = new UIPasswordWidget($sAttCode, $iId, $sNameSuffix); $sHTMLValue = $oWidget->Display($oPage, $aArgs); // Event list & validation is handled directly by the widget break; case 'ExtKey': /** @var \AttributeExternalKey $oAttDef */ $aEventsList[] = 'validate'; $aEventsList[] = 'change'; if ($bPreserveCurrentValue) { $oAllowedValues = MetaModel::GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs, '', $value); } else { $oAllowedValues = MetaModel::GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs); } $sFieldName = $sFieldPrefix.$sAttCode.$sNameSuffix; $aExtKeyParams = $aArgs; $aExtKeyParams['iFieldSize'] = $oAttDef->GetMaxSize(); $aExtKeyParams['iMinChars'] = $oAttDef->GetMinAutoCompleteChars(); $sHTMLValue = UIExtKeyWidget::DisplayFromAttCode($oPage, $sAttCode, $sClass, $oAttDef->GetLabel(), $oAllowedValues, $value, $iId, $bMandatory, $sFieldName, $sFormPrefix, $aExtKeyParams, false, $sInputType); $sHTMLValue .= "\n"; $bHasExtKeyUpdatingRemoteClassFields = ( array_key_exists('replaceDependenciesByRemoteClassFields', $aArgs) && ($aArgs['replaceDependenciesByRemoteClassFields']) ); if ($bHasExtKeyUpdatingRemoteClassFields) { // On this field update we need to update all the corresponding remote class fields // Used when extkey widget is in a linkedset indirect $sWizardHelperJsVarName = $aArgs['wizHelperRemote']; $aDependencies = $aArgs['remoteCodes']; } break; case 'RedundancySetting': $sHTMLValue .= '
'; $sHTMLValue .= $oAttDef->GetDisplayForm($value, $oPage, true); $sHTMLValue .= '
'; $sHTMLValue .= '
'.$sValidationSpan.$sReloadSpan.'
'; $oPage->add_ready_script("$('#$iId :input').on('keyup change validate', function(evt, sFormId) { return ValidateRedundancySettings('$iId',sFormId); } );"); // Custom validation function break; case 'CustomFields': case 'FormField': if ($sAttDefEditClass === 'CustomFields') { /** @var \ormCustomFieldsValue $value */ $oForm = $value->GetForm($sFormPrefix); } else if ($sAttDefEditClass === 'FormField') { $oForm = $oAttDef->GetForm($aArgs['this'], $sFormPrefix); } $oFormRenderer = new ConsoleFormRenderer($oForm); $aFormRenderedContent = $oFormRenderer->Render(); $aFieldSetOptions = array( 'field_identifier_attr' => 'data-field-id', // convention: fields are rendered into a div and are identified by this attribute 'fields_list' => $aFormRenderedContent, 'fields_impacts' => $oForm->GetFieldsImpacts(), 'form_path' => $oForm->GetId(), ); $sFieldSetOptions = json_encode($aFieldSetOptions); $aFormHandlerOptions = array( 'wizard_helper_var_name' => 'oWizardHelper'.$sFormPrefix, 'custom_field_attcode' => $sAttCode, ); $sFormHandlerOptions = json_encode($aFormHandlerOptions); $sHTMLValue .= '
'; $sHTMLValue .= '
'; $sHTMLValue .= '
'; $sHTMLValue .= '
'.$sReloadSpan.'
'; // No validation span for this one: it does handle its own validation! $sHTMLValue .= "\n"; $oPage->LinkScriptFromAppRoot('js/form_handler.js'); $oPage->LinkScriptFromAppRoot('js/console_form_handler.js'); $oPage->LinkScriptFromAppRoot('js/field_set.js'); $oPage->LinkScriptFromAppRoot('js/form_field.js'); $oPage->LinkScriptFromAppRoot('js/subform_field.js'); $oPage->add_ready_script( <<