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->bAllowWrite = false; $this->bAllowDelete = false; } /** * 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 \DBObject $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_script( <<Reload(); $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 * * @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 following: ok, info, error. * @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) * * @see SetSessionMessageFromInstance() to call from within an instance */ public static function SetSessionMessage( $sClass, $iKey, $sMessageId, $sMessage, $sSeverity, $fRank, $bMustNotExist = false ) { $sMessageKey = $sClass.'::'.$iKey; if (!isset($_SESSION['obj_messages'][$sMessageKey])) { $_SESSION['obj_messages'][$sMessageKey] = array(); } if (!$bMustNotExist || !array_key_exists($sMessageId, $_SESSION['obj_messages'][$sMessageKey])) { $_SESSION['obj_messages'][$sMessageKey][$sMessageId] = array( 'rank' => $fRank, 'severity' => $sSeverity, 'message' => $sMessage, ); } } /** * @param \WebPage $oPage * @param bool $bEditMode * * @throws \ArchivedObjectException * @throws \CoreException * @throws \CoreUnexpectedValue * @throws \DictExceptionMissingString * @throws \MySQLException * @throws \OQLException * @throws \Exception */ public function DisplayBareHeader(WebPage $oPage, $bEditMode = false) { // Standard Header with name, actions menu and history block // if (!$oPage->IsPrintableVersion()) { // Is there a message for this object ?? $aMessages = array(); $aRanks = array(); 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').')'; } $aResult['message'] = Dict::Format('UI:CurrentObjectIsLockedBy_User', $sName); $aMessages[] = "
".Dict::Format('UI:CurrentObjectIsLockedBy_User', $sName)."
"; } } $sMessageKey = get_class($this).'::'.$this->GetKey(); if (array_key_exists('obj_messages', $_SESSION) && array_key_exists($sMessageKey, $_SESSION['obj_messages'])) { foreach($_SESSION['obj_messages'][$sMessageKey] as $sMessageId => $aMessageData) { $sMsgClass = 'message_'.$aMessageData['severity']; if(!in_array("
".$aMessageData['message']."
",$aMessages)) { $aMessages[] = "
".$aMessageData['message']."
"; $aRanks[] = $aMessageData['rank']; } } unset($_SESSION['obj_messages'][$sMessageKey]); } array_multisort($aRanks, $aMessages); foreach($aMessages as $sMessage) { $oPage->add($sMessage); } } if (!$oPage->IsPrintableVersion()) { // action menu $oSingletonFilter = new DBObjectSearch(get_class($this)); $oSingletonFilter->AddCondition('id', $this->GetKey(), '='); $oBlock = new MenuBlock($oSingletonFilter, 'details', false); $oBlock->Display($oPage, -1); } // Master data sources $aIcons = array(); if (!$oPage->IsPrintableVersion()) { $oCreatorTask = null; $bCanBeDeletedByTask = false; $bCanBeDeletedByUser = true; $aMasterSources = array(); $aSyncData = $this->GetSynchroData(); 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, 'style="vertical-align:middle"')." $sLink
"; $sTip .= Dict::S('Core:Synchro:LastSynchro').'
'.$sLastSynchro."

"; } $sLabel = htmlentities(Dict::S('Tag:Synchronized'), ENT_QUOTES, 'UTF-8'); $sSynchroTagId = 'synchro_icon-'.$this->GetKey(); $aIcons[] = "
  $sLabel
"; $sTip = addslashes($sTip); $oPage->add_ready_script("$('#$sSynchroTagId').qtip( { content: '$sTip', show: 'mouseover', hide: { fixed: true }, style: { name: 'dark', tip: 'topLeft' }, position: { corner: { target: 'bottomMiddle', tooltip: 'topLeft' }} } );"); } } if ($this->IsArchived()) { $sLabel = htmlentities(Dict::S('Tag:Archived'), ENT_QUOTES, 'UTF-8'); $sTitle = htmlentities(Dict::S('Tag:Archived+'), ENT_QUOTES, 'UTF-8'); $aIcons[] = "
  $sLabel
"; } elseif ($this->IsObsolete()) { $sLabel = htmlentities(Dict::S('Tag:Obsolete'), ENT_QUOTES, 'UTF-8'); $sTitle = htmlentities(Dict::S('Tag:Obsolete+'), ENT_QUOTES, 'UTF-8'); $aIcons[] = "
  $sLabel
"; } $sObjectIcon = $this->GetIcon(); $sClassName = MetaModel::GetName(get_class($this)); $sObjectName = $this->GetName(); if (count($aIcons) > 0) { $sTags = '
'.implode(' ', $aIcons).'
'; } else { $sTags = ''; } $oPage->add( <<
$sObjectIcon

$sClassName: $sObjectName

$sTags
EOF ); } /** * Display history tab of an object * * @param \WebPage $oPage * @param bool $bEditMode * @param int $iLimitCount * @param int $iLimitStart * * @throws \CoreException */ public function DisplayBareHistory(WebPage $oPage, $bEditMode = false, $iLimitCount = 0, $iLimitStart = 0) { // history block (with as a tab) $oHistoryFilter = new DBObjectSearch('CMDBChangeOp'); $oHistoryFilter->AddCondition('objkey', $this->GetKey(), '='); $oHistoryFilter->AddCondition('objclass', get_class($this), '='); $oBlock = new HistoryBlock($oHistoryFilter, 'table', false); $oBlock->SetLimit($iLimitCount, $iLimitStart); $oBlock->Display($oPage, 'history'); } /** * Display properties tab of an object * * @param \WebPage $oPage * @param bool $bEditMode * @param string $sPrefix * @param array $aExtraParams * * @return array * @throws \CoreException */ 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); } } // Special case to display the case log, if any... // WARNING: if you modify the loop below, also check the corresponding code in UpdateObject and DisplayModifyForm foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) { if ($oAttDef instanceof AttributeCaseLog) { $sComment = (isset($aExtraParams['fieldsComments'][$sAttCode])) ? $aExtraParams['fieldsComments'][$sAttCode] : ''; $this->DisplayCaseLog($oPage, $sAttCode, $sComment, $sPrefix, $bEditMode); $aFieldsMap[$sAttCode] = $this->m_iFormId.'_'.$sAttCode; } } 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) { $sClass = get_class($this); $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode); 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(); $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 * * @throws \CoreException * @throws \CoreUnexpectedValue * @throws \DictExceptionMissingString * @throws \MissingQueryArgument * @throws \MySQLException * @throws \MySQLHasGoneAwayException * @throws \OQLException * @throws \Exception */ 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 ($bEditMode) { continue; } $oPage->AddAjaxTab($oAttDef->GetLabel(), utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php?operation=dashboard&class='.get_class($this).'&id='.$this->GetKey().'&attcode='.$oAttDef->GetCode(), true, 'Class:'.$sClass.'/Attribute:'.$sAttCode); continue; } // Display mode if (!$oAttDef->IsLinkset()) { continue; } // Process only linkset attributes... $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; } $sCount = ($iCount != 0) ? " ($iCount)" : ""; $oPage->SetCurrentTab('Class:'.$sClass.'/Attribute:'.$sAttCode, $oAttDef->GetLabel().$sCount); $aArgs = array('this' => $this); $bReadOnly = ($iFlags & (OPT_ATT_READONLY | OPT_ATT_SLAVE)); if ($bEditMode && (!$bReadOnly)) { $sInputId = $this->m_iFormId.'_'.$sAttCode; if ($oAttDef->IsIndirect()) { $oLinkingAttDef = MetaModel::GetAttributeDef($sLinkedClass, $oAttDef->GetExtKeyToRemote()); $sTargetClass = $oLinkingAttDef->GetTargetClass(); } else { $sTargetClass = $sLinkedClass; } $oPage->p(MetaModel::GetClassIcon($sTargetClass)." ".$oAttDef->GetDescription().''); $sDisplayValue = ''; // not used $sHTMLValue = "".self::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $oLinkSet, $sDisplayValue, $sInputId, '', $iFlags, $aArgs).''; $this->AddToFieldsMap($sAttCode, $sInputId); $oPage->add($sHTMLValue); } else { // Display mode if (!$oAttDef->IsIndirect()) { // 1:n links $sTargetClass = $sLinkedClass; $aDefaults = array($oAttDef->GetExtKeyToMe() => $this->GetKey()); $oAppContext = new ApplicationContext(); foreach($oAppContext->GetNames() as $sKey) { // The linked object inherits the parent's value for the context if (MetaModel::IsValidAttCode($sClass, $sKey)) { $aDefaults[$sKey] = $this->Get($sKey); } } $aParams = array( 'target_attr' => $oAttDef->GetExtKeyToMe(), 'object_id' => $this->GetKey(), 'menu' => MetaModel::GetConfig()->Get('allow_menu_on_linkset'), //'menu_actions_target' => '_blank', 'default' => $aDefaults, 'table_id' => $sClass.'_'.$sAttCode, ); } else { // n:n links $oLinkingAttDef = MetaModel::GetAttributeDef($sLinkedClass, $oAttDef->GetExtKeyToRemote()); $sTargetClass = $oLinkingAttDef->GetTargetClass(); $aParams = array( 'link_attr' => $oAttDef->GetExtKeyToMe(), 'object_id' => $this->GetKey(), 'target_attr' => $oAttDef->GetExtKeyToRemote(), 'view_link' => false, 'menu' => false, //'menu_actions_target' => '_blank', 'display_limit' => true, // By default limit the list to speed up the initial load & display 'table_id' => $sClass.'_'.$sAttCode, ); } $oPage->p(MetaModel::GetClassIcon($sTargetClass)." ".$oAttDef->GetDescription()); $oBlock = new DisplayBlock($oLinkSet->GetFilter(), 'list', false); $oBlock->Display($oPage, 'rel_'.$sAttCode, $aParams); } 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)); $oPage->add('
'); $oPage->add(''.$oRedundancyAttDef->GetLabel().''); if ($bEditMode && (!$bRedundancyReadOnly)) { $sInputId = $this->m_iFormId.'_'.$sRedundancyAttCode; $oPage->add("".self::GetFormElementForField($oPage, $sClass, $sRedundancyAttCode, $oRedundancyAttDef, $sValue, '', $sInputId, '', $iFlags, $aArgs).''); } else { $oPage->add($oRedundancyAttDef->GetDisplayForm($sValue, $oPage, false, $this->m_iFormId)); } $oPage->add('
'); } } } $oPage->SetCurrentTab(''); /** @var \iApplicationUIExtension $oExtensionInstance */ foreach(MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance) { $oExtensionInstance->OnDisplayRelations($this, $oPage, $bEditMode); } // Display Notifications after the other tabs since this tab disappears in edition if (!$bEditMode) { // Look for any trigger that considers this object as "In Scope" // If any trigger has been found then display a tab with notifications // $oTriggerSet = new CMDBObjectSet(new DBObjectSearch('Trigger')); $aTriggers = array(); while ($oTrigger = $oTriggerSet->Fetch()) { if ($oTrigger->IsInScope($this)) { $aTriggers[] = $oTrigger->GetKey(); } } if (count($aTriggers) > 0) { $iId = $this->GetKey(); $aParams = array('triggers' => $aTriggers, 'id' => $iId); $aNotifSearches = array(); $iNotifsCount = 0; $aNotificationClasses = MetaModel::EnumChildClasses('EventNotification', ENUM_CHILD_CLASSES_EXCLUDETOP); foreach($aNotificationClasses as $sNotifClass) { $aNotifSearches[$sNotifClass] = DBObjectSearch::FromOQL("SELECT $sNotifClass AS Ev JOIN Trigger AS T ON Ev.trigger_id = T.id WHERE T.id IN (:triggers) AND Ev.object_id = :id"); $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) { $oPage->p(MetaModel::GetClassIcon($sNotifClass, true).' '.MetaModel::GetName($sNotifClass)); $oBlock = new DisplayBlock($aNotifSearches[$sNotifClass], 'list', false); $oBlock->Display($oPage, 'notifications_'.$sNotifClass, array('menu' => false)); } } } } /** * @param \WebPage $oPage * @param bool $bEditMode * @param string $sPrefix * @param array $aExtraParams * * @return array * @throws \ArchivedObjectException * @throws \CoreException * @throws \CoreUnexpectedValue * @throws \DictExceptionMissingString * @throws \MySQLException * @throws \OQLException * @throws \Exception */ 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', ''); // Compute the list of properties to display, first the attributes in the 'details' list, then // all the remaining attributes that are not external fields $sEditMode = ($bEditMode) ? 'edit' : 'view'; $aDetails = array(); $iInputId = 0; $aFieldsMap = array(); $aFieldsComments = (isset($aExtraParams['fieldsComments'])) ? $aExtraParams['fieldsComments'] : array(); $aExtraFlags = (isset($aExtraParams['fieldsFlags'])) ? $aExtraParams['fieldsFlags'] : array(); foreach($aDetailsStruct as $sTab => $aCols) { $aDetails[$sTab] = array(); $aTableStyles[] = 'vertical-align:top'; $aTableClasses = array(); $aColStyles[] = 'vertical-align:top'; $aColClasses = array(); ksort($aCols); $iColCount = count($aCols); if ($iColCount > 1) { $aTableClasses[] = 'n-cols-details'; $aTableClasses[] = $iColCount.'-cols-details'; $aColStyles[] = 'width:'.floor(100 / $iColCount).'%'; } else { $aTableClasses[] = 'one-col-details'; } $oPage->SetCurrentTab($sTab); $oPage->add(''); foreach($aCols as $sColIndex => $aFieldsets) { $oPage->add(''); } $oPage->add('
'); $sPreviousLabel = ''; $aDetails[$sTab][$sColIndex] = array(); foreach($aFieldsets as $sFieldsetName => $aFields) { if (!empty($sFieldsetName) && ($sFieldsetName[0] != '_')) { $sLabel = $sFieldsetName; } else { $sLabel = ''; } if ($sLabel != $sPreviousLabel) { if (!empty($sPreviousLabel)) { $oPage->add('
'); $oPage->add(''.Dict::S($sPreviousLabel).''); } $oPage->Details($aDetails[$sTab][$sColIndex]); if (!empty($sPreviousLabel)) { $oPage->add('
'); } $aDetails[$sTab][$sColIndex] = array(); $sPreviousLabel = $sLabel; } foreach($aFields as $sAttCode) { $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode); $sAttDefClass = get_class($oAttDef); $sAttLabel = MetaModel::GetLabel($sClass, $sAttCode); if ($bEditMode) { $sComments = isset($aFieldsComments[$sAttCode]) ? $aFieldsComments[$sAttCode] : ''; $sInfos = ''; $iFlags = $this->GetFormAttributeFlags($sAttCode); if (array_key_exists($sAttCode, $aExtraFlags)) { // the caller may override some flags if needed $iFlags = $iFlags | $aExtraFlags[$sAttCode]; } if ((!$oAttDef->IsLinkSet()) && (($iFlags & OPT_ATT_HIDDEN) == 0) && !($oAttDef instanceof AttributeDashboard)) { $sInputId = $this->m_iFormId.'_'.$sAttCode; if ($oAttDef->IsWritable()) { if ($sStateAttCode == $sAttCode) { // State attribute is always read-only from the UI $sHTMLValue = $this->GetStateLabel(); $val = array( 'label' => '', 'value' => $sHTMLValue, '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); $sSynchroIcon = " "; $sTip = ''; foreach($aReasons as $aRow) { $sDescription = htmlentities($aRow['description'], ENT_QUOTES, 'UTF-8'); $sDescription = str_replace(array("\r\n", "\n"), "
", $sDescription); $sTip .= "
"; $sTip .= "
Synchronized with {$aRow['name']}
"; $sTip .= "
$sDescription
"; } $sTip = addslashes($sTip); $oPage->add_ready_script("$('#synchro_$sInputId').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );"); $sComments = $sSynchroIcon; } // Attribute is read-only $sHTMLValue = "".$this->GetAsHTML($sAttCode).''; } else { $sValue = $this->Get($sAttCode); $sDisplayValue = $this->GetEditValue($sAttCode); $aArgs = array('this' => $this, 'formPrefix' => $sPrefix); $sHTMLValue = "".self::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $sValue, $sDisplayValue, $sInputId, '', $iFlags, $aArgs).''; } $aFieldsMap[$sAttCode] = $sInputId; $val = array( 'label' => ''.$oAttDef->GetLabel().'', 'value' => $sHTMLValue, 'comments' => $sComments, 'infos' => $sInfos, ); } } else { $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())) ? 'large' : '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 $aDetails[$sTab][$sColIndex][] = $val; $iInputId++; } } } if (!empty($sPreviousLabel)) { $oPage->add('
'); $oPage->add(''.Dict::S($sFieldsetName).''); } $oPage->Details($aDetails[$sTab][$sColIndex]); if (!empty($sPreviousLabel)) { $oPage->add('
'); } $oPage->add('
'); } return $aFieldsMap; } /** * @param \WebPage $oPage * @param bool $bEditMode * * @throws \CoreException * @throws \CoreUnexpectedValue * @throws \DictExceptionMissingString * @throws \MissingQueryArgument * @throws \MySQLException * @throws \MySQLHasGoneAwayException * @throws \OQLException * @throws \Exception */ public function DisplayDetails(WebPage $oPage, $bEditMode = false) { $sClass = get_class($this); $iKey = $this->GetKey(); $sMode = static::ENUM_OBJECT_MODE_VIEW; $sTemplate = Utils::ReadFromFile(MetaModel::GetDisplayTemplate($sClass)); if (!empty($sTemplate)) { $oTemplate = new DisplayTemplate($sTemplate); // Note: to preserve backward compatibility with home-made templates, the placeholder '$pkey$' has been preserved // but the preferred method is to use '$id$' $oTemplate->Render($oPage, array( 'class_name' => MetaModel::GetName($sClass), 'class' => $sClass, 'pkey' => $iKey, 'id' => $iKey, 'name' => $this->GetName(), )); } else { // Object's details // template not found display the object using the *old style* $oPage->add(<<
HTML ); $this->DisplayBareHeader($oPage, $bEditMode); /** @var \iTopWebPage $oPage */ $oPage->AddTabContainer(OBJECT_PROPERTIES_TAB); $oPage->SetCurrentTabContainer(OBJECT_PROPERTIES_TAB); $oPage->SetCurrentTab('UI:PropertiesTab'); $this->DisplayBareProperties($oPage, $bEditMode); $this->DisplayBareRelations($oPage, $bEditMode); //$oPage->SetCurrentTab('UI:HistoryTab'); //$this->DisplayBareHistory($oPage, $bEditMode); $oPage->AddAjaxTab('UI:HistoryTab', utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php?operation=history&class='.$sClass.'&id='.$iKey); $oPage->add(<< HTML ); } } /** * @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 * * @throws \ApplicationException * @throws \CoreException */ public static function DisplaySet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array()) { $oPage->add(self::GetDisplaySet($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'] : null; $bViewLink = true; $sSelectMode = 'none'; $iListId = $sTableId; $sClassAlias = $oSet->GetClassAlias(); $sClassName = $oSet->GetClass(); $sZListName = 'list'; $aClassAliases = array($sClassAlias => $sClassName); $aList = cmdbAbstractObject::FlattenZList(MetaModel::GetZListItems($sClassName, $sZListName)); $oDataTable = new PrintableDataTable($iListId, $oSet, $aClassAliases, $sTableId); $oSettings = DataTableSettings::GetDataModelSettings($aClassAliases, $bViewLink, array($sClassAlias => $aList)); $oSettings->iDefaultPageSize = 0; $oSettings->aSortOrder = MetaModel::GetOrderByDefault($sClassName); return $oDataTable->Display($oPage, $oSettings, false /* $bDisplayMenu */, $sSelectMode, $bViewLink, $aExtraParams); } /** * Get the HTML fragment corresponding to the display of a table representing a set of objects * * @see DisplayBlock to get a similar table but with the JS for pagination & sorting * * @param CMDBObjectSet The set of objects to display * @param array $aExtraParams Some extra configuration parameters to tweak the behavior of the display * * @param WebPage $oPage The page object is used for out-of-band information (mostly scripts) output * * @return String The HTML fragment representing the table of objects. Warning : no JS added to handled * pagination or table sorting ! * * @throws \CoreException*@throws \Exception * @throws \ApplicationException */ public static function GetDisplaySet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array()) { if ($oPage->IsPrintableVersion() || $oPage->is_pdf()) { return self::GetDisplaySetForPrinting($oPage, $oSet, $aExtraParams); } if (empty($aExtraParams['currentId'])) { $iListId = $oPage->GetUniqueId(); // Works only if not in an Ajax page !! } else { $iListId = $aExtraParams['currentId']; } // Initialize and check the parameters $bViewLink = isset($aExtraParams['view_link']) ? $aExtraParams['view_link'] : true; $sLinkageAttribute = isset($aExtraParams['link_attr']) ? $aExtraParams['link_attr'] : ''; $iLinkedObjectId = isset($aExtraParams['object_id']) ? $aExtraParams['object_id'] : 0; $sTargetAttr = isset($aExtraParams['target_attr']) ? $aExtraParams['target_attr'] : ''; if (!empty($sLinkageAttribute)) { if ($iLinkedObjectId == 0) { // if 'links' mode is requested the id of the object to link to must be specified throw new ApplicationException(Dict::S('UI:Error:MandatoryTemplateParameter_object_id')); } if ($sTargetAttr == '') { // if 'links' mode is requested the d of the object to link to must be specified throw new ApplicationException(Dict::S('UI:Error:MandatoryTemplateParameter_target_attr')); } } $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true; $bSelectMode = isset($aExtraParams['selection_mode']) ? $aExtraParams['selection_mode'] == true : false; $bSingleSelectMode = isset($aExtraParams['selection_type']) ? ($aExtraParams['selection_type'] == 'single') : false; $aExtraFieldsRaw = isset($aExtraParams['extra_fields']) ? explode(',', trim($aExtraParams['extra_fields'])) : array(); $aExtraFields = array(); foreach($aExtraFieldsRaw as $sFieldName) { // Ignore attributes not of the main queried class if (preg_match('/^(.*)\.(.*)$/', $sFieldName, $aMatches)) { $sClassAlias = $aMatches[1]; $sAttCode = $aMatches[2]; if ($sClassAlias == $oSet->GetFilter()->GetClassAlias()) { $aExtraFields[] = $sAttCode; } } else { $aExtraFields[] = $sFieldName; } } $sClassName = $oSet->GetFilter()->GetClass(); $sZListName = isset($aExtraParams['zlist']) ? ($aExtraParams['zlist']) : 'list'; if ($sZListName !== false) { $aList = self::FlattenZList(MetaModel::GetZListItems($sClassName, $sZListName)); $aList = array_merge($aList, $aExtraFields); } else { $aList = $aExtraFields; } // Filter the list to removed linked set since we are not able to display them here foreach($aList as $index => $sAttCode) { $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode); if ($oAttDef instanceof AttributeLinkedSet) { // Removed from the display list unset($aList[$index]); } } if (!empty($sLinkageAttribute)) { // 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 foreach($aList as $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) foreach($aList as $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 $aList = $aDisplayList; } $sSelectMode = 'none'; if ($bSelectMode) { $sSelectMode = $bSingleSelectMode ? 'single' : 'multiple'; } $sClassAlias = $oSet->GetClassAlias(); $bDisplayLimit = isset($aExtraParams['display_limit']) ? $aExtraParams['display_limit'] : true; $sTableId = isset($aExtraParams['table_id']) ? $aExtraParams['table_id'] : null; $aClassAliases = array($sClassAlias => $sClassName); $oDataTable = new DataTable($iListId, $oSet, $aClassAliases, $sTableId); $oSettings = DataTableSettings::GetDataModelSettings($aClassAliases, $bViewLink, array($sClassAlias => $aList)); if ($bDisplayLimit) { $iDefaultPageSize = appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit()); $oSettings->iDefaultPageSize = $iDefaultPageSize; } else { $oSettings->iDefaultPageSize = 0; } $oSettings->aSortOrder = MetaModel::GetOrderByDefault($sClassName); return $oDataTable->Display($oPage, $oSettings, $bDisplayMenu, $sSelectMode, $bViewLink, $aExtraParams); } /** * @param \WebPage $oPage * @param \CMDBObjectSet $oSet * @param array $aExtraParams * * @return string * @throws \CoreException * @throws \DictExceptionMissingString * @throws \MissingQueryArgument * @throws \MySQLException * @throws \MySQLHasGoneAwayException */ public static function GetDisplayExtendedSet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array()) { if (empty($aExtraParams['currentId'])) { $iListId = $oPage->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]); } } } $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 */ 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 */ 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", "
", htmlentities($rawValue->__toString(), ENT_QUOTES, 'UTF-8')); // 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 = htmlentities($oFinalAttDef->GetEditValue($rawValue), ENT_QUOTES, 'UTF-8'); } else { $outputValue = htmlentities($rawValue, ENT_QUOTES, 'UTF-8'); } $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 \Combodo\iTop\Application\Search\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 $aArgs * @param bool $bPreserveCurrentValue Preserve the current value even if not allowed * * @return string * @throws \ArchivedObjectException * @throws \CoreException * @throws \DictExceptionMissingString */ public static function GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $value = '', $sDisplayValue = '', $iId = '', $sNameSuffix = '', $iFlags = 0, $aArgs = array(), $bPreserveCurrentValue = true) { $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 = $oPage->GetUniqueId(); } $sHTMLValue = ''; if (!$oAttDef->IsExternalField()) { $bMandatory = 'false'; if ((!$oAttDef->IsNullAllowed()) || ($iFlags & OPT_ATT_MANDATORY)) { $bMandatory = 'true'; } $sValidationSpan = ""; $sReloadSpan = ""; $sHelpText = htmlentities($oAttDef->GetHelpOnEdition(), ENT_QUOTES, 'UTF-8'); // 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) switch ($oAttDef->GetEditClass()) { case 'Date': $aEventsList[] = 'validate'; $aEventsList[] = 'keyup'; $aEventsList[] = 'change'; $sPlaceholderValue = 'placeholder="'.htmlentities(AttributeDate::GetFormat()->ToPlaceholder(), ENT_QUOTES, 'UTF-8').'"'; $sHTMLValue = "
{$sValidationSpan}{$sReloadSpan}"; break; case 'DateTime': $aEventsList[] = 'validate'; $aEventsList[] = 'keyup'; $aEventsList[] = 'change'; $sPlaceholderValue = 'placeholder="'.htmlentities(AttributeDateTime::GetFormat()->ToPlaceholder(), ENT_QUOTES, 'UTF-8').'"'; $sHTMLValue = "
{$sValidationSpan}{$sReloadSpan}"; break; case 'Duration': $aEventsList[] = 'validate'; $aEventsList[] = 'change'; $oPage->add_ready_script("$('#{$iId}_d').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });"); $oPage->add_ready_script("$('#{$iId}_h').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });"); $oPage->add_ready_script("$('#{$iId}_m').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });"); $oPage->add_ready_script("$('#{$iId}_s').bind('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}').bind('update', function(evt, sFormId) { return ToggleDurationField('$iId'); });"); break; case 'Password': $aEventsList[] = 'validate'; $aEventsList[] = 'keyup'; $aEventsList[] = 'change'; $sHTMLValue = "
{$sValidationSpan}{$sReloadSpan}"; break; case 'OQLExpression': case 'Text': $aEventsList[] = 'validate'; $aEventsList[] = 'keyup'; $aEventsList[] = 'change'; $sEditValue = $oAttDef->GetEditValue($value); $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).'"'; } if ($oAttDef->GetEditClass() == 'OQLExpression') { $sTestResId = 'query_res_'.$sFieldPrefix.$sAttCode.$sNameSuffix; //$oPage->GetUniqueId(); $sBaseUrl = utils::GetAbsoluteUrlAppRoot().'pages/run_query.php?expression='; $sInitialUrl = $sBaseUrl.urlencode($sEditValue); $sAdditionalStuff = "".Dict::S('UI:Edit:TestQuery').""; $oPage->add_ready_script("$('#$iId').bind('change keyup', function(evt, sFormId) { $('#$sTestResId').attr('href', '$sBaseUrl'+encodeURIComponent($(this).val())); } );"); } else { $sAdditionalStuff = ""; } // Ok, the text area is drawn here $sHTMLValue = "
$sAdditionalStuff
{$sValidationSpan}{$sReloadSpan}"; $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$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').bind('keyup change validate', function(evt, sFormId) { return ValidateCaseLogField('$iId', $bMandatory, sFormId, $sNullValue, $sOriginalValue) } );"); // Custom validation function // Replace the text area with CKEditor // To change the default settings of the editor, // a) edit the file /js/ckeditor/config.js // b) or override some of the configuration settings, using the second parameter of ckeditor() $aConfig = array(); $sLanguage = strtolower(trim(UserRights::GetUserLanguage())); $aConfig['language'] = $sLanguage; $aConfig['contentsLanguage'] = $sLanguage; $aConfig['extraPlugins'] = 'disabler,codesnippet'; $aConfig['placeholder'] = Dict::S('UI:CaseLogTypeYourTextHere'); $sConfigJS = json_encode($aConfig); $oPage->add_ready_script("$('#$iId').ckeditor(function() { /* callback code */ }, $sConfigJS);"); // Transform $iId into a CKEdit $oPage->add_ready_script( <<GetEditValue($value); $oWidget = new UIHTMLEditorWidget($iId, $oAttDef, $sNameSuffix, $sFieldPrefix, $sHelpText, $sValidationSpan.$sReloadSpan, $sEditValue, $bMandatory); $sHTMLValue = $oWidget->Display($oPage, $aArgs); break; case 'LinkedSet': if ($oAttDef->IsIndirect()) { $oWidget = new UILinksWidget($sClass, $sAttCode, $iId, $sNameSuffix, $oAttDef->DuplicatesAllowed()); } else { $oWidget = new UILinksWidgetDirect($sClass, $sAttCode, $iId, $sNameSuffix); } $aEventsList[] = 'validate'; $aEventsList[] = 'change'; $oObj = isset($aArgs['this']) ? $aArgs['this'] : null; $sHTMLValue = $oWidget->Display($oPage, $value, array(), $sFormPrefix, $oObj); break; case 'Document': $aEventsList[] = 'validate'; $aEventsList[] = 'change'; $oDocument = $value; // Value is an ormDocument object $sFileName = ''; if (is_object($oDocument)) { $sFileName = $oDocument->GetFileName(); } $iMaxFileSize = utils::ConvertToBytes(ini_get('upload_max_filesize')); $sHTMLValue = "
\n"; $sHTMLValue .= "\n"; $sHTMLValue .= "\n"; $sHTMLValue .= "\n"; $sHTMLValue .= "".htmlentities($sFileName, ENT_QUOTES, 'UTF-8')."  "; $sHTMLValue .= "
"; $sHTMLValue .= "
"; $sHTMLValue .= "
"; $sHTMLValue .= "
\n"; $sHTMLValue .= "\n"; $sHTMLValue .= "
\n"; $sHTMLValue .= "{$sValidationSpan}{$sReloadSpan}\n"; if ($sFileName == '') { $oPage->add_ready_script("$('#remove_attr_{$iId}').hide();"); } break; case 'Image': $aEventsList[] = 'validate'; $aEventsList[] = 'change'; $oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'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' => htmlentities(Dict::S('UI:Button:ResetImage'), ENT_QUOTES, 'UTF-8'), 'remove_button' => htmlentities(Dict::S('UI:Button:RemoveImage'), ENT_QUOTES, 'UTF-8'), 'upload_button' => $sHelpText, ), ); $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': $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': $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); $sHTMLValue .= "\n"; break; case 'RedundancySetting': $sHTMLValue = ''; $sHTMLValue .= ''; $sHTMLValue .= ''; $sHTMLValue .= ''; $sHTMLValue .= ''; $sHTMLValue .= '
'; $sHTMLValue .= '
'; $sHTMLValue .= $oAttDef->GetDisplayForm($value, $oPage, true); $sHTMLValue .= '
'; $sHTMLValue .= '
'.$sValidationSpan.$sReloadSpan.'
'; $oPage->add_ready_script("$('#$iId :input').bind('keyup change validate', function(evt, sFormId) { return ValidateRedundancySettings('$iId',sFormId); } );"); // Custom validation function break; case 'CustomFields': $sHTMLValue = ''; $sHTMLValue .= ''; $sHTMLValue .= ''; $sHTMLValue .= ''; // No validation span for this one: it does handle its own validation! $sHTMLValue .= ''; $sHTMLValue .= '
'; $sHTMLValue .= '
'; $sHTMLValue .= '
'; $sHTMLValue .= '
'; $sHTMLValue .= '
'; $sHTMLValue .= '
'.$sReloadSpan.'
'; $sHTMLValue .= "\n"; $oForm = $value->GetForm($sFormPrefix); $oRenderer = new \Combodo\iTop\Renderer\Console\ConsoleFormRenderer($oForm); $aRenderRes = $oRenderer->Render(); $aFieldSetOptions = array( 'field_identifier_attr' => 'data-field-id', // convention: fields are rendered into a div and are identified by this attribute 'fields_list' => $aRenderRes, '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); $oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/form_handler.js'); $oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/console_form_handler.js'); $oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/field_set.js'); $oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/form_field.js'); $oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/subform_field.js'); $oPage->add_ready_script( <<