function ReadMandatoryParam($sName) { $value = utils::ReadParam($sName, null); if (is_null($value)) { echo "<p>Missing mandatory argument <b>{$sName}</b></p>"; exit; } return $value; }
function ReadMandatoryParam($oP, $sParam, $sSanitizationFilter = 'parameter') { $sValue = utils::ReadParam($sParam, null, true, $sSanitizationFilter); if (is_null($sValue)) { $oP->p("ERROR: Missing argument '{$sParam}'\n"); exit(29); } return trim($sValue); }
function ReadMandatoryParam($oP, $sParam, $sSanitizationFilter) { global $aPageParams; assert(isset($aPageParams[$sParam])); assert($aPageParams[$sParam]['mandatory']); $sValue = utils::ReadParam($sParam, null, true, $sSanitizationFilter); if (is_null($sValue)) { $oP->p("ERROR: Missing argument '{$sParam}'\n"); UsageAndExit($oP); } return trim($sValue); }
/** * constructor for the web page * @param string $s_title Not used */ function __construct($s_title) { $sPrintable = utils::ReadParam('printable', '0'); $bPrintable = $sPrintable == '1'; parent::__construct($s_title, $bPrintable); $this->m_sReadyScript = ""; //$this->add_header("Content-type: text/html; charset=utf-8"); $this->add_header("Cache-control: no-cache"); $this->m_oTabs = new TabManager(); $this->sContentType = 'text/html'; $this->sContentDisposition = 'inline'; $this->m_sMenu = ""; }
function MakeArchiveFileName($iRefTime = null) { $sDefaultBackupFileName = sys_get_temp_dir() . '/' . "__DB__-%Y-%m-%d"; $sBackupFile = utils::ReadParam('backup_file', $sDefaultBackupFileName, true, 'raw_data'); $oConfig = new Config(APPCONF . 'production/config-itop.php'); $sBackupFile = str_replace('__HOST__', $oConfig->GetDBHost(), $sBackupFile); $sBackupFile = str_replace('__DB__', $oConfig->GetDBName(), $sBackupFile); $sBackupFile = str_replace('__SUBNAME__', $oConfig->GetDBSubName(), $sBackupFile); if (is_null($iRefTime)) { $sBackupFile = strftime($sBackupFile); } else { $sBackupFile = strftime($sBackupFile, $iRefTime); } return $sBackupFile . '.zip'; }
public function DisplayFormPart(WebPage $oP, $sPartId) { switch ($sPartId) { case 'interactive_fields_spreadsheet': $this->GetInteractiveFieldsWidget($oP, 'interactive_fields_spreadsheet'); break; case 'spreadsheet_options': $sChecked = utils::ReadParam('no_localize', 0) == 1 ? ' checked ' : ''; $oP->add('<fieldset><legend>' . Dict::S('Core:BulkExport:SpreadsheetOptions') . '</legend>'); $oP->add('<table>'); $oP->add('<tr>'); $oP->add('<td><input type="checkbox" id="spreadsheet_no_localize" name="no_localize" value="1"' . $sChecked . '><label for="spreadsheet_no_localize"> ' . Dict::S('Core:BulkExport:OptionNoLocalize') . '</label></td>'); $oP->add('</tr>'); $oP->add('</table>'); $oP->add('</fieldset>'); break; default: return parent::DisplayFormPart($oP, $sPartId); } }
public function __construct($s_title) { $this->s_title = $s_title; $this->s_content = ""; $this->s_deferred_content = ''; $this->a_scripts = array(); $this->a_dict_entries = array(); $this->a_styles = array(); $this->a_linked_scripts = array(); $this->a_linked_stylesheets = array(); $this->a_headers = array(); $this->a_base = array('href' => '', 'target' => ''); $this->iNextId = 0; $this->iTransactionId = 0; $this->sContentType = ''; $this->sContentDisposition = ''; $this->sContentFileName = ''; $this->s_OutputFormat = utils::ReadParam('output_format', 'html'); $this->a_OutputOptions = array(); ob_start(); // Start capturing the output }
/** * Checks the parameters and returns the appropriate exporter (if any) * @param string $sExpression The OQL query to export or null * @param string $sQueryId The entry in the query phrasebook if $sExpression is null * @param string $sFormat The code of export format: csv, pdf, html, xlsx * @throws MissingQueryArgument * @return Ambigous <iBulkExport, NULL> */ function CheckParameters($sExpression, $sQueryId, $sFormat) { $oExporter = null; if ($sExpression === null && $sQueryId === null) { ReportErrorAndUsage("Missing parameter. The parameter 'expression' or 'query' must be specified."); } // Either $sExpression or $sQueryId must be specified if ($sExpression === null) { $oSearch = DBObjectSearch::FromOQL('SELECT QueryOQL WHERE id = :query_id', array('query_id' => $sQueryId)); $oQueries = new DBObjectSet($oSearch); if ($oQueries->Count() > 0) { $oQuery = $oQueries->Fetch(); $sExpression = $oQuery->Get('oql'); $sFields = $oQuery->Get('fields'); if (strlen($sFields) == 0) { $sFields = trim($oQuery->Get('fields')); } } else { ReportErrorAndExit("Invalid query phrasebook identifier: '{$sQueryId}'"); } } if ($sFormat === null) { ReportErrorAndUsage("Missing parameter 'format'."); } // Check if the supplied query is valid (and all the parameters are supplied try { $oSearch = DBObjectSearch::FromOQL($sExpression); $aArgs = array(); foreach ($oSearch->GetQueryParams() as $sParam => $foo) { $value = utils::ReadParam('arg_' . $sParam, null, true, 'raw_data'); if (!is_null($value)) { $aArgs[$sParam] = $value; } else { throw new MissingQueryArgument("Missing parameter '--arg_{$sParam}'"); } } $oSearch->SetInternalParams($aArgs); $sFormat = utils::ReadParam('format', 'html', true, 'raw_data'); $oExporter = BulkExport::FindExporter($sFormat, $oSearch); if ($oExporter == null) { $aSupportedFormats = BulkExport::FindSupportedFormats(); ReportErrorAndExit("Invalid output format: '{$sFormat}'. The supported formats are: " . implode(', ', array_keys($aSupportedFormats))); } } catch (MissingQueryArgument $e) { ReportErrorAndUsage("Invalid OQL query: '{$sExpression}'.\n" . $e->getMessage()); } catch (OQLException $e) { ReportErrorAndExit("Invalid OQL query: '{$sExpression}'.\n" . $e->getMessage()); } catch (Exception $e) { ReportErrorAndExit($e->getMessage()); } $oExporter->SetFormat($sFormat); $oExporter->SetChunkSize(EXPORTER_DEFAULT_CHUNK_SIZE); $oExporter->SetObjectList($oSearch); $oExporter->ReadParameters(); return $oExporter; }
public function RenderContent(WebPage $oPage, $aExtraParams = array()) { $oDashboard = $this->GetDashboard(); if ($oDashboard != null) { $sDivId = preg_replace('/[^a-zA-Z0-9_]/', '', $this->sMenuId); $oPage->add('<div class="dashboard_contents" id="' . $sDivId . '">'); $oDashboard->Render($oPage, false, $aExtraParams); $oPage->add('</div>'); $oDashboard->RenderEditionTools($oPage); if ($oDashboard->GetAutoReload()) { $sId = $this->sMenuId; $sExtraParams = json_encode($aExtraParams); $iReloadInterval = 1000 * $oDashboard->GetAutoReloadInterval(); $oPage->add_script(<<<EOF \t\t\t\t\tsetInterval("ReloadDashboard('{$sDivId}');", {$iReloadInterval}); \t\t\t\t\tfunction ReloadDashboard(sDivId) \t\t\t\t\t{ \t\t\t\t\t\tvar oExtraParams = {$sExtraParams}; \t\t\t\t\t\t// Do not reload when a dialog box is active \t\t\t\t\t\tif (!(\$('.ui-dialog:visible').length > 0)) \t\t\t\t\t\t{ \t\t\t\t\t\t\t\$('.dashboard_contents#'+sDivId).block(); \t\t\t\t\t\t\t\$.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php', \t\t\t\t\t\t\t { operation: 'reload_dashboard', dashboard_id: '{$sId}', extra_params: oExtraParams}, \t\t\t\t\t\t\t function(data){ \t\t\t\t\t\t\t\t \$('.dashboard_contents#'+sDivId).html(data); \t\t\t\t\t\t\t\t \$('.dashboard_contents#'+sDivId).unblock(); \t\t\t\t\t\t\t\t} \t\t\t\t\t\t\t ); \t\t\t\t\t\t} \t\t\t\t\t} EOF ); } $bEdit = utils::ReadParam('edit', false); if ($bEdit) { $sId = addslashes($this->sMenuId); $oPage->add_ready_script("EditDashboard('{$sId}');"); } } else { $oPage->p("Error: failed to load dashboard file: '{$this->sDashboardFile}'"); } }
\t\t\t\tsRes += '</tbody>'; \t\t\t\tsRes += '</table>'; \t\t\t\t\$('#full_text_results').append(sRes); EOF ); } if ($iCount == 0) { $sFullTextSummary = addslashes(Dict::S('UI:Search:NoObjectFound')); $oPage->add_ready_script("\$('#full_text_results').append('<div id=\"no_object_found\">{$sFullTextSummary}</div>');"); } } break; case 'full_text_search_enlarge': $sFullText = trim(utils::ReadParam('text', '', false, 'raw_data')); $sClass = trim(utils::ReadParam('class', '')); $iTune = utils::ReadParam('tune', 0); if (preg_match('/^"(.*)"$/', $sFullText, $aMatches)) { // The text is surrounded by double-quotes, remove the quotes and treat it as one single expression $aFullTextNeedles = array($aMatches[1]); } else { // Split the text on the blanks and treat this as a search for <word1> AND <word2> AND <word3> $aFullTextNeedles = explode(' ', $sFullText); } $oFilter = new DBObjectSearch($sClass); foreach ($aFullTextNeedles as $sSearchText) { $oFilter->AddCondition_FullText($sSearchText); } $oSet = new DBObjectSet($oFilter); $oPage->add("<div class=\"page_header\">\n"); $oPage->add("<h2>" . MetaModel::GetClassIcon($sClass) . " <span class=\"hilite\">" . Dict::Format('UI:Search:Count_ObjectsOf_Class_Found', $oSet->Count(), Metamodel::GetName($sClass)) . "</h2>\n"); $oPage->add("</div>\n");
public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId) { $sHtml = ''; // Add the extra params into the filter if they make sense for such a filter $bDoSearch = utils::ReadParam('dosearch', false); if ($this->m_oSet == null) { $aQueryParams = array(); if (isset($aExtraParams['query_params'])) { $aQueryParams = $aExtraParams['query_params']; } if ($this->m_sStyle != 'links') { $oAppContext = new ApplicationContext(); $sClass = $this->m_oFilter->GetClass(); $aFilterCodes = array_keys(MetaModel::GetClassFilterDefs($sClass)); $aCallSpec = array($sClass, 'MapContextParam'); if (is_callable($aCallSpec)) { foreach ($oAppContext->GetNames() as $sContextParam) { $sParamCode = call_user_func($aCallSpec, $sContextParam); //Map context parameter to the value/filter code depending on the class if (!is_null($sParamCode)) { $sParamValue = $oAppContext->GetCurrentValue($sContextParam, null); if (!is_null($sParamValue)) { $aExtraParams[$sParamCode] = $sParamValue; } } } } foreach ($aFilterCodes as $sFilterCode) { $externalFilterValue = utils::ReadParam($sFilterCode, '', false, 'raw_data'); $condition = null; if (isset($aExtraParams[$sFilterCode])) { $condition = $aExtraParams[$sFilterCode]; } if ($bDoSearch && $externalFilterValue != "") { // Search takes precedence over context params... unset($aExtraParams[$sFilterCode]); if (!is_array($externalFilterValue)) { $condition = trim($externalFilterValue); } else { if (count($externalFilterValue) == 1) { $condition = trim($externalFilterValue[0]); } else { $condition = $externalFilterValue; } } } if (!is_null($condition)) { $sOpCode = null; // default operator if (is_array($condition)) { // Multiple values, add them as AND X IN (v1, v2, v3...) $sOpCode = 'IN'; } $this->AddCondition($sFilterCode, $condition, $sOpCode); } } if ($bDoSearch) { // Keep the table_id identifying this table if we're performing a search $sTableId = utils::ReadParam('_table_id_', null, false, 'raw_data'); if ($sTableId != null) { $aExtraParams['table_id'] = $sTableId; } } } $aOrderBy = array(); if (isset($aExtraParams['order_by'])) { // Convert the string describing the order_by parameter into an array // The syntax is +attCode1,-attCode2 // attCode1 => ascending, attCode2 => descending $aTemp = explode(',', $aExtraParams['order_by']); foreach ($aTemp as $sTemp) { $aMatches = array(); if (preg_match('/^([+-])?(.+)$/', $sTemp, $aMatches)) { $bAscending = true; if ($aMatches[1] == '-') { $bAscending = false; } $aOrderBy[$aMatches[2]] = $bAscending; } } } $this->m_oSet = new CMDBObjectSet($this->m_oFilter, $aOrderBy, $aQueryParams); } switch ($this->m_sStyle) { case 'count': if (isset($aExtraParams['group_by'])) { if (isset($aExtraParams['group_by_label'])) { $oGroupByExp = Expression::FromOQL($aExtraParams['group_by']); $sGroupByLabel = $aExtraParams['group_by_label']; } else { // Backward compatibility: group_by is simply a field id $sAlias = $this->m_oFilter->GetClassAlias(); $oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias); $sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']); } $aGroupBy = array(); $aGroupBy['grouped_by_1'] = $oGroupByExp; $sSql = $this->m_oFilter->MakeGroupByQuery($aQueryParams, $aGroupBy, true); $aRes = CMDBSource::QueryToArray($sSql); $aGroupBy = array(); $aLabels = array(); $aValues = array(); $iTotalCount = 0; foreach ($aRes as $iRow => $aRow) { $sValue = $aRow['grouped_by_1']; $aValues[$iRow] = $sValue; $sHtmlValue = $oGroupByExp->MakeValueLabel($this->m_oFilter, $sValue, $sValue); $aLabels[$iRow] = $sHtmlValue; $aGroupBy[$iRow] = (int) $aRow['_itop_count_']; $iTotalCount += $aRow['_itop_count_']; } $aData = array(); $oAppContext = new ApplicationContext(); $sParams = $oAppContext->GetForLink(); foreach ($aGroupBy as $iRow => $iCount) { // Build the search for this subset $oSubsetSearch = $this->m_oFilter->DeepClone(); $oCondition = new BinaryExpression($oGroupByExp, '=', new ScalarExpression($aValues[$iRow])); $oSubsetSearch->AddConditionExpression($oCondition); $sFilter = urlencode($oSubsetSearch->serialize()); $aData[] = array('group' => $aLabels[$iRow], 'value' => "<a href=\"" . utils::GetAbsoluteUrlAppRoot() . "pages/UI.php?operation=search&dosearch=1&{$sParams}&filter={$sFilter}\">{$iCount}</a>"); // TO DO: add the context information } $aAttribs = array('group' => array('label' => $sGroupByLabel, 'description' => ''), 'value' => array('label' => Dict::S('UI:GroupBy:Count'), 'description' => Dict::S('UI:GroupBy:Count+'))); $sFormat = isset($aExtraParams['format']) ? $aExtraParams['format'] : 'UI:Pagination:HeaderNoSelection'; $sHtml .= $oPage->GetP(Dict::Format($sFormat, $iTotalCount)); $sHtml .= $oPage->GetTable($aAttribs, $aData); } else { // Simply count the number of elements in the set $iCount = $this->m_oSet->Count(); $sFormat = 'UI:CountOfObjects'; if (isset($aExtraParams['format'])) { $sFormat = $aExtraParams['format']; } $sHtml .= $oPage->GetP(Dict::Format($sFormat, $iCount)); } break; case 'join': $aDisplayAliases = isset($aExtraParams['display_aliases']) ? explode(',', $aExtraParams['display_aliases']) : array(); if (!isset($aExtraParams['group_by'])) { $sHtml .= $oPage->GetP(Dict::S('UI:Error:MandatoryTemplateParameter_group_by')); } else { $aGroupByFields = array(); $aGroupBy = explode(',', $aExtraParams['group_by']); foreach ($aGroupBy as $sGroupBy) { $aMatches = array(); if (preg_match('/^(.+)\\.(.+)$/', $sGroupBy, $aMatches) > 0) { $aGroupByFields[] = array('alias' => $aMatches[1], 'att_code' => $aMatches[2]); } } if (count($aGroupByFields) == 0) { $sHtml .= $oPage->GetP(Dict::Format('UI:Error:InvalidGroupByFields', $aExtraParams['group_by'])); } else { $aResults = array(); $aCriteria = array(); while ($aObjects = $this->m_oSet->FetchAssoc()) { $aKeys = array(); foreach ($aGroupByFields as $aField) { $sAlias = $aField['alias']; if (is_null($aObjects[$sAlias])) { $aKeys[$sAlias . '.' . $aField['att_code']] = ''; } else { $aKeys[$sAlias . '.' . $aField['att_code']] = $aObjects[$sAlias]->Get($aField['att_code']); } } $sCategory = implode($aKeys, ' '); $aResults[$sCategory][] = $aObjects; $aCriteria[$sCategory] = $aKeys; } $sHtml .= "<table>\n"; // Construct a new (parametric) query that will return the content of this block $oBlockFilter = $this->m_oFilter->DeepClone(); $aExpressions = array(); $index = 0; foreach ($aGroupByFields as $aField) { $aExpressions[] = '`' . $aField['alias'] . '`.`' . $aField['att_code'] . '` = :param' . $index++; } $sExpression = implode(' AND ', $aExpressions); $oExpression = Expression::FromOQL($sExpression); $oBlockFilter->AddConditionExpression($oExpression); $aExtraParams['menu'] = false; foreach ($aResults as $sCategory => $aObjects) { $sHtml .= "<tr><td><h1>{$sCategory}</h1></td></tr>\n"; if (count($aDisplayAliases) == 1) { $aSimpleArray = array(); foreach ($aObjects as $aRow) { $oObj = $aRow[$aDisplayAliases[0]]; if (!is_null($oObj)) { $aSimpleArray[] = $oObj; } } $oSet = CMDBObjectSet::FromArray($this->m_oFilter->GetClass(), $aSimpleArray); $sHtml .= "<tr><td>" . cmdbAbstractObject::GetDisplaySet($oPage, $oSet, $aExtraParams) . "</td></tr>\n"; } else { $index = 0; $aArgs = array(); foreach ($aGroupByFields as $aField) { $aArgs['param' . $index] = $aCriteria[$sCategory][$aField['alias'] . '.' . $aField['att_code']]; $index++; } $oSet = new CMDBObjectSet($oBlockFilter, array(), $aArgs); $sHtml .= "<tr><td>" . cmdbAbstractObject::GetDisplayExtendedSet($oPage, $oSet, $aExtraParams) . "</td></tr>\n"; } } $sHtml .= "</table>\n"; } } break; case 'list': $aClasses = $this->m_oSet->GetSelectedClasses(); $aAuthorizedClasses = array(); if (count($aClasses) > 1) { // Check the classes that can be read (i.e authorized) by this user... foreach ($aClasses as $sAlias => $sClassName) { if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $this->m_oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS)) { $aAuthorizedClasses[$sAlias] = $sClassName; } } if (count($aAuthorizedClasses) > 0) { if ($this->m_oSet->Count() > 0) { $sHtml .= cmdbAbstractObject::GetDisplayExtendedSet($oPage, $this->m_oSet, $aExtraParams); } else { // Empty set $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay')); } } else { // Not authorized $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay')); } } else { // The list is made of only 1 class of objects, actions on the list are possible if ($this->m_oSet->Count() > 0 && UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_READ, $this->m_oSet) == UR_ALLOWED_YES) { $sHtml .= cmdbAbstractObject::GetDisplaySet($oPage, $this->m_oSet, $aExtraParams); } else { $sHtml .= $oPage->GetP(Dict::S('UI:NoObjectToDisplay')); $sClass = $this->m_oFilter->GetClass(); $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true; if ($bDisplayMenu) { if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES) { $sLinkTarget = ''; $oAppContext = new ApplicationContext(); $sParams = $oAppContext->GetForLink(); // 1:n links, populate the target object as a default value when creating a new linked object if (isset($aExtraParams['target_attr'])) { $sLinkTarget = ' target="_blank" '; $aExtraParams['default'][$aExtraParams['target_attr']] = $aExtraParams['object_id']; } $sDefault = ''; if (!empty($aExtraParams['default'])) { foreach ($aExtraParams['default'] as $sKey => $sValue) { $sDefault .= "&default[{$sKey}]={$sValue}"; } } $sHtml .= $oPage->GetP("<a{$sLinkTarget} href=\"" . utils::GetAbsoluteUrlAppRoot() . "pages/UI.php?operation=new&class={$sClass}&{$sParams}{$sDefault}\">" . Dict::Format('UI:ClickToCreateNew', Metamodel::GetName($sClass)) . "</a>\n"); } } } } break; case 'links': //$bDashboardMode = isset($aExtraParams['dashboard']) ? ($aExtraParams['dashboard'] == 'true') : false; //$bSelectMode = isset($aExtraParams['select']) ? ($aExtraParams['select'] == 'true') : false; if ($this->m_oSet->Count() > 0 && UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_READ, $this->m_oSet) == UR_ALLOWED_YES) { //$sLinkage = isset($aExtraParams['linkage']) ? $aExtraParams['linkage'] : ''; $sHtml .= cmdbAbstractObject::GetDisplaySet($oPage, $this->m_oSet, $aExtraParams); } else { $sClass = $this->m_oFilter->GetClass(); $oAttDef = MetaModel::GetAttributeDef($sClass, $this->m_aParams['target_attr']); $sTargetClass = $oAttDef->GetTargetClass(); $sHtml .= $oPage->GetP(Dict::Format('UI:NoObject_Class_ToDisplay', MetaModel::GetName($sTargetClass))); $bDisplayMenu = isset($this->m_aParams['menu']) ? $this->m_aParams['menu'] == true : true; if ($bDisplayMenu) { if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES) { $oAppContext = new ApplicationContext(); $sParams = $oAppContext->GetForLink(); $sDefaults = ''; if (isset($this->m_aParams['default'])) { foreach ($this->m_aParams['default'] as $sName => $sValue) { $sDefaults .= '&' . urlencode($sName) . '=' . urlencode($sValue); } } $sHtml .= $oPage->GetP("<a href=\"" . utils::GetAbsoluteUrlAppRoot() . "pages/UI.php?operation=modify_links&class={$sClass}&sParams&link_attr=" . $aExtraParams['link_attr'] . "&id=" . $aExtraParams['object_id'] . "&target_class={$sTargetClass}&addObjects=true{$sDefaults}\">" . Dict::Format('UI:ClickToCreateNew', Metamodel::GetName($sClass)) . "</a>\n"); } } } break; case 'details': while ($oObj = $this->m_oSet->Fetch()) { $sHtml .= $oObj->GetDetails($oPage); // Still used ??? } break; case 'actions': $sClass = $this->m_oFilter->GetClass(); $oAppContext = new ApplicationContext(); $bContextFilter = isset($aExtraParams['context_filter']) ? isset($aExtraParams['context_filter']) != 0 : false; if ($bContextFilter) { $aFilterCodes = array_keys(MetaModel::GetClassFilterDefs($this->m_oFilter->GetClass())); foreach ($oAppContext->GetNames() as $sFilterCode) { $sContextParamValue = $oAppContext->GetCurrentValue($sFilterCode, null); if (!is_null($sContextParamValue) && !empty($sContextParamValue) && MetaModel::IsValidFilterCode($sClass, $sFilterCode)) { $this->AddCondition($sFilterCode, $sContextParamValue); } } $aQueryParams = array(); if (isset($aExtraParams['query_params'])) { $aQueryParams = $aExtraParams['query_params']; } $this->m_oSet = new CMDBObjectSet($this->m_oFilter, array(), $aQueryParams); } $iCount = $this->m_oSet->Count(); $sHyperlink = utils::GetAbsoluteUrlAppRoot() . 'pages/UI.php?operation=search&' . $oAppContext->GetForLink() . '&filter=' . urlencode($this->m_oFilter->serialize()); $sHtml .= '<p><a class="actions" href="' . $sHyperlink . '">'; // Note: border set to 0 due to various browser interpretations (IE9 adding a 2px border) $sHtml .= MetaModel::GetClassIcon($sClass, true, 'float;left;margin-right:10px;border:0;'); $sHtml .= MetaModel::GetName($sClass) . ': ' . $iCount . '</a></p>'; $sParams = $oAppContext->GetForLink(); $sHtml .= '<p>'; if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY)) { $sHtml .= "<a href=\"" . utils::GetAbsoluteUrlAppRoot() . "pages/UI.php?operation=new&class={$sClass}&{$sParams}\">" . Dict::Format('UI:ClickToCreateNew', MetaModel::GetName($sClass)) . "</a><br/>\n"; } $sHtml .= "<a href=\"" . utils::GetAbsoluteUrlAppRoot() . "pages/UI.php?operation=search_form&do_search=0&class={$sClass}&{$sParams}\">" . Dict::Format('UI:SearchFor_Class', MetaModel::GetName($sClass)) . "</a>\n"; $sHtml .= '</p>'; break; case 'summary': $sClass = $this->m_oFilter->GetClass(); $oAppContext = new ApplicationContext(); $sTitle = isset($aExtraParams['title[block]']) ? $aExtraParams['title[block]'] : ''; $sLabel = isset($aExtraParams['label[block]']) ? $aExtraParams['label[block]'] : ''; $sStateAttrCode = isset($aExtraParams['status[block]']) ? $aExtraParams['status[block]'] : 'status'; $sStatesList = isset($aExtraParams['status_codes[block]']) ? $aExtraParams['status_codes[block]'] : ''; $bContextFilter = isset($aExtraParams['context_filter']) ? isset($aExtraParams['context_filter']) != 0 : false; if ($bContextFilter) { $aFilterCodes = array_keys(MetaModel::GetClassFilterDefs($this->m_oFilter->GetClass())); foreach ($oAppContext->GetNames() as $sFilterCode) { $sContextParamValue = $oAppContext->GetCurrentValue($sFilterCode, null); if (!is_null($sContextParamValue) && !empty($sContextParamValue) && MetaModel::IsValidFilterCode($sClass, $sFilterCode)) { $this->AddCondition($sFilterCode, $sContextParamValue); } } $aQueryParams = array(); if (isset($aExtraParams['query_params'])) { $aQueryParams = $aExtraParams['query_params']; } $this->m_oSet = new CMDBObjectSet($this->m_oFilter, array(), $aQueryParams); } // Summary details $aCounts = array(); $aStateLabels = array(); if (!empty($sStateAttrCode) && !empty($sStatesList)) { $aStates = explode(',', $sStatesList); $oAttDef = MetaModel::GetAttributeDef($sClass, $sStateAttrCode); foreach ($aStates as $sStateValue) { $oFilter = $this->m_oFilter->DeepClone(); $oFilter->AddCondition($sStateAttrCode, $sStateValue, '='); $oSet = new DBObjectSet($oFilter); $aCounts[$sStateValue] = $oSet->Count(); $aStateLabels[$sStateValue] = htmlentities($oAttDef->GetValueLabel($sStateValue), ENT_QUOTES, 'UTF-8'); if ($aCounts[$sStateValue] == 0) { $aCounts[$sStateValue] = '-'; } else { $sHyperlink = utils::GetAbsoluteUrlAppRoot() . 'pages/UI.php?operation=search&' . $oAppContext->GetForLink() . '&filter=' . urlencode($oFilter->serialize()); $aCounts[$sStateValue] = "<a href=\"{$sHyperlink}\">{$aCounts[$sStateValue]}</a>"; } } } $sHtml .= '<div class="summary-details"><table><tr><th>' . implode('</th><th>', $aStateLabels) . '</th></tr>'; $sHtml .= '<tr><td>' . implode('</td><td>', $aCounts) . '</td></tr></table></div>'; // Title & summary $iCount = $this->m_oSet->Count(); $sHyperlink = utils::GetAbsoluteUrlAppRoot() . 'pages/UI.php?operation=search&' . $oAppContext->GetForLink() . '&filter=' . urlencode($this->m_oFilter->serialize()); $sHtml .= '<h1>' . Dict::S(str_replace('_', ':', $sTitle)) . '</h1>'; $sHtml .= '<a class="summary" href="' . $sHyperlink . '">' . Dict::Format(str_replace('_', ':', $sLabel), $iCount) . '</a>'; $sHtml .= '<div style="clear:both;"></div>'; break; case 'csv': $bAdvancedMode = utils::ReadParam('advanced', false); $sCsvFile = strtolower($this->m_oFilter->GetClass()) . '.csv'; $sDownloadLink = utils::GetAbsoluteUrlAppRoot() . 'webservices/export.php?expression=' . urlencode($this->m_oFilter->ToOQL(true)) . '&format=csv&filename=' . urlencode($sCsvFile); $sLinkToToggle = utils::GetAbsoluteUrlAppRoot() . 'pages/UI.php?operation=search&' . $oAppContext->GetForLink() . '&filter=' . urlencode($this->m_oFilter->serialize()) . '&format=csv'; if ($bAdvancedMode) { $sDownloadLink .= '&fields_advanced=1'; $sChecked = 'CHECKED'; } else { $sLinkToToggle = $sLinkToToggle . '&advanced=1'; $sChecked = ''; } $sAjaxLink = $sDownloadLink . '&charset=UTF-8'; // Includes &fields_advanced=1 if in advanced mode /* $sCSVData = cmdbAbstractObject::GetSetAsCSV($this->m_oSet, array('fields_advanced' => $bAdvancedMode)); $sCharset = MetaModel::GetConfig()->Get('csv_file_default_charset'); if ($sCharset == 'UTF-8') { $bLostChars = false; } else { $sConverted = @iconv('UTF-8', $sCharset, $sCSVData); $sRestored = @iconv($sCharset, 'UTF-8', $sConverted); $bLostChars = ($sRestored != $sCSVData); } if ($bLostChars) { $sCharsetNotice = " <span id=\"csv_charset_issue\">"; $sCharsetNotice .= '<img src="../images/error.png" style="vertical-align:middle"/>'; $sCharsetNotice .= "</span>"; $sTip = "<p>".htmlentities(Dict::S('UI:CSVExport:LostChars'), ENT_QUOTES, 'UTF-8')."</p>"; $sTip .= "<p>".htmlentities(Dict::Format('UI:CSVExport:LostChars+', $sCharset), ENT_QUOTES, 'UTF-8')."</p>"; $oPage->add_ready_script("$('#csv_charset_issue').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );"); } else { $sCharsetNotice = ''; } */ $sCharsetNotice = false; $sHtml .= "<div>"; $sHtml .= '<table style="width:100%" class="transparent">'; $sHtml .= '<tr>'; $sHtml .= '<td><a href="' . $sDownloadLink . '">' . Dict::Format('UI:Download-CSV', $sCsvFile) . '</a>' . $sCharsetNotice . '</td>'; $sHtml .= '<td style="text-align:right"><input type="checkbox" ' . $sChecked . ' onClick="window.location.href=\'' . $sLinkToToggle . '\'"> ' . Dict::S('UI:CSVExport:AdvancedMode') . '</td>'; $sHtml .= '</tr>'; $sHtml .= '</table>'; if ($bAdvancedMode) { $sHtml .= "<p>"; $sHtml .= htmlentities(Dict::S('UI:CSVExport:AdvancedMode+'), ENT_QUOTES, 'UTF-8'); $sHtml .= "</p>"; } $sHtml .= "</div>"; $sHtml .= "<div id=\"csv_content_loading\"><div style=\"width: 250px; height: 20px; background: url(../setup/orange-progress.gif); border: 1px #999 solid; margin-left:auto; margin-right: auto; text-align: center;\">" . Dict::S('UI:Loading') . "</div></div><textarea id=\"csv_content\" style=\"display:none;\">\n"; //$sHtml .= htmlentities($sCSVData, ENT_QUOTES, 'UTF-8'); $sHtml .= "</textarea>\n"; $oPage->add_ready_script("\$.post('{$sAjaxLink}', {}, function(data) { \$('#csv_content').html(data); \$('#csv_content_loading').hide(); \$('#csv_content').show();} );"); break; case 'modify': if (UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_MODIFY, $this->m_oSet) == UR_ALLOWED_YES) { while ($oObj = $this->m_oSet->Fetch()) { $sHtml .= $oObj->GetModifyForm($oPage); } } break; case 'search': $sStyle = isset($aExtraParams['open']) && $aExtraParams['open'] == 'true' ? 'SearchDrawer' : 'SearchDrawer DrawerClosed'; $sHtml .= "<div id=\"ds_{$sId}\" class=\"{$sStyle}\">\n"; $oPage->add_ready_script(<<<EOF \t\$("#dh_{$sId}").click( function() { \t\t\$("#ds_{$sId}").slideToggle('normal', function() { \$("#ds_{$sId}").parent().resize(); FixSearchFormsDisposition(); } ); \t\t\$("#dh_{$sId}").toggleClass('open'); \t}); EOF ); $aExtraParams['currentId'] = $sId; $sHtml .= cmdbAbstractObject::GetSearchForm($oPage, $this->m_oSet, $aExtraParams); $sHtml .= "</div>\n"; $sHtml .= "<div class=\"HRDrawer\"></div>\n"; $sHtml .= "<div id=\"dh_{$sId}\" class=\"DrawerHandle\">" . Dict::S('UI:SearchToggle') . "</div>\n"; break; case 'open_flash_chart': static $iChartCounter = 0; $oAppContext = new ApplicationContext(); $sContext = $oAppContext->GetForLink(); if (!empty($sContext)) { $sContext = '&' . $sContext; } $sChartType = isset($aExtraParams['chart_type']) ? $aExtraParams['chart_type'] : 'pie'; $sTitle = isset($aExtraParams['chart_title']) ? $aExtraParams['chart_title'] : ''; $sGroupBy = isset($aExtraParams['group_by']) ? $aExtraParams['group_by'] : ''; $sGroupByExpr = isset($aExtraParams['group_by_expr']) ? '¶ms[group_by_expr]=' . $aExtraParams['group_by_expr'] : ''; $sFilter = $this->m_oFilter->serialize(); $sHtml .= "<div id=\"my_chart_{$sId}{$iChartCounter}\">If the chart does not display, <a href=\"http://get.adobe.com/flash/\" target=\"_blank\">install Flash</a></div>\n"; $oPage->add_script("function ofc_resize(left, width, top, height) { /* do nothing special */ }"); if (isset($aExtraParams['group_by_label'])) { $sUrl = urlencode(utils::GetAbsoluteUrlAppRoot() . "pages/ajax.render.php?operation=open_flash_chart¶ms[group_by]={$sGroupBy}{$sGroupByExpr}¶ms[group_by_label]={$aExtraParams['group_by_label']}¶ms[chart_type]={$sChartType}¶ms[chart_title]={$sTitle}¶ms[currentId]={$sId}&id={$sId}&filter=" . urlencode($sFilter)); } else { $sUrl = urlencode(utils::GetAbsoluteUrlAppRoot() . "pages/ajax.render.php?operation=open_flash_chart¶ms[group_by]={$sGroupBy}{$sGroupByExpr}¶ms[chart_type]={$sChartType}¶ms[chart_title]={$sTitle}¶ms[currentId]={$sId}&id={$sId}&filter=" . urlencode($sFilter)); } $oPage->add_ready_script("swfobject.embedSWF(\"../images/open-flash-chart.swf\", \"my_chart_{$sId}{$iChartCounter}\", \"100%\", \"300\",\"9.0.0\", \"expressInstall.swf\",\n\t\t\t\t{\"data-file\":\"" . $sUrl . "\"}, {wmode: 'transparent'} );\n"); $iChartCounter++; if (isset($aExtraParams['group_by'])) { if (isset($aExtraParams['group_by_label'])) { $oGroupByExp = Expression::FromOQL($aExtraParams['group_by']); $sGroupByLabel = $aExtraParams['group_by_label']; } else { // Backward compatibility: group_by is simply a field id $sAlias = $this->m_oFilter->GetClassAlias(); $oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias); $sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']); } $aGroupBy = array(); $aGroupBy['grouped_by_1'] = $oGroupByExp; $sSql = $this->m_oFilter->MakeGroupByQuery($aQueryParams, $aGroupBy, true); $aRes = CMDBSource::QueryToArray($sSql); $aGroupBy = array(); $aLabels = array(); $aValues = array(); $iTotalCount = 0; foreach ($aRes as $iRow => $aRow) { $sValue = $aRow['grouped_by_1']; $aValues[$iRow] = $sValue; $sHtmlValue = $oGroupByExp->MakeValueLabel($this->m_oFilter, $sValue, $sValue); $aLabels[$iRow] = $sHtmlValue; $aGroupBy[$iRow] = (int) $aRow['_itop_count_']; $iTotalCount += $aRow['_itop_count_']; } $aData = array(); $idx = 0; $aURLs = array(); foreach ($aGroupBy as $iRow => $iCount) { // Build the search for this subset $oSubsetSearch = $this->m_oFilter->DeepClone(); $oCondition = new BinaryExpression($oGroupByExp, '=', new ScalarExpression($aValues[$iRow])); $oSubsetSearch->AddConditionExpression($oCondition); $aURLs[$idx] = $oSubsetSearch->serialize(); $idx++; } $sURLList = ''; foreach ($aURLs as $index => $sURL) { $sURLList .= "\taURLs[{$index}] = '" . utils::GetAbsoluteUrlAppRoot() . "pages/UI.php?operation=search&format=html{$sContext}&filter=" . urlencode($sURL) . "';\n"; } $oPage->add_script(<<<EOF function ofc_drill_down_{$sId}(index) { \tvar aURLs = new Array(); {$sURLList} \twindow.location.href=aURLs[index]; } EOF ); } break; case 'open_flash_chart_ajax': require_once APPROOT . '/pages/php-ofc-library/open-flash-chart.php'; $sChartType = isset($aExtraParams['chart_type']) ? $aExtraParams['chart_type'] : 'pie'; $sId = utils::ReadParam('id', ''); $oChart = new open_flash_chart(); switch ($sChartType) { case 'bars': $oChartElement = new bar_glass(); if (isset($aExtraParams['group_by'])) { if (isset($aExtraParams['group_by_label'])) { $oGroupByExp = Expression::FromOQL($aExtraParams['group_by']); $sGroupByLabel = $aExtraParams['group_by_label']; } else { // Backward compatibility: group_by is simply a field id $sAlias = $this->m_oFilter->GetClassAlias(); $oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias); $sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']); } $aGroupBy = array(); $aGroupBy['grouped_by_1'] = $oGroupByExp; $sSql = $this->m_oFilter->MakeGroupByQuery($aQueryParams, $aGroupBy, true); $aRes = CMDBSource::QueryToArray($sSql); $aGroupBy = array(); $aLabels = array(); $iTotalCount = 0; foreach ($aRes as $iRow => $aRow) { $sValue = $aRow['grouped_by_1']; $sHtmlValue = $oGroupByExp->MakeValueLabel($this->m_oFilter, $sValue, $sValue); $aLabels[$iRow] = strip_tags($sHtmlValue); $aGroupBy[$iRow] = (int) $aRow['_itop_count_']; $iTotalCount += $aRow['_itop_count_']; } $aData = array(); $aChartLabels = array(); $maxValue = 0; foreach ($aGroupBy as $iRow => $iCount) { $oBarValue = new bar_value($iCount); $oBarValue->on_click("ofc_drill_down_{$sId}"); $aData[] = $oBarValue; if ($iCount > $maxValue) { $maxValue = $iCount; } $aChartLabels[] = html_entity_decode($aLabels[$iRow], ENT_QUOTES, 'UTF-8'); } $oYAxis = new y_axis(); $aMagicValues = array(1, 2, 5, 10); $iMultiplier = 1; $index = 0; $iTop = $aMagicValues[$index % count($aMagicValues)] * $iMultiplier; while ($maxValue > $iTop) { $index++; $iTop = $aMagicValues[$index % count($aMagicValues)] * $iMultiplier; if ($index % count($aMagicValues) == 0) { $iMultiplier = $iMultiplier * 10; } } //echo "oYAxis->set_range(0, $iTop, $iMultiplier);\n"; $oYAxis->set_range(0, $iTop, $iMultiplier); $oChart->set_y_axis($oYAxis); $oChartElement->set_values($aData); $oXAxis = new x_axis(); $oXLabels = new x_axis_labels(); // set them vertical $oXLabels->set_vertical(); // set the label text $oXLabels->set_labels($aChartLabels); // Add the X Axis Labels to the X Axis $oXAxis->set_labels($oXLabels); $oChart->set_x_axis($oXAxis); } break; case 'pie': default: $oChartElement = new pie(); $oChartElement->set_start_angle(35); $oChartElement->set_animate(true); $oChartElement->set_tooltip('#label# - #val# (#percent#)'); $oChartElement->set_colours(array('#FF8A00', '#909980', '#2C2B33', '#CCC08D', '#596664')); if (isset($aExtraParams['group_by'])) { if (isset($aExtraParams['group_by_label'])) { $oGroupByExp = Expression::FromOQL($aExtraParams['group_by']); $sGroupByLabel = $aExtraParams['group_by_label']; } else { // Backward compatibility: group_by is simply a field id $sAlias = $this->m_oFilter->GetClassAlias(); $oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias); $sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']); } $aGroupBy = array(); $aGroupBy['grouped_by_1'] = $oGroupByExp; $sSql = $this->m_oFilter->MakeGroupByQuery($aQueryParams, $aGroupBy, true); $aRes = CMDBSource::QueryToArray($sSql); $aGroupBy = array(); $aLabels = array(); $iTotalCount = 0; foreach ($aRes as $iRow => $aRow) { $sValue = $aRow['grouped_by_1']; $sHtmlValue = $oGroupByExp->MakeValueLabel($this->m_oFilter, $sValue, $sValue); $aLabels[$iRow] = strip_tags($sHtmlValue); $aGroupBy[$iRow] = (int) $aRow['_itop_count_']; $iTotalCount += $aRow['_itop_count_']; } $aData = array(); foreach ($aGroupBy as $iRow => $iCount) { $sFlashLabel = html_entity_decode($aLabels[$iRow], ENT_QUOTES, 'UTF-8'); $PieValue = new pie_value($iCount, $sFlashLabel); //@@ BUG: not passed via ajax !!! $PieValue->on_click("ofc_drill_down_{$sId}"); $aData[] = $PieValue; } $oChartElement->set_values($aData); $oChart->x_axis = null; } } if (isset($aExtraParams['chart_title'])) { // The title has been given in an url, and urlencoded... // and urlencode transforms utf-8 into something similar to ISO-8859-1 // Example: é (C3A9 becomes %E9) // As a consequence, json_encode (called within open-flash-chart.php) // was returning 'null' and the graph was not displayed at all // To make sure that the graph is displayed AND to get a correct title // (at least for european characters) let's transform back into utf-8 ! $sTitle = iconv("ISO-8859-1", "UTF-8//IGNORE", $aExtraParams['chart_title']); // If the title is a dictionnary entry, fetch it $sTitle = Dict::S($sTitle); $oTitle = new title($sTitle); $oChart->set_title($oTitle); $oTitle->set_style("{font-size: 16px; font-family: Tahoma; font-weight: bold; text-align: center;}"); } $oChart->set_bg_colour('#FFFFFF'); $oChart->add_element($oChartElement); $sHtml = $oChart->toPrettyString(); break; default: // Unsupported style, do nothing. $sHtml .= Dict::format('UI:Error:UnsupportedStyleOfBlock', $this->m_sStyle); } return $sHtml; }
/** * Perform all the needed checks to delete one (or more) objects */ public static function DeleteObjects(WebPage $oP, $sClass, $aObjects, $bPreview, $sCustomOperation, $aContextData = array()) { $oDeletionPlan = new DeletionPlan(); foreach ($aObjects as $oObj) { if ($bPreview) { $oObj->CheckToDelete($oDeletionPlan); } else { $oObj->DBDeleteTracked(CMDBObject::GetCurrentChange(), null, $oDeletionPlan); } } if ($bPreview) { if (count($aObjects) == 1) { $oObj = $aObjects[0]; $oP->add("<h1>" . Dict::Format('UI:Delete:ConfirmDeletionOf_Name', $oObj->GetName()) . "</h1>\n"); } else { $oP->add("<h1>" . Dict::Format('UI:Delete:ConfirmDeletionOf_Count_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass)) . "</h1>\n"); } // Explain what should be done // $aDisplayData = array(); foreach ($oDeletionPlan->ListDeletes() as $sTargetClass => $aDeletes) { foreach ($aDeletes as $iId => $aData) { $oToDelete = $aData['to_delete']; $bAutoDel = $aData['mode'] == DEL_SILENT || $aData['mode'] == DEL_AUTO; if (array_key_exists('issue', $aData)) { if ($bAutoDel) { if (isset($aData['requested_explicitely'])) { $sConsequence = Dict::Format('UI:Delete:CannotDeleteBecause', $aData['issue']); } else { $sConsequence = Dict::Format('UI:Delete:ShouldBeDeletedAtomaticallyButNotPossible', $aData['issue']); } } else { $sConsequence = Dict::Format('UI:Delete:MustBeDeletedManuallyButNotPossible', $aData['issue']); } } else { if ($bAutoDel) { if (isset($aData['requested_explicitely'])) { $sConsequence = ''; // not applicable } else { $sConsequence = Dict::S('UI:Delete:WillBeDeletedAutomatically'); } } else { $sConsequence = Dict::S('UI:Delete:MustBeDeletedManually'); } } $aDisplayData[] = array('class' => MetaModel::GetName(get_class($oToDelete)), 'object' => $oToDelete->GetHyperLink(), 'consequence' => $sConsequence); } } foreach ($oDeletionPlan->ListUpdates() as $sRemoteClass => $aToUpdate) { foreach ($aToUpdate as $iId => $aData) { $oToUpdate = $aData['to_reset']; if (array_key_exists('issue', $aData)) { $sConsequence = Dict::Format('UI:Delete:CannotUpdateBecause_Issue', $aData['issue']); } else { $sConsequence = Dict::Format('UI:Delete:WillAutomaticallyUpdate_Fields', $aData['attributes_list']); } $aDisplayData[] = array('class' => MetaModel::GetName(get_class($oToUpdate)), 'object' => $oToUpdate->GetHyperLink(), 'consequence' => $sConsequence); } } $iImpactedIndirectly = $oDeletionPlan->GetTargetCount() - count($aObjects); if ($iImpactedIndirectly > 0) { if (count($aObjects) == 1) { $oObj = $aObjects[0]; $oP->p(Dict::Format('UI:Delete:Count_Objects/LinksReferencing_Object', $iImpactedIndirectly, $oObj->GetName())); } else { $oP->p(Dict::Format('UI:Delete:Count_Objects/LinksReferencingTheObjects', $iImpactedIndirectly)); } $oP->p(Dict::S('UI:Delete:ReferencesMustBeDeletedToEnsureIntegrity')); } if ($iImpactedIndirectly > 0 || $oDeletionPlan->FoundStopper()) { $aDisplayConfig = array(); $aDisplayConfig['class'] = array('label' => 'Class', 'description' => ''); $aDisplayConfig['object'] = array('label' => 'Object', 'description' => ''); $aDisplayConfig['consequence'] = array('label' => 'Consequence', 'description' => Dict::S('UI:Delete:Consequence+')); $oP->table($aDisplayConfig, $aDisplayData); } if ($oDeletionPlan->FoundStopper()) { if ($oDeletionPlan->FoundSecurityIssue()) { $oP->p(Dict::S('UI:Delete:SorryDeletionNotAllowed')); } elseif ($oDeletionPlan->FoundManualOperation()) { $oP->p(Dict::S('UI:Delete:PleaseDoTheManualOperations')); } else { $oP->p(Dict::S('UI:Delete:PleaseDoTheManualOperations')); } $oAppContext = new ApplicationContext(); $oP->add("<form method=\"post\">\n"); $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"" . utils::ReadParam('transaction_id') . "\">\n"); $oP->add("<input type=\"button\" onclick=\"window.history.back();\" value=\"" . Dict::S('UI:Button:Back') . "\">\n"); $oP->add("<input DISABLED type=\"submit\" name=\"\" value=\"" . Dict::S('UI:Button:Delete') . "\">\n"); $oP->add($oAppContext->GetForForm()); $oP->add("</form>\n"); } else { if (count($aObjects) == 1) { $oObj = $aObjects[0]; $id = $oObj->GetKey(); $oP->p('<h1>' . Dict::Format('UI:Delect:Confirm_Object', $oObj->GetHyperLink()) . '</h1>'); } else { $oP->p('<h1>' . Dict::Format('UI:Delect:Confirm_Count_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass)) . '</h1>'); } foreach ($aObjects as $oObj) { $aKeys[] = $oObj->GetKey(); } $oFilter = new DBObjectSearch($sClass); $oFilter->AddCondition('id', $aKeys, 'IN'); $oSet = new CMDBobjectSet($oFilter); $oP->add('<div id="0">'); CMDBAbstractObject::DisplaySet($oP, $oSet, array('display_limit' => false, 'menu' => false)); $oP->add("</div>\n"); $oP->add("<form method=\"post\">\n"); foreach ($aContextData as $sKey => $value) { $oP->add("<input type=\"hidden\" name=\"{$sKey}\" value=\"{$value}\">\n"); } $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"" . utils::GetNewTransactionId() . "\">\n"); $oP->add("<input type=\"hidden\" name=\"operation\" value=\"{$sCustomOperation}\">\n"); $oP->add("<input type=\"hidden\" name=\"filter\" value=\"" . $oFilter->Serialize() . "\">\n"); $oP->add("<input type=\"hidden\" name=\"class\" value=\"{$sClass}\">\n"); foreach ($aObjects as $oObj) { $oP->add("<input type=\"hidden\" name=\"selectObject[]\" value=\"" . $oObj->GetKey() . "\">\n"); } $oP->add("<input type=\"button\" onclick=\"window.history.back();\" value=\"" . Dict::S('UI:Button:Back') . "\">\n"); $oP->add("<input type=\"submit\" name=\"\" value=\"" . Dict::S('UI:Button:Delete') . "\">\n"); $oAppContext = new ApplicationContext(); $oP->add($oAppContext->GetForForm()); $oP->add("</form>\n"); } } else { // Execute the deletion // if (count($aObjects) == 1) { $oObj = $aObjects[0]; $oP->add("<h1>" . Dict::Format('UI:Title:DeletionOf_Object', $oObj->GetName()) . "</h1>\n"); } else { $oP->add("<h1>" . Dict::Format('UI:Title:BulkDeletionOf_Count_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass)) . "</h1>\n"); } // Security - do not allow the user to force a forbidden delete by the mean of page arguments... if ($oDeletionPlan->FoundSecurityIssue()) { throw new CoreException(Dict::S('UI:Error:NotEnoughRightsToDelete')); } if ($oDeletionPlan->FoundManualOperation()) { throw new CoreException(Dict::S('UI:Error:CannotDeleteBecauseManualOpNeeded')); } if ($oDeletionPlan->FoundManualDelete()) { throw new CoreException(Dict::S('UI:Error:CannotDeleteBecauseOfDepencies')); } // Report deletions // $aDisplayData = array(); foreach ($oDeletionPlan->ListDeletes() as $sTargetClass => $aDeletes) { foreach ($aDeletes as $iId => $aData) { $oToDelete = $aData['to_delete']; if (isset($aData['requested_explicitely'])) { $sMessage = Dict::S('UI:Delete:Deleted'); } else { $sMessage = Dict::S('UI:Delete:AutomaticallyDeleted'); } $aDisplayData[] = array('class' => MetaModel::GetName(get_class($oToDelete)), 'object' => $oToDelete->GetName(), 'consequence' => $sMessage); } } // Report updates // foreach ($oDeletionPlan->ListUpdates() as $sTargetClass => $aToUpdate) { foreach ($aToUpdate as $iId => $aData) { $oToUpdate = $aData['to_reset']; $aDisplayData[] = array('class' => MetaModel::GetName(get_class($oToUpdate)), 'object' => $oToUpdate->GetHyperLink(), 'consequence' => Dict::Format('UI:Delete:AutomaticResetOf_Fields', $aData['attributes_list'])); } } // Report automatic jobs // if ($oDeletionPlan->GetTargetCount() > 0) { if (count($aObjects) == 1) { $oObj = $aObjects[0]; $oP->p(Dict::Format('UI:Delete:CleaningUpRefencesTo_Object', $oObj->GetName())); } else { $oP->p(Dict::Format('UI:Delete:CleaningUpRefencesTo_Several_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass))); } $aDisplayConfig = array(); $aDisplayConfig['class'] = array('label' => 'Class', 'description' => ''); $aDisplayConfig['object'] = array('label' => 'Object', 'description' => ''); $aDisplayConfig['consequence'] = array('label' => 'Done', 'description' => Dict::S('UI:Delete:Done+')); $oP->table($aDisplayConfig, $aDisplayData); } } }
/** * Check if the user is already authentified, if yes, then performs some additional validations to redirect towards the desired "portal" * @param string|null $sRequestedPortalId The requested "portal" interface, null for any * @param bool $bMustBeAdmin Whether or not the user must be an admin to access the current page * @param int iOnExit What action to take if the user is not logged on (one of the class constants EXIT_...) */ static function DoLoginEx($sRequestedPortalId = null, $bMustBeAdmin = false, $iOnExit = self::EXIT_PROMPT) { $operation = utils::ReadParam('loginop', ''); $sMessage = self::HandleOperations($operation); // May exit directly $iRet = self::Login($iOnExit); if ($iRet == self::EXIT_CODE_OK) { if ($bMustBeAdmin && !UserRights::IsAdministrator()) { if ($iOnExit == self::EXIT_RETURN) { return self::EXIT_CODE_MUSTBEADMIN; } else { require_once APPROOT . '/setup/setuppage.class.inc.php'; $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError')); $oP->add("<h1>" . Dict::S('UI:Login:Error:AccessAdmin') . "</h1>\n"); $oP->p("<a href=\"" . utils::GetAbsoluteUrlAppRoot() . "pages/logoff.php\">" . Dict::S('UI:LogOffMenu') . "</a>"); $oP->output(); exit; } } $iRet = call_user_func(array(self::$sHandlerClass, 'ChangeLocation'), $sRequestedPortalId, $iOnExit); } if ($iOnExit == self::EXIT_RETURN) { return $iRet; } else { return $sMessage; } }
\t\tDoCheckMapping(); EOF ); } break; case 'get_csv_template': $sClassName = utils::ReadParam('class_name'); $sFormat = utils::ReadParam('format', 'csv'); if (MetaModel::IsValidClass($sClassName)) { $oSearch = new DBObjectSearch($sClassName); $oSearch->AddCondition('id', 0, '='); // Make sure we create an empty set $oSet = new CMDBObjectSet($oSearch); $sResult = cmdbAbstractObject::GetSetAsCSV($oSet, array('showMandatoryFields' => true)); $sClassDisplayName = MetaModel::GetName($sClassName); $sDisposition = utils::ReadParam('disposition', 'inline'); if ($sDisposition == 'attachment') { switch ($sFormat) { case 'xlsx': $oPage = new ajax_page(""); $oPage->SetContentType('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); $oPage->SetContentDisposition('attachment', $sClassDisplayName . '.xlsx'); require_once APPROOT . '/application/excelexporter.class.inc.php'; $writer = new XLSXWriter(); $writer->setAuthor(UserRights::GetUserFriendlyName()); $aHeaders = array(0 => explode(',', $sResult)); // comma is the default separator $writer->writeSheet($aHeaders, $sClassDisplayName, array()); $oPage->add($writer->writeToString()); break; case 'csv':
/** * Do the entire synchronization job */ protected function DoSynchronize() { $this->m_oStatLog->Set('status_curr_job', 1); $this->m_oStatLog->Set('status_curr_pos', -1); $iMaxChunkSize = utils::ReadParam('max_chunk_size', 0, true); if ($iMaxChunkSize > 0) { // Split the execution into several processes // Each process will call DoSynchronizeChunk() // The loop will end when a process does not reply "continue" on the last line of its output if (!utils::IsModeCLI()) { throw new SynchroExceptionNotStarted(Dict::S('Core:SyncSplitModeCLIOnly')); } $aArguments = array(); $aArguments['source'] = $this->m_oDataSource->GetKey(); $aArguments['log'] = $this->m_oStatLog->GetKey(); $aArguments['change'] = $this->m_oChange->GetKey(); $aArguments['chunk'] = $iMaxChunkSize; if ($this->m_oLastFullLoadStartDate) { $aArguments['last_full_load'] = $this->m_oLastFullLoadStartDate->Format('Y-m-d H:i:s'); } else { $aArguments['last_full_load'] = ''; } $this->m_oStatLog->DBUpdate($this->m_oChange); $iStepCount = 0; do { $aArguments['step_count'] = $iStepCount; $iStepCount++; list($iRes, $aOut) = utils::ExecITopScript('synchro/priv_sync_chunk.php', $aArguments); // Reload the log that has been modified by the processes $this->m_oStatLog->Reload(); $sLastRes = strtolower(trim(end($aOut))); switch ($sLastRes) { case 'continue': $bContinue = true; break; case 'finished': $bContinue = false; break; default: $this->m_oStatLog->AddTrace("The script did not reply with the expected keywords:"); $aIndentedOut = array(); foreach ($aOut as $sOut) { $aIndentedOut[] = "-> {$sOut}"; $this->m_oStatLog->AddTrace(">>> {$sOut}"); } throw new Exception("Encountered an error in an underspinned process:\n" . implode("\n", $aIndentedOut)); } } while ($bContinue); } else { $this->PrepareProcessing(); $this->DoJob1(); $this->DoJob2(); $this->DoJob3(); } }
/** * Renders the "Actions" popup menu for the given set of objects * * Note that the menu links containing (or ending) with a hash (#) will have their fragment * part (whatever is after the hash) dynamically replaced (by javascript) when the menu is * displayed, to correspond to the current hash/fragment in the page. This allows modifying * an object in with the same tab active by default as the tab that was active when selecting * the "Modify..." action. */ public function GetRenderContent(WebPage $oPage, $aExtraParams = array(), $sId) { if ($this->m_sStyle == 'popup') { $this->m_sStyle = 'list'; } $sHtml = ''; $oAppContext = new ApplicationContext(); $sContext = $oAppContext->GetForLink(); if (!empty($sContext)) { $sContext = '&' . $sContext; } $sClass = $this->m_oFilter->GetClass(); $oReflectionClass = new ReflectionClass($sClass); $oSet = new CMDBObjectSet($this->m_oFilter); $sFilter = $this->m_oFilter->serialize(); $sFilterDesc = $this->m_oFilter->ToOql(true); $aActions = array(); $sUIPage = cmdbAbstractObject::ComputeStandardUIPage($sClass); $sRootUrl = utils::GetAbsoluteUrlAppRoot(); // 1:n links, populate the target object as a default value when creating a new linked object if (isset($aExtraParams['target_attr'])) { $aExtraParams['default'][$aExtraParams['target_attr']] = $aExtraParams['object_id']; } $sDefault = ''; if (!empty($aExtraParams['default'])) { foreach ($aExtraParams['default'] as $sKey => $sValue) { $sDefault .= "&default[{$sKey}]={$sValue}"; } } $bIsCreationAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_CREATE) == UR_ALLOWED_YES && $oReflectionClass->IsSubclassOf('cmdbAbstractObject'); $sRefreshAction = ''; switch ($oSet->Count()) { case 0: // No object in the set, the only possible action is "new" if ($bIsCreationAllowed) { $aActions['UI:Menu:New'] = array('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/{$sUIPage}?operation=new&class={$sClass}{$sContext}{$sDefault}"); } break; case 1: $oObj = $oSet->Fetch(); if (is_null($oObj)) { if (!isset($aExtraParams['link_attr'])) { if ($bIsCreationAllowed) { $aActions['UI:Menu:New'] = array('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/{$sUIPage}?operation=new&class={$sClass}{$sContext}{$sDefault}"); } } } else { $id = $oObj->GetKey(); if (utils::ReadParam('operation') == 'details') { if ($_SERVER['REQUEST_METHOD'] == 'GET') { $sRefreshAction = "window.location.reload();"; } else { $sRefreshAction = "window.location.href='" . ApplicationContext::MakeObjectUrl(get_class($oObj), $id) . "';"; } } $bLocked = false; if (MetaModel::GetConfig()->Get('concurrent_lock_enabled')) { $aLockInfo = iTopOwnershipLock::IsLocked(get_class($oObj), $id); if ($aLockInfo['locked']) { $bLocked = true; //$this->AddMenuSeparator($aActions); //$aActions['concurrent_lock_unlock'] = array ('label' => Dict::S('UI:Menu:ReleaseConcurrentLock'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=kill_lock&class=$sClass&id=$id{$sContext}"); } } $bRawModifiedAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet) == UR_ALLOWED_YES && $oReflectionClass->IsSubclassOf('cmdbAbstractObject'); $bIsModifyAllowed = !$bLocked && $bRawModifiedAllowed; $bIsDeleteAllowed = !$bLocked && UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, $oSet); // Just one object in the set, possible actions are "new / clone / modify and delete" if (!isset($aExtraParams['link_attr'])) { if ($bIsModifyAllowed) { $aActions['UI:Menu:Modify'] = array('label' => Dict::S('UI:Menu:Modify'), 'url' => "{$sRootUrl}pages/{$sUIPage}?operation=modify&class={$sClass}&id={$id}{$sContext}#"); } if ($bIsCreationAllowed) { $aActions['UI:Menu:New'] = array('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/{$sUIPage}?operation=new&class={$sClass}{$sContext}{$sDefault}"); } if ($bIsDeleteAllowed) { $aActions['UI:Menu:Delete'] = array('label' => Dict::S('UI:Menu:Delete'), 'url' => "{$sRootUrl}pages/{$sUIPage}?operation=delete&class={$sClass}&id={$id}{$sContext}"); } // Transitions / Stimuli if (!$bLocked) { $aTransitions = $oObj->EnumTransitions(); if (count($aTransitions)) { $this->AddMenuSeparator($aActions); $aStimuli = Metamodel::EnumStimuli(get_class($oObj)); foreach ($aTransitions as $sStimulusCode => $aTransitionDef) { $iActionAllowed = get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction' ? UserRights::IsStimulusAllowed($sClass, $sStimulusCode, $oSet) : UR_ALLOWED_NO; switch ($iActionAllowed) { case UR_ALLOWED_YES: $aActions[$sStimulusCode] = array('label' => $aStimuli[$sStimulusCode]->GetLabel(), 'url' => "{$sRootUrl}pages/UI.php?operation=stimulus&stimulus={$sStimulusCode}&class={$sClass}&id={$id}{$sContext}"); break; default: // Do nothing } } } } // Relations... $aRelations = MetaModel::EnumRelationsEx($sClass); if (count($aRelations)) { $this->AddMenuSeparator($aActions); foreach ($aRelations as $sRelationCode => $aRelationInfo) { if (array_key_exists('down', $aRelationInfo)) { $aActions[$sRelationCode . '_down'] = array('label' => $aRelationInfo['down'], 'url' => "{$sRootUrl}pages/{$sUIPage}?operation=swf_navigator&relation={$sRelationCode}&direction=down&class={$sClass}&id={$id}{$sContext}"); } if (array_key_exists('up', $aRelationInfo)) { $aActions[$sRelationCode . '_up'] = array('label' => $aRelationInfo['up'], 'url' => "{$sRootUrl}pages/{$sUIPage}?operation=swf_navigator&relation={$sRelationCode}&direction=up&class={$sClass}&id={$id}{$sContext}"); } } } if ($bLocked && $bRawModifiedAllowed) { // Add a special menu to kill the lock, but only to allowed users who can also modify this object $aAllowedProfiles = MetaModel::GetConfig()->Get('concurrent_lock_override_profiles'); $bCanKill = false; $oUser = UserRights::GetUserObject(); $aUserProfiles = array(); if (!is_null($oUser)) { $oProfileSet = $oUser->Get('profile_list'); while ($oProfile = $oProfileSet->Fetch()) { $aUserProfiles[$oProfile->Get('profile')] = true; } } foreach ($aAllowedProfiles as $sProfile) { if (array_key_exists($sProfile, $aUserProfiles)) { $bCanKill = true; break; } } if ($bCanKill) { $this->AddMenuSeparator($aActions); $aActions['concurrent_lock_unlock'] = array('label' => Dict::S('UI:Menu:KillConcurrentLock'), 'url' => "{$sRootUrl}pages/{$sUIPage}?operation=kill_lock&class={$sClass}&id={$id}{$sContext}"); } } /* $this->AddMenuSeparator($aActions); // Static menus: Email this page & CSV Export $sUrl = ApplicationContext::MakeObjectUrl($sClass, $id); $aActions['UI:Menu:EMail'] = array ('label' => Dict::S('UI:Menu:EMail'), 'url' => "mailto:?subject=".urlencode($oObj->GetRawName())."&body=".urlencode($sUrl)); $aActions['UI:Menu:CSVExport'] = array ('label' => Dict::S('UI:Menu:CSVExport'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=search&filter=".urlencode($sFilter)."&format=csv{$sContext}"); // The style tells us whether the menu is displayed on a list of one object, or on the details of the given object if ($this->m_sStyle == 'list') { // Actions specific to the list $sOQL = addslashes($sFilterDesc); $aActions['UI:Menu:AddToDashboard'] = array ('label' => Dict::S('UI:Menu:AddToDashboard'), 'url' => "#", 'onclick' => "return DashletCreationDlg('$sOQL')"); } */ } $this->AddMenuSeparator($aActions); foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance) { $oSet->Rewind(); foreach ($oExtensionInstance->EnumAllowedActions($oSet) as $sLabel => $sUrl) { $aActions[$sLabel] = array('label' => $sLabel, 'url' => $sUrl); } } } break; default: // Check rights // New / Modify $bIsModifyAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet) && $oReflectionClass->IsSubclassOf('cmdbAbstractObject'); $bIsBulkModifyAllowed = !MetaModel::IsAbstract($sClass) && UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_MODIFY, $oSet) && $oReflectionClass->IsSubclassOf('cmdbAbstractObject'); $bIsBulkDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_DELETE, $oSet); if (isset($aExtraParams['link_attr'])) { $id = $aExtraParams['object_id']; $sTargetAttr = $aExtraParams['target_attr']; $oAttDef = MetaModel::GetAttributeDef($sClass, $sTargetAttr); $sTargetClass = $oAttDef->GetTargetClass(); $bIsDeleteAllowed = UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, $oSet); if ($bIsModifyAllowed) { $aActions['UI:Menu:Add'] = array('label' => Dict::S('UI:Menu:Add'), 'url' => "{$sRootUrl}pages/{$sUIPage}?operation=modify_links&class={$sClass}&link_attr=" . $aExtraParams['link_attr'] . "&target_class={$sTargetClass}&id={$id}&addObjects=true{$sContext}"); } if ($bIsBulkModifyAllowed) { $aActions['UI:Menu:Manage'] = array('label' => Dict::S('UI:Menu:Manage'), 'url' => "{$sRootUrl}pages/{$sUIPage}?operation=modify_links&class={$sClass}&link_attr=" . $aExtraParams['link_attr'] . "&target_class={$sTargetClass}&id={$id}{$sContext}"); } //if ($bIsBulkDeleteAllowed) { $aActions[] = array ('label' => 'Remove All...', 'url' => "#"); } } else { // many objects in the set, possible actions are: new / modify all / delete all if ($bIsCreationAllowed) { $aActions['UI:Menu:New'] = array('label' => Dict::S('UI:Menu:New'), 'url' => "{$sRootUrl}pages/{$sUIPage}?operation=new&class={$sClass}{$sContext}{$sDefault}"); } if ($bIsBulkModifyAllowed) { $aActions['UI:Menu:ModifyAll'] = array('label' => Dict::S('UI:Menu:ModifyAll'), 'url' => "{$sRootUrl}pages/{$sUIPage}?operation=select_for_modify_all&class={$sClass}&filter=" . urlencode($sFilter) . "{$sContext}"); } if ($bIsBulkDeleteAllowed) { $aActions['UI:Menu:BulkDelete'] = array('label' => Dict::S('UI:Menu:BulkDelete'), 'url' => "{$sRootUrl}pages/{$sUIPage}?operation=select_for_deletion&filter=" . urlencode($sFilter) . "{$sContext}"); } // Stimuli $aStates = MetaModel::EnumStates($sClass); // Do not perform time consuming computations if there are too may objects in the list $iLimit = MetaModel::GetConfig()->Get('complex_actions_limit'); if (count($aStates) > 0 && ($iLimit == 0 || $oSet->Count() < $iLimit)) { // Life cycle actions may be available... if all objects are in the same state // // Group by <state> $oGroupByExp = new FieldExpression(MetaModel::GetStateAttributeCode($sClass), $this->m_oFilter->GetClassAlias()); $aGroupBy = array('__state__' => $oGroupByExp); $aQueryParams = array(); if (isset($aExtraParams['query_params'])) { $aQueryParams = $aExtraParams['query_params']; } $sSql = $this->m_oFilter->MakeGroupByQuery($aQueryParams, $aGroupBy); $aRes = CMDBSource::QueryToArray($sSql); if (count($aRes) == 1) { // All objects are in the same state... $sState = $aRes[0]['__state__']; $aTransitions = Metamodel::EnumTransitions($sClass, $sState); if (count($aTransitions)) { $this->AddMenuSeparator($aActions); $aStimuli = Metamodel::EnumStimuli($sClass); foreach ($aTransitions as $sStimulusCode => $aTransitionDef) { $oSet->Rewind(); // As soon as the user rights implementation will browse the object set, // then we might consider using OptimizeColumnLoad() here $iActionAllowed = UserRights::IsStimulusAllowed($sClass, $sStimulusCode, $oSet); $iActionAllowed = get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction' ? $iActionAllowed : UR_ALLOWED_NO; switch ($iActionAllowed) { case UR_ALLOWED_YES: case UR_ALLOWED_DEPENDS: $aActions[$sStimulusCode] = array('label' => $aStimuli[$sStimulusCode]->GetLabel(), 'url' => "{$sRootUrl}pages/UI.php?operation=select_bulk_stimulus&stimulus={$sStimulusCode}&state={$sState}&class={$sClass}&filter=" . urlencode($sFilter) . "{$sContext}"); break; default: // Do nothing } } } } } /* $this->AddMenuSeparator($aActions); $sUrl = utils::GetAbsoluteUrlAppRoot(); $aActions['UI:Menu:EMail'] = array ('label' => Dict::S('UI:Menu:EMail'), 'url' => "mailto:?subject=$sFilterDesc&body=".urlencode("{$sUrl}pages/$sUIPage?operation=search&filter=".urlencode($sFilter)."{$sContext}")); $aActions['UI:Menu:CSVExport'] = array ('label' => Dict::S('UI:Menu:CSVExport'), 'url' => "{$sRootUrl}pages/$sUIPage?operation=search&filter=".urlencode($sFilter)."&format=csv{$sContext}"); $sOQL = addslashes($sFilterDesc); $aActions['UI:Menu:AddToDashboard'] = array ('label' => Dict::S('UI:Menu:AddToDashboard'), 'url' => "#", 'onclick' => "return DashletCreationDlg('$sOQL')"); */ } } $this->AddMenuSeparator($aActions); foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance) { $oSet->Rewind(); foreach ($oExtensionInstance->EnumAllowedActions($oSet) as $sLabel => $data) { if (is_array($data)) { // New plugins can provide javascript handlers via the 'onclick' property //TODO: enable extension of different menus by checking the 'target' property ?? $aActions[$sLabel] = array('label' => $sLabel, 'url' => isset($data['url']) ? $data['url'] : '#', 'onclick' => isset($data['onclick']) ? $data['onclick'] : ''); } else { // Backward compatibility with old plugins $aActions[$sLabel] = array('label' => $sLabel, 'url' => $data); } } } // New extensions based on iPopupMenuItem interface switch ($this->m_sStyle) { case 'list': $oSet->Rewind(); $param = $oSet; $iMenuId = iPopupMenuExtension::MENU_OBJLIST_ACTIONS; break; case 'details': $oSet->Rewind(); $param = $oSet->Fetch(); $iMenuId = iPopupMenuExtension::MENU_OBJDETAILS_ACTIONS; break; } utils::GetPopupMenuItems($oPage, $iMenuId, $param, $aActions); $aFavoriteActions = array(); $aCallSpec = array($sClass, 'GetShortcutActions'); if (is_callable($aCallSpec)) { $aShortcutActions = call_user_func($aCallSpec, $sClass); foreach ($aActions as $key => $aAction) { if (in_array($key, $aShortcutActions)) { $aFavoriteActions[] = $aAction; unset($aActions[$key]); } } } else { $aShortcutActions = array(); } if (!$oPage->IsPrintableVersion()) { if (count($aFavoriteActions) > 0) { $sHtml .= "<div class=\"itop_popup actions_menu\"><ul>\n<li>" . Dict::S('UI:Menu:OtherActions') . "\n<ul>\n"; } else { $sHtml .= "<div class=\"itop_popup actions_menu\"><ul>\n<li>" . Dict::S('UI:Menu:Actions') . "\n<ul>\n"; } $sHtml .= $oPage->RenderPopupMenuItems($aActions, $aFavoriteActions); if (!$oPage->IsPrintableVersion() && $sRefreshAction != '') { $sHtml .= "<div class=\"actions_button\" title=\"" . htmlentities(Dict::S('UI:Button:Refresh'), ENT_QUOTES, 'UTF-8') . "\"><span class=\"refresh-button\" onclick=\"{$sRefreshAction}\"></span></div>"; } } static $bPopupScript = false; if (!$bPopupScript) { // Output this once per page... $oPage->add_ready_script("\$(\"div.itop_popup>ul\").popupmenu();\n"); $bPopupScript = true; } return $sHtml; }
$oDBRS = new DBRestore($sDBHost, $sDBUser, $sDBPwd, $sDBName, $sDBSubName); $oDBRS->SetMySQLBinDir($sMySQLBinDir); $sBackupDir = APPROOT . 'data/backups/'; $sBackupFile = $sBackupDir . $sFile; $sRes = $oDBRS->RestoreFromZip($sBackupFile, $sEnvironment); IssueLog::Info('Backup Restore - Done, releasing the LOCK'); $oRestoreMutex->Unlock(); } catch (Exception $e) { $oRestoreMutex->Unlock(); $oPage->p('Error: ' . $e->getMessage()); } } $oPage->output(); break; case 'download': require_once APPROOT . '/application/startup.inc.php'; require_once APPROOT . '/application/loginwebpage.class.inc.php'; LoginWebPage::DoLogin(true); // Check user rights and prompt if needed (must be admin) if (utils::GetConfig()->Get('demo_mode')) { throw new Exception('iTop is in demonstration mode: the feature is disabled'); } $sFile = utils::ReadParam('file', '', false, 'raw_data'); $oBackup = new DBBackupScheduled(); $sBackupDir = APPROOT . 'data/backups/'; $oBackup->DownloadBackup($sBackupDir . $sFile); break; } } catch (Exception $e) { IssueLog::Error($e->getMessage()); }
/** * Make the wizard run: Start, Next or Back depending WizardUpdateButtons(); on the page's parameters */ public function Run() { $sOperation = utils::ReadParam('operation'); $this->aParameters = utils::ReadParam('_params', array(), false, 'raw_data'); $this->aSteps = json_decode(utils::ReadParam('_steps', '[]', false, 'raw_data'), true); switch ($sOperation) { case 'next': $this->Next(); break; case 'back': $this->Back(); break; default: $this->Start(); } }
$iUserID = UserRights::GetUserId(); $sOQLprofile = "SELECT URP_Profiles AS p JOIN URP_UserProfile AS up ON up.profileid=p.id WHERE up.userid = :user AND p.name = :profile"; $oProfileSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQLprofile), array(), array('user' => $iUserID, 'profile' => PORTAL_POWER_USER_PROFILE)); $bRes = $oProfileSet->count() > 0; return $bRes; } /////////////////////////////////////////////////////////////////////////////// // // Main program // /////////////////////////////////////////////////////////////////////////////// try { require_once APPROOT . '/application/startup.inc.php'; require_once APPROOT . '/application/portalwebpage.class.inc.php'; $oAppContext = new ApplicationContext(); $sOperation = utils::ReadParam('operation', ''); require_once APPROOT . '/application/loginwebpage.class.inc.php'; LoginWebPage::DoLogin(false, true); // Check user rights and prompt if needed ApplicationContext::SetUrlMakerClass('MyPortalURLMaker'); $aClasses = explode(',', MetaModel::GetConfig()->Get('portal_tickets')); $sMainClass = trim(reset($aClasses)); if (!class_exists($sMainClass)) { $oP = new WebPage(Dict::S('Portal:Title')); $oP->p(dict::Format('Portal:NoRequestMgmt', UserRights::GetUserFriendlyName())); } else { $oUserOrg = GetUserOrg(); $sCode = $oUserOrg->Get('code'); $sAlternateStylesheet = ''; if (@file_exists("./{$sCode}/portal.css")) { $sAlternateStylesheet = "{$sCode}";
protected static function UpdateAttachments($oObject, $oChange = null) { self::$m_bIsModified = false; if (utils::ReadParam('attachment_plugin', 'not-in-form') == 'not-in-form') { // Workaround to an issue in iTop < 2.0 // Leave silently if there is no trace of the attachment form return; } $iTransactionId = utils::ReadParam('transaction_id', null); if (!is_null($iTransactionId)) { $aActions = array(); $aAttachmentIds = utils::ReadParam('attachments', array()); // Get all current attachments $oSearch = DBObjectSearch::FromOQL("SELECT Attachment WHERE item_class = :class AND item_id = :item_id"); $oSet = new DBObjectSet($oSearch, array(), array('class' => get_class($oObject), 'item_id' => $oObject->GetKey())); while ($oAttachment = $oSet->Fetch()) { // Remove attachments that are no longer attached to the current object if (!in_array($oAttachment->GetKey(), $aAttachmentIds)) { $oAttachment->DBDelete(); $aActions[] = self::GetActionDescription($oAttachment, false); } } // Attach new (temporary) attachements $sTempId = session_id() . '_' . $iTransactionId; // The object is being created from a form, check if there are pending attachments // for this object, but deleting the "new" ones that were already removed from the form $aRemovedAttachmentIds = utils::ReadParam('removed_attachments', array()); $sOQL = 'SELECT Attachment WHERE temp_id = :temp_id'; $oSearch = DBObjectSearch::FromOQL($sOQL); foreach ($aAttachmentIds as $iAttachmentId) { $oSet = new DBObjectSet($oSearch, array(), array('temp_id' => $sTempId)); while ($oAttachment = $oSet->Fetch()) { if (in_array($oAttachment->GetKey(), $aRemovedAttachmentIds)) { $oAttachment->DBDelete(); // temporary attachment removed, don't even mention it in the history } else { $oAttachment->SetItem($oObject); $oAttachment->Set('temp_id', ''); $oAttachment->DBUpdate(); // temporary attachment confirmed, list it in the history $aActions[] = self::GetActionDescription($oAttachment, true); } } } if (count($aActions) > 0) { if ($oChange == null) { // Let's create a change if non is supplied $oChange = MetaModel::NewObject("CMDBChange"); $oChange->Set("date", time()); $sUserString = CMDBChange::GetCurrentUserName(); $oChange->Set("userinfo", $sUserString); $iChangeId = $oChange->DBInsert(); } foreach ($aActions as $sActionDescription) { self::RecordHistory($oChange, $oObject, $sActionDescription); } self::$m_bIsModified = true; } } }
/** * Create a backup file */ public function DoBackup($sBackupFileName) { $sHost = self::EscapeShellArg($this->sDBHost); $sUser = self::EscapeShellArg($this->sDBUser); $sPwd = self::EscapeShellArg($this->sDBPwd); $sDBName = self::EscapeShellArg($this->sDBName); // Just to check the connection to the DB (better than getting the retcode of mysqldump = 1) $oMysqli = $this->DBConnect(); $sTables = ''; if ($this->sDBSubName != '') { // This instance of iTop uses a prefix for the tables, so there may be other tables in the database // Let's explicitely list all the tables and views to dump $aTables = $this->EnumerateTables(); if (count($aTables) == 0) { // No table has been found with the given prefix throw new BackupException("No table has been found with the given prefix"); } $aEscapedTables = array(); foreach ($aTables as $sTable) { $aEscapedTables[] = self::EscapeShellArg($sTable); } $sTables = implode(' ', $aEscapedTables); } $this->LogInfo("Starting backup of {$this->sDBHost}/{$this->sDBName}(suffix:'{$this->sDBSubName}')"); $sMySQLBinDir = utils::ReadParam('mysql_bindir', $this->sMySQLBinDir, true); if (empty($sMySQLBinDir)) { $sMySQLDump = 'mysqldump'; } else { $sMySQLDump = '"' . $sMySQLBinDir . '/mysqldump"'; } // Store the results in a temporary file $sTmpFileName = self::EscapeShellArg($sBackupFileName); if (is_null($this->iDBPort)) { $sPortOption = ''; } else { $sPortOption = '--port=' . $this->iDBPort . ' '; } // Delete the file created by tempnam() so that the spawned process can write into it (Windows/IIS) unlink($sBackupFileName); $sCommand = "{$sMySQLDump} --opt --default-character-set=utf8 --add-drop-database --single-transaction --host={$sHost} {$sPortOption} --user={$sUser} --password={$sPwd} --result-file={$sTmpFileName} {$sDBName} {$sTables} 2>&1"; $sCommandDisplay = "{$sMySQLDump} --opt --default-character-set=utf8 --add-drop-database --single-transaction --host={$sHost} {$sPortOption} --user=xxxxx --password=xxxxx --result-file={$sTmpFileName} {$sDBName} {$sTables}"; // Now run the command for real $this->LogInfo("Executing command: {$sCommandDisplay}"); $aOutput = array(); $iRetCode = 0; exec($sCommand, $aOutput, $iRetCode); foreach ($aOutput as $sLine) { $this->LogInfo("mysqldump said: {$sLine}"); } if ($iRetCode != 0) { $this->LogError("Failed to execute: {$sCommandDisplay}. The command returned:{$iRetCode}"); foreach ($aOutput as $sLine) { $this->LogError("mysqldump said: {$sLine}"); } if (count($aOutput) == 1) { $sMoreInfo = trim($aOutput[0]); } else { $sMoreInfo = "Check the log files '" . realpath(APPROOT . '/log/setup.log or error.log') . "' for more information."; } throw new BackupException("Failed to execute mysqldump: " . $sMoreInfo); } }
protected function GetWizardStepHistory() { $sRawHistory = trim(utils::ReadParam('step_history', '', false, 'raw_data')); if (strlen($sRawHistory) == 0) { return array(); } else { return explode(',', $sRawHistory); } }
// Needed to read the parameters (with sanitization) require_once APPROOT . 'application/utils.inc.php'; $sModule = utils::ReadParam('exec_module', ''); if ($sModule == '') { echo "Missing argument 'exec_module'"; exit; } $sModule = basename($sModule); // protect against ../.. ... $sPage = utils::ReadParam('exec_page', '', false, 'raw_data'); if ($sPage == '') { echo "Missing argument 'exec_page'"; exit; } $sPage = basename($sPage); // protect against ../.. ... session_name('itop-' . md5(APPROOT)); session_start(); $sEnvironment = utils::ReadParam('exec_env', utils::GetCurrentEnvironment()); session_write_close(); $sTargetPage = APPROOT . 'env-' . $sEnvironment . '/' . $sModule . '/' . $sPage; if (!file_exists($sTargetPage)) { // Do not recall the parameters (security takes precedence) echo "Wrong module, page name or environment..."; exit; } ///////////////////////////////////////// // // GO! // require_once $sTargetPage;
\t-moz-box-sizing: border-box; \tbox-sizing: border-box; \twidth: 100%; \theight: 550px; } .current_line { \tdisplay: none; \tmargin-left: 20px; } EOF ); $sConfigFile = APPROOT . 'conf/' . utils::GetCurrentEnvironment() . '/config-itop.php'; if ($sOperation == 'save') { $sConfig = utils::ReadParam('new_config', '', false, 'raw_data'); $sOrginalConfig = utils::ReadParam('prev_config', '', false, 'raw_data'); if ($sConfig == $sOrginalConfig) { $oP->add('<div id="save_result" class="header_message">' . Dict::S('config-no-change') . '</div>'); } else { try { TestConfig($sConfig, $oP); // throws exceptions @chmod($sConfigFile, 0770); // Allow overwriting the file file_put_contents($sConfigFile, $sConfig); @chmod($sConfigFile, 0444); // Read-only $oP->p('<div id="save_result" class="header_message message_ok">' . Dict::S('Successfully recorded.') . '</div>'); $sOrginalConfig = str_replace("\r\n", "\n", file_get_contents($sConfigFile)); } catch (Exception $e) { $oP->p('<div id="save_result" class="header_message message_error">' . $e->getMessage() . '</div>');
/** * Check that the backup could be executed * @param Page $oP The page used only for its 'log' method * @return array An array of CheckResults objects */ static function CheckBackupPrerequisites($sDestDir) { $aResult = array(); SetupPage::log('Info - CheckBackupPrerequisites'); // zip extension // if (!extension_loaded('zip')) { $sMissingExtensionLink = "<a href=\"http://www.php.net/manual/en/book.zip.php\" target=\"_blank\">zip</a>"; $aResult[] = new CheckResult(CheckResult::ERROR, "Missing PHP extension: zip", $sMissingExtensionLink); } // availability of exec() // $aDisabled = explode(', ', ini_get('disable_functions')); SetupPage::log('Info - PHP functions disabled: ' . implode(', ', $aDisabled)); if (in_array('exec', $aDisabled)) { $aResult[] = new CheckResult(CheckResult::ERROR, "The PHP exec() function has been disabled on this server"); } // availability of mysqldump $sMySQLBinDir = utils::ReadParam('mysql_bindir', '', true); if (empty($sMySQLBinDir)) { $sMySQLDump = 'mysqldump'; } else { SetupPage::log('Info - Found mysql_bindir: ' . $sMySQLBinDir); $sMySQLDump = '"' . $sMySQLBinDir . '/mysqldump"'; } $sCommand = "{$sMySQLDump} -V 2>&1"; $aOutput = array(); $iRetCode = 0; exec($sCommand, $aOutput, $iRetCode); if ($iRetCode == 0) { $aResult[] = new CheckResult(CheckResult::INFO, "mysqldump is present: " . $aOutput[0]); } elseif ($iRetCode == 1) { $aResult[] = new CheckResult(CheckResult::ERROR, "mysqldump could not be found: " . implode(' ', $aOutput) . " - Please make sure it is installed and in the path."); } else { $aResult[] = new CheckResult(CheckResult::ERROR, "mysqldump could not be executed (retcode={$iRetCode}): Please make sure it is installed and in the path"); } foreach ($aOutput as $sLine) { SetupPage::log('Info - mysqldump -V said: ' . $sLine); } // check disk space // to do... evaluate how we can correlate the DB size with the size of the dump (and the zip!) // E.g. 2,28 Mb after a full install, giving a zip of 26 Kb (data = 26 Kb) // Example of query (DB without a suffix) //$sDBSize = "SELECT SUM(ROUND(DATA_LENGTH/1024/1024, 2)) AS size_mb FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = `$sDBName`"; return $aResult; }
$sBlockId = 'audit_errors'; $oP->p("<div id=\"{$sBlockId}\" style=\"clear:both\">\n"); $oBlock = DisplayBlock::FromObjectSet($oErrorObjectSet, 'csv'); $oBlock->Display($oP, 1); $oP->p("</div>\n"); // Adjust the size of the Textarea containing the CSV to fit almost all the remaining space $oP->add_ready_script(" \$('#1>textarea').height(400);"); // adjust the size of the block $sExportUrl = utils::GetAbsoluteUrlAppRoot() . "pages/audit.php?operation=csv&category=" . $oAuditCategory->GetKey() . "&rule=" . $oAuditRule->GetKey(); $oP->add_ready_script("\$('a[href*=\"webservices/export.php?expression=\"]').attr('href', '" . $sExportUrl . "&filename=audit.csv" . $sAdvanced . "');"); $oP->add_ready_script("\$('#1 :checkbox').removeAttr('onclick').click( function() { var sAdvanced = ''; if (this.checked) sAdvanced = '&advanced=1'; window.location.href='{$sExportUrl}'+sAdvanced; } );"); } break; case 'errors': $iCategory = utils::ReadParam('category', ''); $iRuleIndex = utils::ReadParam('rule', 0); $oAuditCategory = MetaModel::GetObject('AuditCategory', $iCategory); $oDefinitionFilter = DBObjectSearch::FromOQL($oAuditCategory->Get('definition_set')); FilterByContext($oDefinitionFilter, $oAppContext); $oDefinitionSet = new CMDBObjectSet($oDefinitionFilter); $oFilter = GetRuleResultFilter($iRuleIndex, $oDefinitionFilter, $oAppContext); $oErrorObjectSet = new CMDBObjectSet($oFilter); $oAuditRule = MetaModel::GetObject('AuditRule', $iRuleIndex); $oP->add('<div class="page_header"><h1>Audit Errors: <span class="hilite">' . $oAuditRule->Get('description') . '</span></h1><img style="margin-top: -20px; margin-right: 10px; float: right;" src="../images/stop.png"/></div>'); $oP->p('<a href="./audit.php?' . $oAppContext->GetForLink() . '">[Back to audit results]</a>'); $sBlockId = 'audit_errors'; $oP->p("<div id=\"{$sBlockId}\" style=\"clear:both\">\n"); $oBlock = DisplayBlock::FromObjectSet($oErrorObjectSet, 'list'); $oBlock->Display($oP, 1); $oP->p("</div>\n"); $sExportUrl = utils::GetAbsoluteUrlAppRoot() . "pages/audit.php?operation=csv&category=" . $oAuditCategory->GetKey() . "&rule=" . $oAuditRule->GetKey();
$oAttachment->Set('item_class', $sObjClass); $oAttachment->SetDefaultOrgId(); $oAttachment->Set('contents', $oDoc); $iAttId = $oAttachment->DBInsert(); $aResult['msg'] = $oDoc->GetFileName(); $aResult['icon'] = utils::GetAbsoluteUrlAppRoot() . AttachmentPlugIn::GetFileIcon($oDoc->GetFileName()); $aResult['att_id'] = $iAttId; $aResult['preview'] = $oDoc->IsPreviewAvailable() ? 'true' : 'false'; } catch (FileUploadException $e) { $aResult['error'] = $e->GetMessage(); } } $oPage->add(json_encode($aResult)); break; case 'remove': $iAttachmentId = utils::ReadParam('att_id', ''); $oSearch = DBObjectSearch::FromOQL("SELECT Attachment WHERE id = :id"); $oSet = new DBObjectSet($oSearch, array(), array('id' => $iAttachmentId)); while ($oAttachment = $oSet->Fetch()) { $oAttachment->DBDelete(); } break; default: $oPage->p("Missing argument 'operation'"); } $oPage->output(); } catch (Exception $e) { // note: transform to cope with XSS attacks echo htmlentities($e->GetMessage(), ENT_QUOTES, 'utf-8'); IssueLog::Error($e->getMessage()); }
/** * Outputs (via some echo) the complete HTML page by assembling all its elements */ public function output() { $sAbsURLAppRoot = addslashes($this->m_sRootUrl); //$this->set_base($this->m_sRootUrl.'pages/'); $sForm = $this->GetSiloSelectionForm(); $this->DisplayMenu(); // Compute the menu // Call the extensions to add content to the page, so that they can also add styles or scripts $sBannerExtraHtml = ''; foreach (MetaModel::EnumPlugins('iPageUIExtension') as $oExtensionInstance) { $sBannerExtraHtml .= $oExtensionInstance->GetBannerHtml($this); } $sNorthPane = ''; foreach (MetaModel::EnumPlugins('iPageUIExtension') as $oExtensionInstance) { $sNorthPane .= $oExtensionInstance->GetNorthPaneHtml($this); } if (UserRights::IsAdministrator() && ExecutionKPI::IsEnabled()) { $sNorthPane .= '<div id="admin-banner"><span style="padding:5px;">' . ExecutionKPI::GetDescription() . '<span></div>'; } //$sSouthPane = '<p>Peak memory Usage: '.sprintf('%.3f MB', memory_get_peak_usage(true) / (1024*1024)).'</p>'; $sSouthPane = ''; foreach (MetaModel::EnumPlugins('iPageUIExtension') as $oExtensionInstance) { $sSouthPane .= $oExtensionInstance->GetSouthPaneHtml($this); } // Put here the 'ready scripts' that must be executed after all others $aMultiselectOptions = array('header' => true, 'checkAllText' => Dict::S('UI:SearchValue:CheckAll'), 'uncheckAllText' => Dict::S('UI:SearchValue:UncheckAll'), 'noneSelectedText' => Dict::S('UI:SearchValue:Any'), 'selectedText' => Dict::S('UI:SearchValue:NbSelected'), 'selectedList' => 1); $sJSMultiselectOptions = json_encode($aMultiselectOptions); $this->add_ready_script(<<<EOF \t\t// Since the event is only triggered when the hash changes, we need to trigger \t\t// the event now, to handle the hash the page may have loaded with. \t\t\$(window).trigger( 'hashchange' ); \t\t \t\t// Some table are sort-able, some are not, let's fix this \t\t\$('table.listResults').each( function() { FixTableSorter(\$(this)); } ); \t\t \t\t\$('.multiselect').multiselect({$sJSMultiselectOptions}); \t\tFixSearchFormsDisposition(); EOF ); if ($this->GetOutputFormat() == 'html') { foreach ($this->a_headers as $s_header) { header($s_header); } } $s_captured_output = $this->ob_get_clean_safe(); $sHtml = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n"; $sHtml .= "<html>\n"; $sHtml .= "<head>\n"; // Make sure that Internet Explorer renders the page using its latest/highest/greatest standards ! $sHtml .= "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n"; $sHtml .= "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n"; $sHtml .= "<title>" . htmlentities($this->s_title, ENT_QUOTES, 'UTF-8') . "</title>\n"; $sHtml .= $this->get_base_tag(); // Stylesheets MUST be loaded before any scripts otherwise // jQuery scripts may face some spurious problems (like failing on a 'reload') foreach ($this->a_linked_stylesheets as $a_stylesheet) { if ($a_stylesheet['condition'] != "") { $sHtml .= "<!--[if {$a_stylesheet['condition']}]>\n"; } $sHtml .= "<link rel=\"stylesheet\" type=\"text/css\" href=\"{$a_stylesheet['link']}\" />\n"; if ($a_stylesheet['condition'] != "") { $sHtml .= "<![endif]-->\n"; } } // special stylesheet for printing, hides the navigation gadgets $sHtml .= "<link rel=\"stylesheet\" media=\"print\" type=\"text/css\" href=\"../css/print.css\" />\n"; if ($this->GetOutputFormat() == 'html') { $sHtml .= $this->output_dict_entries(true); // before any script so that they can benefit from the translations foreach ($this->a_linked_scripts as $s_script) { // Make sure that the URL to the script contains the application's version number // so that the new script do NOT get reloaded from the cache when the application is upgraded if (strpos($s_script, '?') === false) { $s_script .= "?itopversion=" . ITOP_VERSION; } else { $s_script .= "&itopversion=" . ITOP_VERSION; } $sHtml .= "<script type=\"text/javascript\" src=\"{$s_script}\"></script>\n"; } $this->add_script("var iPaneVisWatchDog = window.setTimeout('FixPaneVis()',5000);\n\$(document).ready(function() {\n{$this->m_sInitScript};\nwindow.setTimeout('onDelayedReady()',10)\n});"); if (count($this->m_aReadyScripts) > 0) { $this->add_script("\nonDelayedReady = function() {\n" . implode("\n", $this->m_aReadyScripts) . "\n}\n"); } if (count($this->a_scripts) > 0) { $sHtml .= "<script type=\"text/javascript\">\n"; foreach ($this->a_scripts as $s_script) { $sHtml .= "{$s_script}\n"; } $sHtml .= "</script>\n"; } } if (count($this->a_styles) > 0) { $sHtml .= "<style>\n"; foreach ($this->a_styles as $s_style) { $sHtml .= "{$s_style}\n"; } $sHtml .= "</style>\n"; } $sHtml .= "<link rel=\"search\" type=\"application/opensearchdescription+xml\" title=\"iTop\" href=\"" . utils::GetAbsoluteUrlAppRoot() . "pages/opensearch.xml.php\" />\n"; $sHtml .= "<link rel=\"shortcut icon\" href=\"" . utils::GetAbsoluteUrlAppRoot() . "images/favicon.ico\" />\n"; $sHtml .= "</head>\n"; $sHtml .= "<body>\n"; // Render the revision number if (ITOP_REVISION == '$WCREV$') { // This is NOT a version built using the buil system, just display the main version $sVersionString = Dict::Format('UI:iTopVersion:Short', ITOP_VERSION); } else { // This is a build made from SVN, let display the full information $sVersionString = Dict::Format('UI:iTopVersion:Long', ITOP_VERSION, ITOP_REVISION, ITOP_BUILD_DATE); } // Render the text of the global search form $sText = htmlentities(utils::ReadParam('text', '', false, 'raw_data'), ENT_QUOTES, 'UTF-8'); $sOnClick = ""; if (empty($sText)) { // if no search text is supplied then // 1) the search text is filled with "your search" // 2) clicking on it will erase it $sText = Dict::S("UI:YourSearch"); $sOnClick = " onclick=\"this.value='';this.onclick=null;\""; } // Render the tabs in the page (if any) $this->s_content = $this->m_oTabs->RenderIntoContent($this->s_content); if ($this->GetOutputFormat() == 'html') { $oAppContext = new ApplicationContext(); $sUserName = UserRights::GetUser(); $sIsAdmin = UserRights::IsAdministrator() ? '(Administrator)' : ''; if (UserRights::IsAdministrator()) { $sLogonMessage = Dict::Format('UI:LoggedAsMessage+Admin', $sUserName); } else { $sLogonMessage = Dict::Format('UI:LoggedAsMessage', $sUserName); } $sLogOffMenu = "<span id=\"logOffBtn\"><ul><li><img src=\"../images/onOffBtn.png\"><ul>"; $sLogOffMenu .= "<li><span>{$sLogonMessage}</span></li>\n"; $aActions = array(); $oPrefs = new URLPopupMenuItem('UI:Preferences', Dict::S('UI:Preferences'), utils::GetAbsoluteUrlAppRoot() . "pages/preferences.php?" . $oAppContext->GetForLink()); $aActions[$oPrefs->GetUID()] = $oPrefs->GetMenuItem(); if (utils::CanLogOff()) { $oLogOff = new URLPopupMenuItem('UI:LogOffMenu', Dict::S('UI:LogOffMenu'), utils::GetAbsoluteUrlAppRoot() . 'pages/logoff.php?operation=do_logoff'); $aActions[$oLogOff->GetUID()] = $oLogOff->GetMenuItem(); } if (UserRights::CanChangePassword()) { $oChangePwd = new URLPopupMenuItem('UI:ChangePwdMenu', Dict::S('UI:ChangePwdMenu'), utils::GetAbsoluteUrlAppRoot() . 'pages/UI.php?loginop=change_pwd'); $aActions[$oChangePwd->GetUID()] = $oChangePwd->GetMenuItem(); } utils::GetPopupMenuItems($this, iPopupMenuExtension::MENU_USER_ACTIONS, null, $aActions); $oAbout = new JSPopupMenuItem('UI:AboutBox', Dict::S('UI:AboutBox'), 'return ShowAboutBox();'); $aActions[$oAbout->GetUID()] = $oAbout->GetMenuItem(); $sLogOffMenu .= $this->RenderPopupMenuItems($aActions); $sRestrictions = ''; if (!MetaModel::DBHasAccess(ACCESS_ADMIN_WRITE)) { if (!MetaModel::DBHasAccess(ACCESS_ADMIN_WRITE)) { $sRestrictions = Dict::S('UI:AccessRO-All'); } } elseif (!MetaModel::DBHasAccess(ACCESS_USER_WRITE)) { $sRestrictions = Dict::S('UI:AccessRO-Users'); } $sApplicationBanner = ''; if (strlen($sRestrictions) > 0) { $sAdminMessage = trim(MetaModel::GetConfig()->Get('access_message')); $sApplicationBanner .= '<div id="admin-banner">'; $sApplicationBanner .= '<img src="../images/locked.png" style="vertical-align:middle;">'; $sApplicationBanner .= ' <b>' . $sRestrictions . '</b>'; if (strlen($sAdminMessage) > 0) { $sApplicationBanner .= ' <b>' . $sAdminMessage . '</b>'; } $sApplicationBanner .= '</div>'; } if (strlen($this->m_sMessage)) { $sApplicationBanner .= '<div id="admin-banner"><span style="padding:5px;">' . $this->m_sMessage . '<span></div>'; } $sApplicationBanner .= $sBannerExtraHtml; if (!empty($sNorthPane)) { $sNorthPane = '<div id="bottom-pane" class="ui-layout-north">' . $sNorthPane . '</div>'; } if (!empty($sSouthPane)) { $sSouthPane = '<div id="bottom-pane" class="ui-layout-south">' . $sSouthPane . '</div>'; } $sIconUrl = Utils::GetConfig()->Get('app_icon_url'); $sOnlineHelpUrl = MetaModel::GetConfig()->Get('online_help'); //$sLogOffMenu = "<span id=\"logOffBtn\" style=\"height:55px;padding:0;margin:0;\"><img src=\"../images/onOffBtn.png\"></span>"; $sDisplayIcon = utils::GetAbsoluteUrlAppRoot() . 'images/itop-logo.png'; if (file_exists(MODULESROOT . 'branding/main-logo.png')) { $sDisplayIcon = utils::GetAbsoluteUrlModulesRoot() . 'branding/main-logo.png'; } $sHtml .= $sNorthPane; $sHtml .= '<div id="left-pane" class="ui-layout-west">'; $sHtml .= '<!-- Beginning of the left pane -->'; $sHtml .= ' <div class="ui-layout-north">'; $sHtml .= ' <div id="header-logo">'; $sHtml .= ' <div id="top-left"></div><div id="logo"><a href="' . htmlentities($sIconUrl, ENT_QUOTES, 'UTF-8') . '"><img src="' . $sDisplayIcon . '" title="' . htmlentities($sVersionString, ENT_QUOTES, 'UTF-8') . '" style="border:0; margin-top:16px; margin-right:40px;"/></a></div>'; $sHtml .= ' </div>'; $sHtml .= ' <div class="header-menu">'; if (!MetaModel::GetConfig()->Get('demo_mode')) { $sHtml .= ' <div class="icon ui-state-default ui-corner-all"><span id="tPinMenu" class="ui-icon ui-icon-pin-w">pin</span></div>'; } $sHtml .= ' <div style="text-align:center;">' . self::FilterXSS($sForm) . '</div>'; $sHtml .= ' </div>'; $sHtml .= ' </div>'; $sHtml .= ' <div id="menu" class="ui-layout-center">'; $sHtml .= ' <div id="inner_menu">'; $sHtml .= ' <div id="accordion">'; $sHtml .= self::FilterXSS($this->m_sMenu); $sHtml .= ' <!-- Beginning of the accordion menu -->'; $sHtml .= ' <!-- End of the accordion menu-->'; $sHtml .= ' </div>'; $sHtml .= ' </div> <!-- /inner menu -->'; $sHtml .= ' </div> <!-- /menu -->'; $sHtml .= ' <div class="footer ui-layout-south"><div id="combodo_logo"><a href="http://www.combodo.com" title="www.combodo.com" target="_blank"><img src="../images/logo-combodo.png"/></a></div></div>'; $sHtml .= '<!-- End of the left pane -->'; $sHtml .= '</div>'; $sHtml .= '<div class="ui-layout-center">'; $sHtml .= ' <div id="top-bar" style="width:100%">'; $sHtml .= self::FilterXSS($sApplicationBanner); $sHtml .= ' <div id="global-search"><form action="' . utils::GetAbsoluteUrlAppRoot() . 'pages/UI.php"><table><tr><td></td><td id="g-search-input"><input type="text" name="text" value="' . $sText . '"' . $sOnClick . '/></td>'; $sHtml .= '<td><input type="image" src="../images/searchBtn.png"/></a></td>'; $sHtml .= '<td><a style="background:transparent;" href="' . $sOnlineHelpUrl . '" target="_blank"><img style="border:0;padding-left:20px;padding-right:10px;" title="' . Dict::S('UI:Help') . '" src="../images/help.png"/></td>'; $sHtml .= '<td style="padding-right:20px;padding-left:10px;">' . self::FilterXSS($sLogOffMenu) . '</td><td><input type="hidden" name="operation" value="full_text"/></td></tr></table></form></div>'; //echo '<td> <input type="hidden" name="operation" value="full_text"/></td></tr></table></form></div>'; $sHtml .= ' </div>'; $sHtml .= ' <div class="ui-layout-content" style="overflow:auto;">'; $sHtml .= ' <!-- Beginning of page content -->'; $sHtml .= self::FilterXSS($this->s_content); $sHtml .= ' <!-- End of page content -->'; $sHtml .= ' </div>'; $sHtml .= '</div>'; $sHtml .= $sSouthPane; // Add the captured output if (trim($s_captured_output) != "") { $sHtml .= "<div id=\"rawOutput\" title=\"Debug Output\"><div style=\"height:500px; overflow-y:auto;\">" . self::FilterXSS($s_captured_output) . "</div></div>\n"; } $sHtml .= "<div id=\"at_the_end\">" . self::FilterXSS($this->s_deferred_content) . "</div>"; $sHtml .= "<div style=\"display:none\" title=\"ex2\" id=\"ex2\">Please wait...</div>\n"; // jqModal Window $sHtml .= "<div style=\"display:none\" title=\"dialog\" id=\"ModalDlg\"></div>"; $sHtml .= "<div style=\"display:none\" id=\"ajax_content\"></div>"; } else { $sHtml .= self::FilterXSS($this->s_content); } $sHtml .= "</body>\n"; $sHtml .= "</html>\n"; if ($this->GetOutputFormat() == 'html') { $oKPI = new ExecutionKPI(); echo $sHtml; $oKPI->ComputeAndReport('Echoing (' . round(strlen($sHtml) / 1024) . ' Kb)'); } else { if ($this->GetOutputFormat() == 'pdf' && $this->IsOutputFormatAvailable('pdf')) { if (@is_readable(APPROOT . 'lib/MPDF/mpdf.php')) { require_once APPROOT . 'lib/MPDF/mpdf.php'; $oMPDF = new mPDF('c'); $oMPDF->mirroMargins = false; if ($this->a_base['href'] != '') { $oMPDF->setBasePath($this->a_base['href']); // Seems that the <BASE> tag is not recognized by mPDF... } $oMPDF->showWatermarkText = true; if ($this->GetOutputOption('pdf', 'template_path')) { $oMPDF->setImportUse(); // Allow templates $oMPDF->SetDocTemplate($this->GetOutputOption('pdf', 'template_path'), 1); } $oMPDF->WriteHTML($sHtml); $sOutputName = $this->s_title . '.pdf'; if ($this->GetOutputOption('pdf', 'output_name')) { $sOutputName = $this->GetOutputOption('pdf', 'output_name'); } $oMPDF->Output($sOutputName, 'I'); } } } DBSearch::RecordQueryTrace(); ExecutionKPI::ReportStats(); }
public function DisplayFormPart(WebPage $oP, $sPartId) { switch ($sPartId) { case 'interactive_fields_csv': $this->GetInteractiveFieldsWidget($oP, 'interactive_fields_csv'); break; case 'csv_options': $oP->add('<fieldset><legend>' . Dict::S('Core:BulkExport:CSVOptions') . '</legend>'); $oP->add('<table class="export_parameters"><tr><td style="vertical-align:top">'); $oP->add('<h3>' . Dict::S('UI:CSVImport:SeparatorCharacter') . '</h3>'); $sRawSeparator = utils::ReadParam('separator', ',', true, 'raw_data'); $aSep = array(';' => Dict::S('UI:CSVImport:SeparatorSemicolon+'), ',' => Dict::S('UI:CSVImport:SeparatorComma+'), 'tab' => Dict::S('UI:CSVImport:SeparatorTab+')); $sOtherSeparator = ''; if (!array_key_exists($sRawSeparator, $aSep)) { $sOtherSeparator = $sRawSeparator; $sRawSeparator = 'other'; } $aSep['other'] = Dict::S('UI:CSVImport:SeparatorOther') . ' <input type="text" size="3" name="other-separator" value="' . htmlentities($sOtherSeparator, ENT_QUOTES, 'UTF-8') . '"/>'; foreach ($aSep as $sVal => $sLabel) { $sChecked = $sVal == $sRawSeparator ? 'checked' : ''; $oP->add('<input type="radio" name="separator" value="' . htmlentities($sVal, ENT_QUOTES, 'UTF-8') . '" ' . $sChecked . '/> ' . $sLabel . '<br/>'); } $oP->add('</td><td style="vertical-align:top">'); $oP->add('<h3>' . Dict::S('UI:CSVImport:TextQualifierCharacter') . '</h3>'); $sRawQualifier = utils::ReadParam('text-qualifier', '"', true, 'raw_data'); $aQualifiers = array('"' => Dict::S('UI:CSVImport:QualifierDoubleQuote+'), '\'' => Dict::S('UI:CSVImport:QualifierSimpleQuote+')); $sOtherQualifier = ''; if (!array_key_exists($sRawQualifier, $aQualifiers)) { $sOtherQualifier = $sRawQualifier; $sRawQualifier = 'other'; } $aQualifiers['other'] = Dict::S('UI:CSVImport:QualifierOther') . ' <input type="text" size="3" name="other-text-qualifier" value="' . htmlentities($sOtherQualifier, ENT_QUOTES, 'UTF-8') . '"/>'; foreach ($aQualifiers as $sVal => $sLabel) { $sChecked = $sVal == $sRawQualifier ? 'checked' : ''; $oP->add('<input type="radio" name="text-qualifier" value="' . htmlentities($sVal, ENT_QUOTES, 'UTF-8') . '" ' . $sChecked . '/> ' . $sLabel . '<br/>'); } $sChecked = utils::ReadParam('no_localize', 0) == 1 ? ' checked ' : ''; $oP->add('</td><td style="vertical-align:top">'); $oP->add('<h3>' . Dict::S('Core:BulkExport:CSVLocalization') . '</h3>'); $oP->add('<input type="checkbox" id="csv_no_localize" name="no_localize" value="1"' . $sChecked . '><label for="csv_no_localize"> ' . Dict::S('Core:BulkExport:OptionNoLocalize') . '</label>'); $oP->add('<br/>'); $oP->add('<br/>'); $oP->add(Dict::S('UI:CSVImport:Encoding') . ': <select name="charset" style="font-family:Arial,Helvetica,Sans-serif">'); // IE 8 has some troubles if the font is different $aPossibleEncodings = utils::GetPossibleEncodings(MetaModel::GetConfig()->GetCSVImportCharsets()); $sDefaultEncoding = MetaModel::GetConfig()->Get('csv_file_default_charset'); foreach ($aPossibleEncodings as $sIconvCode => $sDisplayName) { $sSelected = ''; if ($sIconvCode == $sDefaultEncoding) { $sSelected = ' selected'; } $oP->add('<option value="' . $sIconvCode . '"' . $sSelected . '>' . $sDisplayName . '</option>'); } $oP->add('</select>'); $oP->add('</td></tr></table>'); $oP->add('</fieldset>'); break; default: return parent::DisplayFormPart($oP, $sPartId); } }
require_once APPROOT . '/application/startup.inc.php'; require_once APPROOT . '/application/loginwebpage.class.inc.php'; // For developping the Navigator from within Flash //session_start(); //$_SESSION['auth_user'] = '******'; //UserRights::Login($_SESSION['auth_user']); // Set the user's language LoginWebPage::DoLogin(); // Check user rights and prompt if needed $oPage = new ajax_page(""); $oPage->no_cache(); $sClass = utils::ReadParam('class', 'Contact', false, 'class'); $id = utils::ReadParam('id', 1); $sRelation = utils::ReadParam('relation', 'impacts'); $aValidRelations = MetaModel::EnumRelations(); $sFormat = utils::ReadParam('format', 'xml'); $sExcludedClasses = utils::ReadParam('exclude', '', false, 'raw_data'); $aExcludedClasses = explode(',', $sExcludedClasses); if (!in_array($sRelation, $aValidRelations)) { // Not a valid relation, use the default one instead $sRelation = 'impacts'; } try { if ($id != 0) { switch ($sFormat) { case 'html': $oPage->SetContentType('text/html'); $oObj = MetaModel::GetObject($sClass, $id, true); $aResults = array(); $iMaxRecursionDepth = MetaModel::GetConfig()->Get('relations_max_depth', 20); $oObj->GetRelatedObjects($sRelation, $iMaxRecursionDepth, $aResults); $iBlock = 1;