本文整理汇总了PHP中DBObjectSet类的典型用法代码示例。如果您正苦于以下问题:PHP DBObjectSet类的具体用法?PHP DBObjectSet怎么用?PHP DBObjectSet使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DBObjectSet类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: ComputeSLT
/**
* Determines the shortest SLT, for this ticket, for the given metric. Returns null is no SLT was found
* @param string $sMetric Type of metric 'TTO', 'TTR', etc as defined in the SLT class
* @return hash Array with 'SLT' => name of the SLT selected, 'value' => duration in seconds of the SLT metric, null if no SLT applies to this ticket
*/
protected static function ComputeSLT($oTicket, $sMetric = 'TTO')
{
$iDeadline = null;
if (MetaModel::IsValidClass('SLT')) {
$sType = get_class($oTicket);
if ($sType == 'Incident') {
$sRequestType = 'incident';
} else {
$sRequestType = $oTicket->Get('request_type');
}
$aArgs = $oTicket->ToArgs();
$aArgs['metric'] = $sMetric;
$aArgs['request_type'] = $sRequestType;
//echo "<p>Managing:".$sMetric."-".$this->Get('request_type')."-".$this->Get('importance')."</p>\n";
$oSLTSet = new DBObjectSet(DBObjectSearch::FromOQL(RESPONSE_TICKET_SLT_QUERY), array(), $aArgs);
$iMinDuration = PHP_INT_MAX;
$sSLTName = '';
while ($oSLT = $oSLTSet->Fetch()) {
$iDuration = (int) $oSLT->Get('value');
$sUnit = $oSLT->Get('unit');
switch ($sUnit) {
case 'days':
$iDuration = $iDuration * 24;
// 24 hours in 1 days
// Fall though
// 24 hours in 1 days
// Fall though
case 'hours':
$iDuration = $iDuration * 60;
// 60 minutes in 1 hour
// Fall though
// 60 minutes in 1 hour
// Fall though
case 'minutes':
$iDuration = $iDuration * 60;
}
if ($iDuration < $iMinDuration) {
$iMinDuration = $iDuration;
$sSLTName = $oSLT->GetName();
}
}
if ($iMinDuration == PHP_INT_MAX) {
$iDeadline = null;
} else {
// Store $sSLTName to keep track of which SLT has been used
$iDeadline = $iMinDuration;
}
}
return $iDeadline;
}
示例2: AfterDatabaseCreation
public static function AfterDatabaseCreation(Config $oConfiguration, $sPreviousVersion, $sCurrentVersion)
{
// Delete all Triggers corresponding to a no more valid class
$oSearch = new DBObjectSearch('TriggerOnObject');
$oSet = new DBObjectSet($oSearch);
$oChange = null;
while ($oTrigger = $oSet->Fetch()) {
if (!MetaModel::IsValidClass($oTrigger->Get('target_class'))) {
if ($oChange == null) {
// Create the change for its first use
$oChange = new CMDBChange();
$oChange->Set("date", time());
$oChange->Set("userinfo", "Uninstallation");
$oChange->DBInsert();
}
$oTrigger->DBDeleteTracked($oChange);
}
}
}
示例3: CreateTicket
/**
* Create a User Request ticket from the basic information retrieved from an email
* @param string $sSenderEmail eMail address of the sender (From), used to lookup a contact in iTop
* @param string $sSubject eMail's subject, will be turned into the title of the ticket
* @param string $sBody Body of the email, will be fitted into the ticket's description
* @return UserRequest The created ticket, or null if the creation failed for some reason...
*/
function CreateTicket($sSenderEmail, $sSubject, $sBody)
{
$oTicket = null;
try {
$oContactSearch = new DBObjectSearch('Contact');
// Can be either a Person or a Team, but must be a valid Contact
$oContactSearch->AddCondition('email', $sSenderEmail, '=');
$oSet = new DBObjectSet($oContactSearch);
if ($oSet->Count() == 1) {
$oContact = $oSet->Fetch();
$oOrganization = MetaModel::GetObject('Organization', $oContact->Get('org_id'));
$oTicket = new UserRequest();
$oTicket->Set('title', $sSubject);
$oTicket->Set('description', $sBody);
$oTicket->Set('org_id', $oOrganization->GetKey());
$oTicket->Set('caller_id', $oContact->GetKey());
$oTicket->Set('impact', DEFAULT_IMPACT);
$oTicket->Set('urgency', DEFAULT_URGENCY);
$oTicket->Set('product', DEFAULT_PRODUCT);
$oTicket->Set('service_id', DEFAULT_SERVICE_ID);
// Can be replaced by a search for a valid service for this 'org_id'
$oTicket->Set('servicesubcategory_id', DEFAULT_SUBSERVICE_ID);
// Same as above...
$oTicket->Set('workgroup_id', DEFAULT_WORKGROUP_ID);
// Same as above...
// Record the change information about the object
$oMyChange = MetaModel::NewObject("CMDBChange");
$oMyChange->Set("date", time());
$sUserString = $oContact->GetName() . ', submitted by email';
$oMyChange->Set("userinfo", $sUserString);
$iChangeId = $oMyChange->DBInsert();
$oTicket->DBInsertTracked($oMyChange);
} else {
echo "No contact found in iTop having the email: {$sSenderEmail}, email message ignored.\n";
}
} catch (Exception $e) {
echo "Error: exception " . $e->getMessage();
$oTicket = null;
}
return $oTicket;
}
示例4: Process
public function Process($iTimeLimit)
{
$oMyChange = new CMDBChange();
$oMyChange->Set("date", time());
$oMyChange->Set("userinfo", "Automatic updates");
$iChangeId = $oMyChange->DBInsertNoReload();
$aReport = array();
$oSet = new DBObjectSet(DBObjectSearch::FromOQL('SELECT ResponseTicket WHERE status = \'new\' AND tto_escalation_deadline <= NOW()'));
while (time() < $iTimeLimit && ($oToEscalate = $oSet->Fetch())) {
$oToEscalate->ApplyStimulus('ev_timeout');
//$oToEscalate->Set('tto_escalation_deadline', null);
$oToEscalate->DBUpdateTracked($oMyChange, true);
$aReport['reached TTO ESCALATION deadline'][] = $oToEscalate->Get('ref');
}
$oSet = new DBObjectSet(DBObjectSearch::FromOQL('SELECT ResponseTicket WHERE status = \'assigned\' AND ttr_escalation_deadline <= NOW()'));
while (time() < $iTimeLimit && ($oToEscalate = $oSet->Fetch())) {
$oToEscalate->ApplyStimulus('ev_timeout');
//$oToEscalate->Set('ttr_escalation_deadline', null);
$oToEscalate->DBUpdateTracked($oMyChange, true);
$aReport['reached TTR ESCALATION deadline'][] = $oToEscalate->Get('ref');
}
$oSet = new DBObjectSet(DBObjectSearch::FromOQL('SELECT ResponseTicket WHERE status = \'resolved\' AND closure_deadline <= NOW()'));
while (time() < $iTimeLimit && ($oToEscalate = $oSet->Fetch())) {
$oToEscalate->ApplyStimulus('ev_close');
//$oToEscalate->Set('closure_deadline', null);
$oToEscalate->DBUpdateTracked($oMyChange, true);
$aReport['reached closure deadline'][] = $oToEscalate->Get('ref');
}
$aStringReport = array();
foreach ($aReport as $sOperation => $aTicketRefs) {
if (count($aTicketRefs) > 0) {
$aStringReport[] = $sOperation . ': ' . count($aTicketRefs) . ' {' . implode(', ', $aTicketRefs) . '}';
}
}
if (count($aStringReport) == 0) {
return "No ticket to process";
} else {
return "Some tickets reached the limit - " . implode('; ', $aStringReport);
}
}
示例5: AfterDatabaseCreation
/**
* Handler called after the creation/update of the database schema
* @param $oConfiguration Config The new configuration of the application
* @param $sPreviousVersion string PRevious version number of the module (empty string in case of first install)
* @param $sCurrentVersion string Current version number of the module
*/
public static function AfterDatabaseCreation(Config $oConfiguration, $sPreviousVersion, $sCurrentVersion)
{
// For each record having item_org_id unset,
// get the org_id from the container object
//
// Prerequisite: change null into 0 (workaround to the fact that we cannot use IS NULL in OQL)
SetupPage::log_info("Initializing attachment/item_org_id - null to zero");
$sTableName = MetaModel::DBGetTable('Attachment');
$sRepair = "UPDATE `{$sTableName}` SET `item_org_id` = 0 WHERE `item_org_id` IS NULL";
CMDBSource::Query($sRepair);
SetupPage::log_info("Initializing attachment/item_org_id - zero to the container");
$oSearch = DBObjectSearch::FromOQL("SELECT Attachment WHERE item_org_id = 0");
$oSet = new DBObjectSet($oSearch);
$iUpdated = 0;
while ($oAttachment = $oSet->Fetch()) {
$oContainer = MetaModel::GetObject($oAttachment->Get('item_class'), $oAttachment->Get('item_id'), false, true);
if ($oContainer) {
$oAttachment->SetItem($oContainer, true);
$iUpdated++;
}
}
SetupPage::log_info("Initializing attachment/item_org_id - {$iUpdated} records have been adjusted");
}
示例6: GetDescription
/**
* Describe (as a text string) the modifications corresponding to this change
*/
public function GetDescription()
{
// Temporary, until we change the options of GetDescription() -needs a more global revision
$bIsHtml = true;
$sResult = '';
$sTargetObjectClass = 'Attachment';
$iTargetObjectKey = $this->Get('attachment_id');
$sFilename = htmlentities($this->Get('filename'), ENT_QUOTES, 'UTF-8');
$oTargetSearch = new DBObjectSearch($sTargetObjectClass);
$oTargetSearch->AddCondition('id', $iTargetObjectKey, '=');
$oMonoObjectSet = new DBObjectSet($oTargetSearch);
if ($oMonoObjectSet->Count() > 0) {
$oAttachment = $oMonoObjectSet->Fetch();
$oDoc = $oAttachment->Get('contents');
$sPreview = $oDoc->IsPreviewAvailable() ? 'data-preview="true"' : '';
$sResult = Dict::Format('Attachments:History_File_Added', '<span class="attachment-history-added attachment"><a ' . $sPreview . ' target="_blank" href="' . $oDoc->GetDownloadURL($sTargetObjectClass, $iTargetObjectKey, 'contents') . '">' . $sFilename . '</a></span>');
} else {
$sResult = Dict::Format('Attachments:History_File_Added', '<span class="attachment-history-deleted">' . $sFilename . '</span>');
}
return $sResult;
}
示例7: PopulateChildMenus
public function PopulateChildMenus()
{
// Load user shortcuts in DB
//
$oBMSearch = new DBObjectSearch('Shortcut');
$oBMSearch->AddCondition('user_id', UserRights::GetUserId(), '=');
$oBMSet = new DBObjectSet($oBMSearch, array('friendlyname' => true));
// ascending on friendlyname
$fRank = 1;
while ($oShortcut = $oBMSet->Fetch()) {
$sName = $this->GetMenuId() . '_' . $oShortcut->GetKey();
$oShortcutMenu = new ShortcutMenuNode($sName, $oShortcut, $this->GetIndex(), $fRank++);
}
// Complete the tree
//
parent::PopulateChildMenus();
}
示例8: IsPowerUSer
/**
* Determine if the current user can be considered as being a portal power user
*/
function IsPowerUSer()
{
$iUserID = UserRights::GetUserId();
$sOQLprofile = "SELECT URP_Profiles AS p JOIN URP_UserProfile AS up ON up.profileid=p.id WHERE up.userid = :user AND p.name = :profile";
$oProfileSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQLprofile), array(), array('user' => $iUserID, 'profile' => PORTAL_POWER_USER_PROFILE));
$bRes = $oProfileSet->count() > 0;
return $bRes;
}
示例9: GetNextChunk
public function GetNextChunk(&$aStatus)
{
$sRetCode = 'run';
$iPercentage = 0;
$oSet = new DBObjectSet($this->oSearch);
$oSet->SetLimit($this->iChunkSize, $this->aStatusInfo['position']);
$this->OptimizeColumnLoad($oSet);
$iCount = 0;
$sData = '';
$iPreviousTimeLimit = ini_get('max_execution_time');
$iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
while ($aRow = $oSet->FetchAssoc()) {
set_time_limit($iLoopTimeLimit);
$aData = array();
foreach ($this->aStatusInfo['fields'] as $iCol => $aFieldSpec) {
$sAlias = $aFieldSpec['sAlias'];
$sAttCode = $aFieldSpec['sAttCode'];
$sField = '';
$oObj = $aRow[$sAlias];
if ($oObj != null) {
switch ($sAttCode) {
case 'id':
$sField = $oObj->GetKey();
break;
default:
$sField = $oObj->GetAsCSV($sAttCode, $this->aStatusInfo['separator'], $this->aStatusInfo['text_qualifier'], $this->bLocalizeOutput);
}
}
if ($this->aStatusInfo['charset'] != 'UTF-8') {
// Note: due to bugs in the glibc library it's safer to call iconv on the smallest possible string
// and thus to convert field by field and not the whole row or file at once (see ticket #991)
$aData[] = iconv('UTF-8', $this->aStatusInfo['charset'] . '//IGNORE//TRANSLIT', $sField);
} else {
$aData[] = $sField;
}
}
$sData .= implode($this->aStatusInfo['separator'], $aData) . "\n";
$iCount++;
}
set_time_limit($iPreviousTimeLimit);
$this->aStatusInfo['position'] += $this->iChunkSize;
if ($this->aStatusInfo['total'] == 0) {
$iPercentage = 100;
} else {
$iPercentage = floor(min(100.0, 100.0 * $this->aStatusInfo['position'] / $this->aStatusInfo['total']));
}
if ($iCount < $this->iChunkSize) {
$sRetCode = 'done';
}
$aStatus = array('code' => $sRetCode, 'message' => Dict::S('Core:BulkExport:RetrievingData'), 'percentage' => $iPercentage);
return $sData;
}
示例10: Process
public function Process($iTimeLimit)
{
$aList = array();
foreach (MetaModel::GetClasses() as $sClass) {
foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) {
if ($oAttDef instanceof AttributeStopWatch) {
foreach ($oAttDef->ListThresholds() as $iThreshold => $aThresholdData) {
$iPercent = $aThresholdData['percent'];
// could be different than the index !
$sNow = date('Y-m-d H:i:s');
$sExpression = "SELECT {$sClass} WHERE {$sAttCode}_laststart AND {$sAttCode}_{$iThreshold}_triggered = 0 AND {$sAttCode}_{$iThreshold}_deadline < '{$sNow}'";
$oFilter = DBObjectSearch::FromOQL($sExpression);
$oSet = new DBObjectSet($oFilter);
while (time() < $iTimeLimit && ($oObj = $oSet->Fetch())) {
$sClass = get_class($oObj);
$aList[] = $sClass . '::' . $oObj->GetKey() . ' ' . $sAttCode . ' ' . $iThreshold;
// Execute planned actions
//
foreach ($aThresholdData['actions'] as $aActionData) {
$sVerb = $aActionData['verb'];
$aParams = $aActionData['params'];
$aValues = array();
foreach ($aParams as $def) {
if (is_string($def)) {
// Old method (pre-2.1.0) non typed parameters
$aValues[] = $def;
} else {
$sParamType = array_key_exists('type', $def) ? $def['type'] : 'string';
switch ($sParamType) {
case 'int':
$value = (int) $def['value'];
break;
case 'float':
$value = (double) $def['value'];
break;
case 'bool':
$value = (bool) $def['value'];
break;
case 'reference':
$value = ${$def['value']};
break;
case 'string':
default:
$value = (string) $def['value'];
}
$aValues[] = $value;
}
}
$aCallSpec = array($oObj, $sVerb);
call_user_func_array($aCallSpec, $aValues);
}
// Mark the threshold as "triggered"
//
$oSW = $oObj->Get($sAttCode);
$oSW->MarkThresholdAsTriggered($iThreshold);
$oObj->Set($sAttCode, $oSW);
if ($oObj->IsModified()) {
CMDBObject::SetTrackInfo("Automatic - threshold triggered");
$oMyChange = CMDBObject::GetCurrentChange();
$oObj->DBUpdateTracked($oMyChange, true);
}
// Activate any existing trigger
//
$sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
$oTriggerSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnThresholdReached AS t WHERE t.target_class IN ('{$sClassList}') AND stop_watch_code=:stop_watch_code AND threshold_index = :threshold_index"), array(), array('stop_watch_code' => $sAttCode, 'threshold_index' => $iThreshold));
while ($oTrigger = $oTriggerSet->Fetch()) {
$oTrigger->DoActivate($oObj->ToArgs('this'));
}
}
}
}
}
}
$iProcessed = count($aList);
return "Triggered {$iProcessed} threshold(s):" . implode(", ", $aList);
}
示例11: DoUpdateObjectFromPostedForm
/**
* Updates the object form POSTED arguments, and writes it into the DB (applies a stimuli if requested)
* @param DBObject $oObj The object to update
* $param array $aAttList If set, this will limit the list of updated attributes
* @return void
*/
public function DoUpdateObjectFromPostedForm(DBObject $oObj, $aAttList = null)
{
$sTransactionId = utils::ReadPostedParam('transaction_id', '');
if (!utils::IsTransactionValid($sTransactionId)) {
throw new TransactionException();
}
$sClass = get_class($oObj);
$sStimulus = trim(utils::ReadPostedParam('apply_stimulus', ''));
$sTargetState = '';
if (!empty($sStimulus)) {
// Compute the target state
$aTransitions = $oObj->EnumTransitions();
if (!isset($aTransitions[$sStimulus])) {
throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
}
$sTargetState = $aTransitions[$sStimulus]['target_state'];
}
$oObj->UpdateObjectFromPostedForm('', $aAttList, $sTargetState);
// Optional: apply a stimulus
//
if (!empty($sStimulus)) {
if (!$oObj->ApplyStimulus($sStimulus)) {
throw new Exception("Cannot apply stimulus '{$sStimulus}' to {$oObj->GetName()}");
}
}
if ($oObj->IsModified()) {
// Record the change
//
$oObj->DBUpdate();
// Trigger ?
//
$aClasses = MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL);
$sClassList = implode(", ", CMDBSource::Quote($aClasses));
$oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnPortalUpdate AS t WHERE t.target_class IN ({$sClassList})"));
while ($oTrigger = $oSet->Fetch()) {
$oTrigger->DoActivate($oObj->ToArgs('this'));
}
$this->p("<h1>" . Dict::Format('UI:Class_Object_Updated', MetaModel::GetName(get_class($oObj)), $oObj->GetName()) . "</h1>\n");
}
$bLockEnabled = MetaModel::GetConfig()->Get('concurrent_lock_enabled');
if ($bLockEnabled) {
// Release the concurrent lock, if any
$sOwnershipToken = utils::ReadPostedParam('ownership_token', null, false, 'raw_data');
if ($sOwnershipToken !== null) {
// We're done, let's release the lock
iTopOwnershipLock::ReleaseLock(get_class($oObj), $oObj->GetKey(), $sOwnershipToken);
}
}
}
示例12: UpdateAttachments
protected static function UpdateAttachments($oObject, $oChange = null)
{
self::$m_bIsModified = false;
if (utils::ReadParam('attachment_plugin', 'not-in-form') == 'not-in-form') {
// Workaround to an issue in iTop < 2.0
// Leave silently if there is no trace of the attachment form
return;
}
$iTransactionId = utils::ReadParam('transaction_id', null);
if (!is_null($iTransactionId)) {
$aActions = array();
$aAttachmentIds = utils::ReadParam('attachments', array());
// Get all current attachments
$oSearch = DBObjectSearch::FromOQL("SELECT Attachment WHERE item_class = :class AND item_id = :item_id");
$oSet = new DBObjectSet($oSearch, array(), array('class' => get_class($oObject), 'item_id' => $oObject->GetKey()));
while ($oAttachment = $oSet->Fetch()) {
// Remove attachments that are no longer attached to the current object
if (!in_array($oAttachment->GetKey(), $aAttachmentIds)) {
$oAttachment->DBDelete();
$aActions[] = self::GetActionDescription($oAttachment, false);
}
}
// Attach new (temporary) attachements
$sTempId = session_id() . '_' . $iTransactionId;
// The object is being created from a form, check if there are pending attachments
// for this object, but deleting the "new" ones that were already removed from the form
$aRemovedAttachmentIds = utils::ReadParam('removed_attachments', array());
$sOQL = 'SELECT Attachment WHERE temp_id = :temp_id';
$oSearch = DBObjectSearch::FromOQL($sOQL);
foreach ($aAttachmentIds as $iAttachmentId) {
$oSet = new DBObjectSet($oSearch, array(), array('temp_id' => $sTempId));
while ($oAttachment = $oSet->Fetch()) {
if (in_array($oAttachment->GetKey(), $aRemovedAttachmentIds)) {
$oAttachment->DBDelete();
// temporary attachment removed, don't even mention it in the history
} else {
$oAttachment->SetItem($oObject);
$oAttachment->Set('temp_id', '');
$oAttachment->DBUpdate();
// temporary attachment confirmed, list it in the history
$aActions[] = self::GetActionDescription($oAttachment, true);
}
}
}
if (count($aActions) > 0) {
if ($oChange == null) {
// Let's create a change if non is supplied
$oChange = MetaModel::NewObject("CMDBChange");
$oChange->Set("date", time());
$sUserString = CMDBChange::GetCurrentUserName();
$oChange->Set("userinfo", $sUserString);
$iChangeId = $oChange->DBInsert();
}
foreach ($aActions as $sActionDescription) {
self::RecordHistory($oChange, $oObject, $sActionDescription);
}
self::$m_bIsModified = true;
}
}
}
示例13: ComputeRedundancy
/**
* Determine if there is a redundancy (or use the existing one) and add the corresponding nodes/edges
*/
protected function ComputeRedundancy($sRelCode, $aQueryInfo, $oFromNode, $oToNode)
{
$oRedundancyNode = null;
$oObject = $oToNode->GetProperty('object');
if ($this->IsRedundancyEnabled($sRelCode, $aQueryInfo, $oToNode)) {
$sId = RelationRedundancyNode::MakeId($sRelCode, $aQueryInfo['sNeighbour'], $oToNode->GetProperty('object'));
$oRedundancyNode = $this->GetNode($sId);
if (is_null($oRedundancyNode)) {
// Get the upper neighbours
$sQuery = $aQueryInfo['sQueryUp'];
try {
$oFlt = DBObjectSearch::FromOQL($sQuery);
$oObjSet = new DBObjectSet($oFlt, array(), $oObject->ToArgsForQuery());
$iCount = $oObjSet->Count();
} catch (Exception $e) {
throw new Exception("Wrong query (upstream) for the relation {$sRelCode}/{$aQueryInfo['sDefinedInClass']}/{$aQueryInfo['sNeighbour']}: " . $e->getMessage());
}
$iMinUp = $this->GetRedundancyMinUp($sRelCode, $aQueryInfo, $oToNode, $iCount);
$fThreshold = max(0, $iCount - $iMinUp);
$oRedundancyNode = new RelationRedundancyNode($this, $sId, $iMinUp, $fThreshold);
new RelationEdge($this, $oRedundancyNode, $oToNode);
while ($oUpperObj = $oObjSet->Fetch()) {
$sObjectRef = RelationObjectNode::MakeId($oUpperObj);
$oUpperNode = $this->GetNode($sObjectRef);
if (is_null($oUpperNode)) {
$oUpperNode = new RelationObjectNode($this, $oUpperObj);
}
new RelationEdge($this, $oUpperNode, $oRedundancyNode);
}
}
}
return $oRedundancyNode;
}
示例14: DoJob3
/**
* Do the synchronization job #3: Delete replica depending on the obsolescence scheme
* @param integer $iMaxReplica Limit the number of replicas to process
* @param integer $iCurrPos Current position where to resume the processing
* @return true if the process must be continued
*/
protected function DoJob3($iMaxReplica = null, $iCurrPos = -1)
{
$sDeletePolicy = $this->m_oDataSource->Get('delete_policy');
if ($sDeletePolicy != 'update_then_delete') {
// Job complete!
$this->m_oStatLog->Set('status_curr_job', 0);
$this->m_oStatLog->Set('status_curr_pos', -1);
return false;
}
$bFirstPass = $iCurrPos == -1;
// Get all the replicas that are to be deleted
//
$oDeletionDate = $this->m_oLastFullLoadStartDate;
$iDeleteRetention = $this->m_oDataSource->Get('delete_policy_retention');
// Duration in seconds
if ($iDeleteRetention > 0) {
$sInterval = "-{$iDeleteRetention} seconds";
$oDeletionDate->Modify($sInterval);
}
$sDeletionDate = $oDeletionDate->Format('Y-m-d H:i:s');
if ($bFirstPass) {
$this->m_oStatLog->AddTrace("Deletion date: {$sDeletionDate}");
}
$sSelectToDelete = "SELECT SynchroReplica WHERE id > :curr_pos AND sync_source_id = :source_id AND status IN ('obsolete') AND status_last_seen < :last_import";
$oSetScope = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToDelete), array(), array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sDeletionDate, 'curr_pos' => $iCurrPos));
$iCountScope = $oSetScope->Count();
if ($iMaxReplica) {
// Consider a given subset, starting from replica iCurrPos, limited to the count of iMaxReplica
// The replica have to be ordered by id
$oSetToProcess = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToDelete), array('id' => true), array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sDeletionDate, 'curr_pos' => $iCurrPos));
$oSetToProcess->SetLimit($iMaxReplica);
} else {
$oSetToProcess = $oSetScope;
}
$iLastReplicaProcessed = -1;
while ($oReplica = $oSetToProcess->Fetch()) {
$iLastReplicaProcessed = $oReplica->GetKey();
$this->m_oStatLog->AddTrace("Destination object to be DELETED", $oReplica);
$oReplica->DeleteDestObject($this->m_oChange, $this->m_oStatLog);
}
if ($iMaxReplica) {
if ($iMaxReplica < $iCountScope) {
// Continue with this job!
$this->m_oStatLog->Set('status_curr_pos', $iLastReplicaProcessed);
return true;
}
}
// Job complete!
$this->m_oStatLog->Set('status_curr_job', 0);
$this->m_oStatLog->Set('status_curr_pos', -1);
return false;
}
示例15: DeleteConnectedNetworkDevice
protected function DeleteConnectedNetworkDevice()
{
// The device might be already deleted (reentrance in the current procedure when both device are NETWORK devices!)
$oDevice = MetaModel::GetObject('ConnectableCI', $this->Get('connectableci_id'), false);
if (is_object($oDevice) && get_class($oDevice) == 'NetworkDevice') {
// Track and delete the counterpart link
$sOQL = "SELECT lnkConnectableCIToNetworkDevice WHERE connectableci_id = :device AND networkdevice_id = :network AND network_port = :nwport AND device_port = :devport";
$oConnectionSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array(), array('network' => $this->Get('connectableci_id'), 'device' => $this->Get('networkdevice_id'), 'devport' => $this->Get('network_port'), 'nwport' => $this->Get('device_port')));
// There should be one link - do it in a safe manner anyway
while ($oConnection = $oConnectionSet->Fetch()) {
$oConnection->DBDelete();
}
}
}