/** * Use with care! */ public function SetPassword($sNewPassword) { $this->Set('password', $sNewPassword); $oChange = MetaModel::NewObject("CMDBChange"); $oChange->Set("date", time()); $sUserString = CMDBChange::GetCurrentUserName(); $oChange->Set("userinfo", $sUserString); $oChange->DBInsert(); $this->DBUpdateTracked($oChange, true); }
public static function DoCreateProfile($sName, $sDescription) { if (is_null(self::$m_aCacheProfiles)) { self::$m_aCacheProfiles = array(); $oFilterAll = new DBObjectSearch('URP_Profiles'); $oSet = new DBObjectSet($oFilterAll); while ($oProfile = $oSet->Fetch()) { self::$m_aCacheProfiles[$oProfile->Get('name')] = $oProfile->GetKey(); } } $sCacheKey = $sName; if (isset(self::$m_aCacheProfiles[$sCacheKey])) { return self::$m_aCacheProfiles[$sCacheKey]; } $oNewObj = MetaModel::NewObject("URP_Profiles"); $oNewObj->Set('name', $sName); $oNewObj->Set('description', $sDescription); $iId = $oNewObj->DBInsertNoReload(); self::$m_aCacheProfiles[$sCacheKey] = $iId; return $iId; }
public function CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage = 'EN US') { // Create a change to record the history of the User object $oChange = MetaModel::NewObject("CMDBChange"); $oChange->Set("date", time()); $oChange->Set("userinfo", "Initialization"); $iChangeId = $oChange->DBInsert(); $oOrg = new Organization(); $oOrg->Set('name', 'My Company/Department'); $oOrg->Set('code', 'SOMECODE'); // $oOrg->Set('status', 'implementation'); //$oOrg->Set('parent_id', xxx); $iOrgId = $oOrg->DBInsertTrackedNoReload($oChange, true); // Location : optional //$oLocation = new bizLocation(); //$oLocation->Set('name', 'MyOffice'); //$oLocation->Set('status', 'implementation'); //$oLocation->Set('org_id', $iOrgId); //$oLocation->Set('severity', 'high'); //$oLocation->Set('address', 'my building in my city'); //$oLocation->Set('country', 'my country'); //$oLocation->Set('parent_location_id', xxx); //$iLocationId = $oLocation->DBInsertNoReload(); $oContact = new Person(); $oContact->Set('name', 'My last name'); $oContact->Set('first_name', 'My first name'); //$oContact->Set('status', 'available'); $oContact->Set('org_id', $iOrgId); $oContact->Set('email', '*****@*****.**'); //$oContact->Set('phone', ''); //$oContact->Set('location_id', $iLocationId); //$oContact->Set('employee_number', ''); $iContactId = $oContact->DBInsertTrackedNoReload($oChange, true); $oUser = new UserLocal(); $oUser->Set('login', $sAdminUser); $oUser->Set('password', $sAdminPwd); $oUser->Set('contactid', $iContactId); $oUser->Set('language', $sLanguage); // Language was chosen during the installation $iUserId = $oUser->DBInsertTrackedNoReload($oChange, true); // Add this user to the very specific 'admin' profile $oUserProfile = new URP_UserProfile(); $oUserProfile->Set('userid', $iUserId); $oUserProfile->Set('profileid', ADMIN_PROFILE_ID); $oUserProfile->Set('reason', 'By definition, the administrator must have the administrator profile'); $oUserProfile->DBInsertTrackedNoReload($oChange, true); return true; }
protected function DoExecute() { CMDBSource::Query('START TRANSACTION'); //CMDBSource::Query('ROLLBACK'); automatique ! //////////////////////////////////////////////////////////////////////////////// // Set the stage // $oProvider = new Organization(); $oProvider->Set('name', 'Test-Provider1'); $oProvider->DBInsert(); $iProvider = $oProvider->GetKey(); $oDM1 = new DeliveryModel(); $oDM1->Set('name', 'Test-DM-1'); $oDM1->Set('org_id', $iProvider); $oDM1->DBInsert(); $iDM1 = $oDM1->GetKey(); $oDM2 = new DeliveryModel(); $oDM2->Set('name', 'Test-DM-2'); $oDM2->Set('org_id', $iProvider); $oDM2->DBInsert(); $iDM2 = $oDM2->GetKey(); //////////////////////////////////////////////////////////////////////////////// // Scenarii // $aScenarii = array(array('description' => 'Add the first customer', 'organizations' => array(array('deliverymodel_id' => $iDM1, 'name' => 'Test-Customer-1')), 'expected-res' => array("Test-Customer-1, , active, 0, , {$iDM1}, Test-DM-1, , Test-DM-1"), 'history_added' => 0, 'history_removed' => 0, 'history_modified' => 0), array('description' => 'Remove the customer by loading an empty set', 'organizations' => array(), 'expected-res' => array(), 'history_added' => 0, 'history_removed' => 0, 'history_modified' => 0), array('description' => 'Create two customers at once', 'organizations' => array(array('deliverymodel_id' => $iDM1, 'name' => 'Test-Customer-1'), array('deliverymodel_id' => $iDM1, 'name' => 'Test-Customer-2')), 'expected-res' => array("Test-Customer-1, , active, 0, , {$iDM1}, Test-DM-1, , Test-DM-1", "Test-Customer-2, , active, 0, , {$iDM1}, Test-DM-1, , Test-DM-1"), 'history_added' => 0, 'history_removed' => 0, 'history_modified' => 0), array('description' => 'Move Customer-1 to the second Delivery Model', 'organizations' => array(array('id' => "SELECT Organization WHERE name='Test-Customer-1'", 'deliverymodel_id' => $iDM2, 'name' => 'Test-Customer-1'), array('deliverymodel_id' => $iDM1, 'name' => 'Test-Customer-2')), 'expected-res' => array("Test-Customer-2, , active, 0, , {$iDM1}, Test-DM-1, , Test-DM-1"), 'history_added' => 0, 'history_removed' => 0, 'history_modified' => 0), array('description' => 'Move Customer-1 back to the first Delivery Model and reset Customer-2 (no Delivery Model)', 'organizations' => array(array('id' => "SELECT Organization WHERE name='Test-Customer-1'", 'deliverymodel_id' => $iDM1, 'name' => 'Test-Customer-1'), array('id' => "SELECT Organization WHERE name='Test-Customer-2'", 'deliverymodel_id' => 0, 'name' => 'Test-Customer-2')), 'expected-res' => array("Test-Customer-1, , active, 0, , {$iDM1}, Test-DM-1, , Test-DM-1"), 'history_added' => 0, 'history_removed' => 0, 'history_modified' => 0)); foreach ($aScenarii as $aScenario) { echo "<h4>" . $aScenario['description'] . "</h4>\n"; $oChange = MetaModel::NewObject("CMDBChange"); $oChange->Set("date", time()); $oChange->Set("userinfo", CMDBChange::GetCurrentUserName()); $oChange->Set("origin", 'custom-extension'); $oChange->DBInsert(); CMDBObject::SetCurrentChange($oChange); $iChange = $oChange->GetKey(); // Prepare set $oLinkset = DBObjectSet::FromScratch('Organization'); foreach ($aScenario['organizations'] as $aOrgData) { if (array_key_exists('id', $aOrgData)) { $sOQL = $aOrgData['id']; $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL)); $oOrg = $oSet->Fetch(); if (!is_object($oOrg)) { throw new Exception('Failed to find the Organization: ' . $sOQL); } } else { $oOrg = MetaModel::NewObject('Organization'); } foreach ($aOrgData as $sAttCode => $value) { if ($sAttCode == 'id') { continue; } $oOrg->Set($sAttCode, $value); } $oLinkset->AddObject($oOrg); } // Write $oDM = MetaModel::GetObject('DeliveryModel', $iDM1); $oDM->Set('customers_list', $oLinkset); $oDM->DBWrite(); // Check Results $bFoundIssue = false; $oDM = MetaModel::GetObject('DeliveryModel', $iDM1); $oLinkset = $oDM->Get('customers_list'); $aRes = $this->StandardizedDump($oLinkset, 'zzz'); $sRes = var_export($aRes, true); echo "Found: <pre>" . $sRes . "</pre>\n"; $sExpectedRes = var_export($aScenario['expected-res'], true); if ($sRes != $sExpectedRes) { $bFoundIssue = true; echo "NOT COMPLIANT!!! Expecting: <pre>" . $sExpectedRes . "</pre>\n"; } // Check History $aQueryParams = array('change' => $iChange, 'objclass' => get_class($oDM), 'objkey' => $oDM->GetKey()); $oAdded = new DBObjectSet(DBSearch::FromOQL("SELECT CMDBChangeOpSetAttributeLinksAddRemove WHERE objclass = :objclass AND objkey = :objkey AND change = :change AND type = 'added'"), array(), $aQueryParams); echo "added: " . $oAdded->Count() . "<br/>\n"; if ($aScenario['history_added'] != $oAdded->Count()) { $bFoundIssue = true; echo "NOT COMPLIANT!!! Expecting: " . $aScenario['history_added'] . "<br/>\n"; } $oRemoved = new DBObjectSet(DBSearch::FromOQL("SELECT CMDBChangeOpSetAttributeLinksAddRemove WHERE objclass = :objclass AND objkey = :objkey AND change = :change AND type = 'removed'"), array(), $aQueryParams); echo "removed: " . $oRemoved->Count() . "<br/>\n"; if ($aScenario['history_removed'] != $oRemoved->Count()) { $bFoundIssue = true; echo "NOT COMPLIANT!!! Expecting: " . $aScenario['history_removed'] . "<br/>\n"; } $oModified = new DBObjectSet(DBSearch::FromOQL("SELECT CMDBChangeOpSetAttributeLinksTune WHERE objclass = :objclass AND objkey = :objkey AND change = :change"), array(), $aQueryParams); echo "modified: " . $oModified->Count() . "<br/>\n"; if ($aScenario['history_modified'] != $oModified->Count()) { $bFoundIssue = true; echo "NOT COMPLIANT!!! Expecting: " . $aScenario['history_modified'] . "<br/>\n"; } if ($bFoundIssue) { throw new Exception('Stopping on failed scenario'); } } }
/** * Validate the parameters and create the ticket object (based on the page's POSTed parameters) * @param WebPage $oP The current web page for the output * @param Organization $oUserOrg The organization of the current user * @return void */ function DoCreateRequest($oP, $oUserOrg) { $aParameters = $oP->ReadAllParams(PORTAL_ALL_PARAMS . ',template_id'); $sTransactionId = utils::ReadPostedParam('transaction_id', ''); if (!utils::IsTransactionValid($sTransactionId)) { $oP->add("<h1>" . Dict::S('UI:Error:ObjectAlreadyCreated') . "</h1>\n"); //ShowOngoingTickets($oP); return; } // Validate the parameters // 1) ServiceCategory $oSearch = DBObjectSearch::FromOQL(PORTAL_VALIDATE_SERVICECATEGORY_QUERY); $oSearch->AllowAllData(); // In case the user has the rights on his org only $oSet = new CMDBObjectSet($oSearch, array(), array('id' => $aParameters['service_id'], 'org_id' => $oUserOrg->GetKey())); if ($oSet->Count() != 1) { // Invalid service for the current user ! throw new Exception("Invalid Service Category: id={$aParameters['service_id']} - count: " . $oSet->Count()); } $oServiceCategory = $oSet->Fetch(); // 2) Service Subcategory $oSearch = DBObjectSearch::FromOQL(PORTAL_VALIDATE_SERVICESUBCATEGORY_QUERY); RestrictSubcategories($oSearch); $oSearch->AllowAllData(); // In case the user has the rights on his org only $oSet = new CMDBObjectSet($oSearch, array(), array('service_id' => $aParameters['service_id'], 'id' => $aParameters['servicesubcategory_id'], 'org_id' => $oUserOrg->GetKey())); if ($oSet->Count() != 1) { // Invalid subcategory throw new Exception("Invalid ServiceSubcategory: id={$aParameters['servicesubcategory_id']} for service category " . $oServiceCategory->GetName() . "({$aParameters['service_id']}) - count: " . $oSet->Count()); } $oServiceSubCategory = $oSet->Fetch(); $sClass = ComputeClass($oServiceSubCategory->GetKey()); $oRequest = MetaModel::NewObject($sClass); $aAttList = array_merge(explode(',', GetConstant($sClass, 'FORM_ATTRIBUTES')), array('service_id', 'servicesubcategory_id')); $oRequest->UpdateObjectFromPostedForm('', $aAttList); $oRequest->Set('org_id', $oUserOrg->GetKey()); $oRequest->Set('caller_id', UserRights::GetContactId()); if (isset($aParameters['moreinfo'])) { // There is a template, insert it into the description $sLogAttCode = GetConstant($sClass, 'PUBLIC_LOG'); $oRequest->Set($sLogAttCode, $aParameters['moreinfo']); } $sTypeAttCode = GetConstant($sClass, 'TYPE'); if ($sTypeAttCode != '' && PORTAL_SET_TYPE_FROM != '') { $oRequest->Set($sTypeAttCode, $oServiceSubCategory->Get(PORTAL_SET_TYPE_FROM)); } if (MetaModel::IsValidAttCode($sClass, 'origin')) { $oRequest->Set('origin', 'portal'); } $oAttPlugin = new AttachmentPlugIn(); $oAttPlugin->OnFormSubmit($oRequest); list($bRes, $aIssues) = $oRequest->CheckToWrite(); if ($bRes) { if (isset($aParameters['template_id'])) { $oTemplate = MetaModel::GetObject('Template', $aParameters['template_id']); $sLogAttCode = GetConstant($sClass, 'PUBLIC_LOG'); $oRequest->Set($sLogAttCode, $oTemplate->GetPostedValuesAsText($oRequest) . "\n"); $oRequest->DBInsertNoReload(); $oTemplate->RecordExtraDataFromPostedForm($oRequest); } else { $oRequest->DBInsertNoReload(); } $oP->add("<h1>" . Dict::Format('UI:Title:Object_Of_Class_Created', $oRequest->GetName(), MetaModel::GetName($sClass)) . "</h1>\n"); //DisplayObject($oP, $oRequest, $oUserOrg); ShowOngoingTickets($oP); } else { RequestCreationForm($oP, $oUserOrg); $sIssueDesc = Dict::Format('UI:ObjectCouldNotBeWritten', implode(', ', $aIssues)); $oP->add_ready_script("alert('" . addslashes($sIssueDesc) . "');"); } }
protected function CreateObject($sClass, $aData, $sClassDesc = '') { $mu_t1 = MyHelpers::getmicrotime(); $oMyObject = MetaModel::NewObject($sClass); foreach ($aData as $sProp => $value) { if (is_array($value)) { // transform into a link set $sCSVSpec = implode('|', $value); $oAttDef = MetaModel::GetAttributeDef($sClass, $sProp); $value = $oAttDef->MakeValueFromString($sCSVSpec, $bLocalizedValue = false, $sSepItem = '|', $sSepAttribute = ';', $sSepValue = ':', $sAttributeQualifier = '"'); } $oMyObject->Set($sProp, $value); } $iId = $oMyObject->DBInsertTrackedNoReload($this->m_oChange, true); $sClassId = "{$sClass} ({$sClassDesc})"; $this->m_aCreatedByDesc[$sClassId][] = $iId; $this->m_aCreatedByClass[$sClass][] = $iId; $mu_t2 = MyHelpers::getmicrotime(); $this->m_aStatsByClass[$sClass][] = $mu_t2 - $mu_t1; return $iId; }
$oPage = new ajax_page(""); $oPage->no_cache(); $sOperation = utils::ReadParam('operation', ''); switch ($sOperation) { case 'add': $aResult = array('error' => '', 'att_id' => 0, 'preview' => 'false', 'msg' => ''); $sObjClass = stripslashes(utils::ReadParam('obj_class', '', false, 'class')); $sTempId = utils::ReadParam('temp_id', ''); if (empty($sObjClass)) { $aResult['error'] = "Missing argument 'obj_class'"; } elseif (empty($sTempId)) { $aResult['error'] = "Missing argument 'temp_id'"; } else { try { $oDoc = utils::ReadPostedDocument('file'); $oAttachment = MetaModel::NewObject('Attachment'); $oAttachment->Set('expire', time() + 3600); // one hour... $oAttachment->Set('temp_id', $sTempId); $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(); } }
/** * Create an ResponseTicket (Incident or UserRequest) from an external system * Some CIs might be specified (by their name/IP) * * @param string sClass The class of the ticket: Incident or UserRequest * @param string sTitle * @param string sDescription * @param array aCallerDesc * @param array aCustomerDesc * @param array aServiceDesc * @param array aServiceSubcategoryDesc * @param string sProduct * @param array aWorkgroupDesc * @param array aImpactedCIs * @param string sImpact * @param string sUrgency * * @return WebServiceResult */ protected function _CreateResponseTicket($sClass, $sTitle, $sDescription, $aCallerDesc, $aCustomerDesc, $aServiceDesc, $aServiceSubcategoryDesc, $sProduct, $aWorkgroupDesc, $aImpactedCIs, $sImpact, $sUrgency) { $oRes = new WebServiceResult(); try { $oMyChange = MetaModel::NewObject("CMDBChange"); $oMyChange->Set("date", time()); $oMyChange->Set("userinfo", "Administrator"); $iChangeId = $oMyChange->DBInsertNoReload(); $oNewTicket = MetaModel::NewObject($sClass); $this->MyObjectSetScalar('title', 'title', $sTitle, $oNewTicket, $oRes); $this->MyObjectSetScalar('description', 'description', $sDescription, $oNewTicket, $oRes); $this->MyObjectSetExternalKey('org_id', 'customer', $aCustomerDesc, $oNewTicket, $oRes); $this->MyObjectSetExternalKey('caller_id', 'caller', $aCallerDesc, $oNewTicket, $oRes); $this->MyObjectSetExternalKey('service_id', 'service', $aServiceDesc, $oNewTicket, $oRes); if (!array_key_exists('service_id', $aServiceSubcategoryDesc)) { $aServiceSubcategoryDesc['service_id'] = $oNewTicket->Get('service_id'); } $this->MyObjectSetExternalKey('servicesubcategory_id', 'servicesubcategory', $aServiceSubcategoryDesc, $oNewTicket, $oRes); if (MetaModel::IsValidAttCode($sClass, 'product')) { // 1.x data models $this->MyObjectSetScalar('product', 'product', $sProduct, $oNewTicket, $oRes); } if (MetaModel::IsValidAttCode($sClass, 'workgroup_id')) { // 1.x data models $this->MyObjectSetExternalKey('workgroup_id', 'workgroup', $aWorkgroupDesc, $oNewTicket, $oRes); } else { if (MetaModel::IsValidAttCode($sClass, 'team_id')) { // 2.x data models $this->MyObjectSetExternalKey('team_id', 'workgroup', $aWorkgroupDesc, $oNewTicket, $oRes); } } if (MetaModel::IsValidAttCode($sClass, 'ci_list')) { // 1.x data models $aDevicesNotFound = $this->AddLinkedObjects('ci_list', 'impacted_cis', 'FunctionalCI', $aImpactedCIs, $oNewTicket, $oRes); } else { if (MetaModel::IsValidAttCode($sClass, 'functionalcis_list')) { // 2.x data models $aDevicesNotFound = $this->AddLinkedObjects('functionalcis_list', 'impacted_cis', 'FunctionalCI', $aImpactedCIs, $oNewTicket, $oRes); } } if (count($aDevicesNotFound) > 0) { $this->MyObjectSetScalar('description', 'n/a', $sDescription . ' - Related CIs: ' . implode(', ', $aDevicesNotFound), $oNewTicket, $oRes); } else { $this->MyObjectSetScalar('description', 'n/a', $sDescription, $oNewTicket, $oRes); } $this->MyObjectSetScalar('impact', 'impact', $sImpact, $oNewTicket, $oRes); $this->MyObjectSetScalar('urgency', 'urgency', $sUrgency, $oNewTicket, $oRes); $this->MyObjectInsert($oNewTicket, 'created', $oMyChange, $oRes); } catch (CoreException $e) { $oRes->LogError($e->getMessage()); } catch (Exception $e) { $oRes->LogError($e->getMessage()); } $this->LogUsage(__FUNCTION__, $oRes); return $oRes; }
public static function AddToQueue(EMail $oEMail, $oLog) { $oNew = MetaModel::NewObject(__CLASS__); if ($oLog) { $oNew->Set('event_id', $oLog->GetKey()); } $oNew->Set('to', $oEMail->GetRecipientTO(true)); $oNew->Set('subject', $oEMail->GetSubject()); // $oNew->Set('version', 1); // $sMessage = serialize($oEMail); $oNew->Set('version', 2); $sMessage = $oEMail->SerializeV2(); $oNew->Set('message', $sMessage); $oNew->DBInsert(); }
cmdbAbstractObject::DeleteObjects($oP, $sClass, $aObjects, $operation != 'bulk_delete_confirmed', 'bulk_delete_confirmed'); break; /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// case 'apply_new': // Creation of a new object $sClass = utils::ReadPostedParam('class', '', 'class'); $sClassLabel = MetaModel::GetName($sClass); $sTransactionId = utils::ReadPostedParam('transaction_id', ''); if (empty($sClass)) { throw new ApplicationException(Dict::Format('UI:Error:1ParametersMissing', 'class')); } if (!utils::IsTransactionValid($sTransactionId, false)) { $oP->p("<strong>" . Dict::S('UI:Error:ObjectAlreadyCreated') . "</strong>\n"); } else { $oObj = MetaModel::NewObject($sClass); $sStateAttCode = MetaModel::GetStateAttributeCode($sClass); if (!empty($sStateAttCode)) { $sTargetState = utils::ReadPostedParam('obj_state', ''); if ($sTargetState != '') { $oObj->Set($sStateAttCode, $sTargetState); } } $oObj->UpdateObjectFromPostedForm(); } if (isset($oObj) && is_object($oObj)) { $sClass = get_class($oObj); $sClassLabel = MetaModel::GetName($sClass); list($bRes, $aIssues) = $oObj->CheckToWrite(); if ($bRes) { $oObj->DBInsert();
protected function SetupUser($iUserId, $bNewUser = false) { foreach (array('bizmodel', 'application', 'gui', 'core/cmdb') as $sCategory) { foreach (MetaModel::GetClasses($sCategory) as $sClass) { foreach (self::$m_aActionCodes as $iActionCode => $sAction) { if ($bNewUser) { $bAddCell = true; } else { $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT UserRightsMatrixClassGrant WHERE class = '{$sClass}' AND action = '{$sAction}' AND userid = {$iUserId}")); $bAddCell = $oSet->Count() < 1; } if ($bAddCell) { // Create a new entry $oMyClassGrant = MetaModel::NewObject("UserRightsMatrixClassGrant"); $oMyClassGrant->Set("userid", $iUserId); $oMyClassGrant->Set("class", $sClass); $oMyClassGrant->Set("action", $sAction); $oMyClassGrant->Set("permission", "yes"); $iId = $oMyClassGrant->DBInsertNoReload(); } } foreach (MetaModel::EnumStimuli($sClass) as $sStimulusCode => $oStimulus) { if ($bNewUser) { $bAddCell = true; } else { $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT UserRightsMatrixClassStimulusGrant WHERE class = '{$sClass}' AND stimulus = '{$sStimulusCode}' AND userid = {$iUserId}")); $bAddCell = $oSet->Count() < 1; } if ($bAddCell) { // Create a new entry $oMyClassGrant = MetaModel::NewObject("UserRightsMatrixClassStimulusGrant"); $oMyClassGrant->Set("userid", $iUserId); $oMyClassGrant->Set("class", $sClass); $oMyClassGrant->Set("stimulus", $sStimulusCode); $oMyClassGrant->Set("permission", "yes"); $iId = $oMyClassGrant->DBInsertNoReload(); } } foreach (MetaModel::GetAttributesList($sClass) as $sAttCode) { if ($bNewUser) { $bAddCell = true; } else { $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT UserRightsMatrixAttributeGrant WHERE class = '{$sClass}' AND attcode = '{$sAttCode}' AND userid = {$iUserId}")); $bAddCell = $oSet->Count() < 1; } if ($bAddCell) { foreach (array('read', 'modify') as $sAction) { // Create a new entry $oMyAttGrant = MetaModel::NewObject("UserRightsMatrixAttributeGrant"); $oMyAttGrant->Set("userid", $iUserId); $oMyAttGrant->Set("class", $sClass); $oMyAttGrant->Set("attcode", $sAttCode); $oMyAttGrant->Set("action", $sAction); $oMyAttGrant->Set("permission", "yes"); $iId = $oMyAttGrant->DBInsertNoReload(); } } } } } /* // Create the "My Bookmarks" menu item (parent_id = 0, rank = 6) if ($bNewUser) { $bAddMenu = true; } else { $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT menuNode WHERE type = 'user' AND parent_id = 0 AND user_id = $iUserId")); $bAddMenu = ($oSet->Count() < 1); } if ($bAddMenu) { $oMenu = MetaModel::NewObject('menuNode'); $oMenu->Set('type', 'user'); $oMenu->Set('parent_id', 0); // It's a toplevel entry $oMenu->Set('rank', 6); // Located just above the Admin Tools section (=7) $oMenu->Set('name', 'My Bookmarks'); $oMenu->Set('label', 'My Favorite Items'); $oMenu->Set('hyperlink', 'UI.php'); $oMenu->Set('template', '<p></p><p></p><p style="text-align:center; font-family:Georgia, Times, serif; font-size:32px;">My bookmarks</p><p style="text-align:center; font-family:Georgia, Times, serif; font-size:14px;"><i>This section contains my most favorite search results</i></p>'); $oMenu->Set('user_id', $iUserId); $oMenu->DBInsert(); } */ }
/** * Helper function to load the objects from a standard XML file into the database * @param $sFilePath string The full path to the XML file to load * @param $bUpdateKeyCacheOnly bool Set to true to *just* update the keys cache but not reload the objects */ function LoadFile($sFilePath, $bUpdateKeyCacheOnly = false) { global $aKeys; $oXml = simplexml_load_file($sFilePath); $aReplicas = array(); foreach ($oXml as $sClass => $oXmlObj) { if (!MetaModel::IsValidClass($sClass)) { SetupPage::log_error("Unknown class - {$sClass}"); throw new Exception("Unknown class - {$sClass}"); } $iSrcId = (int) $oXmlObj['id']; // Mandatory to cast // Import algorithm // Here enumerate all the attributes of the object // for all attribute that is neither an external field // not an external key, assign it // Store all external keys for further reference // Create the object an store the correspondance between its newly created Id // and its original Id // Once all the objects have been created re-assign all the external keys to // their actual Ids $iExistingId = $this->GetObjectKey($sClass, $iSrcId); if ($iExistingId != 0) { $oTargetObj = MetaModel::GetObject($sClass, $iExistingId); } else { $oTargetObj = MetaModel::NewObject($sClass); } foreach ($oXmlObj as $sAttCode => $oSubNode) { if (!MetaModel::IsValidAttCode($sClass, $sAttCode)) { $sMsg = "Unknown attribute code - {$sClass}/{$sAttCode}"; continue; // ignore silently... //SetupPage::log_error($sMsg); //throw(new Exception($sMsg)); } $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode); if ($oAttDef->IsWritable() && $oAttDef->IsScalar()) { if ($oAttDef->IsExternalKey()) { if (substr(trim($oSubNode), 0, 6) == 'SELECT') { $sQuery = trim($oSubNode); $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sQuery)); $iMatches = $oSet->Count(); if ($iMatches == 1) { $oFoundObject = $oSet->Fetch(); $iExtKey = $oFoundObject->GetKey(); } else { $sMsg = "Ext key not reconcilied - {$sClass}/{$iSrcId} - {$sAttCode}: '" . $sQuery . "' - found {$iMatches} matche(s)"; SetupPage::log_error($sMsg); $this->m_aErrors[] = $sMsg; $iExtKey = 0; } } else { $iDstObj = (int) $oSubNode; // Attempt to find the object in the list of loaded objects $iExtKey = $this->GetObjectKey($oAttDef->GetTargetClass(), $iDstObj); if ($iExtKey == 0) { $iExtKey = -$iDstObj; // Convention: Unresolved keys are stored as negative ! $oTargetObj->RegisterAsDirty(); } // here we allow external keys to be invalid because we will resolve them later on... } //$oTargetObj->CheckValue($sAttCode, $iExtKey); $oTargetObj->Set($sAttCode, $iExtKey); } elseif ($oAttDef instanceof AttributeBlob) { $sMimeType = (string) $oSubNode->mimetype; $sFileName = (string) $oSubNode->filename; $data = base64_decode((string) $oSubNode->data); $oDoc = new ormDocument($data, $sMimeType, $sFileName); $oTargetObj->Set($sAttCode, $oDoc); } else { $value = (string) $oSubNode; if ($value == '') { $value = $oAttDef->GetNullValue(); } $res = $oTargetObj->CheckValue($sAttCode, $value); if ($res !== true) { // $res contains the error description $sMsg = "Value not allowed - {$sClass}/{$iSrcId} - {$sAttCode}: '" . $oSubNode . "' ; {$res}"; SetupPage::log_error($sMsg); $this->m_aErrors[] = $sMsg; } $oTargetObj->Set($sAttCode, $value); } } } $this->StoreObject($sClass, $oTargetObj, $iSrcId, $bUpdateKeyCacheOnly, $bUpdateKeyCacheOnly); } return true; }
protected function RecordAttChanges(array $aValues, array $aOrigValues) { parent::RecordAttChanges($aValues, $aOrigValues); // $aValues is an array of $sAttCode => $value // foreach ($aValues as $sAttCode => $value) { $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode); if ($oAttDef->IsExternalField()) { continue; } if ($oAttDef->IsLinkSet()) { continue; } if ($oAttDef->GetTrackingLevel() == ATTRIBUTE_TRACKING_NONE) { continue; } if (array_key_exists($sAttCode, $aOrigValues)) { $original = $aOrigValues[$sAttCode]; } else { $original = null; } if ($oAttDef instanceof AttributeOneWayPassword) { // One Way encrypted passwords' history is stored -one way- encrypted $oMyChangeOp = MetaModel::NewObject("CMDBChangeOpSetAttributeOneWayPassword"); $oMyChangeOp->Set("objclass", get_class($this)); $oMyChangeOp->Set("objkey", $this->GetKey()); $oMyChangeOp->Set("attcode", $sAttCode); if (is_null($original)) { $original = ''; } $oMyChangeOp->Set("prev_pwd", $original); $iId = $oMyChangeOp->DBInsertNoReload(); } elseif ($oAttDef instanceof AttributeEncryptedString) { // Encrypted string history is stored encrypted $oMyChangeOp = MetaModel::NewObject("CMDBChangeOpSetAttributeEncrypted"); $oMyChangeOp->Set("objclass", get_class($this)); $oMyChangeOp->Set("objkey", $this->GetKey()); $oMyChangeOp->Set("attcode", $sAttCode); if (is_null($original)) { $original = ''; } $oMyChangeOp->Set("prevstring", $original); $iId = $oMyChangeOp->DBInsertNoReload(); } elseif ($oAttDef instanceof AttributeBlob) { // Data blobs $oMyChangeOp = MetaModel::NewObject("CMDBChangeOpSetAttributeBlob"); $oMyChangeOp->Set("objclass", get_class($this)); $oMyChangeOp->Set("objkey", $this->GetKey()); $oMyChangeOp->Set("attcode", $sAttCode); if (is_null($original)) { $original = new ormDocument(); } $oMyChangeOp->Set("prevdata", $original); $iId = $oMyChangeOp->DBInsertNoReload(); } elseif ($oAttDef instanceof AttributeStopWatch) { // Stop watches - record changes for sub items only (they are visible, the rest is not visible) // if (is_null($original)) { $original = new OrmStopWatch(); } foreach ($oAttDef->ListSubItems() as $sSubItemAttCode => $oSubItemAttDef) { $item_value = $oSubItemAttDef->GetValue($value); $item_original = $oSubItemAttDef->GetValue($original); if ($item_value != $item_original) { $oMyChangeOp = MetaModel::NewObject("CMDBChangeOpSetAttributeScalar"); $oMyChangeOp->Set("objclass", get_class($this)); $oMyChangeOp->Set("objkey", $this->GetKey()); $oMyChangeOp->Set("attcode", $sSubItemAttCode); $oMyChangeOp->Set("oldvalue", $item_original); $oMyChangeOp->Set("newvalue", $item_value); $iId = $oMyChangeOp->DBInsertNoReload(); } } } elseif ($oAttDef instanceof AttributeCaseLog) { $oMyChangeOp = MetaModel::NewObject("CMDBChangeOpSetAttributeCaseLog"); $oMyChangeOp->Set("objclass", get_class($this)); $oMyChangeOp->Set("objkey", $this->GetKey()); $oMyChangeOp->Set("attcode", $sAttCode); $oMyChangeOp->Set("lastentry", $value->GetLatestEntryIndex()); $iId = $oMyChangeOp->DBInsertNoReload(); } elseif ($oAttDef instanceof AttributeLongText) { // Data blobs $oMyChangeOp = MetaModel::NewObject("CMDBChangeOpSetAttributeLongText"); $oMyChangeOp->Set("objclass", get_class($this)); $oMyChangeOp->Set("objkey", $this->GetKey()); $oMyChangeOp->Set("attcode", $sAttCode); if (!is_null($original) && $original instanceof ormCaseLog) { $original = $original->GetText(); } $oMyChangeOp->Set("prevdata", $original); $iId = $oMyChangeOp->DBInsertNoReload(); } elseif ($oAttDef instanceof AttributeText) { // Data blobs $oMyChangeOp = MetaModel::NewObject("CMDBChangeOpSetAttributeText"); $oMyChangeOp->Set("objclass", get_class($this)); $oMyChangeOp->Set("objkey", $this->GetKey()); $oMyChangeOp->Set("attcode", $sAttCode); if (!is_null($original) && $original instanceof ormCaseLog) { $original = $original->GetText(); } $oMyChangeOp->Set("prevdata", $original); $iId = $oMyChangeOp->DBInsertNoReload(); } elseif ($oAttDef instanceof AttributeBoolean) { $oMyChangeOp = MetaModel::NewObject("CMDBChangeOpSetAttributeScalar"); $oMyChangeOp->Set("objclass", get_class($this)); $oMyChangeOp->Set("objkey", $this->GetKey()); $oMyChangeOp->Set("attcode", $sAttCode); $oMyChangeOp->Set("oldvalue", $original ? 1 : 0); $oMyChangeOp->Set("newvalue", $value ? 1 : 0); $iId = $oMyChangeOp->DBInsertNoReload(); } elseif ($oAttDef instanceof AttributeHierarchicalKey) { // Hierarchical keys // $oMyChangeOp = MetaModel::NewObject("CMDBChangeOpSetAttributeScalar"); $oMyChangeOp->Set("objclass", get_class($this)); $oMyChangeOp->Set("objkey", $this->GetKey()); $oMyChangeOp->Set("attcode", $sAttCode); $oMyChangeOp->Set("oldvalue", $original); $oMyChangeOp->Set("newvalue", $value[$sAttCode]); $iId = $oMyChangeOp->DBInsertNoReload(); } else { // Scalars // $oMyChangeOp = MetaModel::NewObject("CMDBChangeOpSetAttributeScalar"); $oMyChangeOp->Set("objclass", get_class($this)); $oMyChangeOp->Set("objkey", $this->GetKey()); $oMyChangeOp->Set("attcode", $sAttCode); $oMyChangeOp->Set("oldvalue", $original); $oMyChangeOp->Set("newvalue", $value); $iId = $oMyChangeOp->DBInsertNoReload(); } } }
protected function LoadValues($aArgs) { $this->m_aValues = array(); if (!array_key_exists('this', $aArgs)) { throw new CoreException("Missing 'this' in arguments", array('args' => $aArgs)); } $oTarget = $aArgs['this->object()']; // Nodes from which we will start the search for neighbourhood $oNodes = DBObjectSet::FromLinkSet($oTarget, $this->m_sLinkSetAttCode, $this->m_sExtKeyToRemote); // Neighbours, whatever their class $aRelated = $oNodes->GetRelatedObjects($this->m_sRelationCode, $this->m_iMaxDepth); $sRootClass = MetaModel::GetRootClass($this->m_sTargetClass); if (array_key_exists($sRootClass, $aRelated)) { $aLinksToCreate = array(); foreach ($aRelated[$sRootClass] as $iKey => $oObject) { if (MetaModel::IsParentClass($this->m_sTargetClass, get_class($oObject))) { $oNewLink = MetaModel::NewObject($this->m_sTargetLinkClass); $oNewLink->Set($this->m_sTargetExtKey, $iKey); //$oNewLink->Set('role', 'concerned by an impacted CI'); $aLinksToCreate[] = $oNewLink; } } // #@# or AddObjectArray($aObjects) ? $oSetToCreate = DBObjectSet::FromArray($this->m_sTargetLinkClass, $aLinksToCreate); $this->m_aValues[$oObject->GetKey()] = $oObject->GetName(); } return true; }
/** * A one-row form for editing a link record * @param WebPage $oP Web page used for the ouput * @param DBObject $oLinkedObj The object to which all the elements of the linked set refer to * @param mixed $linkObjOrId Either the object linked or a unique number for new link records to add * @param Hash $aArgs Extra context arguments * @return string The HTML fragment of the one-row form */ protected function GetFormRow(WebPage $oP, DBObject $oLinkedObj, $linkObjOrId = null, $aArgs = array(), $oCurrentObj) { $sPrefix = "{$this->m_sAttCode}{$this->m_sNameSuffix}"; $aRow = array(); $aFieldsMap = array(); if (is_object($linkObjOrId) && !$linkObjOrId->IsNew()) { $key = $linkObjOrId->GetKey(); $iRemoteObjKey = $linkObjOrId->Get($this->m_sExtKeyToRemote); $sPrefix .= "[{$key}]["; $sNameSuffix = "]"; // To make a tabular form $aArgs['prefix'] = $sPrefix; $aArgs['wizHelper'] = "oWizardHelper{$this->m_iInputId}{$key}"; $aArgs['this'] = $linkObjOrId; $aRow['form::checkbox'] = "<input class=\"selection\" type=\"checkbox\" onClick=\"oWidget" . $this->m_iInputId . ".OnSelectChange();\" value=\"{$key}\">"; $aRow['form::checkbox'] .= "<input type=\"hidden\" name=\"attr_{$sPrefix}id{$sNameSuffix}\" value=\"{$key}\">"; foreach ($this->m_aEditableFields as $sFieldCode) { $sFieldId = $this->m_iInputId . '_' . $sFieldCode . '[' . $linkObjOrId->GetKey() . ']'; $sSafeId = utils::GetSafeId($sFieldId); $oAttDef = MetaModel::GetAttributeDef($this->m_sLinkedClass, $sFieldCode); $aRow[$sFieldCode] = cmdbAbstractObject::GetFormElementForField($oP, $this->m_sLinkedClass, $sFieldCode, $oAttDef, $linkObjOrId->Get($sFieldCode), '', $sSafeId, $sNameSuffix, 0, $aArgs); $aFieldsMap[$sFieldCode] = $sSafeId; } $sState = $linkObjOrId->GetState(); } else { // form for creating a new record if (is_object($linkObjOrId)) { // New link existing only in memory $oNewLinkObj = $linkObjOrId; $iRemoteObjKey = $oNewLinkObj->Get($this->m_sExtKeyToRemote); $oRemoteObj = MetaModel::GetObject($this->m_sRemoteClass, $iRemoteObjKey); $oNewLinkObj->Set($this->m_sExtKeyToMe, $oCurrentObj); // Setting the extkey with the object also fills the related external fields $linkObjOrId = -$iRemoteObjKey; } else { $iRemoteObjKey = -$linkObjOrId; $oNewLinkObj = MetaModel::NewObject($this->m_sLinkedClass); $oRemoteObj = MetaModel::GetObject($this->m_sRemoteClass, -$linkObjOrId); $oNewLinkObj->Set($this->m_sExtKeyToRemote, $oRemoteObj); // Setting the extkey with the object alsoo fills the related external fields $oNewLinkObj->Set($this->m_sExtKeyToMe, $oCurrentObj); // Setting the extkey with the object also fills the related external fields } $sPrefix .= "[{$linkObjOrId}]["; $sNameSuffix = "]"; // To make a tabular form $aArgs['prefix'] = $sPrefix; $aArgs['wizHelper'] = "oWizardHelper{$this->m_iInputId}_" . -$linkObjOrId; $aArgs['this'] = $oNewLinkObj; $aRow['form::checkbox'] = "<input class=\"selection\" type=\"checkbox\" onClick=\"oWidget" . $this->m_iInputId . ".OnSelectChange();\" value=\"{$linkObjOrId}\">"; $aRow['form::checkbox'] .= "<input type=\"hidden\" name=\"attr_{$sPrefix}id{$sNameSuffix}\" value=\"\">"; foreach ($this->m_aEditableFields as $sFieldCode) { $sFieldId = $this->m_iInputId . '_' . $sFieldCode . '[' . $linkObjOrId . ']'; $sSafeId = utils::GetSafeId($sFieldId); $oAttDef = MetaModel::GetAttributeDef($this->m_sLinkedClass, $sFieldCode); $aRow[$sFieldCode] = cmdbAbstractObject::GetFormElementForField($oP, $this->m_sLinkedClass, $sFieldCode, $oAttDef, $oNewLinkObj->Get($sFieldCode), '', $sSafeId, $sNameSuffix, 0, $aArgs); $aFieldsMap[$sFieldCode] = $sSafeId; } $sState = ''; $oP->add_script(<<<EOF \$(".date-pick").datepicker({ \t\tshowOn: 'button', \t\tbuttonImage: '../images/calendar.png', \t\tbuttonImageOnly: true, \t\tdateFormat: 'yy-mm-dd', \t\tconstrainInput: false, \t\tchangeMonth: true, \t\tchangeYear: true \t}); \$(".datetime-pick").datepicker({ \t\tshowOn: 'button', \t\tbuttonImage: '../images/calendar.png', \t\tbuttonImageOnly: true, \t\tdateFormat: 'yy-mm-dd 00:00:00', \t\tconstrainInput: false, \t\tchangeMonth: true, \t\tchangeYear: true }); EOF ); } $sExtKeyToMeId = utils::GetSafeId($sPrefix . $this->m_sExtKeyToMe); $aFieldsMap[$this->m_sExtKeyToMe] = $sExtKeyToMeId; $aRow['form::checkbox'] .= "<input type=\"hidden\" id=\"{$sExtKeyToMeId}\" value=\"" . $oCurrentObj->GetKey() . "\">"; $sExtKeyToRemoteId = utils::GetSafeId($sPrefix . $this->m_sExtKeyToRemote); $aFieldsMap[$this->m_sExtKeyToRemote] = $sExtKeyToRemoteId; $aRow['form::checkbox'] .= "<input type=\"hidden\" id=\"{$sExtKeyToRemoteId}\" value=\"{$iRemoteObjKey}\">"; $iFieldsCount = count($aFieldsMap); $sJsonFieldsMap = json_encode($aFieldsMap); $oP->add_script(<<<EOF var {$aArgs['wizHelper']} = new WizardHelper('{$this->m_sLinkedClass}', '', '{$sState}'); {$aArgs['wizHelper']}.SetFieldsMap({$sJsonFieldsMap}); {$aArgs['wizHelper']}.SetFieldsCount({$iFieldsCount}); EOF ); $aRow['static::key'] = $oLinkedObj->GetHyperLink(); foreach (MetaModel::GetZListItems($this->m_sRemoteClass, 'list') as $sFieldCode) { $aRow['static::' . $sFieldCode] = $oLinkedObj->GetAsHTML($sFieldCode); } return $aRow; }
protected static function SetProfilesFromCAS($oUser, $aGroups) { if (!MetaModel::IsValidClass('URP_Profiles')) { phpCAS::log("URP_Profiles is not a valid class. Automatic creation of Users is not supported in this context, sorry."); return false; } // read all the existing profiles $oProfilesSearch = new DBObjectSearch('URP_Profiles'); $oProfilesSet = new DBObjectSet($oProfilesSearch); $aAllProfiles = array(); while ($oProfile = $oProfilesSet->Fetch()) { $aAllProfiles[strtolower($oProfile->GetName())] = $oProfile->GetKey(); } // Translate the CAS/LDAP group names into iTop profile names $aProfiles = array(); $sPattern = MetaModel::GetConfig()->Get('cas_profile_pattern'); foreach ($aGroups as $sGroupName) { if (preg_match($sPattern, $sGroupName, $aMatches)) { if (array_key_exists(strtolower($aMatches[1]), $aAllProfiles)) { $aProfiles[] = $aAllProfiles[strtolower($aMatches[1])]; phpCAS::log("Info: Adding the profile '{$aMatches[1]}' from CAS."); } else { phpCAS::log("Warning: {$aMatches[1]} is not a valid iTop profile (extracted from group name: '{$sGroupName}'). Ignored."); } } else { phpCAS::log("Info: The CAS group '{$sGroupName}' does not seem to match an iTop pattern. Ignored."); } } if (count($aProfiles) == 0) { phpCAS::log("Info: The user '" . $oUser->GetName() . "' has no profiles retrieved from CAS. Default profile(s) will be used."); // Second attempt: check if there is/are valid default profile(s) $sCASDefaultProfiles = MetaModel::GetConfig()->Get('cas_default_profiles'); $aCASDefaultProfiles = explode(';', $sCASDefaultProfiles); foreach ($aCASDefaultProfiles as $sDefaultProfileName) { if (array_key_exists(strtolower($sDefaultProfileName), $aAllProfiles)) { $aProfiles[] = $aAllProfiles[strtolower($sDefaultProfileName)]; phpCAS::log("Info: Adding the default profile '" . $aAllProfiles[strtolower($sDefaultProfileName)] . "' from CAS."); } else { phpCAS::log("Warning: the default profile {$sDefaultProfileName} is not a valid iTop profile. Ignored."); } } if (count($aProfiles) == 0) { phpCAS::log("Error: The user '" . $oUser->GetName() . "' has no profiles in iTop, and therefore cannot be created."); return false; } } // Now synchronize the profiles $oProfilesSet = DBObjectSet::FromScratch('URP_UserProfile'); foreach ($aProfiles as $iProfileId) { $oLink = new URP_UserProfile(); $oLink->Set('profileid', $iProfileId); $oLink->Set('reason', 'CAS/LDAP Synchro'); $oProfilesSet->AddObject($oLink); } $oUser->Set('profile_list', $oProfilesSet); phpCAS::log("Info: the user '" . $oUser->GetName() . "' (id=" . $oUser->GetKey() . ") now has the following profiles: '" . implode("', '", $aProfiles) . "'."); if ($oUser->IsModified()) { $oMyChange = MetaModel::NewObject("CMDBChange"); $oMyChange->Set("date", time()); $oMyChange->Set("userinfo", 'CAS/LDAP Synchro'); $oMyChange->DBInsert(); if ($oUser->IsNew()) { $oUser->DBInsertTracked($oMyChange); } else { $oUser->DBUpdateTracked($oMyChange); } } return true; }
/** * Helper to form a value, given JSON decoded data * The operation is the opposite to GetForJSON */ public function FromJSONToValue($json) { $sTargetClass = $this->Get('linked_class'); $aLinks = array(); foreach ($json as $aValues) { if (isset($aValues['finalclass'])) { $sLinkClass = $aValues['finalclass']; if (!is_subclass_of($sLinkClass, $sTargetClass)) { throw new CoreException('Wrong class for link attribute specification', array('requested_class' => $sLinkClass, 'expected_class' => $sTargetClass)); } } elseif (MetaModel::IsAbstract($sTargetClass)) { throw new CoreException('Missing finalclass for link attribute specification'); } else { $sLinkClass = $sTargetClass; } $oLink = MetaModel::NewObject($sLinkClass); foreach ($aValues as $sAttCode => $sValue) { $oLink->Set($sAttCode, $sValue); } // Check (roughly) if such a link is valid $aErrors = array(); foreach (MetaModel::ListAttributeDefs($sTargetClass) as $sAttCode => $oAttDef) { if ($oAttDef->IsExternalKey()) { if ($oAttDef->GetTargetClass() == $this->GetHostClass() || is_subclass_of($this->GetHostClass(), $oAttDef->GetTargetClass())) { continue; // Don't check the key to self } } if ($oAttDef->IsWritable() && $oAttDef->IsNull($oLink->Get($sAttCode)) && !$oAttDef->IsNullAllowed()) { $aErrors[] = $sAttCode; } } if (count($aErrors) > 0) { throw new CoreException("Missing value for mandatory attribute(s): " . implode(', ', $aErrors)); } $aLinks[] = $oLink; } $oSet = DBObjectSet::FromArray($sTargetClass, $aLinks); return $oSet; }
public function MakeValueFromString($sProposedValue, $bLocalizedValue = false, $sSepItem = null, $sSepAttribute = null, $sSepValue = null, $sAttributeQualifier = null) { if (is_null($sSepItem) || empty($sSepItem)) { $sSepItem = MetaModel::GetConfig()->Get('link_set_item_separator'); } if (is_null($sSepAttribute) || empty($sSepAttribute)) { $sSepAttribute = MetaModel::GetConfig()->Get('link_set_attribute_separator'); } if (is_null($sSepValue) || empty($sSepValue)) { $sSepValue = MetaModel::GetConfig()->Get('link_set_value_separator'); } if (is_null($sAttributeQualifier) || empty($sAttributeQualifier)) { $sAttributeQualifier = MetaModel::GetConfig()->Get('link_set_attribute_qualifier'); } $sTargetClass = $this->Get('linked_class'); $sInput = str_replace($sSepItem, "\n", $sProposedValue); $oCSVParser = new CSVParser($sInput, $sSepAttribute, $sAttributeQualifier); $aInput = $oCSVParser->ToArray(0); $aLinks = array(); foreach ($aInput as $aRow) { // 1st - get the values, split the extkey->searchkey specs, and eventually get the finalclass value $aExtKeys = array(); $aValues = array(); foreach ($aRow as $sCell) { $iSepPos = strpos($sCell, $sSepValue); if ($iSepPos === false) { // Houston... throw new CoreException('Wrong format for link attribute specification', array('value' => $sCell)); } $sAttCode = trim(substr($sCell, 0, $iSepPos)); $sValue = substr($sCell, $iSepPos + strlen($sSepValue)); if (preg_match('/^(.+)->(.+)$/', $sAttCode, $aMatches)) { $sKeyAttCode = $aMatches[1]; $sRemoteAttCode = $aMatches[2]; $aExtKeys[$sKeyAttCode][$sRemoteAttCode] = $sValue; if (!MetaModel::IsValidAttCode($sTargetClass, $sKeyAttCode)) { throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sTargetClass, 'attcode' => $sKeyAttCode)); } $oKeyAttDef = MetaModel::GetAttributeDef($sTargetClass, $sKeyAttCode); $sRemoteClass = $oKeyAttDef->GetTargetClass(); if (!MetaModel::IsValidAttCode($sRemoteClass, $sRemoteAttCode)) { throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sRemoteClass, 'attcode' => $sRemoteAttCode)); } } else { if (!MetaModel::IsValidAttCode($sTargetClass, $sAttCode)) { throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sTargetClass, 'attcode' => $sAttCode)); } $aValues[$sAttCode] = $sValue; } } // 2nd - Instanciate the object and set the value if (isset($aValues['finalclass'])) { $sLinkClass = $aValues['finalclass']; if (!is_subclass_of($sLinkClass, $sTargetClass)) { throw new CoreException('Wrong class for link attribute specification', array('requested_class' => $sLinkClass, 'expected_class' => $sTargetClass)); } } elseif (MetaModel::IsAbstract($sTargetClass)) { throw new CoreException('Missing finalclass for link attribute specification'); } else { $sLinkClass = $sTargetClass; } $oLink = MetaModel::NewObject($sLinkClass); foreach ($aValues as $sAttCode => $sValue) { $oLink->Set($sAttCode, $sValue); } // 3rd - Set external keys from search conditions foreach ($aExtKeys as $sKeyAttCode => $aReconciliation) { $oKeyAttDef = MetaModel::GetAttributeDef($sTargetClass, $sKeyAttCode); $sKeyClass = $oKeyAttDef->GetTargetClass(); $oExtKeyFilter = new CMDBSearchFilter($sKeyClass); $aReconciliationDesc = array(); foreach ($aReconciliation as $sRemoteAttCode => $sValue) { $oExtKeyFilter->AddCondition($sRemoteAttCode, $sValue, '='); $aReconciliationDesc[] = "{$sRemoteAttCode}={$sValue}"; } $oExtKeySet = new CMDBObjectSet($oExtKeyFilter); switch ($oExtKeySet->Count()) { case 0: $sReconciliationDesc = implode(', ', $aReconciliationDesc); throw new CoreException("Found no match", array('ext_key' => $sKeyAttCode, 'reconciliation' => $sReconciliationDesc)); break; case 1: $oRemoteObj = $oExtKeySet->Fetch(); $oLink->Set($sKeyAttCode, $oRemoteObj->GetKey()); break; default: $sReconciliationDesc = implode(', ', $aReconciliationDesc); throw new CoreException("Found several matches", array('ext_key' => $sKeyAttCode, 'reconciliation' => $sReconciliationDesc)); // Found several matches, ambiguous } } // Check (roughly) if such a link is valid $aErrors = array(); foreach (MetaModel::ListAttributeDefs($sTargetClass) as $sAttCode => $oAttDef) { if ($oAttDef->IsExternalKey()) { if ($oAttDef->GetTargetClass() == $this->GetHostClass() || is_subclass_of($this->GetHostClass(), $oAttDef->GetTargetClass())) { continue; // Don't check the key to self } } if ($oAttDef->IsWritable() && $oAttDef->IsNull($oLink->Get($sAttCode)) && !$oAttDef->IsNullAllowed()) { $aErrors[] = $sAttCode; } } if (count($aErrors) > 0) { throw new CoreException("Missing value for mandatory attribute(s): " . implode(', ', $aErrors)); } $aLinks[] = $oLink; } $oSet = DBObjectSet::FromArray($sTargetClass, $aLinks); return $oSet; }
/** * Create the persistant information records, for the current synchronization * In fact, those records ARE defining what is the "current" synchronization */ protected function PrepareLogs() { if (!is_null($this->m_oChange)) { return; } // Create a change used for logging all the modifications/creations happening during the synchro $this->m_oChange = MetaModel::NewObject("CMDBChange"); $this->m_oChange->Set("date", time()); $sUserString = CMDBChange::GetCurrentUserName(); $this->m_oChange->Set("userinfo", $sUserString . ' ' . Dict::S('Core:SyncDataExchangeComment')); $this->m_oChange->Set("origin", 'synchro-data-source'); $iChangeId = $this->m_oChange->DBInsert(); // Start logging this execution (stats + protection against reentrance) // $this->m_oStatLog = new SynchroLog(); $this->m_oStatLog->Set('sync_source_id', $this->m_oDataSource->GetKey()); $this->m_oStatLog->Set('start_date', time()); $this->m_oStatLog->Set('status', 'running'); $this->m_oStatLog->Set('stats_nb_replica_seen', 0); $this->m_oStatLog->Set('stats_nb_replica_total', 0); $this->m_oStatLog->Set('stats_nb_obj_deleted', 0); $this->m_oStatLog->Set('stats_nb_obj_deleted_errors', 0); $this->m_oStatLog->Set('stats_nb_obj_obsoleted', 0); $this->m_oStatLog->Set('stats_nb_obj_obsoleted_errors', 0); $this->m_oStatLog->Set('stats_nb_obj_created', 0); $this->m_oStatLog->Set('stats_nb_obj_created_errors', 0); $this->m_oStatLog->Set('stats_nb_obj_created_warnings', 0); $this->m_oStatLog->Set('stats_nb_obj_updated', 0); $this->m_oStatLog->Set('stats_nb_obj_updated_warnings', 0); $this->m_oStatLog->Set('stats_nb_obj_updated_errors', 0); $this->m_oStatLog->Set('stats_nb_obj_unchanged_warnings', 0); // $this->m_oStatLog->Set('stats_nb_replica_reconciled', 0); $this->m_oStatLog->Set('stats_nb_replica_reconciled_errors', 0); $this->m_oStatLog->Set('stats_nb_replica_disappeared_no_action', 0); $this->m_oStatLog->Set('stats_nb_obj_new_updated', 0); $this->m_oStatLog->Set('stats_nb_obj_new_updated_warnings', 0); $this->m_oStatLog->Set('stats_nb_obj_new_unchanged', 0); $this->m_oStatLog->Set('stats_nb_obj_new_unchanged_warnings', 0); $sSelectTotal = "SELECT SynchroReplica WHERE sync_source_id = :source_id"; $oSetTotal = new DBObjectSet(DBObjectSearch::FromOQL($sSelectTotal), array(), array('source_id' => $this->m_oDataSource->GetKey())); $this->m_iCountAllReplicas = $oSetTotal->Count(); $this->m_oStatLog->Set('stats_nb_replica_total', $this->m_iCountAllReplicas); $this->m_oStatLog->DBInsertTracked($this->m_oChange); }
/** * Helper to link objects * * @param string sLinkAttCode * @param string sLinkedClass * @param array $aLinkList * @param DBObject oTargetObj * @param WebServiceResult oRes * * @return array List of objects that could not be found */ protected function AddLinkedObjects($sLinkAttCode, $sParamName, $sLinkedClass, $aLinkList, &$oTargetObj, &$oRes) { $oLinkAtt = MetaModel::GetAttributeDef(get_class($oTargetObj), $sLinkAttCode); $sLinkClass = $oLinkAtt->GetLinkedClass(); $sExtKeyToItem = $oLinkAtt->GetExtKeyToRemote(); $aItemsFound = array(); $aItemsNotFound = array(); if (is_null($aLinkList)) { return $aItemsNotFound; } foreach ($aLinkList as $aItemData) { if (!array_key_exists('class', $aItemData)) { $oRes->LogWarning("Parameter {$sParamName}: missing 'class' specification"); continue; // skip } $sTargetClass = $aItemData['class']; if (!MetaModel::IsValidClass($sTargetClass)) { $oRes->LogError("Parameter {$sParamName}: invalid class '{$sTargetClass}'"); continue; // skip } if (!MetaModel::IsParentClass($sLinkedClass, $sTargetClass)) { $oRes->LogError("Parameter {$sParamName}: '{$sTargetClass}' is not a child class of '{$sLinkedClass}'"); continue; // skip } $oReconFilter = new CMDBSearchFilter($sTargetClass); $aCIStringDesc = array(); foreach ($aItemData['search'] as $sAttCode => $value) { if (!MetaModel::IsValidFilterCode($sTargetClass, $sAttCode)) { $aCodes = array_keys(MetaModel::GetClassFilterDefs($sTargetClass)); $oRes->LogError("Parameter {$sParamName}: '{$sAttCode}' is not a valid filter code for class '{$sTargetClass}', expecting a value in {" . implode(', ', $aCodes) . "}"); continue 2; // skip the entire item } $aCIStringDesc[] = "{$sAttCode}: {$value}"; // The attribute is one of our reconciliation key $oReconFilter->AddCondition($sAttCode, $value, '='); } if (count($aCIStringDesc) == 1) { // take the last and unique value to describe the object $sItemDesc = $value; } else { // describe the object by the given keys $sItemDesc = $sTargetClass . '(' . implode('/', $aCIStringDesc) . ')'; } $oExtObjects = new CMDBObjectSet($oReconFilter); switch ($oExtObjects->Count()) { case 0: $oRes->LogWarning("Parameter {$sParamName}: object to link {$sLinkedClass} / {$sItemDesc} could not be found (searched: '" . $oReconFilter->ToOQL(true) . "')"); $aItemsNotFound[] = $sItemDesc; break; case 1: $aItemsFound[] = array('object' => $oExtObjects->Fetch(), 'link_values' => @$aItemData['link_values'], 'desc' => $sItemDesc); break; default: $oRes->LogWarning("Parameter {$sParamName}: Found " . $oExtObjects->Count() . " matches for item '{$sItemDesc}' (searched: '" . $oReconFilter->ToOQL(true) . "')"); $aItemsNotFound[] = $sItemDesc; } } if (count($aItemsFound) > 0) { $aLinks = array(); foreach ($aItemsFound as $aItemData) { $oLink = MetaModel::NewObject($sLinkClass); $oLink->Set($sExtKeyToItem, $aItemData['object']->GetKey()); foreach ($aItemData['link_values'] as $sKey => $value) { if (!MetaModel::IsValidAttCode($sLinkClass, $sKey)) { $oRes->LogWarning("Parameter {$sParamName}: Attaching item '" . $aItemData['desc'] . "', the attribute code '{$sKey}' is not valid ; check the class '{$sLinkClass}'"); } else { $oLink->Set($sKey, $value); } } $aLinks[] = $oLink; } $oImpactedInfraSet = DBObjectSet::FromArray($sLinkClass, $aLinks); $oTargetObj->Set($sLinkAttCode, $oImpactedInfraSet); } return $aItemsNotFound; }
/** * Get the form to create a new object of the 'target' class */ public function DoCreateObject($oPage) { $oObj = MetaModel::NewObject($this->sTargetClass); $aErrors = $oObj->UpdateObjectFromPostedForm($this->iId); if (count($aErrors) == 0) { $oObj->DBInsert(); return array('name' => $oObj->GetName(), 'id' => $oObj->GetKey()); } else { return array('name' => implode(' ', $aErrors), 'id' => 0); } }
*/ $sFileName = Utils::ReadParam('file', '', false, 'raw_data'); $oP = new WebPage("iTop - Backoffice data loader"); try { // Note: the data model must be loaded first $oDataLoader = new XMLDataLoader(); if (empty($sFileName)) { throw new Exception("Missing argument 'file'"); } if (!file_exists($sFileName)) { throw new Exception("File {$sFileName} does not exist"); } SetMemoryLimit($oP); // The XMLDataLoader constructor has initialized the DB, let's start a transaction CMDBSource::Query('START TRANSACTION'); $oChange = MetaModel::NewObject("CMDBChange"); $oChange->Set("date", time()); $oChange->Set("userinfo", "Initialization"); $iChangeId = $oChange->DBInsert(); $oP->p("Starting data load."); $oDataLoader->StartSession($oChange); $oDataLoader->LoadFile($sFileName); $oP->p("Ending data load session"); if ($oDataLoader->EndSession(true)) { $iCountCreated = $oDataLoader->GetCountCreated(); CMDBSource::Query('COMMIT'); $oP->p("Data successfully written into the DB: {$iCountCreated} objects created"); } else { CMDBSource::Query('ROLLBACK'); $oP->p("Some issues have been encountered, changes will not be recorded, please review the source data"); $aErrors = $oDataLoader->GetErrors();
// reloads the page, doing a GET even if we arrived via a POST } } break; case 'shortcut_list_dlg': $sOQL = utils::ReadParam('oql', '', false, 'raw_data'); $sTableSettings = utils::ReadParam('table_settings', '', false, 'raw_data'); ShortcutOQL::GetCreationDlgFromOQL($oPage, $sOQL, $sTableSettings); break; case 'shortcut_list_create': $oForm = ShortcutOQL::GetCreationForm(); $aValues = $oForm->ReadParams(); $oAppContext = new ApplicationContext(); $aContext = $oAppContext->GetAsHash(); $sContext = serialize($aContext); $oShortcut = MetaModel::NewObject("ShortcutOQL"); $oShortcut->Set('user_id', UserRights::GetUserId()); $oShortcut->Set("context", $sContext); $oShortcut->Set("name", $aValues['name']); $oShortcut->Set("oql", $aValues['oql']); $iAutoReload = (int) $aValues['auto_reload_sec']; if ($aValues['auto_reload'] && $iAutoReload > 0) { $oShortcut->Set("auto_reload_sec", max(5, $iAutoReload)); $oShortcut->Set("auto_reload", 'custom'); } $iId = $oShortcut->DBInsertNoReload(); $oShortcut->CloneTableSettings($aValues['table_settings']); // Add the menu node in the right place // // Mmmm... already done because the newly created menu is read from the DB // as soon as we invoke DisplayMenu
public function CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage = 'EN US') { // Create a change to record the history of the User object $oChange = MetaModel::NewObject("CMDBChange"); $oChange->Set("date", time()); $oChange->Set("userinfo", "Initialization"); $iChangeId = $oChange->DBInsert(); $iContactId = 0; // Support drastic data model changes: no organization class (or not writable)! if (MetaModel::IsValidClass('Organization') && !MetaModel::IsAbstract('Organization')) { $oOrg = new Organization(); $oOrg->Set('name', 'My Company/Department'); $oOrg->Set('code', 'SOMECODE'); $iOrgId = $oOrg->DBInsertTrackedNoReload($oChange, true); // Support drastic data model changes: no Person class (or not writable)! if (MetaModel::IsValidClass('Person') && !MetaModel::IsAbstract('Person')) { $oContact = new Person(); $oContact->Set('name', 'My last name'); $oContact->Set('first_name', 'My first name'); if (MetaModel::IsValidAttCode('Person', 'org_id')) { $oContact->Set('org_id', $iOrgId); } if (MetaModel::IsValidAttCode('Person', 'phone')) { $oContact->Set('phone', '+00 000 000 000'); } $oContact->Set('email', '*****@*****.**'); $iContactId = $oContact->DBInsertTrackedNoReload($oChange, true); } } $oUser = new UserLocal(); $oUser->Set('login', $sAdminUser); $oUser->Set('password', $sAdminPwd); if (MetaModel::IsValidAttCode('UserLocal', 'contactid') && $iContactId != 0) { $oUser->Set('contactid', $iContactId); } $oUser->Set('language', $sLanguage); // Language was chosen during the installation // Add this user to the very specific 'admin' profile $oAdminProfile = MetaModel::GetObjectFromOQL("SELECT URP_Profiles WHERE name = :name", array('name' => ADMIN_PROFILE_NAME), true); if (is_object($oAdminProfile)) { $oUserProfile = new URP_UserProfile(); //$oUserProfile->Set('userid', $iUserId); $oUserProfile->Set('profileid', $oAdminProfile->GetKey()); $oUserProfile->Set('reason', 'By definition, the administrator must have the administrator profile'); //$oUserProfile->DBInsertTrackedNoReload($oChange, true /* skip security */); $oSet = DBObjectSet::FromObject($oUserProfile); $oUser->Set('profile_list', $oSet); } $iUserId = $oUser->DBInsertTrackedNoReload($oChange, true); return true; }
private static function RecordHistory(CMDBChange $oChange, $oTargetObject, $sDescription) { $oMyChangeOp = MetaModel::NewObject("CMDBChangeOpPlugin"); $oMyChangeOp->Set("change", $oChange->GetKey()); $oMyChangeOp->Set("objclass", get_class($oTargetObject)); $oMyChangeOp->Set("objkey", $oTargetObject->GetKey()); $oMyChangeOp->Set("description", $sDescription); $iId = $oMyChangeOp->DBInsertNoReload(); }
/** * Common to the recording of link set changes (add/remove/modify) */ private function PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, $sChangeOpClass, $aOriginalValues = null) { if ($iLinkSetOwnerId <= 0) { return null; } if (!is_subclass_of($oLinkSet->GetHostClass(), 'CMDBObject')) { // The link set owner class does not keep track of its history return null; } // Determine the linked item class and id // if ($oLinkSet->IsIndirect()) { // The "item" is on the other end (N-N links) $sExtKeyToRemote = $oLinkSet->GetExtKeyToRemote(); $oExtKeyToRemote = MetaModel::GetAttributeDef(get_class($this), $sExtKeyToRemote); $sItemClass = $oExtKeyToRemote->GetTargetClass(); if ($aOriginalValues) { // Get the value from the original values $iItemId = $aOriginalValues[$sExtKeyToRemote]; } else { $iItemId = $this->Get($sExtKeyToRemote); } } else { // I am the "item" (1-N links) $sItemClass = get_class($this); $iItemId = $this->GetKey(); } // Get the remote object, to determine its exact class // Possible optimization: implement a tool in MetaModel, to get the final class of an object (not always querying + query reduced to a select on the root table! $oOwner = MetaModel::GetObject($oLinkSet->GetHostClass(), $iLinkSetOwnerId, false); if ($oOwner) { $sLinkSetOwnerClass = get_class($oOwner); $oMyChangeOp = MetaModel::NewObject($sChangeOpClass); $oMyChangeOp->Set("objclass", $sLinkSetOwnerClass); $oMyChangeOp->Set("objkey", $iLinkSetOwnerId); $oMyChangeOp->Set("attcode", $oLinkSet->GetCode()); $oMyChangeOp->Set("item_class", $sItemClass); $oMyChangeOp->Set("item_id", $iItemId); return $oMyChangeOp; } else { // Depending on the deletion order, it may happen that the id is already invalid... ignore return null; } }
/** * Updates the object from a flat array of values * @param string $aValues array of attcode => scalar or array (N-N links) * @return void */ public function UpdateObjectFromArray($aValues) { foreach ($aValues as $sAttCode => $value) { $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode); if ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect()) { $aLinks = $value; $sLinkedClass = $oAttDef->GetLinkedClass(); $sExtKeyToRemote = $oAttDef->GetExtKeyToRemote(); $sExtKeyToMe = $oAttDef->GetExtKeyToMe(); $oLinkedSet = DBObjectSet::FromScratch($sLinkedClass); if (is_array($aLinks)) { foreach ($aLinks as $id => $aData) { if (is_numeric($id)) { if ($id < 0) { // New link to be created, the opposite of the id (-$id) is the ID of the remote object $oLink = MetaModel::NewObject($sLinkedClass); $oLink->Set($sExtKeyToRemote, -$id); $oLink->Set($sExtKeyToMe, $this->GetKey()); } else { // Existing link, potentially to be updated... $oLink = MetaModel::GetObject($sLinkedClass, $id); } // Now populate the attributes foreach ($aData as $sName => $value) { if (MetaModel::IsValidAttCode($sLinkedClass, $sName)) { $oLinkAttDef = MetaModel::GetAttributeDef($sLinkedClass, $sName); if ($oLinkAttDef->IsWritable()) { $oLink->Set($sName, $value); } } } $oLinkedSet->AddObject($oLink); } } } $this->Set($sAttCode, $oLinkedSet); } elseif ($oAttDef->GetEditClass() == 'Document') { // There should be an uploaded file with the named attr_<attCode> $oDocument = $value['fcontents']; if (!$oDocument->IsEmpty()) { // A new file has been uploaded $this->Set($sAttCode, $oDocument); } } elseif ($oAttDef->GetEditClass() == 'One Way Password') { // Check if the password was typed/changed $aPwdData = $value; if (!is_null($aPwdData) && $aPwdData['changed']) { // The password has been changed or set $this->Set($sAttCode, $aPwdData['value']); } } elseif ($oAttDef->GetEditClass() == 'Duration') { $aDurationData = $value; if (!is_array($aDurationData)) { continue; } $iValue = ((24 * $aDurationData['d'] + $aDurationData['h']) * 60 + $aDurationData['m']) * 60 + $aDurationData['s']; $this->Set($sAttCode, $iValue); $previousValue = $this->Get($sAttCode); if ($previousValue !== $iValue) { $this->Set($sAttCode, $iValue); } } else { if ($oAttDef->GetEditClass() == 'LinkedSet' && !$oAttDef->IsIndirect() && ($oAttDef->GetEditMode() == LINKSET_EDITMODE_INPLACE || $oAttDef->GetEditMode() == LINKSET_EDITMODE_ADDREMOVE)) { $oLinkset = $this->Get($sAttCode); $sLinkedClass = $oLinkset->GetClass(); $aObjSet = array(); $oLinkset->Rewind(); $bModified = false; while ($oLink = $oLinkset->Fetch()) { if (in_array($oLink->GetKey(), $value['to_be_deleted'])) { // The link is to be deleted, don't copy it in the array $bModified = true; } else { if (!array_key_exists('to_be_removed', $value) || !in_array($oLink->GetKey(), $value['to_be_removed'])) { $aObjSet[] = $oLink; } } } if (array_key_exists('to_be_created', $value) && count($value['to_be_created']) > 0) { // Now handle the links to be created foreach ($value['to_be_created'] as $aData) { $sSubClass = $aData['class']; if ($sLinkedClass == $sSubClass || is_subclass_of($sSubClass, $sLinkedClass)) { $aObjData = $aData['data']; $oLink = new $sSubClass(); $oLink->UpdateObjectFromArray($aObjData); $aObjSet[] = $oLink; $bModified = true; } } } if (array_key_exists('to_be_added', $value) && count($value['to_be_added']) > 0) { // Now handle the links to be added by making the remote object point to self foreach ($value['to_be_added'] as $iObjKey) { $oLink = MetaModel::GetObject($sLinkedClass, $iObjKey, false); if ($oLink) { $aObjSet[] = $oLink; $bModified = true; } } } if (array_key_exists('to_be_removed', $value) && count($value['to_be_removed']) > 0) { // Now handle the links to be removed by making the remote object point to nothing // Keep them in the set (modified), DBWriteLinks will handle them foreach ($value['to_be_removed'] as $iObjKey) { $oLink = MetaModel::GetObject($sLinkedClass, $iObjKey, false); if ($oLink) { $sExtKeyToMe = $oAttDef->GetExtKeyToMe(); $oLink->Set($sExtKeyToMe, null); $aObjSet[] = $oLink; $bModified = true; } } } if ($bModified) { $oNewSet = DBObjectSet::FromArray($oLinkset->GetClass(), $aObjSet); $this->Set($sAttCode, $oNewSet); } } else { if (!is_null($value)) { $aAttributes[$sAttCode] = trim($value); $previousValue = $this->Get($sAttCode); if ($previousValue !== $aAttributes[$sAttCode]) { $this->Set($sAttCode, $aAttributes[$sAttCode]); } } } } } }
/** * Interpret a Rest/Json structure that defines attribute values, and build an object * * @param string $sClass Name of the class * @param array $aFields A hash of attribute code => value specification. * @return DBObject The newly created object * @throws Exception If the specification of the values is not valid * @api */ public static function MakeObjectFromFields($sClass, $aFields) { $oObject = MetaModel::NewObject($sClass); foreach ($aFields as $sAttCode => $value) { $realValue = static::MakeValue($sClass, $sAttCode, $value); try { $oObject->Set($sAttCode, $realValue); } catch (Exception $e) { throw new Exception("{$sAttCode}: " . $e->getMessage(), $e->getCode()); } } return $oObject; }
static function ParseJsonSet($oMe, $sLinkClass, $sExtKeyToMe, $sJsonSet) { $aSet = json_decode($sJsonSet, true); // true means hash array instead of object $oSet = CMDBObjectSet::FromScratch($sLinkClass); foreach ($aSet as $aLinkObj) { $oLink = MetaModel::NewObject($sLinkClass); foreach ($aLinkObj as $sAttCode => $value) { $oAttDef = MetaModel::GetAttributeDef($sLinkClass, $sAttCode); if ($oAttDef->IsExternalKey() && $value != '' && $value > 0) { // For external keys: load the target object so that external fields // get filled too $oTargetObj = MetaModel::GetObject($oAttDef->GetTargetClass(), $value); $oLink->Set($sAttCode, $oTargetObj); } $oLink->Set($sAttCode, $value); } $oLink->Set($sExtKeyToMe, $oMe->GetKey()); $oSet->AddObject($oLink); } return $oSet; }
public function UpdatePredefinedObjects() { // Constant classes (e.g. User profiles) // foreach (MetaModel::GetClasses() as $sClass) { $aPredefinedObjects = call_user_func(array($sClass, 'GetPredefinedObjects')); if ($aPredefinedObjects != null) { $this->log_info("{$sClass}::GetPredefinedObjects() returned " . count($aPredefinedObjects) . " elements."); // Create/Delete/Update objects of this class, // according to the given constant values // $aDBIds = array(); $oAll = new DBObjectSet(new DBObjectSearch($sClass)); while ($oObj = $oAll->Fetch()) { if (array_key_exists($oObj->GetKey(), $aPredefinedObjects)) { $aObjValues = $aPredefinedObjects[$oObj->GetKey()]; foreach ($aObjValues as $sAttCode => $value) { $oObj->Set($sAttCode, $value); } $oObj->DBUpdate(); $aDBIds[$oObj->GetKey()] = true; } else { $oObj->DBDelete(); } } foreach ($aPredefinedObjects as $iRefId => $aObjValues) { if (!array_key_exists($iRefId, $aDBIds)) { $oNewObj = MetaModel::NewObject($sClass); $oNewObj->SetKey($iRefId); foreach ($aObjValues as $sAttCode => $value) { $oNewObj->Set($sAttCode, $value); } $oNewObj->DBInsert(); } } } } }