/**
  * 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;
 }
 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);
         }
     }
 }
Example #3
0
/**
 * 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;
}
 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);
     }
 }
 /**
  * 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");
 }
 protected function GetHistoryTable(WebPage $oPage, DBObjectSet $oSet)
 {
     $sHtml = '';
     // First the latest change that the user is allowed to see
     $oSet->Rewind();
     // Reset the pointer to the beginning of the set
     $aChanges = array();
     while ($oChangeOp = $oSet->Fetch()) {
         $sChangeDescription = $oChangeOp->GetDescription();
         if ($sChangeDescription != '') {
             // The change is visible for the current user
             $changeId = $oChangeOp->Get('change');
             $aChanges[$changeId]['date'] = $oChangeOp->Get('date');
             $aChanges[$changeId]['userinfo'] = $oChangeOp->Get('userinfo');
             if (!isset($aChanges[$changeId]['log'])) {
                 $aChanges[$changeId]['log'] = array();
             }
             $aChanges[$changeId]['log'][] = $sChangeDescription;
         }
     }
     $aAttribs = array('date' => array('label' => Dict::S('UI:History:Date'), 'description' => Dict::S('UI:History:Date+')), 'userinfo' => array('label' => Dict::S('UI:History:User'), 'description' => Dict::S('UI:History:User+')), 'log' => array('label' => Dict::S('UI:History:Changes'), 'description' => Dict::S('UI:History:Changes+')));
     $aValues = array();
     foreach ($aChanges as $aChange) {
         $aValues[] = array('date' => $aChange['date'], 'userinfo' => htmlentities($aChange['userinfo'], ENT_QUOTES, 'UTF-8'), 'log' => "<ul><li>" . implode('</li><li>', $aChange['log']) . "</li></ul>");
     }
     $sHtml .= $oPage->GetTable($aAttribs, $aValues);
     return $sHtml;
 }
 /**
  * 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;
 }
 /**
  * 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);
         }
     }
 }
 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);
 }
 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();
 }
Example #11
0
/**
 * Checks the parameters and returns the appropriate exporter (if any)
 * @param string $sExpression The OQL query to export or null
 * @param string $sQueryId The entry in the query phrasebook if $sExpression is null
 * @param string $sFormat The code of export format: csv, pdf, html, xlsx
 * @throws MissingQueryArgument
 * @return Ambigous <iBulkExport, NULL>
 */
function CheckParameters($sExpression, $sQueryId, $sFormat)
{
    $oExporter = null;
    if ($sExpression === null && $sQueryId === null) {
        ReportErrorAndUsage("Missing parameter. The parameter 'expression' or 'query' must be specified.");
    }
    // Either $sExpression or $sQueryId must be specified
    if ($sExpression === null) {
        $oSearch = DBObjectSearch::FromOQL('SELECT QueryOQL WHERE id = :query_id', array('query_id' => $sQueryId));
        $oQueries = new DBObjectSet($oSearch);
        if ($oQueries->Count() > 0) {
            $oQuery = $oQueries->Fetch();
            $sExpression = $oQuery->Get('oql');
            $sFields = $oQuery->Get('fields');
            if (strlen($sFields) == 0) {
                $sFields = trim($oQuery->Get('fields'));
            }
        } else {
            ReportErrorAndExit("Invalid query phrasebook identifier: '{$sQueryId}'");
        }
    }
    if ($sFormat === null) {
        ReportErrorAndUsage("Missing parameter 'format'.");
    }
    // Check if the supplied query is valid (and all the parameters are supplied
    try {
        $oSearch = DBObjectSearch::FromOQL($sExpression);
        $aArgs = array();
        foreach ($oSearch->GetQueryParams() as $sParam => $foo) {
            $value = utils::ReadParam('arg_' . $sParam, null, true, 'raw_data');
            if (!is_null($value)) {
                $aArgs[$sParam] = $value;
            } else {
                throw new MissingQueryArgument("Missing parameter '--arg_{$sParam}'");
            }
        }
        $oSearch->SetInternalParams($aArgs);
        $sFormat = utils::ReadParam('format', 'html', true, 'raw_data');
        $oExporter = BulkExport::FindExporter($sFormat, $oSearch);
        if ($oExporter == null) {
            $aSupportedFormats = BulkExport::FindSupportedFormats();
            ReportErrorAndExit("Invalid output format: '{$sFormat}'. The supported formats are: " . implode(', ', array_keys($aSupportedFormats)));
        }
    } catch (MissingQueryArgument $e) {
        ReportErrorAndUsage("Invalid OQL query: '{$sExpression}'.\n" . $e->getMessage());
    } catch (OQLException $e) {
        ReportErrorAndExit("Invalid OQL query: '{$sExpression}'.\n" . $e->getMessage());
    } catch (Exception $e) {
        ReportErrorAndExit($e->getMessage());
    }
    $oExporter->SetFormat($sFormat);
    $oExporter->SetChunkSize(EXPORTER_DEFAULT_CHUNK_SIZE);
    $oExporter->SetObjectList($oSearch);
    $oExporter->ReadParameters();
    return $oExporter;
}
Example #12
0
function DisplayStatus($oP)
{
    $oSearch = new DBObjectSearch('BackgroundTask');
    $oTasks = new DBObjectSet($oSearch);
    $oP->p('+---------------------------+---------+---------------------+---------------------+--------+-----------+');
    $oP->p('| Task Class                | Status  | Last Run            | Next Run            | Nb Run | Avg. Dur. |');
    $oP->p('+---------------------------+---------+---------------------+---------------------+--------+-----------+');
    while ($oTask = $oTasks->Fetch()) {
        $sTaskName = $oTask->Get('class_name');
        $sStatus = $oTask->Get('status');
        $sLastRunDate = $oTask->Get('latest_run_date');
        $sNextRunDate = $oTask->Get('next_run_date');
        $iNbRun = (int) $oTask->Get('total_exec_count');
        $sAverageRunTime = $oTask->Get('average_run_duration');
        $oP->p(sprintf('| %1$-25.25s | %2$-7s | %3$-19s | %4$-19s | %5$6d | %6$7s s |', $sTaskName, $sStatus, $sLastRunDate, $sNextRunDate, $iNbRun, $sAverageRunTime));
    }
    $oP->p('+---------------------------+---------+---------------------+---------------------+--------+-----------+');
}
Example #13
0
 /**
  * Build a new set (in memory) made of objects of the given set which are NOT present in the current set
  * 
  * Limitations:
  * The objects inside the set must be written in the database since the comparison is based on their identifiers
  * Sets with several objects per row are NOT supported
  * 
  * @param DBObjectSet $oObjectSet
  * @throws CoreException
  * 
  * @return DBObjectSet The "delta" set.
  */
 public function CreateDelta(DBObjectSet $oObjectSet)
 {
     if ($this->GetRootClass() != $oObjectSet->GetRootClass()) {
         throw new CoreException("Could not 'delta' two objects sets if they don't have the same root class");
     }
     if (!$this->m_bLoaded) {
         $this->Load();
     }
     $aId2Row = array();
     $iCurrPos = $this->m_iCurrRow;
     // Save the cursor
     $idx = 0;
     while ($oObj = $this->Fetch()) {
         $aId2Row[$oObj->GetKey()] = $idx;
         $idx++;
     }
     $oNewSet = DBObjectSet::FromScratch($this->GetClass());
     $oObjectSet->Seek(0);
     while ($oObject = $oObjectSet->Fetch()) {
         if (!array_key_exists($oObject->GetKey(), $aId2Row)) {
             $oNewSet->AddObject($oObject);
         }
     }
     $this->Seek($iCurrPos);
     // Restore the cursor
     return $oNewSet;
 }
 public function LoadCache()
 {
     if (!is_null($this->m_aProfiles)) {
         return;
     }
     // Could be loaded in a shared memory (?)
     $oKPI = new ExecutionKPI();
     if (self::HasSharing()) {
         SharedObject::InitSharedClassProperties();
     }
     $oProfileSet = new DBObjectSet(DBObjectSearch::FromOQL_AllData("SELECT URP_Profiles"));
     $this->m_aProfiles = array();
     while ($oProfile = $oProfileSet->Fetch()) {
         $this->m_aProfiles[$oProfile->GetKey()] = $oProfile;
     }
     $oKPI->ComputeAndReport('Load of user management cache (excepted Action Grants)');
     /*
     		echo "<pre>\n";
     		print_r($this->m_aProfiles);
     		print_r($this->m_aUserProfiles);
     		print_r($this->m_aUserOrgs);
     		echo "</pre>\n";
     exit;
     */
     return true;
 }
 /**
  * Applies the defined parameters into the SQL query
  * @return string the SQL query to execute
  */
 public function BuildQuery()
 {
     $oAppContext = new ApplicationContext();
     $sQuery = $this->m_sQuery;
     $sQuery = str_replace('$DB_PREFIX$', MetaModel::GetConfig()->GetDBSubname(), $sQuery);
     // put the tables DB prefix (if any)
     foreach ($this->m_aParams as $sName => $aParam) {
         if ($aParam['type'] == 'context') {
             $sSearchPattern = '/\\$CONDITION\\(' . $sName . ',([^\\)]+)\\)\\$/';
             $value = $oAppContext->GetCurrentValue($aParam['mapping']);
             if (empty($value)) {
                 $sSQLExpr = '(1)';
             } else {
                 // Special case for managing the hierarchy of organizations
                 if ($aParam['mapping'] == 'org_id' && MetaModel::IsValidClass('Organization')) {
                     $sHierarchicalKeyCode = MetaModel::IsHierarchicalClass('Organization');
                     if ($sHierarchicalKeyCode != false) {
                         // organizations are in hierarchy... gather all the orgs below the given one...
                         $sOQL = "SELECT Organization AS node JOIN Organization AS root ON node.{$sHierarchicalKeyCode} BELOW root.id WHERE root.id = :value";
                         $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array(), array('value' => $value));
                         $aOrgIds = array();
                         while ($oOrg = $oSet->Fetch()) {
                             $aOrgIds[] = $oOrg->GetKey();
                         }
                         $sSQLExpr = '($1 IN(' . implode(',', $aOrgIds) . '))';
                     } else {
                         $sSQLExpr = '($1 = ' . CMDBSource::Quote($value) . ')';
                     }
                 } else {
                     $sSQLExpr = '($1 = ' . CMDBSource::Quote($value) . ')';
                 }
             }
             $sQuery = preg_replace($sSearchPattern, $sSQLExpr, $sQuery);
         }
     }
     return $sQuery;
 }
Example #16
0
 public function InSyncScope()
 {
     //
     // Optimization: cache the list of Data Sources and classes candidates for synchro
     //
     static $aSynchroClasses = null;
     if (is_null($aSynchroClasses)) {
         $aSynchroClasses = array();
         $sOQL = "SELECT SynchroDataSource AS datasource";
         $oSourceSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array(), array());
         while ($oSource = $oSourceSet->Fetch()) {
             $sTarget = $oSource->Get('scope_class');
             $aSynchroClasses[] = $sTarget;
         }
     }
     foreach ($aSynchroClasses as $sClass) {
         if ($this instanceof $sClass) {
             return true;
         }
     }
     return false;
 }
 public function ReadParameters()
 {
     parent::ReadParameters();
     $sQueryId = utils::ReadParam('query', null, true);
     $sFields = utils::ReadParam('fields', null, true, 'raw_data');
     if (($sFields === null || $sFields === '') && $sQueryId === null) {
         throw new BulkExportMissingParameterException('fields');
     } else {
         if ($sQueryId !== null && $sQueryId !== null) {
             $oSearch = DBObjectSearch::FromOQL('SELECT QueryOQL WHERE id = :query_id', array('query_id' => $sQueryId));
             $oQueries = new DBObjectSet($oSearch);
             if ($oQueries->Count() > 0) {
                 $oQuery = $oQueries->Fetch();
                 if ($sFields === null || $sFields === '') {
                     // No 'fields' parameter supplied, take the fields from the query phrasebook definition
                     $sFields = trim($oQuery->Get('fields'));
                     if ($sFields === '') {
                         throw new BulkExportMissingParameterException('fields');
                     }
                 }
             } else {
                 throw BulkExportException('Invalid value for the parameter: query. There is no Query Phrasebook with id = ' . $sQueryId, Dict::Format('Core:BulkExport:InvalidParameter_Query', $sQueryId));
             }
         }
     }
     $aFields = explode(',', $sFields);
     $this->aStatusInfo['fields'] = array();
     foreach ($aFields as $sField) {
         // Trim the values since it's too temping to write: fields=name, first_name, org_name instead of fields=name,first_name,org_name
         $this->aStatusInfo['fields'][] = trim($sField);
     }
 }
 /**
  * Loads the preferences for the current user, creating the record in the database
  * if needed
  */
 protected static function Load()
 {
     if (self::$oUserPrefs != null) {
         return;
     }
     $oSearch = new DBObjectSearch('appUserPreferences');
     $oSearch->AddCondition('userid', UserRights::GetUserId(), '=');
     $oSet = new DBObjectSet($oSearch);
     $oObj = $oSet->Fetch();
     if ($oObj == null) {
         // No prefs (yet) for this user, create the object
         $oObj = new appUserPreferences();
         $oObj->Set('userid', UserRights::GetUserId());
         $oObj->Set('preferences', array());
         // Default preferences: an empty array
         try {
             $oObj->DBInsert();
         } catch (Exception $e) {
             // Ignore errors
         }
     }
     self::$oUserPrefs = $oObj;
 }
 /**
  * Describe (as a text string) the modifications corresponding to this change
  */
 public function GetDescription()
 {
     $sResult = '';
     $oTargetObjectClass = $this->Get('objclass');
     $oTargetObjectKey = $this->Get('objkey');
     $oTargetSearch = new DBObjectSearch($oTargetObjectClass);
     $oTargetSearch->AddCondition('id', $oTargetObjectKey, '=');
     $oMonoObjectSet = new DBObjectSet($oTargetSearch);
     if (UserRights::IsActionAllowedOnAttribute($this->Get('objclass'), $this->Get('attcode'), UR_ACTION_READ, $oMonoObjectSet) == UR_ALLOWED_YES) {
         if (!MetaModel::IsValidAttCode($this->Get('objclass'), $this->Get('attcode'))) {
             return '';
         }
         // Protects against renamed attributes...
         $oAttDef = MetaModel::GetAttributeDef($this->Get('objclass'), $this->Get('attcode'));
         $sAttName = $oAttDef->GetLabel();
         $sLinkClass = $oAttDef->GetLinkedClass();
         $aLinkClasses = MetaModel::EnumChildClasses($sLinkClass, ENUM_CHILD_CLASSES_ALL);
         // Search for changes on the corresponding link
         //
         $oSearch = new DBObjectSearch('CMDBChangeOpSetAttribute');
         $oSearch->AddCondition('change', $this->Get('change'), '=');
         $oSearch->AddCondition('objkey', $this->Get('link_id'), '=');
         if (count($aLinkClasses) == 1) {
             // Faster than the whole building of the expression below for just one value ??
             $oSearch->AddCondition('objclass', $sLinkClass, '=');
         } else {
             $oField = new FieldExpression('objclass', $oSearch->GetClassAlias());
             $sListExpr = '(' . implode(', ', CMDBSource::Quote($aLinkClasses)) . ')';
             $sOQLCondition = $oField->Render() . " IN {$sListExpr}";
             $oNewCondition = Expression::FromOQL($sOQLCondition);
             $oSearch->AddConditionExpression($oNewCondition);
         }
         $oSet = new DBObjectSet($oSearch);
         $aChanges = array();
         while ($oChangeOp = $oSet->Fetch()) {
             $aChanges[] = $oChangeOp->GetDescription();
         }
         if (count($aChanges) == 0) {
             return '';
         }
         $sItemDesc = MetaModel::GetHyperLink($this->Get('item_class'), $this->Get('item_id'));
         $sResult = $sAttName . ' - ';
         $sResult .= Dict::Format('Change:LinkSet:Modified', $sItemDesc);
         $sResult .= ' : ' . implode(', ', $aChanges);
     }
     return $sResult;
 }
 /**
  * Find an object from a polymorph search specification (Rest/Json)
  * 	 
  * @param string $sClass Name of the class
  * @param mixed $key Either search criteria (substructure), or an object or an OQL string.
  * @param bool $bAllowNullValue Allow the cases such as key = 0 or key = {null} and return null then
  * @return DBObject The object found
  * @throws Exception If the input structure is not valid or it could not find exactly one object
  * @api
  */
 public static function FindObjectFromKey($sClass, $key, $bAllowNullValue = false)
 {
     if (is_object($key)) {
         $res = static::FindObjectFromCriteria($sClass, $key);
     } elseif (is_numeric($key)) {
         if ($bAllowNullValue && $key == 0) {
             $res = null;
         } else {
             $res = MetaModel::GetObject($sClass, $key, false);
             if (is_null($res)) {
                 throw new Exception("Invalid object {$sClass}::{$key}");
             }
         }
     } elseif (is_string($key)) {
         // OQL
         $oSearch = DBObjectSearch::FromOQL($key);
         $oSet = new DBObjectSet($oSearch);
         $iCount = $oSet->Count();
         if ($iCount == 0) {
             throw new Exception("No item found for query: {$key}");
         } elseif ($iCount > 1) {
             throw new Exception("Several items found ({$iCount}) for query: {$key}");
         }
         $res = $oSet->Fetch();
     } else {
         throw new Exception("Wrong format for key");
     }
     return $res;
 }
Example #21
0
     $aFullTextNeedles = array($aMatches[1]);
 } else {
     // Split the text on the blanks and treat this as a search for <word1> AND <word2> AND <word3>
     $aFullTextNeedles = explode(' ', $sFullText);
 }
 $oFilter = new DBObjectSearch($sClass);
 foreach ($aFullTextNeedles as $sSearchText) {
     $oFilter->AddCondition_FullText($sSearchText);
 }
 $oSet = new DBObjectSet($oFilter);
 $oPage->add("<div class=\"page_header\">\n");
 $oPage->add("<h2>" . MetaModel::GetClassIcon($sClass) . "&nbsp;<span class=\"hilite\">" . Dict::Format('UI:Search:Count_ObjectsOf_Class_Found', $oSet->Count(), Metamodel::GetName($sClass)) . "</h2>\n");
 $oPage->add("</div>\n");
 if ($oSet->Count() > 0) {
     $aLeafs = array();
     while ($oObj = $oSet->Fetch()) {
         if (get_class($oObj) == $sClass) {
             $aLeafs[] = $oObj->GetKey();
         }
     }
     $oLeafsFilter = new DBObjectSearch($sClass);
     if (count($aLeafs) > 0) {
         $oLeafsFilter->AddCondition('id', $aLeafs, 'IN');
         $oBlock = new DisplayBlock($oLeafsFilter, 'list', false);
         $sBlockId = 'global_search_' . $sClass;
         $oPage->add('<div id="' . $sBlockId . '">');
         $oBlock->RenderContent($oPage, array('table_id' => $sBlockId, 'currentId' => $sBlockId));
         $oPage->add('</div>');
         $oPage->P('&nbsp;');
         // Some space ?
         // Hide "no object found"
Example #22
0
/**
 * Displays the form for the final step of the ticket creation
 * @param WebPage $oP The current web page for the form output
 * @param Organization $oUserOrg The organization of the current user
 * @param integer $iSvcId The identifier of the service (fall through when there is only one service)
 * @param integer $iSubSvcId The identifier of the sub-service (fall through when there is only one sub-service)
 * @param integer $iTemplateId The identifier of the template (fall through when there is only one template)
 * @return void
 */
function RequestCreationForm($oP, $oUserOrg, $iSvcId = null, $iSubSvcId = null, $iTemplateId = null)
{
    $aParameters = $oP->ReadAllParams(PORTAL_ALL_PARAMS . ',template_id');
    if (!is_null($iSvcId)) {
        $aParameters['service_id'] = $iSvcId;
    }
    if (!is_null($iSubSvcId)) {
        $aParameters['servicesubcategory_id'] = $iSubSvcId;
    }
    if (!is_null($iTemplateId)) {
        $aParameters['template_id'] = $iTemplateId;
    }
    $sDescription = '';
    if (isset($aParameters['template_id']) && $aParameters['template_id'] != 0) {
        $aTemplateFields = array();
        $oTemplate = MetaModel::GetObject('Template', $aParameters['template_id'], false);
        if (is_object($oTemplate)) {
            $oFieldSearch = DBObjectSearch::FromOQL('SELECT TemplateField WHERE template_id = :template_id');
            $oFieldSearch->AllowAllData();
            $oFieldSet = new DBObjectSet($oFieldSearch, array('order' => true), array('template_id' => $oTemplate->GetKey()));
            while ($oField = $oFieldSet->Fetch()) {
                $sAttCode = $oField->Get('code');
                if (isset($aParameters[$sAttCode])) {
                    $oField->Set('initial_value', $aParameters[$sAttCode]);
                }
                $aTemplateFields[$sAttCode] = $oField;
            }
        }
    }
    $oServiceCategory = MetaModel::GetObject('Service', $aParameters['service_id'], false, true);
    $oServiceSubCategory = MetaModel::GetObject('ServiceSubcategory', $aParameters['servicesubcategory_id'], false, true);
    if (is_object($oServiceCategory) && is_object($oServiceSubCategory)) {
        $sClass = ComputeClass($oServiceSubCategory->GetKey());
        $oRequest = MetaModel::NewObject($sClass);
        $oRequest->Set('org_id', $oUserOrg->GetKey());
        $oRequest->Set('caller_id', UserRights::GetContactId());
        $oRequest->Set('service_id', $aParameters['service_id']);
        $oRequest->Set('servicesubcategory_id', $aParameters['servicesubcategory_id']);
        $oAttDef = MetaModel::GetAttributeDef($sClass, 'service_id');
        $aDetails[] = array('label' => $oAttDef->GetLabel(), 'value' => $oServiceCategory->GetName());
        $oAttDef = MetaModel::GetAttributeDef($sClass, 'servicesubcategory_id');
        $aDetails[] = array('label' => $oAttDef->GetLabel(), 'value' => $oServiceSubCategory->GetName());
        $aList = explode(',', GetConstant($sClass, 'FORM_ATTRIBUTES'));
        $iFlags = 0;
        foreach ($aList as $sAttCode) {
            $value = '';
            if (isset($aParameters[$sAttCode])) {
                $value = $aParameters[$sAttCode];
                $oRequest->Set($sAttCode, $value);
            }
        }
        $aFieldsMap = array();
        foreach ($aList as $sAttCode) {
            $value = '';
            $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
            $iFlags = $oRequest->GetAttributeFlags($sAttCode);
            if (isset($aParameters[$sAttCode])) {
                $value = $aParameters[$sAttCode];
            }
            $aArgs = array('this' => $oRequest);
            $sInputId = 'attr_' . $sAttCode;
            $aFieldsMap[$sAttCode] = $sInputId;
            $sValue = "<span id=\"field_{$sInputId}\">" . $oRequest->GetFormElementForField($oP, $sClass, $sAttCode, $oAttDef, $value, '', 'attr_' . $sAttCode, '', $iFlags, $aArgs) . '</span>';
            $aDetails[] = array('label' => $oAttDef->GetLabel(), 'value' => $sValue);
        }
        $aHidden = array();
        if (!empty($aTemplateFields)) {
            foreach ($aTemplateFields as $sAttCode => $oField) {
                $sValue = $oField->GetFormElement($oP, $sClass);
                if ($oField->Get('input_type') == 'hidden') {
                    $aHidden[] = $sValue;
                } else {
                    $aDetails[] = array('label' => $oField->GetAsHTML('label'), 'value' => $sValue);
                }
            }
        }
        $oP->add_script(<<<EOF
// Create the object once at the beginning of the page...
\tvar oWizardHelper = new WizardHelper('{$sClass}', '');
EOF
);
        $oP->add_linked_script("../js/json.js");
        $oP->add_linked_script("../js/forms-json-utils.js");
        $oP->add_linked_script("../js/wizardhelper.js");
        $oP->add_linked_script("../js/wizard.utils.js");
        $oP->add_linked_script("../js/linkswidget.js");
        $oP->add_linked_script("../js/extkeywidget.js");
        $oP->add_linked_script("../js/jquery.blockUI.js");
        $oP->add("<div class=\"wizContainer\" id=\"form_request_description\">\n");
        $oP->add("<h1 id=\"title_request_form\">" . Dict::S('Portal:DescriptionOfTheRequest') . "</h1>\n");
        $oP->WizardFormStart('request_form', 4);
        $oP->details($aDetails);
        // Add hidden fields for known values, enabling dependant attributes to be computed correctly
        //
        foreach ($oRequest->ListChanges() as $sAttCode => $value) {
            if (!in_array($sAttCode, $aList)) {
                $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
                if ($oAttDef->IsScalar() && $oAttDef->IsWritable()) {
                    $sValue = htmlentities($oRequest->Get($sAttCode), ENT_QUOTES, 'UTF-8');
                    $oP->add("<input type=\"hidden\" id=\"attr_{$sAttCode}\" name=\"attr_{$sAttCode}\" value=\"{$sValue}\">");
                    $aFieldsMap[$sAttCode] = 'attr_' . $sAttCode;
                }
            }
        }
        if (isset($aParameters['template_id']) && $aParameters['template_id'] != 0) {
            $oP->add("<input type=\"hidden\" name=\"attr_template_id\" value=\"{$aParameters['template_id']}\">");
        }
        $oP->add(implode("\n", $aHidden));
        $oAttPlugin = new AttachmentPlugIn();
        $oAttPlugin->OnDisplayRelations($oRequest, $oP, true);
        $oP->add("<input type=\"hidden\" name=\"operation\" value=\"create_request\">");
        $oP->WizardFormButtons(BUTTON_BACK | BUTTON_FINISH | BUTTON_CANCEL);
        //Back button automatically discarded if on the first page
        $oP->WizardFormEnd();
        $oP->add("</div>\n");
        $iFieldsCount = count($aFieldsMap);
        $sJsonFieldsMap = json_encode($aFieldsMap);
        $oP->add_ready_script(<<<EOF
\t\toWizardHelper.SetFieldsMap({$sJsonFieldsMap});
\t\toWizardHelper.SetFieldsCount({$iFieldsCount});

\t\t// Starts the validation when the page is ready
\t\tCheckFields('request_form', false);
\t\t\$('#request_form').submit( function() {
\t\t\treturn OnSubmit('request_form');
\t\t});
EOF
);
    } else {
        // User not authorized to use this service ?
        //ShowOngoingTickets($oP);
    }
}
 /**
  * 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;
 }
 public function IsStimulusAllowed($oUser, $sClass, $sStimulusCode, $oInstanceSet = null)
 {
     $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT UserRightsMatrixClassStimulusGrant WHERE class = '{$sClass}' AND stimulus = '{$sStimulusCode}' AND userid = '{$oUser->GetKey()}'"));
     if ($oSet->Count() < 1) {
         return UR_ALLOWED_NO;
     }
     $oGrantRecord = $oSet->Fetch();
     switch ($oGrantRecord->Get('permission')) {
         case 'yes':
             $iRetCode = UR_ALLOWED_YES;
             break;
         case 'no':
         default:
             $iRetCode = UR_ALLOWED_NO;
             break;
     }
     return $iRetCode;
 }
 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;
         }
     }
 }
 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();
         }
     }
 }
Example #27
0
                    $oAttachment->Set('item_class', $sObjClass);
                    $oAttachment->SetDefaultOrgId();
                    $oAttachment->Set('contents', $oDoc);
                    $iAttId = $oAttachment->DBInsert();
                    $aResult['msg'] = $oDoc->GetFileName();
                    $aResult['icon'] = utils::GetAbsoluteUrlAppRoot() . AttachmentPlugIn::GetFileIcon($oDoc->GetFileName());
                    $aResult['att_id'] = $iAttId;
                    $aResult['preview'] = $oDoc->IsPreviewAvailable() ? 'true' : 'false';
                } catch (FileUploadException $e) {
                    $aResult['error'] = $e->GetMessage();
                }
            }
            $oPage->add(json_encode($aResult));
            break;
        case 'remove':
            $iAttachmentId = utils::ReadParam('att_id', '');
            $oSearch = DBObjectSearch::FromOQL("SELECT Attachment WHERE id = :id");
            $oSet = new DBObjectSet($oSearch, array(), array('id' => $iAttachmentId));
            while ($oAttachment = $oSet->Fetch()) {
                $oAttachment->DBDelete();
            }
            break;
        default:
            $oPage->p("Missing argument 'operation'");
    }
    $oPage->output();
} catch (Exception $e) {
    // note: transform to cope with XSS attacks
    echo htmlentities($e->GetMessage(), ENT_QUOTES, 'utf-8');
    IssueLog::Error($e->getMessage());
}
 /**
  * Prepare structures in memory, to speedup the processing of a given replica
  */
 public function PrepareProcessing($bFirstPass = true)
 {
     if ($this->m_oDataSource->Get('status') == 'obsolete') {
         throw new SynchroExceptionNotStarted(Dict::S('Core:SyncDataSourceObsolete'));
     }
     if (!UserRights::IsAdministrator() && $this->m_oDataSource->Get('user_id') != UserRights::GetUserId()) {
         throw new SynchroExceptionNotStarted(Dict::S('Core:SyncDataSourceAccessRestriction'));
     }
     // Get the list of SQL columns
     $sClass = $this->m_oDataSource->GetTargetClass();
     $aAttCodesExpected = array();
     $aAttCodesToReconcile = array();
     $aAttCodesToUpdate = array();
     $sSelectAtt = "SELECT SynchroAttribute WHERE sync_source_id = :source_id AND (update = 1 OR reconcile = 1)";
     $oSetAtt = new DBObjectSet(DBObjectSearch::FromOQL($sSelectAtt), array(), array('source_id' => $this->m_oDataSource->GetKey()));
     while ($oSyncAtt = $oSetAtt->Fetch()) {
         if ($oSyncAtt->Get('update')) {
             $aAttCodesToUpdate[$oSyncAtt->Get('attcode')] = $oSyncAtt;
         }
         if ($oSyncAtt->Get('reconcile')) {
             $aAttCodesToReconcile[$oSyncAtt->Get('attcode')] = $oSyncAtt;
         }
         $aAttCodesExpected[$oSyncAtt->Get('attcode')] = $oSyncAtt;
     }
     $aColumns = $this->m_oDataSource->GetSQLColumns(array_keys($aAttCodesExpected));
     $aExtDataFields = array_keys($aColumns);
     $aExtDataFields[] = 'primary_key';
     $this->m_aExtDataSpec = array('table' => $this->m_oDataSource->GetDataTable(), 'join_key' => 'id', 'fields' => $aExtDataFields);
     // Get the list of attributes, determine reconciliation keys and update targets
     //
     if ($this->m_oDataSource->Get('reconciliation_policy') == 'use_attributes') {
         $this->m_aReconciliationKeys = $aAttCodesToReconcile;
     } elseif ($this->m_oDataSource->Get('reconciliation_policy') == 'use_primary_key') {
         // Override the settings made at the attribute level !
         $this->m_aReconciliationKeys = array("primary_key" => null);
     }
     if ($bFirstPass) {
         $this->m_oStatLog->AddTrace("Update of: {" . implode(', ', array_keys($aAttCodesToUpdate)) . "}");
         $this->m_oStatLog->AddTrace("Reconciliation on: {" . implode(', ', array_keys($this->m_aReconciliationKeys)) . "}");
     }
     if (count($aAttCodesToUpdate) == 0) {
         $this->m_oStatLog->AddTrace("No attribute to update");
         throw new SynchroExceptionNotStarted('There is no attribute to update');
     }
     if (count($this->m_aReconciliationKeys) == 0) {
         $this->m_oStatLog->AddTrace("No attribute for reconciliation");
         throw new SynchroExceptionNotStarted('No attribute for reconciliation');
     }
     $this->m_aAttributes = array();
     foreach ($aAttCodesToUpdate as $sAttCode => $oSyncAtt) {
         $oAttDef = MetaModel::GetAttributeDef($this->m_oDataSource->GetTargetClass(), $sAttCode);
         if ($oAttDef->IsWritable()) {
             $this->m_aAttributes[$sAttCode] = $oSyncAtt;
         }
     }
     // Compute and keep track of the limit date taken into account for obsoleting replicas
     //
     if ($this->m_oLastFullLoadStartDate == null) {
         // No previous import known, use the full_load_periodicity value... and the current date
         $this->m_oLastFullLoadStartDate = new DateTime();
         // Now
         $iLoadPeriodicity = $this->m_oDataSource->Get('full_load_periodicity');
         // Duration in seconds
         if ($iLoadPeriodicity > 0) {
             $sInterval = "-{$iLoadPeriodicity} seconds";
             $this->m_oLastFullLoadStartDate->Modify($sInterval);
         } else {
             $this->m_oLastFullLoadStartDate = new DateTime('1970-01-01');
         }
     }
     if ($bFirstPass) {
         $this->m_oStatLog->AddTrace("Limit Date: " . $this->m_oLastFullLoadStartDate->Format('Y-m-d H:i:s'));
     }
 }
 public function GetClassStimulusGrant($iProfile, $sClass, $sStimulusCode)
 {
     if (isset($this->m_aClassStimulusGrants[$iProfile][$sClass][$sStimulusCode])) {
         return $this->m_aClassStimulusGrants[$iProfile][$sClass][$sStimulusCode];
     }
     // Get the permission for this profile/class/stimulus
     $oSearch = DBObjectSearch::FromOQL_AllData("SELECT URP_StimulusGrant WHERE class = :class AND stimulus = :stimulus AND profileid = :profile AND permission = 'yes'");
     $oSet = new DBObjectSet($oSearch, array(), array('class' => $sClass, 'stimulus' => $sStimulusCode, 'profile' => $iProfile));
     if ($oSet->Count() >= 1) {
         $oGrantRecord = $oSet->Fetch();
     } else {
         $oGrantRecord = null;
     }
     $this->m_aClassStimulusGrants[$iProfile][$sClass][$sStimulusCode] = $oGrantRecord;
     return $oGrantRecord;
 }
 public function ReadParameters()
 {
     parent::ReadParameters();
     $sQueryId = utils::ReadParam('query', null, true);
     $sFields = utils::ReadParam('fields', null, true, 'raw_data');
     if (($sFields === null || $sFields === '') && $sQueryId === null) {
         throw new BulkExportMissingParameterException('fields');
     } else {
         if ($sQueryId !== null && $sQueryId !== null) {
             $oSearch = DBObjectSearch::FromOQL('SELECT QueryOQL WHERE id = :query_id', array('query_id' => $sQueryId));
             $oQueries = new DBObjectSet($oSearch);
             if ($oQueries->Count() > 0) {
                 $oQuery = $oQueries->Fetch();
                 if ($sFields === null || $sFields === '') {
                     // No 'fields' parameter supplied, take the fields from the query phrasebook definition
                     $sFields = trim($oQuery->Get('fields'));
                     if ($sFields === '') {
                         throw new BulkExportMissingParameterException('fields');
                     }
                 }
             } else {
                 throw BulkExportException('Invalid value for the parameter: query. There is no Query Phrasebook with id = ' . $sQueryId, Dict::Format('Core:BulkExport:InvalidParameter_Query', $sQueryId));
             }
         }
     }
     // Interpret (and check) the list of fields
     //
     $aSelectedClasses = $this->oSearch->GetSelectedClasses();
     $aAliases = array_keys($aSelectedClasses);
     $aAuthorizedClasses = array();
     foreach ($aSelectedClasses as $sAlias => $sClassName) {
         if (UserRights::IsActionAllowed($sClassName, UR_ACTION_BULK_READ) == UR_ALLOWED_YES) {
             $aAuthorizedClasses[$sAlias] = $sClassName;
         }
     }
     $aFields = explode(',', $sFields);
     $this->aStatusInfo['fields'] = array();
     foreach ($aFields as $sFieldSpec) {
         // Trim the values since it's natural to write: fields=name, first_name, org_name instead of fields=name,first_name,org_name
         $sExtendedAttCode = trim($sFieldSpec);
         if (preg_match('/^([^\\.]+)\\.(.+)$/', $sExtendedAttCode, $aMatches)) {
             $sAlias = $aMatches[1];
             $sAttCode = $aMatches[2];
         } else {
             $sAlias = reset($aAliases);
             $sAttCode = $sExtendedAttCode;
         }
         if (!array_key_exists($sAlias, $aSelectedClasses)) {
             throw new Exception("Invalid alias '{$sAlias}' for the column '{$sExtendedAttCode}'. Availables aliases: '" . implode("', '", $aAliases) . "'");
         }
         $sClass = $aSelectedClasses[$sAlias];
         if (!array_key_exists($sAlias, $aAuthorizedClasses)) {
             throw new Exception("You do not have enough permissions to bulk read data of class '{$sClass}' (alias: {$sAlias})");
         }
         if ($this->bLocalizeOutput) {
             try {
                 $sLabel = MetaModel::GetLabel($sClass, $sAttCode);
             } catch (Exception $e) {
                 throw new Exception("Wrong field specification '{$sFieldSpec}': " . $e->getMessage());
             }
         } else {
             $sLabel = $sAttCode;
         }
         if (count($aAuthorizedClasses) > 1) {
             $sColLabel = $sAlias . '.' . $sLabel;
         } else {
             $sColLabel = $sLabel;
         }
         $this->aStatusInfo['fields'][] = array('sFieldSpec' => $sExtendedAttCode, 'sAlias' => $sAlias, 'sClass' => $sClass, 'sAttCode' => $sAttCode, 'sLabel' => $sLabel, 'sColLabel' => $sColLabel);
     }
 }