本文整理汇总了PHP中MetaModel::NewObject方法的典型用法代码示例。如果您正苦于以下问题:PHP MetaModel::NewObject方法的具体用法?PHP MetaModel::NewObject怎么用?PHP MetaModel::NewObject使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类MetaModel
的用法示例。
在下文中一共展示了MetaModel::NewObject方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: SetPassword
/**
* 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);
}
示例2: DoCreateProfile
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;
}
示例3: CreateAdministrator
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', 'my.email@foo.org');
//$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;
}
示例4: DoExecute
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');
}
}
}
示例5: DoCreateRequest
/**
* 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) . "');");
}
}
示例6: CreateObject
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;
}
示例7: ajax_page
$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();
}
}
示例8: _CreateResponseTicket
/**
* 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;
}
示例9: AddToQueue
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();
}
示例10: ApplicationException
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();
示例11: SetupUser
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();
}
*/
}
示例12: LoadFile
/**
* 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;
}
示例13: RecordAttChanges
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();
}
//.........这里部分代码省略.........
示例14: LoadValues
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;
}
示例15: GetFormRow
/**
* 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});
//.........这里部分代码省略.........