\n");
$sTitle = addslashes(Dict::S('UI:WelcomeMenu:Title'));
$oP->add_ready_script(
<< ($(window).height()-70))
{
$('#welcome_popup').height($(window).height()-70);
}
EOF
);
$_SESSION['welcome'] = 'ok';
}
}
}
}
/**
* Apply the 'next-action' to the given object or redirect to the page that prompts for additional information if needed
*
* @param $oP WebPage The page for the output
* @param $oObj CMDBObject The object to process
* @param $sNextAction string The code of the stimulus for the 'action' (i.e. Transition) to apply
*
* @throws \ApplicationException
* @throws \CoreException
* @throws \CoreUnexpectedValue
*/
function ApplyNextAction(Webpage $oP, CMDBObject $oObj, $sNextAction)
{
// Here handle the apply stimulus
$aTransitions = $oObj->EnumTransitions();
if (!isset($aTransitions[$sNextAction]))
{
// Invalid stimulus
throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sNextAction, $oObj->GetName(), $oObj->GetStateLabel()));
}
// Get the list of missing mandatory fields for the target state, considering only the changes from the previous form (i.e don't prompt twice)
$aExpectedAttributes = $oObj->GetTransitionAttributes($sNextAction);
if (count($aExpectedAttributes) == 0)
{
// If all the mandatory fields are already present, just apply the transition silently...
if ($oObj->ApplyStimulus($sNextAction))
{
$oObj->DBUpdate();
}
else
{
throw new ApplicationException(Dict::S('UI:FailedToApplyStimuli'));
}
ReloadAndDisplay($oP, $oObj);
}
else
{
// redirect to the 'stimulus' action
$oAppContext = new ApplicationContext();
//echo "
Missing Attributes
".print_r($aExpectedAttributes, true)."
\n";
$oP->add_header('Location: '.utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=stimulus&class='.get_class($oObj).'&stimulus='.$sNextAction.'&id='.$oObj->getKey().'&'.$oAppContext->GetForLink());
}
}
function ReloadAndDisplay($oPage, $oObj, $sMessageId = '', $sMessage = '', $sSeverity = null)
{
$oAppContext = new ApplicationContext();
if ($sMessageId != '')
{
cmdbAbstractObject::SetSessionMessage(get_class($oObj), $oObj->GetKey(), $sMessageId, $sMessage, $sSeverity, 0, true /* must not exist */);
}
$oPage->add_header('Location: '.utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=details&class='.get_class($oObj).'&id='.$oObj->getKey().'&'.$oAppContext->GetForLink());
}
/**
* Displays the details of an object
*
* @param WebPage $oP Page for the output
* @param string $sClass The name of the class of the object
* @param \cmdbAbstractObject $oObj The object to display
* @param mixed $id Identifier of the object (name or ID)
*
* @throws \CoreException
* @throws \DictExceptionMissingString
* @throws \SecurityException
*/
function DisplayDetails($oP, $sClass, $oObj, $id)
{
$sClassLabel = MetaModel::GetName($sClass);
// 2018-04-11 : removal of the search block
// $oSearch = new DBObjectSearch($sClass);
// $oBlock = new DisplayBlock($oSearch, 'search', false);
// $oBlock->Display($oP, 0, array(
// 'table_id' => 'search-widget-results-outer',
// 'open' => false,
// 'update_history' => false,
// ));
// The object could be listed, check if it is actually allowed to view it
$oSet = CMDBObjectSet::FromObject($oObj);
if (UserRights::IsActionAllowed($sClass, UR_ACTION_READ, $oSet) == UR_ALLOWED_NO)
{
throw new SecurityException('User not allowed to view this object', array('class' => $sClass, 'id' => $id));
}
$oP->set_title(Dict::Format('UI:DetailsPageTitle', $oObj->GetRawName(), $sClassLabel)); // Set title will take care of the encoding
$oObj->DisplayDetails($oP);
}
/**
* Display the session messages relative to the object identified by its "message key" (class::id)
* @param string $sMessageKey
* @param WebPage $oPage
*/
function DisplayMessages($sMessageKey, WebPage $oPage)
{
if (array_key_exists('obj_messages', $_SESSION) && array_key_exists($sMessageKey, $_SESSION['obj_messages']))
{
$aMessages = array();
$aRanks = array();
foreach ($_SESSION['obj_messages'][$sMessageKey] as $sMessageId => $aMessageData)
{
$sMsgClass = 'message_'.$aMessageData['severity'];
$aMessages[] = "
".$aMessageData['message']."
";
$aRanks[] = $aMessageData['rank'];
}
unset($_SESSION['obj_messages'][$sMessageKey]);
array_multisort($aRanks, $aMessages);
foreach ($aMessages as $sMessage)
{
$oPage->add($sMessage);
}
}
}
/**
* Helper to update the breadrumb for the current object
* @param DBObject $oObj
* @param WebPage $oPage
* @throws \CoreException
* @throws \DictExceptionMissingString
*/
function SetObjectBreadCrumbEntry(DBObject $oObj, WebPage $oPage)
{
$sClass = get_class($oObj); // get the leaf class
$sIcon = MetaModel::GetClassIcon($sClass, false);
if ($sIcon == '')
{
$sIcon = utils::GetAbsoluteUrlAppRoot().'images/breadcrumb_object.png';
}
$oPage->SetBreadCrumbEntry("ui-details-$sClass-".$oObj->GetKey(), $oObj->Get('friendlyname'), MetaModel::GetName($sClass).': '.$oObj->Get('friendlyname'), '', $sIcon);
}
/**
* Displays the result of a search request
* @param $oP WebPage Web page for the output
* @param $oFilter DBSearch The search of objects to display
* @param $bSearchForm boolean Whether or not to display the search form at the top the page
* @param $sBaseClass string The base class for the search (can be different from the actual class of the results)
* @param $sFormat string The format to use for the output: csv or html
* @param $bDoSearch bool True to display the search results below the search form
* @param $bSearchFormOpen bool True to display the search form fully expanded (only if $bSearchForm of course)
* @throws \CoreException
* @throws \DictExceptionMissingString
*/
function DisplaySearchSet($oP, $oFilter, $bSearchForm = true, $sBaseClass = '', $sFormat = '', $bDoSearch = true, $bSearchFormOpen = true)
{
if ($bSearchForm)
{
$aParams = array('open' => $bSearchFormOpen, 'table_id' => '1');
if (!empty($sBaseClass))
{
$aParams['baseClass'] = $sBaseClass;
}
$oBlock = new DisplayBlock($oFilter, 'search', false /* Asynchronous */, $aParams);
$oBlock->Display($oP, 0);
}
if ($bDoSearch)
{
if (strtolower($sFormat) == 'csv')
{
$oBlock = new DisplayBlock($oFilter, 'csv', false);
$oBlock->Display($oP, 1);
// Adjust the size of the Textarea containing the CSV to fit almost all the remaining space
$oP->add_ready_script(" $('#1>textarea').height($('#1').parent().height() - $('#0').outerHeight() - 30).width( $('#1').parent().width() - 20);"); // adjust the size of the block
}
else
{
$oBlock = new DisplayBlock($oFilter, 'list', false);
$oBlock->Display($oP, 1);
// Breadcrumb
//$iCount = $oBlock->GetDisplayedCount();
$sPageId = "ui-search-".$oFilter->GetClass();
$sLabel = MetaModel::GetName($oFilter->GetClass());
$oP->SetBreadCrumbEntry($sPageId, $sLabel, '', '', '../images/breadcrumb-search.png');
}
}
}
/**
* Displays a form (checkboxes) to select the objects for which to apply a given action
* Only the objects for which the action is valid can be checked. By default all valid objects are checked
*
* @param \WebPage $oP WebPage The page for output
* @param \DBSearch $oFilter DBSearch The filter that defines the list of objects
* @param string $sNextOperation string The next operation (code) to be executed when the form is submitted
* @param ActionChecker $oChecker ActionChecker The helper class/instance used to check for which object the action is valid
* @param array $aExtraFormParams
*
* @throws \ApplicationException
*/
function DisplayMultipleSelectionForm($oP, $oFilter, $sNextOperation, $oChecker, $aExtraFormParams = array())
{
$oAppContext = new ApplicationContext();
$iBulkActionAllowed = $oChecker->IsAllowed();
$aExtraParams = array('selection_type' => 'multiple', 'selection_mode' => true, 'display_limit' => false, 'menu' => false);
if ($iBulkActionAllowed == UR_ALLOWED_DEPENDS)
{
$aExtraParams['selection_enabled'] = $oChecker->GetAllowedIDs();
}
else if(UR_ALLOWED_NO)
{
throw new ApplicationException(Dict::Format('UI:ActionNotAllowed'));
}
$oBlock = new DisplayBlock($oFilter, 'list', false);
$oP->add("\n");
$oP->add_ready_script("$('#1 table.listResults').trigger('check_all');");
}
/**
* @param $oP
* @param $aResults
* @param $sRelation
* @param $sDirection
* @param $oObj
* for operation : 'swf_navigator'
*
* @throws \DictExceptionMissingString
*/
function DisplayNavigatorListTab($oP, $aResults, $sRelation, $sDirection, $oObj)
{
$oP->SetCurrentTab('UI:RelationshipList');
$oP->add("
");
}
function DisplayNavigatorGroupTab($oP)
{
$oP->SetCurrentTab('UI:RelationGroups');
$oP->add("
");
$oP->add('');
/*
* Content is rendered asynchronously via pages/ajax.render.php?operation=relation_groups
*/
$oP->add("
");
}
/***********************************************************************************
*
* Main user interface page starts here
*
***********************************************************************************/
require_once('../approot.inc.php');
require_once(APPROOT.'/application/application.inc.php');
require_once(APPROOT.'/application/itopwebpage.class.inc.php');
require_once(APPROOT.'/application/wizardhelper.class.inc.php');
require_once(APPROOT.'/application/startup.inc.php');
try
{
$operation = utils::ReadParam('operation', '');
$bPrintable = (utils::ReadParam('printable', 0) == '1');
$oKPI = new ExecutionKPI();
$oKPI->ComputeAndReport('Data model loaded');
$oKPI = new ExecutionKPI();
require_once(APPROOT.'/application/loginwebpage.class.inc.php');
$sLoginMessage = LoginWebPage::DoLogin(); // Check user rights and prompt if needed
$oAppContext = new ApplicationContext();
$oKPI->ComputeAndReport('User login');
$oP = new iTopWebPage(Dict::S('UI:WelcomeToITop'), $bPrintable);
$oP->SetMessage($sLoginMessage);
// All the following actions use advanced forms that require more javascript to be loaded
switch($operation)
{
case 'new': // Form to create a new object
case 'modify': // Form to modify an object
case 'apply_new': // Creation of a new object
case 'apply_modify': // Applying the modifications to an existing object
case 'form_for_modify_all': // Form to modify multiple objects (bulk modify)
case 'bulk_stimulus': // For to apply a stimulus to multiple objects
case 'stimulus': // Form displayed when applying a stimulus (state change)
case 'apply_stimulus': // Form displayed when applying a stimulus (state change)
$oP->add_linked_script("../js/json.js");
$oP->add_linked_script("../js/forms-json-utils.js");
$oP->add_linked_script("../js/wizardhelper.js");
$oP->add_linked_script("../js/wizard.utils.js");
$oP->add_linked_script("../js/linkswidget.js");
$oP->add_linked_script("../js/linksdirectwidget.js");
$oP->add_linked_script("../js/extkeywidget.js");
$oP->add_linked_script("../js/jquery.blockUI.js");
break;
}
switch($operation)
{
///////////////////////////////////////////////////////////////////////////////////////////
case 'details': // Details of an object
$sClass = utils::ReadParam('class', '');
$id = utils::ReadParam('id', '');
if ( empty($sClass) || empty($id))
{
throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'id'));
}
if (is_numeric($id))
{
$oObj = MetaModel::GetObject($sClass, $id, false /* MustBeFound */);
}
else
{
$oObj = MetaModel::GetObjectByName($sClass, $id, false /* MustBeFound */);
}
if (is_null($oObj))
{
// Check anyhow if there is a message for this object (like you've just created it)
$sMessageKey = $sClass.'::'.$id;
DisplayMessages($sMessageKey, $oP);
$oP->set_title(Dict::S('UI:ErrorPageTitle'));
// Attempt to load the object in archive mode
utils::PushArchiveMode(true);
if (is_numeric($id))
{
$oObj = MetaModel::GetObject($sClass, $id, false /* MustBeFound */);
}
else
{
$oObj = MetaModel::GetObjectByName($sClass, $id, false /* MustBeFound */);
}
utils::PopArchiveMode();
if (is_null($oObj))
{
$oP->P(Dict::S('UI:ObjectDoesNotExist'));
}
else
{
SetObjectBreadCrumbEntry($oObj, $oP);
$oP->P(Dict::S('UI:ObjectArchived'));
}
}
else
{
try
{
$oObj->Reload();
}
catch(Exception $e)
{
// Probably not allowed to see this instance of a derived class
// Check anyhow if there is a message for this object (like you've just created it)
$sMessageKey = $sClass.'::'.$id;
DisplayMessages($sMessageKey, $oP);
$oObj = null;
$oP->set_title(Dict::S('UI:ErrorPageTitle'));
$oP->P(Dict::S('UI:ObjectDoesNotExist'));
}
if (!is_null($oObj))
{
SetObjectBreadCrumbEntry($oObj, $oP);
DisplayDetails($oP, $sClass, $oObj, $id);
}
}
break;
case 'release_lock_and_details':
$oP->DisableBreadCrumb();
$sClass = utils::ReadParam('class', '');
$id = utils::ReadParam('id', '');
$oObj = MetaModel::GetObject($sClass, $id);
$sToken = utils::ReadParam('token', '');
if ($sToken != '')
{
iTopOwnershipLock::ReleaseLock($sClass, $id, $sToken);
}
cmdbAbstractObject::ReloadAndDisplay($oP, $oObj, array('operation' => 'details'));
break;
///////////////////////////////////////////////////////////////////////////////////////////
case 'search_oql': // OQL query
$sOQLClass = utils::ReadParam('oql_class', '', false, 'class');
$sBaseClass = utils::ReadParam('base_class', $sOQLClass, false, 'class');
$sOQLClause = utils::ReadParam('oql_clause', '', false, 'raw_data');
$sFormat = utils::ReadParam('format', '');
$bSearchForm = utils::ReadParam('search_form', true);
$sTitle = utils::ReadParam('title', 'UI:SearchResultsPageTitle');
if (empty($sOQLClass))
{
throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'oql_class'));
}
$oP->set_title(Dict::S($sTitle));
$oP->add('
\n");
$sJSClass = addslashes($sClassName);
$sJSNeedles = json_encode($aFullTextNeedles);
$oP->add_ready_script(
<< 0)
{
$oP->add_script("var oTimeStatistics = {};");
}
}
}
break;
///////////////////////////////////////////////////////////////////////////////////////////
case 'modify': // Form to modify an object
$oP->DisableBreadCrumb();
$sClass = utils::ReadParam('class', '', false, 'class');
$id = utils::ReadParam('id', '');
if ( empty($sClass) || empty($id)) // TO DO: check that the class name is valid !
{
throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'id'));
}
// Check if the user can modify this object
$oObj = MetaModel::GetObject($sClass, $id, false /* MustBeFound */);
if (is_null($oObj))
{
$oP->set_title(Dict::S('UI:ErrorPageTitle'));
$oP->P(Dict::S('UI:ObjectDoesNotExist'));
}
else
{
// The object could be read - check if it is allowed to modify it
$oSet = CMDBObjectSet::FromObject($oObj);
if (UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY, $oSet) == UR_ALLOWED_NO)
{
throw new SecurityException('User not allowed to modify this object', array('class' => $sClass, 'id' => $id));
}
// Note: code duplicated to the case 'apply_modify' when a data integrity issue has been found
$oObj->DisplayModifyForm($oP, array('wizard_container' => 1)); // wizard_container: Display the blue borders and the title above the form
}
break;
///////////////////////////////////////////////////////////////////////////////////////////
case 'select_for_modify_all': // Select the list of objects to be modified (bulk modify)
$oP->DisableBreadCrumb();
$oP->set_title(Dict::S('UI:ModifyAllPageTitle'));
$sFilter = utils::ReadParam('filter', '', false, 'raw_data');
if (empty($sFilter))
{
throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'filter'));
}
$oFilter = DBObjectSearch::unserialize($sFilter); //TODO : check that the filter is valid
// Add user filter
$oFilter->UpdateContextFromUser();
$sClass = $oFilter->GetClass();
$oChecker = new ActionChecker($oFilter, UR_ACTION_BULK_MODIFY);
$oP->add("
".Dict::S('UI:ModifyAllPageTitle')."
\n");
DisplayMultipleSelectionForm($oP, $oFilter, 'form_for_modify_all', $oChecker);
break;
///////////////////////////////////////////////////////////////////////////////////////////
case 'form_for_modify_all': // Form to modify multiple objects (bulk modify)
$oP->DisableBreadCrumb();
$sFilter = utils::ReadParam('filter', '', false, 'raw_data');
$sClass = utils::ReadParam('class', '', false, 'class');
$oFullSetFilter = DBObjectSearch::unserialize($sFilter);
// Add user filter
$oFullSetFilter->UpdateContextFromUser();
$aSelectedObj = utils::ReadMultipleSelection($oFullSetFilter);
$sCancelUrl = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
$aContext = array('filter' => htmlentities($sFilter, ENT_QUOTES, 'UTF-8'));
cmdbAbstractObject::DisplayBulkModifyForm($oP, $sClass, $aSelectedObj, 'preview_or_modify_all', $sCancelUrl, array(), $aContext);
break;
///////////////////////////////////////////////////////////////////////////////////////////
case 'preview_or_modify_all': // Preview or apply bulk modify
$oP->DisableBreadCrumb();
$sFilter = utils::ReadParam('filter', '', false, 'raw_data');
$oFilter = DBObjectSearch::unserialize($sFilter); // TO DO : check that the filter is valid
// Add user filter
$oFilter->UpdateContextFromUser();
$oChecker = new ActionChecker($oFilter, UR_ACTION_BULK_MODIFY);
$sClass = utils::ReadParam('class', '', false, 'class');
$bPreview = utils::ReadParam('preview_mode', '');
$sSelectedObj = utils::ReadParam('selectObj', '', false, 'raw_data');
if ( empty($sClass) || empty($sSelectedObj)) // TO DO: check that the class name is valid !
{
throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'selectObj'));
}
$aSelectedObj = explode(',', $sSelectedObj);
$sCancelUrl = "./UI.php?operation=search&filter=".urlencode($sFilter)."&".$oAppContext->GetForLink();
$aContext = array(
'filter' => htmlentities($sFilter, ENT_QUOTES, 'UTF-8'),
'selectObj' => $sSelectedObj,
);
cmdbAbstractObject::DoBulkModify($oP, $sClass, $aSelectedObj, 'preview_or_modify_all', $bPreview, $sCancelUrl, $aContext);
break;
///////////////////////////////////////////////////////////////////////////////////////////
case 'new': // Form to create a new object
$oP->DisableBreadCrumb();
$sClass = utils::ReadParam('class', '', false, 'class');
$sStateCode = utils::ReadParam('state', '');
$bCheckSubClass = utils::ReadParam('checkSubclass', true);
if ( empty($sClass) )
{
throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'class'));
}
/*
$aArgs = utils::ReadParam('default', array(), false, 'raw_data');
$aContext = $oAppContext->GetAsHash();
foreach( $oAppContext->GetNames() as $key)
{
$aArgs[$key] = $oAppContext->GetCurrentValue($key);
}
*/
// If the specified class has subclasses, ask the user an instance of which class to create
$aSubClasses = MetaModel::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL); // Including the specified class itself
$aPossibleClasses = array();
$sRealClass = '';
if ($bCheckSubClass)
{
foreach($aSubClasses as $sCandidateClass)
{
if (!MetaModel::IsAbstract($sCandidateClass) && (UserRights::IsActionAllowed($sCandidateClass, UR_ACTION_MODIFY) == UR_ALLOWED_YES))
{
$aPossibleClasses[$sCandidateClass] = MetaModel::GetName($sCandidateClass);
}
}
// Only one of the subclasses can be instantiated...
if (count($aPossibleClasses) == 1)
{
$aKeys = array_keys($aPossibleClasses);
$sRealClass = $aKeys[0];
}
}
else
{
$sRealClass = $sClass;
}
if (!empty($sRealClass))
{
// Set all the default values in an object and clone this "default" object
$oObjToClone = MetaModel::NewObject($sRealClass);
// 1st - set context values
$oAppContext->InitObjectFromContext($oObjToClone);
// 2nd - set values from the page argument 'default'
$oObjToClone->UpdateObjectFromArg('default');
$aPrefillFormParam = array( 'user' => $_SESSION["auth_user"],
'context' => $oAppContext->GetAsHash(),
'default' => utils::ReadParam('default', array(), '', 'raw_data'),
'origin' => 'console'
);
// 3rd - prefill API
$oObjToClone->PrefillForm('creation_from_0',$aPrefillFormParam);
// Display the creation form
$sClassLabel = MetaModel::GetName($sRealClass);
$sClassIcon = MetaModel::GetClassIcon($sRealClass);
$sObjectTmpKey = $oObjToClone->GetKey();
$sHeaderTitle = Dict::Format('UI:CreationTitle_Class', $sClassLabel);
// Note: some code has been duplicated to the case 'apply_new' when a data integrity issue has been found
$oP->set_title(Dict::Format('UI:CreationPageTitle_Class', $sClassLabel));
$oP->add(<<
$sClassIcon $sHeaderTitle
HTML
);
cmdbAbstractObject::DisplayCreationForm($oP, $sRealClass, $oObjToClone, array());
$oP->add(<<
HTML
);
}
else
{
// Select the derived class to create
$sClassLabel = MetaModel::GetName($sClass);
$sClassIcon = MetaModel::GetClassIcon($sClass);
$sHeaderTitle = Dict::Format('UI:CreationTitle_Class', $sClassLabel);
$oP->add(<<
$sClassIcon $sHeaderTitle
HTML
);
$oP->add('');
$oP->add(<<
HTML
);
}
break;
///////////////////////////////////////////////////////////////////////////////////////////
case 'apply_modify': // Applying the modifications to an existing object
$oP->DisableBreadCrumb();
$sClass = utils::ReadPostedParam('class', '');
$sClassLabel = MetaModel::GetName($sClass);
$id = utils::ReadPostedParam('id', '');
$sTransactionId = utils::ReadPostedParam('transaction_id', '', 'transaction_id');
if ( empty($sClass) || empty($id)) // TO DO: check that the class name is valid !
{
IssueLog::Trace('Object not updated (empty class or id)', $sClass, array(
'$operation' => $operation,
'$id' => $id,
'$sTransactionId' => $sTransactionId,
'$sUser' => UserRights::GetUser(),
'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'],
'REQUEST_URI' => @$_SERVER['REQUEST_URI'],
));
throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'id'));
}
$bDisplayDetails = true;
$oObj = MetaModel::GetObject($sClass, $id, false);
if ($oObj == null)
{
$bDisplayDetails = false;
$oP->set_title(Dict::S('UI:ErrorPageTitle'));
$oP->P(Dict::S('UI:ObjectDoesNotExist'));
IssueLog::Trace('Object not updated (id not found)', $sClass, array(
'$operation' => $operation,
'$id' => $id,
'$sTransactionId' => $sTransactionId,
'$sUser' => UserRights::GetUser(),
'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'],
'REQUEST_URI' => @$_SERVER['REQUEST_URI'],
));
}
elseif (!utils::IsTransactionValid($sTransactionId, false))
{
//TODO: since $bDisplayDetails= true, there will be an redirection, thus, the content generated here is ignored, only the $sMessage and $sSeverity are used afeter the redirection
$sUser = UserRights::GetUser();
IssueLog::Error("UI.php '$operation' : invalid transaction_id ! data: user='$sUser', class='$sClass'");
$oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetRawName(), $sClassLabel)); // Set title will take care of the encoding
$oP->p("".Dict::S('UI:Error:ObjectAlreadyUpdated')."\n");
$sMessage = Dict::Format('UI:Error:ObjectAlreadyUpdated', MetaModel::GetName(get_class($oObj)), $oObj->GetName());
$sSeverity = 'error';
IssueLog::Trace('Object not updated (invalid transaction_id)', $sClass, array(
'$operation' => $operation,
'$id' => $id,
'$sTransactionId' => $sTransactionId,
'$sUser' => UserRights::GetUser(),
'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'],
'REQUEST_URI' => @$_SERVER['REQUEST_URI'],
));
}
else
{
$aErrors = $oObj->UpdateObjectFromPostedForm();
$sMessage = '';
$sSeverity = 'ok';
if (!$oObj->IsModified() && empty($aErrors))
{
$oP->set_title(Dict::Format('UI:ModificationPageTitle_Object_Class', $oObj->GetRawName(), $sClassLabel)); // Set title will take care of the encoding
$sMessage = Dict::Format('UI:Class_Object_NotUpdated', MetaModel::GetName(get_class($oObj)), $oObj->GetName());
$sSeverity = 'info';
IssueLog::Trace('Object not updated (see either $aErrors or IsModified)', $sClass, array(
'$operation' => $operation,
'$id' => $id,
'$sTransactionId' => $sTransactionId,
'$aErrors' => $aErrors,
'IsModified' => $oObj->IsModified(),
'$sUser' => UserRights::GetUser(),
'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'],
'REQUEST_URI' => @$_SERVER['REQUEST_URI'],
));
}
else
{
IssueLog::Trace('Object updated', $sClass, array(
'$operation' => $operation,
'$id' => $id,
'$sTransactionId' => $sTransactionId,
'$aErrors' => $aErrors,
'IsModified' => $oObj->IsModified(),
'$sUser' => UserRights::GetUser(),
'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'],
'REQUEST_URI' => @$_SERVER['REQUEST_URI'],
));
try
{
if (!empty($aErrors))
{
throw new CoreCannotSaveObjectException(array('id' => $oObj->GetKey(), 'class' => $sClass, 'issues' => $aErrors));
}
$oObj->CheckChangedExtKeysValues();
// Transactions are now handled in DBUpdate
$oObj->DBUpdate();
$sMessage = Dict::Format('UI:Class_Object_Updated', MetaModel::GetName(get_class($oObj)), $oObj->GetName());
$sSeverity = 'ok';
}
catch (CoreCannotSaveObjectException $e)
{
// Found issues, explain and give the user a second chance
//
$bDisplayDetails = false;
$aIssues = $e->getIssues();
$oP->AddHeaderMessage($e->getHtmlMessage(), 'message_error');
$oObj->DisplayModifyForm($oP,
array('wizard_container' => true)); // wizard_container: display the wizard border and the title
}
catch (DeleteException $e)
{
// Say two things:
// - 1) Don't be afraid nothing was modified
$sMessage = Dict::Format('UI:Class_Object_NotUpdated', MetaModel::GetName(get_class($oObj)), $oObj->GetName());
$sSeverity = 'info';
cmdbAbstractObject::SetSessionMessage(get_class($oObj), $oObj->GetKey(), 'UI:Class_Object_NotUpdated', $sMessage,
$sSeverity, 0, true /* must not exist */);
// - 2) Ok, there was some trouble indeed
$sMessage = $e->getMessage();
$sSeverity = 'error';
}
utils::RemoveTransaction($sTransactionId);
}
}
if ($bDisplayDetails)
{
$oObj = MetaModel::GetObject(get_class($oObj), $oObj->GetKey()); //Workaround: reload the object so that the linkedset are displayed properly
$sNextAction = utils::ReadPostedParam('next_action', '');
if (!empty($sNextAction))
{
try
{
ApplyNextAction($oP, $oObj, $sNextAction);
}
catch (ApplicationException $e)
{
$sMessage = $e->getMessage();
$sSeverity = 'info';
ReloadAndDisplay($oP, $oObj, 'update', $sMessage, $sSeverity);
}
}
else
{
// Nothing more to do
$sMessage = isset($sMessage) ? $sMessage : '';
$sSeverity = isset($sSeverity) ? $sSeverity : null;
ReloadAndDisplay($oP, $oObj, 'update', $sMessage, $sSeverity);
}
$bLockEnabled = MetaModel::GetConfig()->Get('concurrent_lock_enabled');
if ($bLockEnabled)
{
// Release the concurrent lock, if any
$sOwnershipToken = utils::ReadPostedParam('ownership_token', null, 'raw_data');
if ($sOwnershipToken !== null)
{
// We're done, let's release the lock
iTopOwnershipLock::ReleaseLock(get_class($oObj), $oObj->GetKey(), $sOwnershipToken);
}
}
}
break;
///////////////////////////////////////////////////////////////////////////////////////////
case 'select_for_deletion': // Select multiple objects for deletion
$oP->DisableBreadCrumb();
$sFilter = utils::ReadParam('filter', '', false, 'raw_data');
if (empty($sFilter))
{
throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'filter'));
}
$oP->set_title(Dict::S('UI:BulkDeletePageTitle'));
$oP->add("
".Dict::S('UI:BulkDeleteTitle')."
\n");
$oFilter = DBSearch::unserialize($sFilter); // TO DO : check that the filter is valid
$oFilter->UpdateContextFromUser();
$oChecker = new ActionChecker($oFilter, UR_ACTION_BULK_DELETE);
DisplayMultipleSelectionForm($oP, $oFilter, 'bulk_delete', $oChecker);
break;
///////////////////////////////////////////////////////////////////////////////////////////
case 'bulk_delete_confirmed': // Confirm bulk deletion of objects
$oP->DisableBreadCrumb();
$sTransactionId = utils::ReadPostedParam('transaction_id', '', 'transaction_id');
if (!utils::IsTransactionValid($sTransactionId))
{
$sUser = UserRights::GetUser();
$sClass = utils::ReadParam('class', '', false, 'class');
IssueLog::Error("UI.php '$operation' : invalid transaction_id ! data: user='$sUser', class='$sClass'");
throw new ApplicationException(Dict::S('UI:Error:ObjectsAlreadyDeleted'));
}
// Fall through
///////////////////////////////////////////////////////////////////////////////////////////
case 'delete':
case 'bulk_delete': // Actual bulk deletion (if confirmed)
$oP->DisableBreadCrumb();
$sClass = utils::ReadParam('class', '', false, 'class');
$sClassLabel = MetaModel::GetName($sClass);
$aObjects = array();
if ($operation == 'delete')
{
// Single object
$id = utils::ReadParam('id', '');
$oObj = MetaModel::GetObject($sClass, $id);
$aObjects[] = $oObj;
if (!UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, DBObjectSet::FromObject($oObj)))
{
throw new SecurityException(Dict::Format('UI:Error:DeleteNotAllowedOn_Class', $sClassLabel));
}
}
else
{
// Several objects
$sFilter = utils::ReadPostedParam('filter', '', 'raw_data');
$oFullSetFilter = DBObjectSearch::unserialize($sFilter);
// Add user filter
$oFullSetFilter->UpdateContextFromUser();
$aSelectObject = utils::ReadMultipleSelection($oFullSetFilter);
if ( empty($sClass) || empty($aSelectObject)) // TO DO: check that the class name is valid !
{
throw new ApplicationException(Dict::Format('UI:Error:2ParametersMissing', 'class', 'selectObject[]'));
}
foreach($aSelectObject as $iId)
{
$aObjects[] = MetaModel::GetObject($sClass, $iId);
}
if (count($aObjects) == 1)
{
if (!UserRights::IsActionAllowed($sClass, UR_ACTION_DELETE, DBObjectSet::FromArray($sClass, $aObjects)))
{
throw new SecurityException(Dict::Format('UI:Error:BulkDeleteNotAllowedOn_Class', $sClassLabel));
}
}
else
{
if (!UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_DELETE, DBObjectSet::FromArray($sClass, $aObjects)))
{
throw new SecurityException(Dict::Format('UI:Error:BulkDeleteNotAllowedOn_Class', $sClassLabel));
}
$oP->set_title(Dict::S('UI:BulkDeletePageTitle'));
}
}
// Go for the common part... (delete single, delete bulk, delete confirmed)
cmdbAbstractObject::DeleteObjects($oP, $sClass, $aObjects, ($operation != 'bulk_delete_confirmed'), 'bulk_delete_confirmed');
break;
///////////////////////////////////////////////////////////////////////////////////////////
case 'apply_new': // Creation of a new object
$oP->DisableBreadCrumb();
$sClass = utils::ReadPostedParam('class', '', 'class');
$sClassLabel = MetaModel::GetName($sClass);
$sTransactionId = utils::ReadPostedParam('transaction_id', '', 'transaction_id');
$aErrors = array();
$aWarnings = array();
if ( empty($sClass) ) // TO DO: check that the class name is valid !
{
IssueLog::Trace('Object not created (empty class)', $sClass, array(
'$operation' => $operation,
'$sTransactionId' => $sTransactionId,
'$sUser' => UserRights::GetUser(),
'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'],
'REQUEST_URI' => @$_SERVER['REQUEST_URI'],
));
throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'class'));
}
if (!utils::IsTransactionValid($sTransactionId, false))
{
$sUser = UserRights::GetUser();
IssueLog::Error("UI.php '$operation' : invalid transaction_id ! data: user='$sUser', class='$sClass'");
$oP->p("".Dict::S('UI:Error:ObjectAlreadyCreated')."\n");
IssueLog::Trace('Object not created (invalid transaction_id)', $sClass, array(
'$operation' => $operation,
'$sTransactionId' => $sTransactionId,
'$sUser' => UserRights::GetUser(),
'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'],
'REQUEST_URI' => @$_SERVER['REQUEST_URI'],
));
}
else
{
/** @var \cmdbAbstractObject $oObj */
$oObj = MetaModel::NewObject($sClass);
$sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
if (!empty($sStateAttCode))
{
$sTargetState = utils::ReadPostedParam('obj_state', '');
if ($sTargetState != '')
{
$sOrigState = utils::ReadPostedParam('obj_state_orig', '');
if ($sTargetState != $sOrigState)
{
$aWarnings[] = Dict::S('UI:StateChanged');
}
$oObj->Set($sStateAttCode, $sTargetState);
}
}
$aErrors = $oObj->UpdateObjectFromPostedForm();
}
if (isset($oObj) && is_object($oObj))
{
$sClass = get_class($oObj);
$sClassLabel = MetaModel::GetName($sClass);
try
{
if (!empty($aErrors) || !empty($aWarnings))
{
IssueLog::Trace('Object not created (see $aErrors)', $sClass, array(
'$operation' => $operation,
'$sTransactionId' => $sTransactionId,
'$aErrors' => $aErrors,
'$sUser' => UserRights::GetUser(),
'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'],
'REQUEST_URI' => @$_SERVER['REQUEST_URI'],
));
throw new CoreCannotSaveObjectException(array('id' => $oObj->GetKey(), 'class' => $sClass, 'issues' => $aErrors));
}
$oObj->CheckChangedExtKeysValues();
$oObj->DBInsertNoReload();// No need to reload
IssueLog::Trace('Object created', $sClass, array(
'$operation' => $operation,
'$id' => $oObj->GetKey(),
'$sTransactionId' => $sTransactionId,
'$aErrors' => $aErrors,
'$sUser' => UserRights::GetUser(),
'HTTP_REFERER' => @$_SERVER['HTTP_REFERER'],
'REQUEST_URI' => @$_SERVER['REQUEST_URI'],
));
utils::RemoveTransaction($sTransactionId);
$oP->set_title(Dict::S('UI:PageTitle:ObjectCreated'));
// Compute the name, by reloading the object, even if it disappeared from the silo
$oObj = MetaModel::GetObject($sClass, $oObj->GetKey(), true /* Must be found */, true /* Allow All Data*/);
$sName = $oObj->GetName();
$sMessage = Dict::Format('UI:Title:Object_Of_Class_Created', $sName, $sClassLabel);
$sNextAction = utils::ReadPostedParam('next_action', '');
if (!empty($sNextAction))
{
$oP->add("
$sMessage
");
try
{
ApplyNextAction($oP, $oObj, $sNextAction);
}
catch (ApplicationException $e)
{
$sMessage = $e->getMessage();
$sSeverity = 'info';
ReloadAndDisplay($oP, $oObj, 'create', $sMessage, $sSeverity);
}
}
else
{
// Nothing more to do
ReloadAndDisplay($oP, $oObj, 'create', $sMessage, 'ok');
}
}
catch (CoreCannotSaveObjectException $e)
{
// Found issues, explain and give the user a second chance
//
$aIssues = $e->getIssues();
$sObjKey = $oObj->GetKey();
$sClassIcon = MetaModel::GetClassIcon($sClass);
$sHeaderTitle = Dict::Format('UI:CreationTitle_Class', $sClassLabel);
$oP->set_title(Dict::Format('UI:CreationPageTitle_Class', $sClassLabel));
$oP->add(<<
$sClassIcon $sHeaderTitle
HTML
);
if (!empty($aIssues))
{
$oP->AddHeaderMessage($e->getHtmlMessage(), 'message_error');
}
if (!empty($aWarnings))
{
$sWarnings = implode(', ', $aWarnings);
$oP->AddHeaderMessage($sWarnings, 'message_info');
}
cmdbAbstractObject::DisplayCreationForm($oP, $sClass, $oObj, [], ['transaction_id' => $sTransactionId]);
$oP->add(<<
HTML
);
}
}
break;
///////////////////////////////////////////////////////////////////////////////////////////
case 'select_bulk_stimulus': // Form displayed when applying a stimulus to many objects
$oP->DisableBreadCrumb();
$sFilter = utils::ReadParam('filter', '', false, 'raw_data');
$sStimulus = utils::ReadParam('stimulus', '');
$sState = utils::ReadParam('state', '');
if (empty($sFilter) || empty($sStimulus) || empty($sState))
{
throw new ApplicationException(Dict::Format('UI:Error:3ParametersMissing', 'filter', 'stimulus', 'state'));
}
$oFilter = DBObjectSearch::unserialize($sFilter);
$oFilter->UpdateContextFromUser();
$sClass = $oFilter->GetClass();
$aStimuli = MetaModel::EnumStimuli($sClass);
$sActionLabel = $aStimuli[$sStimulus]->GetLabel();
$sActionDetails = $aStimuli[$sStimulus]->GetDescription();
$oP->set_title($sActionLabel);
$oP->add('
');
$aExpectedAttributes = MetaModel::GetTransitionAttributes($sClass, $sStimulus, $sState);
$aDetails = array();
$sFormId = 'apply_stimulus';
$sFormPrefix = $sFormId.'_';
$iFieldIndex = 0;
$aFieldsMap = array();
$aValues = array();
$aObjects = array();
foreach($aSelectObject as $iId)
{
$aObjects[] = MetaModel::GetObject($sClass, $iId);
}
$oSet = DBObjectSet::FromArray($sClass, $aObjects);
$oObj = $oSet->ComputeCommonObject($aValues);
$sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
$oObj->Set($sStateAttCode,$sTargetState);
$sReadyScript = '';
foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
{
$sFieldInputId = $sFormPrefix.$sAttCode;
// Prompt for an attribute if
// - the attribute must be changed or must be displayed to the user for confirmation
// - or the field is mandatory and currently empty
if ( ($iExpectCode & (OPT_ATT_MUSTCHANGE | OPT_ATT_MUSTPROMPT)) ||
(($iExpectCode & OPT_ATT_MANDATORY) && ($oObj->Get($sAttCode) == '')) )
{
$aAttributesDef = MetaModel::ListAttributeDefs($sClass);
$oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
$aPrerequisites = MetaModel::GetPrerequisiteAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
if (count($aPrerequisites) > 0)
{
// When 'enabling' a field, all its prerequisites must be enabled too
$sFieldList = "['{$sFormPrefix}".implode("','{$sFormPrefix}", $aPrerequisites)."']";
$oP->add_ready_script("$('#enable_{$sFieldInputId}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, true); } );\n");
}
$aDependents = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
if (count($aDependents) > 0)
{
// When 'disabling' a field, all its dependent fields must be disabled too
$sFieldList = "['{$sFormPrefix}".implode("','{$sFormPrefix}", $aDependents)."']";
$oP->add_ready_script("$('#enable_{$sFieldInputId}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, false); } );\n");
}
$aArgs = array('this' => $oObj);
$sHTMLValue = cmdbAbstractObject::GetFormElementForField($oP, $sClass, $sAttCode, $oAttDef, $oObj->Get($sAttCode), $oObj->GetEditValue($sAttCode), $sFieldInputId, '', $iExpectCode, $aArgs);
$sComments = '';
if (!isset($aValues[$sAttCode]))
{
$aValues[$sAttCode] = array();
}
if (count($aValues[$sAttCode]) == 1)
{
$sComments .= '